answer
stringlengths
17
10.2M
/* * @author Kruttik,Ramakrishna */ package edu.duke.cabig.c3pr.dao; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.Criteria; import org.hibernate.criterion.CriteriaSpecification; import org.hibernate.criterion.Example; import org.hibernate.criterion.Expression; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import org.springframework.dao.DataAccessException; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.transaction.annotation.Transactional; import edu.duke.cabig.c3pr.domain.CompanionStudyAssociation; import edu.duke.cabig.c3pr.domain.Identifier; import edu.duke.cabig.c3pr.domain.OrganizationAssignedIdentifier; import edu.duke.cabig.c3pr.domain.Participant; import edu.duke.cabig.c3pr.domain.ScheduledEpoch; import edu.duke.cabig.c3pr.domain.Study; import edu.duke.cabig.c3pr.domain.StudySite; import edu.duke.cabig.c3pr.domain.StudySubject; import edu.duke.cabig.c3pr.domain.StudySubjectConsentVersion; import edu.duke.cabig.c3pr.domain.SystemAssignedIdentifier; import edu.duke.cabig.c3pr.utils.StringUtils; import edu.emory.mathcs.backport.java.util.Collections; import gov.nih.nci.cabig.ctms.dao.MutableDomainObjectDao; /** * The Class StudySubjectDao. */ public class StudySubjectDao extends GridIdentifiableDao<StudySubject> implements MutableDomainObjectDao<StudySubject> { /** The SUBSTRIN g_ matc h_ properties. */ private List<String> SUBSTRING_MATCH_PROPERTIES = Arrays .asList("studySite.study.shortTitleText"); /** The EXAC t_ matc h_ properties. */ private List<String> EXACT_MATCH_PROPERTIES = Collections.emptyList(); /** The log. */ private static Log log = LogFactory.getLog(StudySubjectDao.class); /** The study dao. */ private StudyDao studyDao; /** The study site dao. */ private StudySiteDao studySiteDao; /** The participant dao. */ private ParticipantDao participantDao; /** * Sets the study dao. * * @param studyDao * the new study dao */ public void setStudyDao(StudyDao studyDao) { this.studyDao = studyDao; } /** * Instantiates a new study subject dao. */ public StudySubjectDao() { } /* (non-Javadoc) * @see edu.duke.cabig.c3pr.dao.C3PRBaseDao#domainClass() */ @Override public Class<StudySubject> domainClass() { return StudySubject.class; } /** * Reporting. * * @param registration * the registration * @param startDate * the start date * @param endDate * the end date * @param ccId * the cc id * * @return list of matching registration objects based on the date present * in the sample object that is passsed in. Also takes the date * range(startDate, endDate) and gets all objects having their * informedConsentSignedDate between these two dates. list of * StudySubject objects. */ public List<StudySubject> advancedSearch(StudySubject registration, Date startDate, Date endDate, String ccId) { Criteria registrationCriteria = getHibernateTemplate().getSessionFactory() .getCurrentSession().createCriteria(StudySubject.class); Criteria studySubjectStudyVersionCriteria = registrationCriteria.createCriteria("studySubjectStudyVersions"); Criteria studySubjectConsentVersionCriteria = studySubjectStudyVersionCriteria.createCriteria("studySubjectConsentVersionsInternal"); Criteria studySiteCriteria = studySubjectStudyVersionCriteria.createCriteria("studySiteStudyVersion").createCriteria("studySite"); Criteria participantCriteria = registrationCriteria.createCriteria("participant"); Criteria studyCriteria = studySiteCriteria.createCriteria("studyInternal"); Criteria studyVersionCriteria = studyCriteria.createCriteria("studyVersionsInternal"); Criteria siteCriteria = studySiteCriteria.createCriteria("healthcareSite"); Criteria identifiersAssignedToOrganizationCriteria = siteCriteria.createCriteria("identifiersAssignedToOrganization"); Criteria identifiersCriteria = studyCriteria.createCriteria("identifiers"); // Study Criteria if (registration.getStudySite().getStudy().getShortTitleText() != null && !registration.getStudySite().getStudy().getShortTitleText().equals("")) { studyVersionCriteria.add(Expression.ilike("shortTitleText", "%" + registration.getStudySite().getStudy().getShortTitleText() + "%")); } // Site criteria if (registration.getStudySite().getHealthcareSite().getName() != null && !registration.getStudySite().getHealthcareSite().getName().equals("")) { siteCriteria.add(Expression.ilike("name", "%" + registration.getStudySite().getHealthcareSite().getName() + "%")); } if (registration.getStudySite().getHealthcareSite().getPrimaryIdentifier() != null && !registration.getStudySite().getHealthcareSite().getPrimaryIdentifier() .equals("")) { identifiersAssignedToOrganizationCriteria.add(Expression.ilike("value", "%" + registration.getStudySite().getHealthcareSite().getPrimaryIdentifier() + "%")); } // registration consent criteria if (startDate != null && endDate != null) { studySubjectConsentVersionCriteria.add(Expression.between("informedConsentSignedDate", startDate, endDate)); }else if(startDate != null){ studySubjectConsentVersionCriteria.add(Expression.ge("informedConsentSignedDate", startDate)); }else if(endDate != null){ studySubjectConsentVersionCriteria.add(Expression.le("informedConsentSignedDate", endDate)); } // participant/subject criteria if (registration.getParticipant().getBirthDate() != null) { participantCriteria.add(Expression.eq("birthDate", registration.getParticipant() .getBirthDate())); } if (registration.getParticipant().getRaceCode() != null && !registration.getParticipant().getRaceCode().equals("")) { participantCriteria.add(Expression.ilike("raceCode", "%" + registration.getParticipant() .getRaceCode() + "%" ) ); } if (ccId != null && !ccId.equals("")) { identifiersCriteria.add(Expression.ilike("value", "%" + ccId + "%")); } registrationCriteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); registrationCriteria.addOrder(Order.asc("id")); return registrationCriteria.list(); } /* * This is the advanced search method used for Study Reports generation. */ /** * Advanced study search. * * @param studySubject * the study subject * * @return the list< study subject> */ public List<StudySubject> advancedStudySearch(StudySubject studySubject) { String selectClause = "select ssub from StudySubject ssub "; String whereClause = ""; List<Object> params = new ArrayList<Object>(); Study study= studySubject.getStudySite().getStudy(); boolean addStudySelectClause = true; String studyClause="join ssub.studySubjectStudyVersions ssbsv " + "join ssbsv.studySiteStudyVersion ssisv " + "join ssisv.studyVersion sv "; if (!StringUtils.getBlankIfNull(study.getShortTitleText()).equals("")) { selectClause += studyClause; whereClause += "sv.shortTitleText like ? "; params.add(study.getShortTitleText()); addStudySelectClause = false; } if (study.getIdentifiers().size() > 0){ if(addStudySelectClause) selectClause += studyClause; selectClause += "join sv.study study join study.identifiers sid "; whereClause += "and sid.value like ? "; params.add(study.getIdentifiers().get(0).getValue()); } Participant participant= studySubject.getParticipant(); boolean addParticipantSelectClause = true; String participantClause = "join ssub.participant prt "; if(!StringUtils.getBlankIfNull(participant.getFirstName()).equals("")){ selectClause += participantClause; whereClause += "and prt.firstName like ? "; params.add(participant.getFirstName()); addParticipantSelectClause = false; } if(!StringUtils.getBlankIfNull(participant.getLastName()).equals("")){ if(addParticipantSelectClause) selectClause += participantClause; whereClause += "and prt.lastName like ? "; params.add(participant.getLastName()); addParticipantSelectClause = false; } if (participant.getIdentifiers().size() > 0){ if(addParticipantSelectClause) selectClause += participantClause; selectClause += "join prt.identifiers pid "; whereClause += "and pid.value like ?"; params.add(participant.getIdentifiers().get(0).getValue()); } whereClause = "where " + (whereClause.startsWith("and")?whereClause.replaceFirst("and", ""):whereClause); String advanceQuery = selectClause + whereClause; return (List<StudySubject>)getHibernateTemplate().find(advanceQuery, params.toArray()); // Criteria studySubjectCriteria = getHibernateTemplate().getSessionFactory() // .getCurrentSession().createCriteria(StudySubject.class); // Criteria studySiteCriteria = studySubjectCriteria.createCriteria("studySite"); // Criteria participantCriteria = studySubjectCriteria.createCriteria("participant"); // Criteria studyCriteria = studySiteCriteria.createCriteria("study"); // Criteria studyVersionCriteria = studyCriteria.createCriteria("studyVersionsInternal"); // Criteria sIdentifiersCriteria = studyCriteria.createCriteria("identifiers"); // Criteria pIdentifiersCriteria = participantCriteria.createCriteria("identifiers"); // // Study Criteria // if (studySubject.getStudySite().getStudy().getShortTitleText() != null // && !studySubject.getStudySite().getStudy().getShortTitleText().equals("")) { // studyVersionCriteria.add(Expression.ilike("shortTitleText", "%" // + studySubject.getStudySite().getStudy().getShortTitleText() + "%")); // if (studySubject.getStudySite().getStudy().getIdentifiers().size() > 0) { // if (studySubject.getStudySite().getStudy().getIdentifiers().get(0).getValue() != null // && studySubject.getStudySite().getStudy().getIdentifiers().get(0) // .getValue() != "") { // sIdentifiersCriteria.add(Expression.ilike("value", "%" // + studySubject.getStudySite().getStudy().getIdentifiers().get(0) // .getValue() + "%")); // // participant/subject criteria // if (studySubject.getParticipant().getFirstName() != null // && !studySubject.getParticipant().getFirstName().equals("")) { // participantCriteria.add(Expression.ilike("firstName", "%" // + studySubject.getParticipant().getFirstName() + "%")); // if (studySubject.getParticipant().getLastName() != null // && !studySubject.getParticipant().getLastName().equals("")) { // participantCriteria.add(Expression.ilike("lastName", "%" // + studySubject.getParticipant().getLastName() + "%")); // if (studySubject.getParticipant().getIdentifiers().size() > 0) { // if (studySubject.getParticipant().getIdentifiers().get(0).getValue() != null // && !studySubject.getParticipant().getIdentifiers().get(0).getValue() // .equals("")) { // pIdentifiersCriteria.add(Expression.ilike("value", "%" // + studySubject.getParticipant().getIdentifiers().get(0).getValue() // studySubjectCriteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); // return studySubjectCriteria.list(); } /* * Used by searchRegistrationsController */ /** * Search by participant id. * * @param participantId * the participant id * * @return the list< study subject> */ public List<StudySubject> searchByParticipantId(Integer participantId) { return participantDao.getById(participantId).getStudySubjects(); } /* * Used by searchRegistrationsController */ /** * Search by study id. * * @param studyId * the study id * * @return the list< study subject> */ public List<StudySubject> searchByStudyId(Integer studyId) { List<StudySubject> registrations = new ArrayList<StudySubject>(); Study study = studyDao.getById(studyId); for (StudySite studySite : study.getStudySites()) { for (StudySubject studySubject : studySite.getStudySubjects()) { registrations.add(studySubject); } } if(study.getCompanionIndicator()){ for(CompanionStudyAssociation companionStudyAssociation : study.getParentStudyAssociations()){ for(StudySite studySite : companionStudyAssociation.getStudySites()){ for (StudySubject studySubject : studySite.getStudySubjects()) { registrations.add(studySubject); } } } } return registrations; } /** * *. * * @param registration * the registration * @param isWildCard * the is wild card * @param maxResults * the max results * * @return list of matching registration objects based on your sample * registration object */ public List<StudySubject> searchByExample(StudySubject registration, boolean isWildCard, int maxResults) { List<StudySubject> result = new ArrayList<StudySubject>(); Example example = Example.create(registration).excludeZeroes().ignoreCase(); try { Criteria studySubjectCriteria = getSession().createCriteria(StudySubject.class); studySubjectCriteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY); if (isWildCard) { example.excludeProperty("doNotUse").enableLike(MatchMode.ANYWHERE); studySubjectCriteria.add(example); if (maxResults > 0) studySubjectCriteria.setMaxResults(maxResults); if (registration.getIdentifiers().size() > 1) { studySubjectCriteria.createCriteria("identifiers").add( Restrictions.ilike("value", "%" + registration.getIdentifiers().get(0) .getValue() + "%")).add( Restrictions.ilike("value", "%" + registration.getIdentifiers().get(1) .getValue() + "%")); } else if (registration.getIdentifiers().size() > 0) { studySubjectCriteria.createCriteria("identifiers").add( Restrictions.ilike("value", "%" + registration.getIdentifiers().get(0) .getValue() + "%")); } result = studySubjectCriteria.list(); } result = studySubjectCriteria.add(example).list(); } catch (Exception e) { log.error(e.getMessage()); } return result; } /** * *. * * @param registration * the registration * * @return list of matching registration objects based on your sample * registration object */ public List<StudySubject> searchBySubjectAndStudySite(StudySubject registration) { Example example = Example.create(registration).excludeZeroes().ignoreCase(); Criteria registrationCriteria = getHibernateTemplate().getSessionFactory() .getCurrentSession().createCriteria(StudySubject.class); registrationCriteria.add(example); registrationCriteria.createCriteria("participant").add( Restrictions.like("id", registration.getParticipant().getId())); registrationCriteria.createCriteria("studySubjectStudyVersions").createCriteria("studySiteStudyVersion").createCriteria("studySite").add( Restrictions.like("id", registration.getStudySite().getId())); return registrationCriteria.list(); } /** * Search by scheduled epoch. * * @param scheduledEpoch * the scheduled epoch * * @return the list< study subject> */ public List<StudySubject> searchByScheduledEpoch(ScheduledEpoch scheduledEpoch) { StudySubject registration = new StudySubject(true); Example example = Example.create(registration).excludeZeroes().ignoreCase(); Criteria registrationCriteria = getHibernateTemplate().getSessionFactory() .getCurrentSession().createCriteria(StudySubject.class); registrationCriteria.add(example); registrationCriteria.createCriteria("studySubjectStudyVersions").createCriteria("scheduledEpochs").createCriteria("epoch").add( Restrictions.like("id", scheduledEpoch.getEpoch().getId())); return registrationCriteria.list(); } /** * Gets the all. * * @return the all * * @throws DataAccessException * the data access exception */ public List<StudySubject> getAll() throws DataAccessException { return getHibernateTemplate().find("from StudySubject"); } /** * Search by example. * * @param registration * the registration * @param maxResults * the max results * * @return the list< study subject> */ public List<StudySubject> searchByExample(StudySubject registration, int maxResults) { return searchByExample(registration, true, maxResults); } /** * Gets the incomplete registrations. * * @param registration * the registration * @param maxResults * the max results * * @return the incomplete registrations */ public List<StudySubject> getIncompleteRegistrations(int maxResults){ HibernateTemplate template = getHibernateTemplate() ; if(maxResults > 0){ template.setMaxResults(maxResults); } List<StudySubject> studySubjects = (List<StudySubject>) template.find( "select distinct ss from StudySubject ss join ss.studySubjectStudyVersions sssv join sssv.scheduledEpochs se where (se.scEpochWorkflowStatus = 'PENDING' OR se.scEpochWorkflowStatus = 'REGISTERED_BUT_NOT_RANDOMIZED')"); for(StudySubject studySubject : studySubjects){ initialize(studySubject); } return studySubjects ; } /** * Initialize. * * @param studySubject * the study subject * * @throws DataAccessException * the data access exception */ @Transactional(readOnly = false) public void initialize(StudySubject studySubject) throws DataAccessException { studyDao.initialize(studySubject.getStudySite().getStudy()); studySiteDao.initialize(studySubject.getStudySite()); participantDao.initialize(studySubject.getParticipant()); getHibernateTemplate().initialize(studySubject.getStudySite().getStudyInvestigatorsInternal()); getHibernateTemplate().initialize(studySubject.getStudySite().getStudyPersonnelInternal()); getHibernateTemplate().initialize(studySubject.getStudySite().getStudySiteStudyVersions()); getHibernateTemplate().initialize(studySubject.getChildStudySubjects()); getHibernateTemplate().initialize(studySubject.getParticipant().getIdentifiers()); getHibernateTemplate().initialize(studySubject.getParticipant().getRaceCodes()); getHibernateTemplate().initialize(studySubject.getParticipant().getContactMechanisms()); getHibernateTemplate().initialize(studySubject.getScheduledEpochs()); getHibernateTemplate().initialize(studySubject.getIdentifiers()); for(ScheduledEpoch scheduledEpoch: studySubject.getScheduledEpochs()){ getHibernateTemplate().initialize(scheduledEpoch.getScheduledArmsInternal()); getHibernateTemplate().initialize(scheduledEpoch.getSubjectEligibilityAnswersInternal()); getHibernateTemplate().initialize(scheduledEpoch.getSubjectStratificationAnswersInternal()); } for(StudySubject childStudySubject : studySubject.getChildStudySubjects()){ initialize(childStudySubject); } } /** * Search by sys identifier. * * @param id the id * * @return the list< study subject> */ @SuppressWarnings("unchecked") public List<StudySubject> searchBySysIdentifier(SystemAssignedIdentifier id) { return (List<StudySubject>) getHibernateTemplate() .find("select S from StudySubject S, SystemAssignedIdentifier I where I.systemName=?" + " and I.value=? and I.typeInternal=? and I=any elements(S.identifiers)", new Object[] { id.getSystemName(), id.getValue(), id.getType()}); } /** * Search by org identifier. * * @param id the id * * @return the list< study subject> */ @SuppressWarnings("unchecked") public List<StudySubject> searchByOrgIdentifier(OrganizationAssignedIdentifier id) { return (List<StudySubject>) getHibernateTemplate() .find("select S from StudySubject S, OrganizationAssignedIdentifier I where " + "I.value=? and I.typeInternal=? and I=any elements(S.identifiers)", new Object[]{id.getValue(), id.getTypeInternal()}); } /** * Gets study subjects by identifiers. * * @param studySubjectIdentifiers * the study subject identifiers * * @return the by identifiers */ public List<StudySubject> getByIdentifiers(List<Identifier> studySubjectIdentifiers) { List<StudySubject> studySubjects = new ArrayList<StudySubject>(); for (Identifier identifier : studySubjectIdentifiers) { if (identifier instanceof SystemAssignedIdentifier){ studySubjects.addAll(searchBySysIdentifier((SystemAssignedIdentifier) identifier)); } else if (identifier instanceof OrganizationAssignedIdentifier) { studySubjects.addAll(searchByOrgIdentifier((OrganizationAssignedIdentifier) identifier)); } } Set<StudySubject> set = new LinkedHashSet<StudySubject>(); set.addAll(studySubjects); return new ArrayList<StudySubject>(set); } /* (non-Javadoc) * @see gov.nih.nci.cabig.ctms.dao.MutableDomainObjectDao#save(gov.nih.nci.cabig.ctms.domain.MutableDomainObject) */ @Transactional(readOnly = false) public void save(StudySubject obj) { getHibernateTemplate().saveOrUpdate(obj); } /** * Merge. * * @param obj * the obj * * @return the study subject */ @Transactional(readOnly = false) public StudySubject merge(StudySubject obj) { return (StudySubject) getHibernateTemplate().merge(obj); } /*public List<StudySubject> searchByExample(StudySubject ss) { return searchByExample(ss, false, 0); }*/ /** * Search by example. * * @param ss * the ss * @param isWildCard * the is wild card * * @return the list< study subject> */ public List<StudySubject> searchByExample(StudySubject ss, boolean isWildCard) { return searchByExample(ss, isWildCard, 0); } /** * Gets the participant dao. * * @return the participant dao */ public ParticipantDao getParticipantDao() { return participantDao; } /** * Sets the participant dao. * * @param participantDao * the new participant dao */ public void setParticipantDao(ParticipantDao participantDao) { this.participantDao = participantDao; } /** * Search by identifier. * * @param id * the id * * @return the list< study subject> */ @SuppressWarnings("unchecked") public List<StudySubject> searchByIdentifier(int id) { return (List<StudySubject>) getHibernateTemplate().find( "select SS from StudySubject SS, Identifier I where I.id=? and I=any elements(SS.identifiers)", new Object[] {id}); } /** * Gets the study site dao. * * @return the study site dao */ public StudySiteDao getStudySiteDao() { return studySiteDao; } /** * Sets the study site dao. * * @param studySiteDao * the new study site dao */ public void setStudySiteDao(StudySiteDao studySiteDao) { this.studySiteDao = studySiteDao; } }
package net.fortuna.ical4j.model; import java.io.Serializable; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import net.fortuna.ical4j.model.parameter.Value; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Defines a recurrence. * * @author Ben Fortuna */ public class Recur implements Serializable { private static final long serialVersionUID = -7333226591784095142L; private static final String FREQ = "FREQ"; private static final String UNTIL = "UNTIL"; private static final String COUNT = "COUNT"; private static final String INTERVAL = "INTERVAL"; private static final String BYSECOND = "BYSECOND"; private static final String BYMINUTE = "BYMINUTE"; private static final String BYHOUR = "BYHOUR"; private static final String BYDAY = "BYDAY"; private static final String BYMONTHDAY = "BYMONTHDAY"; private static final String BYYEARDAY = "BYYEARDAY"; private static final String BYWEEKNO = "BYWEEKNO"; private static final String BYMONTH = "BYMONTH"; private static final String BYSETPOS = "BYSETPOS"; private static final String WKST = "WKST"; // frequencies.. public static final String SECONDLY = "SECONDLY"; public static final String MINUTELY = "MINUTELY"; public static final String HOURLY = "HOURLY"; public static final String DAILY = "DAILY"; public static final String WEEKLY = "WEEKLY"; public static final String MONTHLY = "MONTHLY"; public static final String YEARLY = "YEARLY"; private static Log log = LogFactory.getLog(Recur.class); private String frequency; private Date until; private int count = -1; private int interval = -1; private NumberList secondList; private NumberList minuteList; private NumberList hourList; private WeekDayList dayList; private NumberList monthDayList; private NumberList yearDayList; private NumberList weekNoList; private NumberList monthList; private NumberList setPosList; private String weekStartDay; private Map experimentalValues = new HashMap(); // The order, or layout, of the date as it appears in a string // e.g. 20050415T093000 (April 15th, 9:30:00am) private static final int[] DATE_ORDER = {Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND}; /** * Constructor. * * @param aValue * a string representation of a recurrence. * @throws ParseException * thrown when the specified string contains an invalid * representation of an UNTIL date value */ public Recur(final String aValue) throws ParseException { for (StringTokenizer t = new StringTokenizer(aValue, ";="); t .hasMoreTokens();) { String token = t.nextToken(); if (FREQ.equals(token)) { frequency = t.nextToken(); } else if (UNTIL.equals(token)) { String untilString = t.nextToken(); try { until = new Date(untilString); } catch (ParseException pe) { until = new DateTime(untilString); } } else if (COUNT.equals(token)) { count = Integer.parseInt(t.nextToken()); } else if (INTERVAL.equals(token)) { interval = Integer.parseInt(t.nextToken()); } else if (BYSECOND.equals(token)) { secondList = new NumberList(t.nextToken()); } else if (BYMINUTE.equals(token)) { minuteList = new NumberList(t.nextToken()); } else if (BYHOUR.equals(token)) { hourList = new NumberList(t.nextToken()); } else if (BYDAY.equals(token)) { dayList = new WeekDayList(t.nextToken()); } else if (BYMONTHDAY.equals(token)) { monthDayList = new NumberList(t.nextToken()); } else if (BYYEARDAY.equals(token)) { yearDayList = new NumberList(t.nextToken()); } else if (BYWEEKNO.equals(token)) { weekNoList = new NumberList(t.nextToken()); } else if (BYMONTH.equals(token)) { monthList = new NumberList(t.nextToken()); } else if (BYSETPOS.equals(token)) { setPosList = new NumberList(t.nextToken()); } else if (WKST.equals(token)) { weekStartDay = t.nextToken(); } // assume experimental value.. else { experimentalValues.put(token, t.nextToken()); } } } /** * @param frequency * @param until */ public Recur(final String frequency, final Date until) { this.frequency = frequency; this.until = until; } /** * @param frequency * @param count */ public Recur(final String frequency, final int count) { this.frequency = frequency; this.count = count; } /** * @return Returns the dayList. */ public final WeekDayList getDayList() { if (dayList == null) { dayList = new WeekDayList(); } return dayList; } /** * @return Returns the hourList. */ public final NumberList getHourList() { if (hourList == null) { hourList = new NumberList(); } return hourList; } /** * @return Returns the minuteList. */ public final NumberList getMinuteList() { if (minuteList == null) { minuteList = new NumberList(); } return minuteList; } /** * @return Returns the monthDayList. */ public final NumberList getMonthDayList() { if (monthDayList == null) { monthDayList = new NumberList(); } return monthDayList; } /** * @return Returns the monthList. */ public final NumberList getMonthList() { if (monthList == null) { monthList = new NumberList(); } return monthList; } /** * @return Returns the secondList. */ public final NumberList getSecondList() { if (secondList == null) { secondList = new NumberList(); } return secondList; } /** * @return Returns the setPosList. */ public final NumberList getSetPosList() { if (setPosList == null) { setPosList = new NumberList(); } return setPosList; } /** * @return Returns the weekNoList. */ public final NumberList getWeekNoList() { if (weekNoList == null) { weekNoList = new NumberList(); } return weekNoList; } /** * @return Returns the yearDayList. */ public final NumberList getYearDayList() { if (yearDayList == null) { yearDayList = new NumberList(); } return yearDayList; } /** * @return Returns the count. */ public final int getCount() { return count; } /** * @return Returns the experimentalValues. */ public final Map getExperimentalValues() { return experimentalValues; } /** * @return Returns the frequency. */ public final String getFrequency() { return frequency; } /** * @return Returns the interval. */ public final int getInterval() { return interval; } /** * @return Returns the until. */ public final Date getUntil() { return until; } /** * @return Returns the weekStartDay. */ public final String getWeekStartDay() { return weekStartDay; } /** * @param weekStartDay The weekStartDay to set. */ public final void setWeekStartDay(final String weekStartDay) { this.weekStartDay = weekStartDay; } /** * @see java.lang.Object#toString() */ public final String toString() { StringBuffer b = new StringBuffer(); b.append(FREQ); b.append('='); b.append(frequency); if (weekStartDay != null) { b.append(';'); b.append(WKST); b.append('='); b.append(weekStartDay); } if (interval >= 1) { b.append(';'); b.append(INTERVAL); b.append('='); b.append(interval); } if (until != null) { b.append(';'); b.append(UNTIL); b.append('='); // Note: date-time representations should always be in UTC time. b.append(until); } if (count >= 1) { b.append(';'); b.append(COUNT); b.append('='); b.append(count); } if (!getMonthList().isEmpty()) { b.append(';'); b.append(BYMONTH); b.append('='); b.append(monthList); } if (!getWeekNoList().isEmpty()) { b.append(';'); b.append(BYWEEKNO); b.append('='); b.append(weekNoList); } if (!getYearDayList().isEmpty()) { b.append(';'); b.append(BYYEARDAY); b.append('='); b.append(yearDayList); } if (!getMonthDayList().isEmpty()) { b.append(';'); b.append(BYMONTHDAY); b.append('='); b.append(monthDayList); } if (!getDayList().isEmpty()) { b.append(';'); b.append(BYDAY); b.append('='); b.append(dayList); } if (!getHourList().isEmpty()) { b.append(';'); b.append(BYHOUR); b.append('='); b.append(hourList); } if (!getMinuteList().isEmpty()) { b.append(';'); b.append(BYMINUTE); b.append('='); b.append(minuteList); } if (!getSecondList().isEmpty()) { b.append(';'); b.append(BYSECOND); b.append('='); b.append(secondList); } if (!getSetPosList().isEmpty()) { b.append(';'); b.append(BYSETPOS); b.append('='); b.append(setPosList); } return b.toString(); } /** * Returns a list of start dates in the specified period represented by this recur. * Any date fields not specified by this recur are retained from the period start, * and as such you should ensure the period start is initialised correctly. * @param periodStart the start of the period * @param periodEnd the end of the period * @param value the type of dates to generate (i.e. date/date-time) * @return a list of dates */ public final DateList getDates(final Date periodStart, final Date periodEnd, final Value value) { return getDates(periodStart, periodStart, periodEnd, value); } /** * Returns a list of start dates in the specified period represented * by this recur. This method includes a base date argument, which * indicates the start of the fist occurrence of this recurrence. * * The base date is used to inject default values to return a set of dates in * the correct format. For example, if the search start date (start) is * Wed, Mar 23, 12:19PM, but the recurrence is Mon - Fri, 9:00AM - 5:00PM, * the start dates returned should all be at 9:00AM, and not 12:19PM. * * @return a list of dates represented by this recur instance * @param base the start date of this Recurrence's first instance * @param periodStart the start of the period * @param periodEnd the end of the period * @param value the type of dates to generate (i.e. date/date-time) */ public final DateList getDates(final Date base, final Date periodStart, final Date periodEnd, final Value value) { DateList dates = new DateList(value); // Should never happen! base is always required! if (base == null) { return dates; } Date start = (Date) periodStart.clone(); // We don't want to see or search any dates that occur before the // first instance of this recurrence. if (start.before(base)) { start = base; } Calendar baseCalendar = Calendar.getInstance(); baseCalendar.setTime(base); Calendar cal = Calendar.getInstance(); cal.setTime(start); cal.set(Calendar.MILLISECOND, 0); int lvf = getLowestVariableField(); // Set everything to the right of the LVF to match the DTSTART. // Everything else comes from the query start date. int[] matchFields = getMatchFields(lvf); for (int i = 0; i < matchFields.length; i++) { cal.set(matchFields[i], baseCalendar.get(matchFields[i])); } // Deal with rolling over to the next time period if necessary. if (cal.getTime().before(periodStart)) { cal.add(lvf, 1); } // Weekly frequencies need to match up the week day. (i.e. if it's // Friday, and that's not part of our criteria, keep adding a day // until they match). /*if (getFrequency().equals(WEEKLY)) { while (cal.get(Calendar.DAY_OF_WEEK) != dtStartCalendar.get(Calendar.DAY_OF_WEEK)) { cal.add(Calendar.DAY_OF_MONTH, 1); } }*/ cal.setTime(base); // apply frequency/interval rules.. if (getUntil() != null) { while (!cal.getTime().after(getUntil()) && !(periodEnd != null && cal.getTime().after(periodEnd))) { dates.add(new Date(cal.getTime().getTime())); increment(cal); } } /* else if (getCount() >= 1) { for (int i = 0; i < getCount() && !(periodEnd != null && cal.getTime().after(periodEnd)); i++) { dates.add(cal.getTime()); increment(cal); } } */ else if (periodEnd != null) { while (!cal.getTime().after(periodEnd)) { dates.add(new Date(cal.getTime().getTime())); increment(cal); } } else { // if no end-point specified we can't calculate a finite // set of dates.. return dates; } // debugging.. if (log.isDebugEnabled()) { log.debug("Dates after FREQUENCY/INTERVAL processing: " + dates); } dates = getMonthVariants(dates); // debugging.. if (log.isDebugEnabled()) { log.debug("Dates after BYMONTH processing: " + dates); } dates = getWeekNoVariants(dates); // debugging.. if (log.isDebugEnabled()) { log.debug("Dates after BYWEEKNO processing: " + dates); } dates = getYearDayVariants(dates); // debugging.. if (log.isDebugEnabled()) { log.debug("Dates after BYYEARDAY processing: " + dates); } dates = getMonthDayVariants(dates); // debugging.. if (log.isDebugEnabled()) { log.debug("Dates after BYMONTHDAY processing: " + dates); } dates = getDayVariants(dates); // debugging.. if (log.isDebugEnabled()) { log.debug("Dates after BYDAY processing: " + dates); } dates = getHourVariants(dates); // debugging.. if (log.isDebugEnabled()) { log.debug("Dates after BYHOUR processing: " + dates); } dates = getMinuteVariants(dates); // debugging.. if (log.isDebugEnabled()) { log.debug("Dates after BYMINUTE processing: " + dates); } dates = getSecondVariants(dates); // debugging.. if (log.isDebugEnabled()) { log.debug("Dates after BYSECOND processing: " + dates); } // check count.. if (getCount() >= 1 && dates.size() >= getCount()) { for (int i = getCount(); i < dates.size();) { dates.remove(i); } } // debugging.. if (log.isDebugEnabled()) { log.debug("Dates after COUNT processing: " + dates); } // final post-processing.. for (int i = 0; i < dates.size(); i++) { Date date = (Date) dates.get(i); if (periodStart != null && date.before(periodStart)) { dates.remove(date); i } else if (periodEnd != null && date.after(periodEnd)) { dates.remove(date); i } else if (getUntil() != null && date.after(getUntil())) { dates.remove(date); i } /* else if (getCount() >= 1 && i >= getCount()) { dates.remove(date); i--; } */ } return dates; } /** * Returns the finest precision at which this recurrence will modify * a date value. * @return an int representing a <code>java.util.Calendar</code> field. */ private int getLowestVariableField() { int lowestVariableField = 9999; // check frequency precision.. if (YEARLY.equals(frequency)) { lowestVariableField = Calendar.YEAR; } else if (MONTHLY.equals(frequency)) { lowestVariableField = Calendar.MONTH; } else if (WEEKLY.equals(frequency)) { lowestVariableField = Calendar.DAY_OF_MONTH; } else if (DAILY.equals(frequency)) { lowestVariableField = Calendar.DAY_OF_MONTH; } else if (HOURLY.equals(frequency)) { lowestVariableField = Calendar.HOUR_OF_DAY; } else if (MINUTELY.equals(frequency)) { lowestVariableField = Calendar.MINUTE; } else if (SECONDLY.equals(frequency)) { lowestVariableField = Calendar.SECOND; } // check BY* rules precision.. if (!getMonthList().isEmpty() && Calendar.MONTH < lowestVariableField) { lowestVariableField = Calendar.MONTH; } if (!getWeekNoList().isEmpty() && Calendar.DAY_OF_MONTH < lowestVariableField) { lowestVariableField = Calendar.DAY_OF_MONTH; } if (!getYearDayList().isEmpty() && Calendar.DAY_OF_MONTH < lowestVariableField) { lowestVariableField = Calendar.DAY_OF_MONTH; } if (!getMonthDayList().isEmpty() && Calendar.DAY_OF_MONTH < lowestVariableField) { lowestVariableField = Calendar.DAY_OF_MONTH; } if (!getDayList().isEmpty() && Calendar.DAY_OF_MONTH < lowestVariableField) { lowestVariableField = Calendar.DAY_OF_MONTH; } if (!getHourList().isEmpty() && Calendar.HOUR_OF_DAY < lowestVariableField) { lowestVariableField = Calendar.HOUR_OF_DAY; } if (!getMinuteList().isEmpty() && Calendar.MINUTE < lowestVariableField) { lowestVariableField = Calendar.MINUTE; } if (!getSecondList().isEmpty() && Calendar.SECOND < lowestVariableField) { lowestVariableField = Calendar.SECOND; } return lowestVariableField; } /** * Return all the items to the right of LVF in a date string. * * @param lowestVariableField * @return */ private int[] getMatchFields(int lowestVariableField) { int[] matchFields = new int[0]; int lvfIndex = getDateOrderIndex(lowestVariableField); for (int i = 0; i < DATE_ORDER.length; i++) { int nextItem = DATE_ORDER[i]; if (i > lvfIndex) { int[] tmpArray = matchFields; matchFields = new int[tmpArray.length + 1]; System.arraycopy(tmpArray, 0, matchFields, 0, tmpArray.length); matchFields[matchFields.length - 1] = nextItem; } } return matchFields; } /** * Return the index of this item in the DATE_ORDER array. * * @param val * @return */ private int getDateOrderIndex(int val) { for (int i = 0; i < DATE_ORDER.length; i++) { int nextVal = DATE_ORDER[i]; if (nextVal == val) { return i; } } return -1; } /** * Increments the specified calendar according to the * frequency and interval specified in this recurrence * rule. * @param cal a java.util.Calendar to increment */ private void increment(final Calendar cal) { // initialise interval.. int calInterval = (getInterval() >= 1) ? getInterval() : 1; if (SECONDLY.equals(getFrequency())) { cal.add(Calendar.SECOND, calInterval); } else if (MINUTELY.equals(getFrequency())) { cal.add(Calendar.MINUTE, calInterval); } else if (HOURLY.equals(getFrequency())) { cal.add(Calendar.HOUR_OF_DAY, calInterval); } else if (DAILY.equals(getFrequency())) { cal.add(Calendar.DAY_OF_YEAR, calInterval); } else if (WEEKLY.equals(getFrequency())) { cal.add(Calendar.WEEK_OF_YEAR, calInterval); } else if (MONTHLY.equals(getFrequency())) { cal.add(Calendar.MONTH, calInterval); } else if (YEARLY.equals(getFrequency())) { cal.add(Calendar.YEAR, calInterval); } } /** * Applies BYMONTH rules specified in this Recur instance to the * specified date list. If no BYMONTH rules are specified the * date list is returned unmodified. * @param dates * @return */ private DateList getMonthVariants(final DateList dates) { if (getMonthList().isEmpty()) { return dates; } Calendar cal = Calendar.getInstance(); DateList monthlyDates = new DateList(dates.getType()); for (Iterator i = dates.iterator(); i.hasNext();) { Date date = (Date) i.next(); cal.setTime(date); for (Iterator j = getMonthList().iterator(); j.hasNext();) { Integer month = (Integer) j.next(); // Java months are zero-based.. cal.set(Calendar.MONTH, month.intValue() - 1); monthlyDates.add(new Date(cal.getTime().getTime())); } } // apply BYSETPOS rules.. if (!getSetPosList().isEmpty() && getWeekNoList().isEmpty() && getYearDayList().isEmpty() && getMonthDayList().isEmpty() && getDayList().isEmpty() && getHourList().isEmpty() && getMinuteList().isEmpty() && getSecondList().isEmpty()) { DateList setPosDates = new DateList(dates.getType()); for (Iterator i = getSetPosList().iterator(); i.hasNext();) { Integer setPos = (Integer) i.next(); if (setPos.intValue() > 0) { setPosDates.add(monthlyDates.get(setPos.intValue())); } else { setPosDates.add(monthlyDates.get(monthlyDates.size() + setPos.intValue())); } } return setPosDates; } return monthlyDates; } /** * Applies BYWEEKNO rules specified in this Recur instance to the * specified date list. If no BYWEEKNO rules are specified the * date list is returned unmodified. * @param dates * @return */ private DateList getWeekNoVariants(final DateList dates) { if (getWeekNoList().isEmpty()) { return dates; } Calendar cal = Calendar.getInstance(); DateList weekNoDates = new DateList(dates.getType()); for (Iterator i = dates.iterator(); i.hasNext();) { Date date = (Date) i.next(); cal.setTime(date); for (Iterator j = getWeekNoList().iterator(); j.hasNext();) { Integer weekNo = (Integer) j.next(); cal.set(Calendar.WEEK_OF_YEAR, getAbsWeekNo(cal.getTime(), weekNo.intValue())); weekNoDates.add(cal.getTime()); } } // apply BYSETPOS rules.. if (!getSetPosList().isEmpty() && getYearDayList().isEmpty() && getMonthDayList().isEmpty() && getDayList().isEmpty() && getHourList().isEmpty() && getMinuteList().isEmpty() && getSecondList().isEmpty()) { DateList setPosDates = new DateList(dates.getType()); for (Iterator i = getSetPosList().iterator(); i.hasNext();) { Integer setPos = (Integer) i.next(); if (setPos.intValue() > 0) { setPosDates.add(weekNoDates.get(setPos.intValue())); } else { setPosDates.add(weekNoDates.get(weekNoDates.size() + setPos.intValue())); } } return setPosDates; } return weekNoDates; } private int getAbsWeekNo(final java.util.Date date, final int weekNo) { if (weekNo == 0 || weekNo < -53 || weekNo > 53) { throw new IllegalArgumentException("Invalid week number [" + weekNo + "]"); } if (weekNo > 0) { return weekNo; } Calendar cal = Calendar.getInstance(); cal.setTime(date); int year = cal.get(Calendar.YEAR); // construct a list of possible week numbers.. List weeks = new ArrayList(); cal.set(Calendar.WEEK_OF_YEAR, 1); while (cal.get(Calendar.YEAR) == year) { weeks.add(new Integer(cal.get(Calendar.WEEK_OF_YEAR))); cal.add(Calendar.WEEK_OF_YEAR, 1); } return ((Integer) weeks.get(weeks.size() + weekNo)).intValue(); } /** * Applies BYYEARDAY rules specified in this Recur instance to the * specified date list. If no BYYEARDAY rules are specified the * date list is returned unmodified. * @param dates * @return */ private DateList getYearDayVariants(final DateList dates) { if (getYearDayList().isEmpty()) { return dates; } Calendar cal = Calendar.getInstance(); DateList yearDayDates = new DateList(dates.getType()); for (Iterator i = dates.iterator(); i.hasNext();) { Date date = (Date) i.next(); cal.setTime(date); for (Iterator j = getYearDayList().iterator(); j.hasNext();) { Integer yearDay = (Integer) j.next(); cal.set(Calendar.DAY_OF_YEAR, getAbsYearDay(cal.getTime(), yearDay.intValue())); yearDayDates.add(cal.getTime()); } } // apply BYSETPOS rules.. if (!getSetPosList().isEmpty() && getMonthDayList().isEmpty() && getDayList().isEmpty() && getHourList().isEmpty() && getMinuteList().isEmpty() && getSecondList().isEmpty()) { DateList setPosDates = new DateList(dates.getType()); for (Iterator i = getSetPosList().iterator(); i.hasNext();) { Integer setPos = (Integer) i.next(); if (setPos.intValue() > 0) { setPosDates.add(yearDayDates.get(setPos.intValue())); } else { setPosDates.add(yearDayDates.get(yearDayDates.size() + setPos.intValue())); } } return setPosDates; } return yearDayDates; } private int getAbsYearDay(final java.util.Date date, final int yearDay) { if (yearDay == 0 || yearDay < -366 || yearDay > 366) { throw new IllegalArgumentException("Invalid year day [" + yearDay + "]"); } if (yearDay > 0) { return yearDay; } Calendar cal = Calendar.getInstance(); cal.setTime(date); int year = cal.get(Calendar.YEAR); // construct a list of possible year days.. List days = new ArrayList(); cal.set(Calendar.DAY_OF_YEAR, 1); while (cal.get(Calendar.YEAR) == year) { days.add(new Integer(cal.get(Calendar.DAY_OF_YEAR))); cal.add(Calendar.DAY_OF_YEAR, 1); } return ((Integer) days.get(days.size() + yearDay)).intValue(); } /** * Applies BYMONTHDAY rules specified in this Recur instance to the * specified date list. If no BYMONTHDAY rules are specified the * date list is returned unmodified. * @param dates * @return */ private DateList getMonthDayVariants(final DateList dates) { if (getMonthDayList().isEmpty()) { return dates; } Calendar cal = Calendar.getInstance(); DateList monthDayDates = new DateList(dates.getType()); for (Iterator i = dates.iterator(); i.hasNext();) { Date date = (Date) i.next(); cal.setTime(date); for (Iterator j = getMonthDayList().iterator(); j.hasNext();) { Integer monthDay = (Integer) j.next(); cal.set(Calendar.DAY_OF_YEAR, getAbsMonthDay(cal.getTime(), monthDay.intValue())); monthDayDates.add(new Date(cal.getTime().getTime())); } } // apply BYSETPOS rules.. if (!getSetPosList().isEmpty() && getDayList().isEmpty() && getHourList().isEmpty() && getMinuteList().isEmpty() && getSecondList().isEmpty()) { DateList setPosDates = new DateList(dates.getType()); for (Iterator i = getSetPosList().iterator(); i.hasNext();) { Integer setPos = (Integer) i.next(); if (setPos.intValue() > 0) { setPosDates.add(monthDayDates.get(setPos.intValue())); } else { setPosDates.add(monthDayDates.get(monthDayDates.size() + setPos.intValue())); } } return setPosDates; } return monthDayDates; } private int getAbsMonthDay(final java.util.Date date, final int monthDay) { if (monthDay == 0 || monthDay < -31 || monthDay > 31) { throw new IllegalArgumentException("Invalid month day [" + monthDay + "]"); } if (monthDay > 0) { return monthDay; } Calendar cal = Calendar.getInstance(); cal.setTime(date); int month = cal.get(Calendar.MONTH); // construct a list of possible month days.. List days = new ArrayList(); cal.set(Calendar.DAY_OF_MONTH, 1); while (cal.get(Calendar.MONTH) == month) { days.add(new Integer(cal.get(Calendar.DAY_OF_MONTH))); cal.add(Calendar.DAY_OF_MONTH, 1); } return ((Integer) days.get(days.size() + monthDay)).intValue(); } /** * Applies BYDAY rules specified in this Recur instance to the * specified date list. If no BYDAY rules are specified the * date list is returned unmodified. * @param dates * @return */ private DateList getDayVariants(final DateList dates) { if (getDayList().isEmpty()) { return dates; } DateList weekDayDates = new DateList(dates.getType()); for (Iterator i = dates.iterator(); i.hasNext();) { Date date = (Date) i.next(); for (Iterator j = getDayList().iterator(); j.hasNext();) { WeekDay weekDay = (WeekDay) j.next(); weekDayDates.addAll(getAbsWeekDays(date, weekDay)); } } // apply BYSETPOS rules.. if (!getSetPosList().isEmpty() && getHourList().isEmpty() && getMinuteList().isEmpty() && getSecondList().isEmpty()) { DateList setPosDates = new DateList(dates.getType()); for (Iterator i = getSetPosList().iterator(); i.hasNext();) { Integer setPos = (Integer) i.next(); if (setPos.intValue() > 0) { setPosDates.add(weekDayDates.get(setPos.intValue())); } else { setPosDates.add(weekDayDates.get(weekDayDates.size() + setPos.intValue())); } } return setPosDates; } return weekDayDates; } /** * Returns a list of applicable dates corresponding to the specified * week day in accordance with the frequency specified by this recurrence * rule. * @param date * @param weekDay * @return */ private List getAbsWeekDays(final Date date, final WeekDay weekDay) { Calendar cal = Calendar.getInstance(); cal.setTime(date); int calDay = -1; DateList days = new DateList(Value.DATE); if (WeekDay.SU.getDay().equals(weekDay.getDay())) { calDay = Calendar.SUNDAY; } else if (WeekDay.MO.getDay().equals(weekDay.getDay())) { calDay = Calendar.MONDAY; } else if (WeekDay.TU.getDay().equals(weekDay.getDay())) { calDay = Calendar.TUESDAY; } else if (WeekDay.WE.getDay().equals(weekDay.getDay())) { calDay = Calendar.WEDNESDAY; } else if (WeekDay.TH.getDay().equals(weekDay.getDay())) { calDay = Calendar.THURSDAY; } else if (WeekDay.FR.getDay().equals(weekDay.getDay())) { calDay = Calendar.FRIDAY; } else if (WeekDay.SA.getDay().equals(weekDay.getDay())) { calDay = Calendar.SATURDAY; } else { // a matching weekday cannot be identified.. return days; } if (DAILY.equals(getFrequency())) { if (cal.get(Calendar.DAY_OF_WEEK) == calDay) { // only one date is applicable.. days.add(new Date(cal.getTime().getTime())); } } else if (WEEKLY.equals(getFrequency()) || !getWeekNoList().isEmpty()) { //int weekNo = cal.get(Calendar.WEEK_OF_YEAR); // construct a list of possible week days.. // cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1); while (cal.get(Calendar.DAY_OF_WEEK) != calDay) { cal.add(Calendar.DAY_OF_WEEK, 1); } int weekNo = cal.get(Calendar.WEEK_OF_YEAR); while (cal.get(Calendar.WEEK_OF_YEAR) == weekNo) { days.add(new Date(cal.getTime().getTime())); cal.add(Calendar.DAY_OF_WEEK, 7); } } else if (MONTHLY.equals(getFrequency()) || !getMonthList().isEmpty()) { int month = cal.get(Calendar.MONTH); // construct a list of possible month days.. cal.set(Calendar.DAY_OF_MONTH, 1); while (cal.get(Calendar.DAY_OF_WEEK) != calDay) { cal.add(Calendar.DAY_OF_MONTH, 1); } while (cal.get(Calendar.MONTH) == month) { days.add(new Date(cal.getTime().getTime())); cal.add(Calendar.DAY_OF_MONTH, 7); } } else if (YEARLY.equals(getFrequency())) { int year = cal.get(Calendar.YEAR); // construct a list of possible year days.. cal.set(Calendar.DAY_OF_YEAR, 1); while (cal.get(Calendar.DAY_OF_WEEK) != calDay) { cal.add(Calendar.DAY_OF_YEAR, 1); } while (cal.get(Calendar.YEAR) == year) { days.add(new Date(cal.getTime().getTime())); cal.add(Calendar.DAY_OF_YEAR, 7); } } DateList weekDays = new DateList(days.getType()); if (weekDay.getOffset() < 0) { weekDays.add(days.get(days.size() + weekDay.getOffset())); } // FIXME: Should this be [days.get(weekDay.getOffset() - 1)]?? else if (weekDay.getOffset() > 0 && days.size() > (weekDay.getOffset() + 2)) { weekDays.add(days.get(weekDay.getOffset() + 1)); } else { weekDays.addAll(days); } return weekDays; } /** * Applies BYHOUR rules specified in this Recur instance to the * specified date list. If no BYHOUR rules are specified the * date list is returned unmodified. * @param dates * @return */ private DateList getHourVariants(final DateList dates) { if (getHourList().isEmpty()) { return dates; } Calendar cal = Calendar.getInstance(); DateList hourlyDates = new DateList(dates.getType()); for (Iterator i = dates.iterator(); i.hasNext();) { Date date = (Date) i.next(); cal.setTime(date); for (Iterator j = getHourList().iterator(); j.hasNext();) { Integer hour = (Integer) j.next(); cal.set(Calendar.HOUR_OF_DAY, hour.intValue()); hourlyDates.add(new Date(cal.getTime().getTime())); } } // apply BYSETPOS rules.. if (!getSetPosList().isEmpty() && getMinuteList().isEmpty() && getSecondList().isEmpty()) { DateList setPosDates = new DateList(dates.getType()); for (Iterator i = getSetPosList().iterator(); i.hasNext();) { Integer setPos = (Integer) i.next(); if (setPos.intValue() > 0) { setPosDates.add(hourlyDates.get(setPos.intValue())); } else { setPosDates.add(hourlyDates.get(hourlyDates.size() + setPos.intValue())); } } return setPosDates; } return hourlyDates; } /** * Applies BYMINUTE rules specified in this Recur instance to the * specified date list. If no BYMINUTE rules are specified the * date list is returned unmodified. * @param dates * @return */ private DateList getMinuteVariants(final DateList dates) { if (getMinuteList().isEmpty()) { return dates; } Calendar cal = Calendar.getInstance(); DateList minutelyDates = new DateList(dates.getType()); for (Iterator i = dates.iterator(); i.hasNext();) { Date date = (Date) i.next(); cal.setTime(date); for (Iterator j = getMinuteList().iterator(); j.hasNext();) { Integer minute = (Integer) j.next(); cal.set(Calendar.MINUTE, minute.intValue()); minutelyDates.add(new Date(cal.getTime().getTime())); } } // apply BYSETPOS rules.. if (!getSetPosList().isEmpty() && getSecondList().isEmpty()) { DateList setPosDates = new DateList(dates.getType()); for (Iterator i = getSetPosList().iterator(); i.hasNext();) { Integer setPos = (Integer) i.next(); if (setPos.intValue() > 0) { setPosDates.add(minutelyDates.get(setPos.intValue())); } else { setPosDates.add(minutelyDates.get(minutelyDates.size() + setPos.intValue())); } } return setPosDates; } return minutelyDates; } /** * Applies BYSECOND rules specified in this Recur instance to the * specified date list. If no BYSECOND rules are specified the * date list is returned unmodified. * @param dates * @return */ private DateList getSecondVariants(final DateList dates) { if (getSecondList().isEmpty()) { return dates; } Calendar cal = Calendar.getInstance(); DateList secondlyDates = new DateList(dates.getType()); for (Iterator i = dates.iterator(); i.hasNext();) { Date date = (Date) i.next(); cal.setTime(date); for (Iterator j = getSecondList().iterator(); j.hasNext();) { Integer second = (Integer) j.next(); cal.set(Calendar.SECOND, second.intValue()); secondlyDates.add(new Date(cal.getTime().getTime())); } } // apply BYSETPOS rules.. if (!getSetPosList().isEmpty()) { DateList setPosDates = new DateList(dates.getType()); for (Iterator i = getSetPosList().iterator(); i.hasNext();) { Integer setPos = (Integer) i.next(); if (setPos.intValue() > 0) { setPosDates.add(secondlyDates.get(setPos.intValue())); } else { setPosDates.add(secondlyDates.get(secondlyDates.size() + setPos.intValue())); } } return setPosDates; } return secondlyDates; } /** * @param count The count to set. */ public final void setCount(final int count) { this.count = count; this.until = null; } /** * @param frequency The frequency to set. */ public final void setFrequency(final String frequency) { this.frequency = frequency; } /** * @param interval The interval to set. */ public final void setInterval(final int interval) { this.interval = interval; } /** * @param until The until to set. */ public final void setUntil(final Date until) { this.until = until; this.count = -1; } }
package org.jfree.chart.plot; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Composite; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Point; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import java.util.TreeMap; import org.jfree.chart.LegendItem; import org.jfree.chart.LegendItemCollection; import org.jfree.chart.axis.Axis; import org.jfree.chart.axis.AxisState; import org.jfree.chart.axis.NumberTick; import org.jfree.chart.axis.NumberTickUnit; import org.jfree.chart.axis.TickType; import org.jfree.chart.axis.TickUnit; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.axis.ValueTick; import org.jfree.chart.event.PlotChangeEvent; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.event.RendererChangeListener; import org.jfree.chart.renderer.PolarItemRenderer; import org.jfree.chart.util.ParamChecks; import org.jfree.chart.util.ResourceBundleWrapper; import org.jfree.data.Range; import org.jfree.data.general.Dataset; import org.jfree.data.general.DatasetChangeEvent; import org.jfree.data.general.DatasetUtilities; import org.jfree.data.xy.XYDataset; import org.jfree.io.SerialUtilities; import org.jfree.text.TextUtilities; import org.jfree.ui.RectangleEdge; import org.jfree.ui.RectangleInsets; import org.jfree.ui.TextAnchor; import org.jfree.util.ObjectList; import org.jfree.util.ObjectUtilities; import org.jfree.util.PaintUtilities; import org.jfree.util.PublicCloneable; /** * Plots data that is in (theta, radius) pairs where * theta equal to zero is due north and increases clockwise. */ public class PolarPlot extends Plot implements ValueAxisPlot, Zoomable, RendererChangeListener, Cloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 3794383185924179525L; /** The default margin. */ private static final int DEFAULT_MARGIN = 20; /** The annotation margin. */ private static final double ANNOTATION_MARGIN = 7.0; /** * The default angle tick unit size. * * @since 1.0.10 */ public static final double DEFAULT_ANGLE_TICK_UNIT_SIZE = 45.0; /** * The default angle offset. * * @since 1.0.14 */ public static final double DEFAULT_ANGLE_OFFSET = -90.0; /** The default grid line stroke. */ public static final Stroke DEFAULT_GRIDLINE_STROKE = new BasicStroke( 0.5f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0.0f, new float[]{2.0f, 2.0f}, 0.0f); /** The default grid line paint. */ public static final Paint DEFAULT_GRIDLINE_PAINT = Color.gray; /** The resourceBundle for the localization. */ protected static ResourceBundle localizationResources = ResourceBundleWrapper.getBundle( "org.jfree.chart.plot.LocalizationBundle"); /** The angles that are marked with gridlines. */ private List angleTicks; /** The range axis (used for the y-values). */ private ObjectList axes; /** The axis locations. */ private ObjectList axisLocations; /** Storage for the datasets. */ private ObjectList datasets; /** Storage for the renderers. */ private ObjectList renderers; /** * The tick unit that controls the spacing between the angular grid lines. * * @since 1.0.10 */ private TickUnit angleTickUnit; /** * An offset for the angles, to start with 0 degrees at north, east, south * or west. * * @since 1.0.14 */ private double angleOffset; /** * A flag indicating if the angles increase counterclockwise or clockwise. * * @since 1.0.14 */ private boolean counterClockwise; /** A flag that controls whether or not the angle labels are visible. */ private boolean angleLabelsVisible = true; /** The font used to display the angle labels - never null. */ private Font angleLabelFont = new Font("SansSerif", Font.PLAIN, 12); /** The paint used to display the angle labels. */ private transient Paint angleLabelPaint = Color.black; /** A flag that controls whether the angular grid-lines are visible. */ private boolean angleGridlinesVisible; /** The stroke used to draw the angular grid-lines. */ private transient Stroke angleGridlineStroke; /** The paint used to draw the angular grid-lines. */ private transient Paint angleGridlinePaint; /** A flag that controls whether the radius grid-lines are visible. */ private boolean radiusGridlinesVisible; /** The stroke used to draw the radius grid-lines. */ private transient Stroke radiusGridlineStroke; /** The paint used to draw the radius grid-lines. */ private transient Paint radiusGridlinePaint; /** * A flag that controls whether the radial minor grid-lines are visible. * @since 1.0.15 */ private boolean radiusMinorGridlinesVisible; /** The annotations for the plot. */ private List cornerTextItems = new ArrayList(); /** * The actual margin in pixels. * * @since 1.0.14 */ private int margin; /** * An optional collection of legend items that can be returned by the * getLegendItems() method. */ private LegendItemCollection fixedLegendItems; /** * Storage for the mapping between datasets/renderers and range axes. The * keys in the map are Integer objects, corresponding to the dataset * index. The values in the map are List objects containing Integer * objects (corresponding to the axis indices). If the map contains no * entry for a dataset, it is assumed to map to the primary domain axis * (index = 0). */ private Map datasetToAxesMap; /** * Default constructor. */ public PolarPlot() { this(null, null, null); } /** * Creates a new plot. * * @param dataset the dataset (<code>null</code> permitted). * @param radiusAxis the radius axis (<code>null</code> permitted). * @param renderer the renderer (<code>null</code> permitted). */ public PolarPlot(XYDataset dataset, ValueAxis radiusAxis, PolarItemRenderer renderer) { super(); this.datasets = new ObjectList(); this.datasets.set(0, dataset); if (dataset != null) { dataset.addChangeListener(this); } this.angleTickUnit = new NumberTickUnit(DEFAULT_ANGLE_TICK_UNIT_SIZE); this.axes = new ObjectList(); this.datasetToAxesMap = new TreeMap(); this.axes.set(0, radiusAxis); if (radiusAxis != null) { radiusAxis.setPlot(this); radiusAxis.addChangeListener(this); } // define the default locations for up to 8 axes... this.axisLocations = new ObjectList(); this.axisLocations.set(0, PolarAxisLocation.EAST_ABOVE); this.axisLocations.set(1, PolarAxisLocation.NORTH_LEFT); this.axisLocations.set(2, PolarAxisLocation.WEST_BELOW); this.axisLocations.set(3, PolarAxisLocation.SOUTH_RIGHT); this.axisLocations.set(4, PolarAxisLocation.EAST_BELOW); this.axisLocations.set(5, PolarAxisLocation.NORTH_RIGHT); this.axisLocations.set(6, PolarAxisLocation.WEST_ABOVE); this.axisLocations.set(7, PolarAxisLocation.SOUTH_LEFT); this.renderers = new ObjectList(); this.renderers.set(0, renderer); if (renderer != null) { renderer.setPlot(this); renderer.addChangeListener(this); } this.angleOffset = DEFAULT_ANGLE_OFFSET; this.counterClockwise = false; this.angleGridlinesVisible = true; this.angleGridlineStroke = DEFAULT_GRIDLINE_STROKE; this.angleGridlinePaint = DEFAULT_GRIDLINE_PAINT; this.radiusGridlinesVisible = true; this.radiusMinorGridlinesVisible = true; this.radiusGridlineStroke = DEFAULT_GRIDLINE_STROKE; this.radiusGridlinePaint = DEFAULT_GRIDLINE_PAINT; this.margin = DEFAULT_MARGIN; } /** * Returns the plot type as a string. * * @return A short string describing the type of plot. */ public String getPlotType() { return PolarPlot.localizationResources.getString("Polar_Plot"); } /** * Returns the primary axis for the plot. * * @return The primary axis (possibly <code>null</code>). * * @see #setAxis(ValueAxis) */ public ValueAxis getAxis() { return getAxis(0); } /** * Returns an axis for the plot. * * @param index the axis index. * * @return The axis (<code>null</code> possible). * * @see #setAxis(int, ValueAxis) * * @since 1.0.14 */ public ValueAxis getAxis(int index) { ValueAxis result = null; if (index < this.axes.size()) { result = (ValueAxis) this.axes.get(index); } return result; } /** * Sets the primary axis for the plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param axis the new primary axis (<code>null</code> permitted). */ public void setAxis(ValueAxis axis) { setAxis(0, axis); } /** * Sets an axis for the plot and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param index the axis index. * @param axis the axis (<code>null</code> permitted). * * @see #getAxis(int) * * @since 1.0.14 */ public void setAxis(int index, ValueAxis axis) { setAxis(index, axis, true); } /** * Sets an axis for the plot and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param index the axis index. * @param axis the axis (<code>null</code> permitted). * @param notify notify listeners? * * @see #getAxis(int) * * @since 1.0.14 */ public void setAxis(int index, ValueAxis axis, boolean notify) { ValueAxis existing = getAxis(index); if (existing != null) { existing.removeChangeListener(this); } if (axis != null) { axis.setPlot(this); } this.axes.set(index, axis); if (axis != null) { axis.configure(); axis.addChangeListener(this); } if (notify) { fireChangeEvent(); } } /** * Returns the location of the primary axis. * * @return The location (never <code>null</code>). * * @see #setAxisLocation(PolarAxisLocation) * * @since 1.0.14 */ public PolarAxisLocation getAxisLocation() { return getAxisLocation(0); } /** * Returns the location for an axis. * * @param index the axis index. * * @return The location (never <code>null</code>). * * @see #setAxisLocation(int, PolarAxisLocation) * * @since 1.0.14 */ public PolarAxisLocation getAxisLocation(int index) { PolarAxisLocation result = null; if (index < this.axisLocations.size()) { result = (PolarAxisLocation) this.axisLocations.get(index); } return result; } /** * Sets the location of the primary axis and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param location the location (<code>null</code> not permitted). * * @see #getAxisLocation() * * @since 1.0.14 */ public void setAxisLocation(PolarAxisLocation location) { // delegate... setAxisLocation(0, location, true); } /** * Sets the location of the primary axis and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param location the location (<code>null</code> not permitted). * @param notify notify listeners? * * @see #getAxisLocation() * * @since 1.0.14 */ public void setAxisLocation(PolarAxisLocation location, boolean notify) { // delegate... setAxisLocation(0, location, notify); } /** * Sets the location for an axis and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param index the axis index. * @param location the location (<code>null</code> not permitted). * * @see #getAxisLocation(int) * * @since 1.0.14 */ public void setAxisLocation(int index, PolarAxisLocation location) { // delegate... setAxisLocation(index, location, true); } /** * Sets the axis location for an axis and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param index the axis index. * @param location the location (<code>null</code> not permitted). * @param notify notify listeners? * * @since 1.0.14 */ public void setAxisLocation(int index, PolarAxisLocation location, boolean notify) { ParamChecks.nullNotPermitted(location, "location"); this.axisLocations.set(index, location); if (notify) { fireChangeEvent(); } } /** * Returns the number of domain axes. * * @return The axis count. * * @since 1.0.14 **/ public int getAxisCount() { return this.axes.size(); } /** * Returns the primary dataset for the plot. * * @return The primary dataset (possibly <code>null</code>). * * @see #setDataset(XYDataset) */ public XYDataset getDataset() { return getDataset(0); } /** * Returns the dataset with the specified index, if any. * * @param index the dataset index. * * @return The dataset (possibly <code>null</code>). * * @see #setDataset(int, XYDataset) * * @since 1.0.14 */ public XYDataset getDataset(int index) { XYDataset result = null; if (index < this.datasets.size()) { result = (XYDataset) this.datasets.get(index); } return result; } /** * Sets the primary dataset for the plot, replacing the existing dataset * if there is one, and sends a {@code link PlotChangeEvent} to all * registered listeners. * * @param dataset the dataset (<code>null</code> permitted). * * @see #getDataset() */ public void setDataset(XYDataset dataset) { setDataset(0, dataset); } /** * Sets a dataset for the plot, replacing the existing dataset at the same * index if there is one, and sends a {@code link PlotChangeEvent} to all * registered listeners. * * @param index the dataset index. * @param dataset the dataset (<code>null</code> permitted). * * @see #getDataset(int) * * @since 1.0.14 */ public void setDataset(int index, XYDataset dataset) { XYDataset existing = getDataset(index); if (existing != null) { existing.removeChangeListener(this); } this.datasets.set(index, dataset); if (dataset != null) { dataset.addChangeListener(this); } // send a dataset change event to self... DatasetChangeEvent event = new DatasetChangeEvent(this, dataset); datasetChanged(event); } /** * Returns the number of datasets. * * @return The number of datasets. * * @since 1.0.14 */ public int getDatasetCount() { return this.datasets.size(); } /** * Returns the index of the specified dataset, or <code>-1</code> if the * dataset does not belong to the plot. * * @param dataset the dataset (<code>null</code> not permitted). * * @return The index. * * @since 1.0.14 */ public int indexOf(XYDataset dataset) { int result = -1; for (int i = 0; i < this.datasets.size(); i++) { if (dataset == this.datasets.get(i)) { result = i; break; } } return result; } /** * Returns the primary renderer. * * @return The renderer (possibly <code>null</code>). * * @see #setRenderer(PolarItemRenderer) */ public PolarItemRenderer getRenderer() { return getRenderer(0); } /** * Returns the renderer at the specified index, if there is one. * * @param index the renderer index. * * @return The renderer (possibly <code>null</code>). * * @see #setRenderer(int, PolarItemRenderer) * * @since 1.0.14 */ public PolarItemRenderer getRenderer(int index) { PolarItemRenderer result = null; if (index < this.renderers.size()) { result = (PolarItemRenderer) this.renderers.get(index); } return result; } /** * Sets the primary renderer, and notifies all listeners of a change to the * plot. If the renderer is set to <code>null</code>, no data items will * be drawn for the corresponding dataset. * * @param renderer the new renderer (<code>null</code> permitted). * * @see #getRenderer() */ public void setRenderer(PolarItemRenderer renderer) { setRenderer(0, renderer); } /** * Sets a renderer and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param index the index. * @param renderer the renderer. * * @see #getRenderer(int) * * @since 1.0.14 */ public void setRenderer(int index, PolarItemRenderer renderer) { setRenderer(index, renderer, true); } /** * Sets a renderer and, if requested, sends a {@link PlotChangeEvent} to * all registered listeners. * * @param index the index. * @param renderer the renderer. * @param notify notify listeners? * * @see #getRenderer(int) * * @since 1.0.14 */ public void setRenderer(int index, PolarItemRenderer renderer, boolean notify) { PolarItemRenderer existing = getRenderer(index); if (existing != null) { existing.removeChangeListener(this); } this.renderers.set(index, renderer); if (renderer != null) { renderer.setPlot(this); renderer.addChangeListener(this); } if (notify) { fireChangeEvent(); } } /** * Returns the tick unit that controls the spacing of the angular grid * lines. * * @return The tick unit (never <code>null</code>). * * @since 1.0.10 */ public TickUnit getAngleTickUnit() { return this.angleTickUnit; } /** * Sets the tick unit that controls the spacing of the angular grid * lines, and sends a {@link PlotChangeEvent} to all registered listeners. * * @param unit the tick unit (<code>null</code> not permitted). * * @since 1.0.10 */ public void setAngleTickUnit(TickUnit unit) { ParamChecks.nullNotPermitted(unit, "unit"); this.angleTickUnit = unit; fireChangeEvent(); } /** * Returns the offset that is used for all angles. * * @return The offset for the angles. * @since 1.0.14 */ public double getAngleOffset() { return this.angleOffset; } /** * Sets the offset that is used for all angles and sends a * {@link PlotChangeEvent} to all registered listeners. * * This is useful to let 0 degrees be at the north, east, south or west * side of the chart. * * @param offset The offset * @since 1.0.14 */ public void setAngleOffset(double offset) { this.angleOffset = offset; fireChangeEvent(); } /** * Get the direction for growing angle degrees. * * @return <code>true</code> if angle increases counterclockwise, * <code>false</code> otherwise. * @since 1.0.14 */ public boolean isCounterClockwise() { return this.counterClockwise; } /** * Sets the flag for increasing angle degrees direction. * * <code>true</code> for counterclockwise, <code>false</code> for * clockwise. * * @param counterClockwise The flag. * @since 1.0.14 */ public void setCounterClockwise(boolean counterClockwise) { this.counterClockwise = counterClockwise; } /** * Returns a flag that controls whether or not the angle labels are visible. * * @return A boolean. * * @see #setAngleLabelsVisible(boolean) */ public boolean isAngleLabelsVisible() { return this.angleLabelsVisible; } /** * Sets the flag that controls whether or not the angle labels are visible, * and sends a {@link PlotChangeEvent} to all registered listeners. * * @param visible the flag. * * @see #isAngleLabelsVisible() */ public void setAngleLabelsVisible(boolean visible) { if (this.angleLabelsVisible != visible) { this.angleLabelsVisible = visible; fireChangeEvent(); } } /** * Returns the font used to display the angle labels. * * @return A font (never <code>null</code>). * * @see #setAngleLabelFont(Font) */ public Font getAngleLabelFont() { return this.angleLabelFont; } /** * Sets the font used to display the angle labels and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param font the font (<code>null</code> not permitted). * * @see #getAngleLabelFont() */ public void setAngleLabelFont(Font font) { ParamChecks.nullNotPermitted(font, "font"); this.angleLabelFont = font; fireChangeEvent(); } /** * Returns the paint used to display the angle labels. * * @return A paint (never <code>null</code>). * * @see #setAngleLabelPaint(Paint) */ public Paint getAngleLabelPaint() { return this.angleLabelPaint; } /** * Sets the paint used to display the angle labels and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). */ public void setAngleLabelPaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.angleLabelPaint = paint; fireChangeEvent(); } /** * Returns <code>true</code> if the angular gridlines are visible, and * <code>false</code> otherwise. * * @return <code>true</code> or <code>false</code>. * * @see #setAngleGridlinesVisible(boolean) */ public boolean isAngleGridlinesVisible() { return this.angleGridlinesVisible; } /** * Sets the flag that controls whether or not the angular grid-lines are * visible. * <p> * If the flag value is changed, a {@link PlotChangeEvent} is sent to all * registered listeners. * * @param visible the new value of the flag. * * @see #isAngleGridlinesVisible() */ public void setAngleGridlinesVisible(boolean visible) { if (this.angleGridlinesVisible != visible) { this.angleGridlinesVisible = visible; fireChangeEvent(); } } /** * Returns the stroke for the grid-lines (if any) plotted against the * angular axis. * * @return The stroke (possibly <code>null</code>). * * @see #setAngleGridlineStroke(Stroke) */ public Stroke getAngleGridlineStroke() { return this.angleGridlineStroke; } /** * Sets the stroke for the grid lines plotted against the angular axis and * sends a {@link PlotChangeEvent} to all registered listeners. * <p> * If you set this to <code>null</code>, no grid lines will be drawn. * * @param stroke the stroke (<code>null</code> permitted). * * @see #getAngleGridlineStroke() */ public void setAngleGridlineStroke(Stroke stroke) { this.angleGridlineStroke = stroke; fireChangeEvent(); } /** * Returns the paint for the grid lines (if any) plotted against the * angular axis. * * @return The paint (possibly <code>null</code>). * * @see #setAngleGridlinePaint(Paint) */ public Paint getAngleGridlinePaint() { return this.angleGridlinePaint; } /** * Sets the paint for the grid lines plotted against the angular axis. * <p> * If you set this to <code>null</code>, no grid lines will be drawn. * * @param paint the paint (<code>null</code> permitted). * * @see #getAngleGridlinePaint() */ public void setAngleGridlinePaint(Paint paint) { this.angleGridlinePaint = paint; fireChangeEvent(); } /** * Returns <code>true</code> if the radius axis grid is visible, and * <code>false</code> otherwise. * * @return <code>true</code> or <code>false</code>. * * @see #setRadiusGridlinesVisible(boolean) */ public boolean isRadiusGridlinesVisible() { return this.radiusGridlinesVisible; } /** * Sets the flag that controls whether or not the radius axis grid lines * are visible. * <p> * If the flag value is changed, a {@link PlotChangeEvent} is sent to all * registered listeners. * * @param visible the new value of the flag. * * @see #isRadiusGridlinesVisible() */ public void setRadiusGridlinesVisible(boolean visible) { if (this.radiusGridlinesVisible != visible) { this.radiusGridlinesVisible = visible; fireChangeEvent(); } } /** * Returns the stroke for the grid lines (if any) plotted against the * radius axis. * * @return The stroke (possibly <code>null</code>). * * @see #setRadiusGridlineStroke(Stroke) */ public Stroke getRadiusGridlineStroke() { return this.radiusGridlineStroke; } /** * Sets the stroke for the grid lines plotted against the radius axis and * sends a {@link PlotChangeEvent} to all registered listeners. * <p> * If you set this to <code>null</code>, no grid lines will be drawn. * * @param stroke the stroke (<code>null</code> permitted). * * @see #getRadiusGridlineStroke() */ public void setRadiusGridlineStroke(Stroke stroke) { this.radiusGridlineStroke = stroke; fireChangeEvent(); } /** * Returns the paint for the grid lines (if any) plotted against the radius * axis. * * @return The paint (possibly <code>null</code>). * * @see #setRadiusGridlinePaint(Paint) */ public Paint getRadiusGridlinePaint() { return this.radiusGridlinePaint; } /** * Sets the paint for the grid lines plotted against the radius axis and * sends a {@link PlotChangeEvent} to all registered listeners. * <p> * If you set this to <code>null</code>, no grid lines will be drawn. * * @param paint the paint (<code>null</code> permitted). * * @see #getRadiusGridlinePaint() */ public void setRadiusGridlinePaint(Paint paint) { this.radiusGridlinePaint = paint; fireChangeEvent(); } /** * Return the current value of the flag indicating if radial minor * grid-lines will be drawn or not. * * @return Returns <code>true</code> if radial minor grid-lines are drawn. * @since 1.0.15 */ public boolean isRadiusMinorGridlinesVisible() { return this.radiusMinorGridlinesVisible; } /** * Set the flag that determines if radial minor grid-lines will be drawn. * * @param flag <code>true</code> to draw the radial minor grid-lines, * <code>false</code> to hide them. * @since 1.0.15 */ public void setRadiusMinorGridlinesVisible(boolean flag) { this.radiusMinorGridlinesVisible = flag; } /** * Returns the margin around the plot area. * * @return The actual margin in pixels. * * @since 1.0.14 */ public int getMargin() { return this.margin; } /** * Set the margin around the plot area and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param margin The new margin in pixels. * * @since 1.0.14 */ public void setMargin(int margin) { this.margin = margin; fireChangeEvent(); } /** * Returns the fixed legend items, if any. * * @return The legend items (possibly <code>null</code>). * * @see #setFixedLegendItems(LegendItemCollection) * * @since 1.0.14 */ public LegendItemCollection getFixedLegendItems() { return this.fixedLegendItems; } /** * Sets the fixed legend items for the plot. Leave this set to * <code>null</code> if you prefer the legend items to be created * automatically. * * @param items the legend items (<code>null</code> permitted). * * @see #getFixedLegendItems() * * @since 1.0.14 */ public void setFixedLegendItems(LegendItemCollection items) { this.fixedLegendItems = items; fireChangeEvent(); } /** * Add text to be displayed in the lower right hand corner and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param text the text to display (<code>null</code> not permitted). * * @see #removeCornerTextItem(String) */ public void addCornerTextItem(String text) { ParamChecks.nullNotPermitted(text, "text"); this.cornerTextItems.add(text); fireChangeEvent(); } /** * Remove the given text from the list of corner text items and * sends a {@link PlotChangeEvent} to all registered listeners. * * @param text the text to remove (<code>null</code> ignored). * * @see #addCornerTextItem(String) */ public void removeCornerTextItem(String text) { boolean removed = this.cornerTextItems.remove(text); if (removed) { fireChangeEvent(); } } /** * Clear the list of corner text items and sends a {@link PlotChangeEvent} * to all registered listeners. * * @see #addCornerTextItem(String) * @see #removeCornerTextItem(String) */ public void clearCornerTextItems() { if (this.cornerTextItems.size() > 0) { this.cornerTextItems.clear(); fireChangeEvent(); } } /** * Generates a list of tick values for the angular tick marks. * * @return A list of {@link NumberTick} instances. * * @since 1.0.10 */ protected List refreshAngleTicks() { List ticks = new ArrayList(); for (double currentTickVal = 0.0; currentTickVal < 360.0; currentTickVal += this.angleTickUnit.getSize()) { TextAnchor ta = calculateTextAnchor(currentTickVal); NumberTick tick = new NumberTick(new Double(currentTickVal), this.angleTickUnit.valueToString(currentTickVal), ta, TextAnchor.CENTER, 0.0); ticks.add(tick); } return ticks; } /** * Calculate the text position for the given degrees. * * @param angleDegrees the angle in degrees. * * @return The optimal text anchor. * @since 1.0.14 */ protected TextAnchor calculateTextAnchor(double angleDegrees) { TextAnchor ta = TextAnchor.CENTER; // normalize angle double offset = this.angleOffset; while (offset < 0.0) { offset += 360.0; } double normalizedAngle = (((this.counterClockwise ? -1 : 1) * angleDegrees) + offset) % 360; while (this.counterClockwise && (normalizedAngle < 0.0)) { normalizedAngle += 360.0; } if (normalizedAngle == 0.0) { ta = TextAnchor.CENTER_LEFT; } else if (normalizedAngle > 0.0 && normalizedAngle < 90.0) { ta = TextAnchor.TOP_LEFT; } else if (normalizedAngle == 90.0) { ta = TextAnchor.TOP_CENTER; } else if (normalizedAngle > 90.0 && normalizedAngle < 180.0) { ta = TextAnchor.TOP_RIGHT; } else if (normalizedAngle == 180) { ta = TextAnchor.CENTER_RIGHT; } else if (normalizedAngle > 180.0 && normalizedAngle < 270.0) { ta = TextAnchor.BOTTOM_RIGHT; } else if (normalizedAngle == 270) { ta = TextAnchor.BOTTOM_CENTER; } else if (normalizedAngle > 270.0 && normalizedAngle < 360.0) { ta = TextAnchor.BOTTOM_LEFT; } return ta; } /** * Maps a dataset to a particular axis. All data will be plotted * against axis zero by default, no mapping is required for this case. * * @param index the dataset index (zero-based). * @param axisIndex the axis index. * * @since 1.0.14 */ public void mapDatasetToAxis(int index, int axisIndex) { List axisIndices = new java.util.ArrayList(1); axisIndices.add(new Integer(axisIndex)); mapDatasetToAxes(index, axisIndices); } /** * Maps the specified dataset to the axes in the list. Note that the * conversion of data values into Java2D space is always performed using * the first axis in the list. * * @param index the dataset index (zero-based). * @param axisIndices the axis indices (<code>null</code> permitted). * * @since 1.0.14 */ public void mapDatasetToAxes(int index, List axisIndices) { if (index < 0) { throw new IllegalArgumentException("Requires 'index' >= 0."); } checkAxisIndices(axisIndices); Integer key = new Integer(index); this.datasetToAxesMap.put(key, new ArrayList(axisIndices)); // fake a dataset change event to update axes... datasetChanged(new DatasetChangeEvent(this, getDataset(index))); } /** * This method is used to perform argument checking on the list of * axis indices passed to mapDatasetToAxes(). * * @param indices the list of indices (<code>null</code> permitted). */ private void checkAxisIndices(List indices) { // axisIndices can be: // 1. null; // 2. non-empty, containing only Integer objects that are unique. if (indices == null) { return; } int count = indices.size(); if (count == 0) { throw new IllegalArgumentException("Empty list not permitted."); } HashSet set = new HashSet(); for (int i = 0; i < count; i++) { Object item = indices.get(i); if (!(item instanceof Integer)) { throw new IllegalArgumentException( "Indices must be Integer instances."); } if (set.contains(item)) { throw new IllegalArgumentException("Indices must be unique."); } set.add(item); } } /** * Returns the axis for a dataset. * * @param index the dataset index. * * @return The axis. * * @since 1.0.14 */ public ValueAxis getAxisForDataset(int index) { ValueAxis valueAxis; List axisIndices = (List) this.datasetToAxesMap.get( new Integer(index)); if (axisIndices != null) { // the first axis in the list is used for data <--> Java2D Integer axisIndex = (Integer) axisIndices.get(0); valueAxis = getAxis(axisIndex.intValue()); } else { valueAxis = getAxis(0); } return valueAxis; } /** * Returns the index of the given axis. * * @param axis the axis. * * @return The axis index or -1 if axis is not used in this plot. * * @since 1.0.14 */ public int getAxisIndex(ValueAxis axis) { int result = this.axes.indexOf(axis); if (result < 0) { // try the parent plot Plot parent = getParent(); if (parent instanceof PolarPlot) { PolarPlot p = (PolarPlot) parent; result = p.getAxisIndex(axis); } } return result; } /** * Returns the index of the specified renderer, or <code>-1</code> if the * renderer is not assigned to this plot. * * @param renderer the renderer (<code>null</code> permitted). * * @return The renderer index. * * @since 1.0.14 */ public int getIndexOf(PolarItemRenderer renderer) { return this.renderers.indexOf(renderer); } /** * Draws the plot on a Java 2D graphics device (such as the screen or a * printer). * <P> * This plot relies on a {@link PolarItemRenderer} to draw each * item in the plot. This allows the visual representation of the data to * be changed easily. * <P> * The optional info argument collects information about the rendering of * the plot (dimensions, tooltip information etc). Just pass in * <code>null</code> if you do not need this information. * * @param g2 the graphics device. * @param area the area within which the plot (including axes and * labels) should be drawn. * @param anchor the anchor point (<code>null</code> permitted). * @param parentState ignored. * @param info collects chart drawing information (<code>null</code> * permitted). */ public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState, PlotRenderingInfo info) { // if the plot area is too small, just return... boolean b1 = (area.getWidth() <= MINIMUM_WIDTH_TO_DRAW); boolean b2 = (area.getHeight() <= MINIMUM_HEIGHT_TO_DRAW); if (b1 || b2) { return; } // record the plot area... if (info != null) { info.setPlotArea(area); } // adjust the drawing area for the plot insets (if any)... RectangleInsets insets = getInsets(); insets.trim(area); Rectangle2D dataArea = area; if (info != null) { info.setDataArea(dataArea); } // draw the plot background and axes... drawBackground(g2, dataArea); int axisCount = this.axes.size(); AxisState state = null; for (int i = 0; i < axisCount; i++) { ValueAxis axis = getAxis(i); if (axis != null) { PolarAxisLocation location = (PolarAxisLocation) this.axisLocations.get(i); AxisState s = this.drawAxis(axis, location, g2, dataArea); if (i == 0) { state = s; } } } // now for each dataset, get the renderer and the appropriate axis // and render the dataset... Shape originalClip = g2.getClip(); Composite originalComposite = g2.getComposite(); g2.clip(dataArea); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getForegroundAlpha())); this.angleTicks = refreshAngleTicks(); drawGridlines(g2, dataArea, this.angleTicks, state.getTicks()); render(g2, dataArea, info); g2.setClip(originalClip); g2.setComposite(originalComposite); drawOutline(g2, dataArea); drawCornerTextItems(g2, dataArea); } /** * Draws the corner text items. * * @param g2 the drawing surface. * @param area the area. */ protected void drawCornerTextItems(Graphics2D g2, Rectangle2D area) { if (this.cornerTextItems.isEmpty()) { return; } g2.setColor(Color.black); double width = 0.0; double height = 0.0; for (Iterator it = this.cornerTextItems.iterator(); it.hasNext();) { String msg = (String) it.next(); FontMetrics fm = g2.getFontMetrics(); Rectangle2D bounds = TextUtilities.getTextBounds(msg, g2, fm); width = Math.max(width, bounds.getWidth()); height += bounds.getHeight(); } double xadj = ANNOTATION_MARGIN * 2.0; double yadj = ANNOTATION_MARGIN; width += xadj; height += yadj; double x = area.getMaxX() - width; double y = area.getMaxY() - height; g2.drawRect((int) x, (int) y, (int) width, (int) height); x += ANNOTATION_MARGIN; for (Iterator it = this.cornerTextItems.iterator(); it.hasNext();) { String msg = (String) it.next(); Rectangle2D bounds = TextUtilities.getTextBounds(msg, g2, g2.getFontMetrics()); y += bounds.getHeight(); g2.drawString(msg, (int) x, (int) y); } } /** * Draws the axis with the specified index. * * @param axis the axis. * @param location the axis location. * @param g2 the graphics target. * @param plotArea the plot area. * * @return The axis state. * * @since 1.0.14 */ protected AxisState drawAxis(ValueAxis axis, PolarAxisLocation location, Graphics2D g2, Rectangle2D plotArea) { double centerX = plotArea.getCenterX(); double centerY = plotArea.getCenterY(); double r = Math.min(plotArea.getWidth() / 2.0, plotArea.getHeight() / 2.0) - this.margin; double x = centerX - r; double y = centerY - r; Rectangle2D dataArea = null; AxisState result = null; if (location == PolarAxisLocation.NORTH_RIGHT) { dataArea = new Rectangle2D.Double(x, y, r, r); result = axis.draw(g2, centerX, plotArea, dataArea, RectangleEdge.RIGHT, null); } else if (location == PolarAxisLocation.NORTH_LEFT) { dataArea = new Rectangle2D.Double(centerX, y, r, r); result = axis.draw(g2, centerX, plotArea, dataArea, RectangleEdge.LEFT, null); } else if (location == PolarAxisLocation.SOUTH_LEFT) { dataArea = new Rectangle2D.Double(centerX, centerY, r, r); result = axis.draw(g2, centerX, plotArea, dataArea, RectangleEdge.LEFT, null); } else if (location == PolarAxisLocation.SOUTH_RIGHT) { dataArea = new Rectangle2D.Double(x, centerY, r, r); result = axis.draw(g2, centerX, plotArea, dataArea, RectangleEdge.RIGHT, null); } else if (location == PolarAxisLocation.EAST_ABOVE) { dataArea = new Rectangle2D.Double(centerX, centerY, r, r); result = axis.draw(g2, centerY, plotArea, dataArea, RectangleEdge.TOP, null); } else if (location == PolarAxisLocation.EAST_BELOW) { dataArea = new Rectangle2D.Double(centerX, y, r, r); result = axis.draw(g2, centerY, plotArea, dataArea, RectangleEdge.BOTTOM, null); } else if (location == PolarAxisLocation.WEST_ABOVE) { dataArea = new Rectangle2D.Double(x, centerY, r, r); result = axis.draw(g2, centerY, plotArea, dataArea, RectangleEdge.TOP, null); } else if (location == PolarAxisLocation.WEST_BELOW) { dataArea = new Rectangle2D.Double(x, y, r, r); result = axis.draw(g2, centerY, plotArea, dataArea, RectangleEdge.BOTTOM, null); } return result; } /** * Draws a representation of the data within the dataArea region, using the * current m_Renderer. * * @param g2 the graphics device. * @param dataArea the region in which the data is to be drawn. * @param info an optional object for collection dimension * information (<code>null</code> permitted). */ protected void render(Graphics2D g2, Rectangle2D dataArea, PlotRenderingInfo info) { // now get the data and plot it (the visual representation will depend // on the m_Renderer that has been set)... boolean hasData = false; int datasetCount = this.datasets.size(); for (int i = datasetCount - 1; i >= 0; i XYDataset dataset = getDataset(i); if (dataset == null) { continue; } PolarItemRenderer renderer = getRenderer(i); if (renderer == null) { continue; } if (!DatasetUtilities.isEmptyOrNull(dataset)) { hasData = true; int seriesCount = dataset.getSeriesCount(); for (int series = 0; series < seriesCount; series++) { renderer.drawSeries(g2, dataArea, info, this, dataset, series); } } } if (!hasData) { drawNoDataMessage(g2, dataArea); } } /** * Draws the gridlines for the plot, if they are visible. * * @param g2 the graphics device. * @param dataArea the data area. * @param angularTicks the ticks for the angular axis. * @param radialTicks the ticks for the radial axis. */ protected void drawGridlines(Graphics2D g2, Rectangle2D dataArea, List angularTicks, List radialTicks) { PolarItemRenderer renderer = getRenderer(); // no renderer, no gridlines... if (renderer == null) { return; } // draw the domain grid lines, if any... if (isAngleGridlinesVisible()) { Stroke gridStroke = getAngleGridlineStroke(); Paint gridPaint = getAngleGridlinePaint(); if ((gridStroke != null) && (gridPaint != null)) { renderer.drawAngularGridLines(g2, this, angularTicks, dataArea); } } // draw the radius grid lines, if any... if (isRadiusGridlinesVisible()) { Stroke gridStroke = getRadiusGridlineStroke(); Paint gridPaint = getRadiusGridlinePaint(); if ((gridStroke != null) && (gridPaint != null)) { List ticks = buildRadialTicks(radialTicks); renderer.drawRadialGridLines(g2, this, getAxis(), ticks, dataArea); } } } /** * Create a list of ticks based on the given list and plot properties. * Only ticks of a specific type may be in the result list. * * @param allTicks A list of all available ticks for the primary axis. * <code>null</code> not permitted. * @return Ticks to use for radial gridlines. * @since 1.0.15 */ protected List buildRadialTicks(List allTicks) { List ticks = new ArrayList(); Iterator it = allTicks.iterator(); while (it.hasNext()) { ValueTick tick = (ValueTick) it.next(); if (isRadiusMinorGridlinesVisible() || TickType.MAJOR.equals(tick.getTickType())) { ticks.add(tick); } } return ticks; } /** * Zooms the axis ranges by the specified percentage about the anchor point. * * @param percent the amount of the zoom. */ public void zoom(double percent) { for (int axisIdx = 0; axisIdx < getAxisCount(); axisIdx++) { final ValueAxis axis = getAxis(axisIdx); if (axis != null) { if (percent > 0.0) { double radius = axis.getUpperBound(); double scaledRadius = radius * percent; axis.setUpperBound(scaledRadius); axis.setAutoRange(false); } else { axis.setAutoRange(true); } } } } /** * A utility method that returns a list of datasets that are mapped to a * particular axis. * * @param axisIndex the axis index (<code>null</code> not permitted). * * @return A list of datasets. * * @since 1.0.14 */ private List getDatasetsMappedToAxis(Integer axisIndex) { ParamChecks.nullNotPermitted(axisIndex, "axisIndex"); List result = new ArrayList(); for (int i = 0; i < this.datasets.size(); i++) { List mappedAxes = (List) this.datasetToAxesMap.get(new Integer(i)); if (mappedAxes == null) { if (axisIndex.equals(ZERO)) { result.add(this.datasets.get(i)); } } else { if (mappedAxes.contains(axisIndex)) { result.add(this.datasets.get(i)); } } } return result; } /** * Returns the range for the specified axis. * * @param axis the axis. * * @return The range. */ public Range getDataRange(ValueAxis axis) { Range result = null; int axisIdx = getAxisIndex(axis); List mappedDatasets = new ArrayList(); if (axisIdx >= 0) { mappedDatasets = getDatasetsMappedToAxis(new Integer(axisIdx)); } // iterate through the datasets that map to the axis and get the union // of the ranges. Iterator iterator = mappedDatasets.iterator(); int datasetIdx = -1; while (iterator.hasNext()) { datasetIdx++; XYDataset d = (XYDataset) iterator.next(); if (d != null) { // FIXME better ask the renderer instead of DatasetUtilities result = Range.combine(result, DatasetUtilities.findRangeBounds(d)); } } return result; } /** * Receives notification of a change to the plot's m_Dataset. * <P> * The axis ranges are updated if necessary. * * @param event information about the event (not used here). */ public void datasetChanged(DatasetChangeEvent event) { for (int i = 0; i < this.axes.size(); i++) { final ValueAxis axis = (ValueAxis) this.axes.get(i); if (axis != null) { axis.configure(); } } if (getParent() != null) { getParent().datasetChanged(event); } else { super.datasetChanged(event); } } /** * Notifies all registered listeners of a property change. * <P> * One source of property change events is the plot's m_Renderer. * * @param event information about the property change. */ public void rendererChanged(RendererChangeEvent event) { fireChangeEvent(); } /** * Returns the legend items for the plot. Each legend item is generated by * the plot's m_Renderer, since the m_Renderer is responsible for the visual * representation of the data. * * @return The legend items. */ public LegendItemCollection getLegendItems() { if (this.fixedLegendItems != null) { return this.fixedLegendItems; } LegendItemCollection result = new LegendItemCollection(); int count = this.datasets.size(); for (int datasetIndex = 0; datasetIndex < count; datasetIndex++) { XYDataset dataset = getDataset(datasetIndex); PolarItemRenderer renderer = getRenderer(datasetIndex); if (dataset != null && renderer != null) { int seriesCount = dataset.getSeriesCount(); for (int i = 0; i < seriesCount; i++) { LegendItem item = renderer.getLegendItem(i); result.add(item); } } } return result; } /** * Tests this plot for equality with another object. * * @param obj the object (<code>null</code> permitted). * * @return <code>true</code> or <code>false</code>. */ public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof PolarPlot)) { return false; } PolarPlot that = (PolarPlot) obj; if (!this.axes.equals(that.axes)) { return false; } if (!this.axisLocations.equals(that.axisLocations)) { return false; } if (!this.renderers.equals(that.renderers)) { return false; } if (!this.angleTickUnit.equals(that.angleTickUnit)) { return false; } if (this.angleGridlinesVisible != that.angleGridlinesVisible) { return false; } if (this.angleOffset != that.angleOffset) { return false; } if (this.counterClockwise != that.counterClockwise) { return false; } if (this.angleLabelsVisible != that.angleLabelsVisible) { return false; } if (!this.angleLabelFont.equals(that.angleLabelFont)) { return false; } if (!PaintUtilities.equal(this.angleLabelPaint, that.angleLabelPaint)) { return false; } if (!ObjectUtilities.equal(this.angleGridlineStroke, that.angleGridlineStroke)) { return false; } if (!PaintUtilities.equal( this.angleGridlinePaint, that.angleGridlinePaint )) { return false; } if (this.radiusGridlinesVisible != that.radiusGridlinesVisible) { return false; } if (!ObjectUtilities.equal(this.radiusGridlineStroke, that.radiusGridlineStroke)) { return false; } if (!PaintUtilities.equal(this.radiusGridlinePaint, that.radiusGridlinePaint)) { return false; } if (this.radiusMinorGridlinesVisible != that.radiusMinorGridlinesVisible) { return false; } if (!this.cornerTextItems.equals(that.cornerTextItems)) { return false; } if (this.margin != that.margin) { return false; } if (!ObjectUtilities.equal(this.fixedLegendItems, that.fixedLegendItems)) { return false; } return super.equals(obj); } /** * Returns a clone of the plot. * * @return A clone. * * @throws CloneNotSupportedException this can occur if some component of * the plot cannot be cloned. */ public Object clone() throws CloneNotSupportedException { PolarPlot clone = (PolarPlot) super.clone(); clone.axes = (ObjectList) ObjectUtilities.clone(this.axes); for (int i = 0; i < this.axes.size(); i++) { ValueAxis axis = (ValueAxis) this.axes.get(i); if (axis != null) { ValueAxis clonedAxis = (ValueAxis) axis.clone(); clone.axes.set(i, clonedAxis); clonedAxis.setPlot(clone); clonedAxis.addChangeListener(clone); } } // the datasets are not cloned, but listeners need to be added... clone.datasets = (ObjectList) ObjectUtilities.clone(this.datasets); for (int i = 0; i < clone.datasets.size(); ++i) { XYDataset d = getDataset(i); if (d != null) { d.addChangeListener(clone); } } clone.renderers = (ObjectList) ObjectUtilities.clone(this.renderers); for (int i = 0; i < this.renderers.size(); i++) { PolarItemRenderer renderer2 = (PolarItemRenderer) this.renderers.get(i); if (renderer2 instanceof PublicCloneable) { PublicCloneable pc = (PublicCloneable) renderer2; PolarItemRenderer rc = (PolarItemRenderer) pc.clone(); clone.renderers.set(i, rc); rc.setPlot(clone); rc.addChangeListener(clone); } } clone.cornerTextItems = new ArrayList(this.cornerTextItems); return clone; } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writeStroke(this.angleGridlineStroke, stream); SerialUtilities.writePaint(this.angleGridlinePaint, stream); SerialUtilities.writeStroke(this.radiusGridlineStroke, stream); SerialUtilities.writePaint(this.radiusGridlinePaint, stream); SerialUtilities.writePaint(this.angleLabelPaint, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.angleGridlineStroke = SerialUtilities.readStroke(stream); this.angleGridlinePaint = SerialUtilities.readPaint(stream); this.radiusGridlineStroke = SerialUtilities.readStroke(stream); this.radiusGridlinePaint = SerialUtilities.readPaint(stream); this.angleLabelPaint = SerialUtilities.readPaint(stream); int rangeAxisCount = this.axes.size(); for (int i = 0; i < rangeAxisCount; i++) { Axis axis = (Axis) this.axes.get(i); if (axis != null) { axis.setPlot(this); axis.addChangeListener(this); } } int datasetCount = this.datasets.size(); for (int i = 0; i < datasetCount; i++) { Dataset dataset = (Dataset) this.datasets.get(i); if (dataset != null) { dataset.addChangeListener(this); } } int rendererCount = this.renderers.size(); for (int i = 0; i < rendererCount; i++) { PolarItemRenderer renderer = (PolarItemRenderer) this.renderers.get(i); if (renderer != null) { renderer.addChangeListener(this); } } } /** * This method is required by the {@link Zoomable} interface, but since * the plot does not have any domain axes, it does nothing. * * @param factor the zoom factor. * @param state the plot state. * @param source the source point (in Java2D coordinates). */ public void zoomDomainAxes(double factor, PlotRenderingInfo state, Point2D source) { // do nothing } /** * This method is required by the {@link Zoomable} interface, but since * the plot does not have any domain axes, it does nothing. * * @param factor the zoom factor. * @param state the plot state. * @param source the source point (in Java2D coordinates). * @param useAnchor use source point as zoom anchor? * * @since 1.0.7 */ public void zoomDomainAxes(double factor, PlotRenderingInfo state, Point2D source, boolean useAnchor) { // do nothing } /** * This method is required by the {@link Zoomable} interface, but since * the plot does not have any domain axes, it does nothing. * * @param lowerPercent the new lower bound. * @param upperPercent the new upper bound. * @param state the plot state. * @param source the source point (in Java2D coordinates). */ public void zoomDomainAxes(double lowerPercent, double upperPercent, PlotRenderingInfo state, Point2D source) { // do nothing } /** * Multiplies the range on the range axis/axes by the specified factor. * * @param factor the zoom factor. * @param state the plot state. * @param source the source point (in Java2D coordinates). */ public void zoomRangeAxes(double factor, PlotRenderingInfo state, Point2D source) { zoom(factor); } /** * Multiplies the range on the range axis by the specified factor. * * @param factor the zoom factor. * @param info the plot rendering info. * @param source the source point (in Java2D space). * @param useAnchor use source point as zoom anchor? * * @see #zoomDomainAxes(double, PlotRenderingInfo, Point2D, boolean) * * @since 1.0.7 */ public void zoomRangeAxes(double factor, PlotRenderingInfo info, Point2D source, boolean useAnchor) { // get the source coordinate - this plot has always a VERTICAL // orientation final double sourceX = source.getX(); for (int axisIdx = 0; axisIdx < getAxisCount(); axisIdx++) { final ValueAxis axis = getAxis(axisIdx); if (axis != null) { if (useAnchor) { double anchorX = axis.java2DToValue(sourceX, info.getDataArea(), RectangleEdge.BOTTOM); axis.resizeRange(factor, anchorX); } else { axis.resizeRange(factor); } } } } /** * Zooms in on the range axes. * * @param lowerPercent the new lower bound. * @param upperPercent the new upper bound. * @param state the plot state. * @param source the source point (in Java2D coordinates). */ public void zoomRangeAxes(double lowerPercent, double upperPercent, PlotRenderingInfo state, Point2D source) { zoom((upperPercent + lowerPercent) / 2.0); } /** * Returns <code>false</code> always. * * @return <code>false</code> always. */ public boolean isDomainZoomable() { return false; } /** * Returns <code>true</code> to indicate that the range axis is zoomable. * * @return <code>true</code>. */ public boolean isRangeZoomable() { return true; } /** * Returns the orientation of the plot. * * @return The orientation. */ public PlotOrientation getOrientation() { return PlotOrientation.HORIZONTAL; } /** * Translates a (theta, radius) pair into Java2D coordinates. If * <code>radius</code> is less than the lower bound of the axis, then * this method returns the centre point. * * @param angleDegrees the angle in degrees. * @param radius the radius. * @param axis the axis. * @param dataArea the data area. * * @return A point in Java2D space. * * @since 1.0.14 */ public Point translateToJava2D(double angleDegrees, double radius, ValueAxis axis, Rectangle2D dataArea) { if (counterClockwise) { angleDegrees = -angleDegrees; } double radians = Math.toRadians(angleDegrees + this.angleOffset); double minx = dataArea.getMinX() + this.margin; double maxx = dataArea.getMaxX() - this.margin; double miny = dataArea.getMinY() + this.margin; double maxy = dataArea.getMaxY() - this.margin; double halfWidth = (maxx - minx) / 2.0; double halfHeight = (maxy - miny) / 2.0; double midX = minx + halfWidth; double midY = miny + halfHeight; double l = Math.min(halfWidth, halfHeight); Rectangle2D quadrant = new Rectangle2D.Double(midX, midY, l, l); double axisMin = axis.getLowerBound(); double adjustedRadius = Math.max(radius, axisMin); double length = axis.valueToJava2D(adjustedRadius, quadrant, RectangleEdge.BOTTOM) - midX; float x = (float) (midX + Math.cos(radians) * length); float y = (float) (midY + Math.sin(radians) * length); int ix = Math.round(x); int iy = Math.round(y); Point p = new Point(ix, iy); return p; } /** * Translates a (theta, radius) pair into Java2D coordinates. If * <code>radius</code> is less than the lower bound of the axis, then * this method returns the centre point. * * @param angleDegrees the angle in degrees. * @param radius the radius. * @param dataArea the data area. * * @return A point in Java2D space. * * @deprecated Since 1.0.14, use {@link #translateToJava2D(double, double, * org.jfree.chart.axis.ValueAxis, java.awt.geom.Rectangle2D)} instead. */ public Point translateValueThetaRadiusToJava2D(double angleDegrees, double radius, Rectangle2D dataArea) { return translateToJava2D(angleDegrees, radius, getAxis(), dataArea); } /** * Returns the upper bound of the radius axis. * * @return The upper bound. * * @deprecated Since 1.0.14, use {@link #getAxis()} and call the * getUpperBound() method. */ public double getMaxRadius() { return getAxis().getUpperBound(); } /** * Returns the number of series in the dataset for this plot. If the * dataset is <code>null</code>, the method returns 0. * * @return The series count. * * @deprecated Since 1.0.14, grab a reference to the dataset and check * the series count directly. */ public int getSeriesCount() { int result = 0; XYDataset dataset = getDataset(0); if (dataset != null) { result = dataset.getSeriesCount(); } return result; } /** * A utility method for drawing the axes. * * @param g2 the graphics device. * @param plotArea the plot area. * @param dataArea the data area. * * @return A map containing the axis states. * * @deprecated As of version 1.0.14, this method is no longer used. */ protected AxisState drawAxis(Graphics2D g2, Rectangle2D plotArea, Rectangle2D dataArea) { return getAxis().draw(g2, dataArea.getMinY(), plotArea, dataArea, RectangleEdge.TOP, null); } }
package ru.pinkponies.server; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.BufferOverflowException; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import ru.pinkponies.app.NetworkingThread; import ru.pinkponies.protocol.LocationUpdatePacket; import ru.pinkponies.protocol.LoginPacket; import ru.pinkponies.protocol.Packet; import ru.pinkponies.protocol.Protocol; import ru.pinkponies.protocol.SayPacket; public final class Server { private static final int SERVER_PORT = 4266; private static final int BUFFER_SIZE = 8192; private final static Logger logger = Logger.getLogger(Server.class.getName()); private ServerSocketChannel serverSocketChannel; private Selector selector; private Map<SocketChannel, ByteBuffer> incomingData = new HashMap<SocketChannel, ByteBuffer>(); private Map<SocketChannel, ByteBuffer> outgoingData = new HashMap<SocketChannel, ByteBuffer>(); private Protocol protocol; private void initialize() { try { serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.configureBlocking(false); InetSocketAddress address = new InetSocketAddress(SERVER_PORT); serverSocketChannel.socket().bind(address); selector = Selector.open(); SelectionKey key = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); System.out.println("serverSocketChannel's registered key is " + key.channel().toString() + "."); protocol = new Protocol(); } catch (Exception e) { logger.log(Level.SEVERE, "Exception", e); } } private void start() throws IOException { System.out.println("Server is listening on port " + serverSocketChannel.socket().getLocalPort() + "."); while(true) { pumpEvents(); } } private void pumpEvents() throws IOException { selector.select(); Set<SelectionKey> selectedKeys = selector.selectedKeys(); Iterator<SelectionKey> iterator = selectedKeys.iterator(); while (iterator.hasNext()) { SelectionKey key = (SelectionKey) iterator.next(); iterator.remove(); if (!key.isValid()) { continue; } try { if (key.isAcceptable()) { accept(key); } else if (key.isReadable()) { read(key); } else if (key.isWritable()) { write(key); } } catch (IOException e) { close(key); logger.log(Level.SEVERE, "Exception", e); } } } public void accept(SelectionKey key) throws IOException { SocketChannel channel = serverSocketChannel.accept(); channel.configureBlocking(false); channel.register(selector, SelectionKey.OP_READ); //channel.register(selector, SelectionKey.OP_WRITE); incomingData.put(channel, ByteBuffer.allocate(BUFFER_SIZE)); outgoingData.put(channel, ByteBuffer.allocate(BUFFER_SIZE)); onConnect(channel); } public void close(SelectionKey key) throws IOException { SocketChannel channel = (SocketChannel) key.channel(); incomingData.remove(channel); outgoingData.remove(channel); channel.close(); key.cancel(); } public void read(SelectionKey key) throws IOException { SocketChannel channel = (SocketChannel) key.channel(); ByteBuffer buffer = incomingData.get(channel); buffer.limit(buffer.capacity()); int numRead = -1; try { numRead = channel.read(buffer); } catch (IOException e) { close(key); logger.log(Level.SEVERE, "Exception", e); return; } if (numRead == -1) { close(key); logger.severe("Read failed."); return; } onMessage(channel, buffer); } public void write(SelectionKey key) throws IOException { SocketChannel channel = (SocketChannel) key.channel(); synchronized (outgoingData) { ByteBuffer buffer = outgoingData.get(channel); buffer.flip(); channel.write(buffer); buffer.compact(); if (buffer.remaining() == 0) { key.interestOps(SelectionKey.OP_READ); } } } public void onConnect(SocketChannel channel) { System.out.println("Client connected from " + channel.socket().getRemoteSocketAddress().toString() + "."); } public void onMessage(SocketChannel channel, ByteBuffer buffer) throws IOException { System.out.println("Message from " + channel.socket().getRemoteSocketAddress().toString() + ":"); Packet packet = null; buffer.flip(); try { packet = protocol.unpack(buffer); } catch (Exception e) { e.printStackTrace(); } buffer.compact(); if (packet == null) { return; } if (packet instanceof LoginPacket) { LoginPacket loginPacket = (LoginPacket) packet; System.out.println(loginPacket.toString()); } else if (packet instanceof SayPacket) { SayPacket sayPacket = (SayPacket) packet; System.out.println(sayPacket.toString()); } else if (packet instanceof LocationUpdatePacket) { LocationUpdatePacket locUpdate = (LocationUpdatePacket) packet; System.out.println(locUpdate.toString()); //say(channel, "Thank you!"); // XXX. } } public void sendMessage(SocketChannel channel, byte[] data) { synchronized (outgoingData) { ByteBuffer buffer = outgoingData.get(channel); try { buffer.put(data); } catch(BufferOverflowException e) { e.printStackTrace(); } } } private void sendPacket(SocketChannel channel, Packet packet) throws IOException { sendMessage(channel, protocol.pack(packet)); } private void say(SocketChannel channel, String message) throws IOException { SayPacket packet = new SayPacket(message); sendPacket(channel, packet); } public static void main(String[] args) { try { Server server = new Server(); server.initialize(); server.start(); } catch (Exception e) { logger.log(Level.SEVERE, "Exception", e); } } }
package map.intersection; import java.util.HashMap; import java.util.ArrayList; public class Intersection { private Segment[] segments; //Just holds all Segments. private HashMap<Integer,Segment> startPoints; //Gives the first segment coming from each of the 4 directions. public Intersection() { segments = new Segment[9]; startPoints = new HashMap<>(); init(); } private class Segment { private ArrayList<Segment> siblingSegments; //Holds a list of all segments that can cause collision with this one. private HashMap<Integer,Segment> split; //Tells which Segment a car has to enter given its destination as key. Null instead of a Segment if destination is reached. public Segment() { siblingSegments = new ArrayList<>(); split = new HashMap<>(); } public void linkSegment(int destination, Segment seg) { split.put(destination,seg); } } private void init() { for(int i = 0; i < segments.length; i++) { segments[0] = new Segment(); } startPoints.put(0,segments[0]); segments[0].linkSegment(1,segments[4]); segments[4].linkSegment(1,segments[5]); segments[5].linkSegment(1,segments[6]); segments[6].linkSegment(1,null); segments[0].linkSegment(2,segments[1]); segments[1].linkSegment(2,segments[2]); segments[2].linkSegment(2,segments[3]); segments[3].linkSegment(2,null); segments[0].linkSegment(3,segments[1]); segments[1].linkSegment(3,segments[7]); segments[7].linkSegment(3,segments[8]); segments[3].linkSegment(3,null); } }
package Semant; import Translate.Exp; import Types.Type; import java.util.*; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Random; public class Semant { Env env; public Semant(ErrorMsg.ErrorMsg err) { this(new Env(err)); } Semant(Env e) { env = e; } public void transProg(Absyn.Exp exp) { transExp(exp); } private void Error(int pos, String msg) { env.errorMsg.error(pos, msg); } static final Types.VOID VOID = new Types.VOID(); static final Types.INT INT = new Types.INT(); static final Types.STRING STRING = new Types.STRING(); static final Types.NIL NIL = new Types.NIL(); private Exp checkInt(ExpTy et, int pos) { if (!INT.coerceTo(et.ty)) Error(pos, "integer required"); return et.exp; } // DDDDDDDDDDDDD // D::::::::::::DDD // D:::::::::::::::DD // DDD:::::DDDDD:::::D // D:::::D D:::::D eeeeeeeeeeee cccccccccccccccc // D:::::D D:::::D ee::::::::::::ee cc:::::::::::::::c // D:::::D D:::::D e::::::eeeee:::::ee c:::::::::::::::::c // D:::::D D:::::De::::::e e:::::ec:::::::cccccc:::::c // D:::::D D:::::De:::::::eeeee::::::ec::::::c ccccccc // D:::::D D:::::De:::::::::::::::::e c:::::c // D:::::D D:::::De::::::eeeeeeeeeee c:::::c // D:::::D D:::::D e:::::::e c::::::c ccccccc // DDD:::::DDDDD:::::D e::::::::e c:::::::cccccc:::::c // D:::::::::::::::DD e::::::::eeeeeeee c:::::::::::::::::c // D::::::::::::DDD ee:::::::::::::e cc:::::::::::::::c // DDDDDDDDDDDDD eeeeeeeeeeeeee cccccccccccccccc Exp transDec(Absyn.Dec e) { if (e instanceof Absyn.FunctionDec) return transDec((Absyn.FunctionDec)e); if (e instanceof Absyn.VarDec) return transDec((Absyn.VarDec)e); if (e instanceof Absyn.TypeDec) return transDec((Absyn.TypeDec)e); return null; } Exp transDec(Absyn.TypeDec d){ if (((Types.NAME)env.tenv.get(d.name)).isLoop()) { Error(d.pos, "No definition for " + d.name); } return null; } Exp transDec(Absyn.VarDec d) { ExpTy var = transExp(d.init); if (d.typ != null) { Type dec = transTy(d.typ); if (dec instanceof Types.NAME) dec = dec.actual(); if (!var.ty.coerceTo(dec)) if(!((dec instanceof Types.RECORD) && var.ty instanceof Types.NIL) ) Error(d.pos, "Initailizing type is not matched"); } else { if (var.ty instanceof Types.NIL) env.errorMsg.error(d.pos, "Nil initialization of " + d.name.toString()); } env.venv.put(d.name, new VarEntry(var.ty)); return null; } Exp transDec(Absyn.FunctionDec d){ ArrayList<String> list =new ArrayList<String>(); env.venv.beginScope(); Type re=transTy(d.result); for(Absyn.FieldList f=d.params;f!=null;f=f.tail){ if(list.contains(f.name.toString())) Error(d.pos, "function parameter '"+f.name+"' has been already defined "); list.add(f.name.toString()); Type ty=(Type)env.tenv.get(f.typ); if(ty==null) Error(f.pos, "undefined type '"+f.typ+"'"); env.venv.put(f.name, new VarEntry(ty)); } ExpTy et=transExp(d.body); if(!(re.actual().coerceTo(et.ty.actual()) || re.actual() instanceof Types.RECORD && et.ty.actual() instanceof Types.NIL)) Error(d.pos, "function return type is not matched"); env.venv.endScope(); return null; } Types.RECORD transTypeFields(Absyn.FieldList fl){ if (fl == null) return null; Types.RECORD rec = new Types.RECORD(fl.name, (Type)env.tenv.get(fl.typ), null); Types.RECORD result = rec; for (Absyn.FieldList field = fl.tail; field != null; field = field.tail, rec = rec.tail) rec.tail = new Types.RECORD(field.name, (Type)env.tenv.get(field.typ), null); return result; } // VVVVVVVV VVVVVVVV // V::::::V V::::::V // V::::::V V::::::V // V::::::V V::::::V // V:::::V V:::::V aaaaaaaaaaaaa rrrrr rrrrrrrrr // V:::::V V:::::V a::::::::::::a r::::rrr:::::::::r // V:::::V V:::::V aaaaaaaaa:::::a r:::::::::::::::::r // V:::::V V:::::V a::::a rr::::::rrrrr::::::r // V:::::V V:::::V aaaaaaa:::::a r:::::r r:::::r // V:::::V V:::::V aa::::::::::::a r:::::r rrrrrrr // V:::::V:::::V a::::aaaa::::::a r:::::r // V:::::::::V a::::a a:::::a r:::::r // V:::::::V a::::a a:::::a r:::::r // V:::::V a:::::aaaa::::::a r:::::r // V:::V a::::::::::aa:::a r:::::r // VVV aaaaaaaaaa aaaa rrrrrrr ExpTy transVar(Absyn.Var e) { if (e instanceof Absyn.SimpleVar) return transVar((Absyn.SimpleVar)e); if (e instanceof Absyn.FieldVar) return transVar((Absyn.FieldVar)e); if (e instanceof Absyn.SubscriptVar) return transVar((Absyn.SubscriptVar)e); Error(e.pos, "Variable error."); return new ExpTy(null, new Types.VOID()); } ExpTy transVar(Absyn.SimpleVar v) { System.out.println(v.name); Entry x = (Entry)env.venv.get(v.name); if(x instanceof VarEntry) { VarEntry ent = (VarEntry)x; return new ExpTy(null, ent.ty); } else { Error(v.pos, "Error in variable " + '\"' + v.name + '\"'); } return new ExpTy(null, new Types.VOID()); } ExpTy transVar(Absyn.FieldVar v) { ExpTy fvar = transExp(new Absyn.VarExp(v.pos, v.var)); if (fvar.ty instanceof Types.NAME) { Types.RECORD field = (Types.RECORD)fvar.ty.actual(); for(;field != null;field = field.tail) { if (field.fieldName.equals(v.field)) break; } if (field == null) env.errorMsg.error(v.pos, "'"+v.field+"' is a member of "+v.var); else return new ExpTy(null, field.fieldType); } else env.errorMsg.error(v.pos,"'"+v.field+"' is not a valid field variable"); return new ExpTy(null, new Types.VOID()); } ExpTy transVar(Absyn.SubscriptVar v) { ExpTy sub = transExp(new Absyn.VarExp(v.pos, v.var)); Type svar = sub.ty; if (svar instanceof Types.NAME) svar = svar.actual(); if (!(svar instanceof Types.ARRAY)) env.errorMsg.error(v.pos, "The variable is not an array"); ExpTy p = transExp(v.index); if (!(p.ty instanceof Types.INT)) env.errorMsg.error(v.pos, "The index must be an integer"); if (!(svar instanceof Types.ARRAY)) return new ExpTy(null, svar); else return new ExpTy(null,((Types.ARRAY)svar).element); } // TTTTTTTTTTTTTTTTTTTTTTT // T:::::TT:::::::TT:::::T // TTTTTT T:::::T TTTTTTyyyyyyy yyyyyyy // T:::::T y:::::y y:::::y // T:::::T y:::::y y:::::y // T:::::T y:::::y y:::::y // T:::::T y:::::y y:::::y // T:::::T y:::::y y:::::y // T:::::T y:::::y:::::y // T:::::T y:::::::::y // TT:::::::TT y:::::::y // T:::::::::T y:::::y // T:::::::::T y:::::y // TTTTTTTTTTT y:::::y // yyyyyyy Type transTy(Absyn.Ty e) { if (e instanceof Absyn.NameTy) return transTy((Absyn.NameTy)e); if (e instanceof Absyn.RecordTy) return transTy((Absyn.RecordTy)e); if (e instanceof Absyn.ArrayTy) return transTy((Absyn.ArrayTy)e); Error(e.pos, "Type issue."); return null; } Type transTy(Absyn.NameTy t) { if (t == null) return new Types.VOID(); Type nameTy = (Type)env.tenv.get(t.name); return nameTy; } Type transTy(Absyn.RecordTy t){ Types.RECORD result = null, tmp = null; if (env.tenv.get(t.fields.typ) == null) Error(t.pos, "undefined type '"+t.fields.typ+"'"); result = new Types.RECORD(t.fields.name,(Type)env.tenv.get(t.fields.typ),null); ArrayList<String> list = new ArrayList<String>(); list.add(t.fields.name.toString()); tmp = result; env.venv.beginScope(); for(Absyn.FieldList fieldList = t.fields.tail; fieldList != null; fieldList = fieldList.tail) { if (list.contains(fieldList.name.toString())) Error(t.pos, "Redefinition of field " + fieldList.name); else list.add(fieldList.name.toString()); Type p=(Type)env.tenv.get(fieldList.typ); if (p==null) Error(t.pos, "undefined type '"+fieldList.typ+"'"); env.venv.put(fieldList.name, new VarEntry(p)); tmp.tail = new Types.RECORD(fieldList.name,p,null); tmp = tmp.tail; } env.venv.endScope(); return result; } Type transTy(Absyn.ArrayTy t) { Type type = (Type) (env.tenv.get(t.typ)); if (type == null) { Error(t.pos, "Undefined type " + t.typ.toString()); return INT; } return new Types.ARRAY(type); } // EEEEEEEEEEEEEEEEEEEEEE // EE::::::EEEEEEEEE::::E // E:::::E EEEEEExxxxxxx xxxxxxxppppp ppppppppp // E:::::E x:::::x x:::::x p::::ppp:::::::::p // E::::::EEEEEEEEEE x:::::x x:::::x p:::::::::::::::::p // E:::::::::::::::E x:::::xx:::::x pp::::::ppppp::::::p // E:::::::::::::::E x::::::::::x p:::::p p:::::p // E::::::EEEEEEEEEE x::::::::x p:::::p p:::::p // E:::::E x::::::::x p:::::p p:::::p // E:::::E EEEEEE x::::::::::x p:::::p p::::::p // EE::::::EEEEEEEE:::::E x:::::xx:::::x p:::::ppppp:::::::p // E::::::::::::::::::::E x:::::x x:::::x p::::::::::::::::p // E::::::::::::::::::::E x:::::x x:::::x p::::::::::::::pp // EEEEEEEEEEEEEEEEEEEEEExxxxxxx xxxxxxx p::::::pppppppp // ppppppppp ExpTy transExp(Absyn.Exp e) { ExpTy result; if (e instanceof Absyn.VarExp) result = transExp((Absyn.VarExp)e); if (e instanceof Absyn.NilExp) result = transExp((Absyn.NilExp)e); if (e instanceof Absyn.IntExp) result = transExp((Absyn.IntExp)e); if (e instanceof Absyn.StringExp) result = transExp((Absyn.StringExp)e); if (e instanceof Absyn.CallExp) result = transExp((Absyn.CallExp)e); if (e instanceof Absyn.OpExp) result = transExp((Absyn.OpExp)e); if (e instanceof Absyn.RecordExp) result = transExp((Absyn.RecordExp)e); if (e instanceof Absyn.SeqExp) result = transExp((Absyn.SeqExp)e); if (e instanceof Absyn.AssignExp) result = transExp((Absyn.AssignExp)e); if (e instanceof Absyn.IfExp) result = transExp((Absyn.IfExp)e); if (e instanceof Absyn.WhileExp) result = transExp((Absyn.WhileExp)e); if (e instanceof Absyn.ForExp) result = transExp((Absyn.ForExp)e); if (e instanceof Absyn.BreakExp) result = transExp((Absyn.BreakExp)e); if (e instanceof Absyn.LetExp) result = transExp((Absyn.LetExp)e); if (e instanceof Absyn.ArrayExp) result = transExp((Absyn.ArrayExp)e); return new ExpTy(null, new Types.VOID()); } ExpTy transExp(Absyn.IntExp e) { return new ExpTy(null, new Types.INT()); } ExpTy transExp(Absyn.StringExp e) { return new ExpTy(null, new Types.STRING()); } ExpTy transExp(Absyn.NilExp e) { return new ExpTy(null, new Types.NIL()); } ExpTy transExp(Absyn.VarExp e) { return transVar(e.var); } ExpTy transExp(Absyn.SeqExp e){ if (e == null || e.list == null) return new ExpTy(null, new Types.VOID()); ExpTy type = null; for (Absyn.ExpList seq = e.list; seq != null; seq = seq.tail) type = transExp(seq.head); return type; } ExpTy transExp(Absyn.ArrayExp e){ ExpTy index = transExp(e.size); if (!(index.ty instanceof Types.INT)) Error(e.pos, "Index NAN."); Type type = (Type)env.tenv.get(e.typ); if (!(type instanceof Types.NAME) || !(type.actual() instanceof Types.ARRAY)){ Error(e.pos, "Invalid array: " + e.typ); return index; } Type arr = type; if (type instanceof Types.NAME) arr = type.actual(); if (arr instanceof Types.ARRAY) { if (!((Types.ARRAY)arr).element.coerceTo(transExp(e.init).ty)) Error(e.pos, "Mismatched array types."); } return new ExpTy(null, arr); } ExpTy transExp(Absyn.RecordExp e){ Type type = (Type)env.tenv.get(e.typ); if (type instanceof Types.NAME) { Types.RECORD rec = (Types.RECORD)type.actual(); Absyn.FieldExpList f = e.fields; for(;rec != null && f != null; rec = rec.tail, f = f.tail){ if (!f.name.equals(rec.fieldName)) Error(e.pos, "undefined field '" + f.name+"'"); Type ftype = rec.fieldType; if (rec.fieldType instanceof Types.NAME) ftype=((Types.NAME)rec.fieldType).actual(); if (!ftype.coerceTo(transExp(f.init).ty) && !(transExp(f.init).ty instanceof Types.NIL)) Error(e.pos, "unmatched type '" + rec.fieldName + "'"); } if (rec != null || f != null) Error(e.pos, "unmatched type"); return new ExpTy(null, type); } else Error(e.pos, "undefined type '" + e.typ + "'"); return new ExpTy(null, new Types.VOID()); } ExpTy transExp(Absyn.OpExp e) { ExpTy left = transExp(e.left); ExpTy right = transExp(e.right); switch (e.oper) { case Absyn.OpExp.PLUS: case Absyn.OpExp.MINUS: case Absyn.OpExp.MUL: case Absyn.OpExp.DIV: if (!(left.ty.coerceTo(INT) && right.ty.coerceTo(INT))) Error(e.pos, "Illegal operator. Integer required on both sides."); return new ExpTy(null, new Types.INT()); case Absyn.OpExp.EQ: case Absyn.OpExp.NE: case Absyn.OpExp.LT: case Absyn.OpExp.LE: case Absyn.OpExp.GT: case Absyn.OpExp.GE: if (left.ty.coerceTo(INT) && right.ty.coerceTo(INT) || (left.ty.coerceTo(STRING) && right.ty.coerceTo(STRING)) || (left.ty.coerceTo(right.ty) && right.ty.actual() instanceof Types.ARRAY) || (left.ty.coerceTo(right.ty) && right.ty.actual() instanceof Types.RECORD) || (left.ty.coerceTo(NIL) && right.ty.actual() instanceof Types.RECORD) || (left.ty.actual() instanceof Types.RECORD && right.ty.coerceTo(NIL)) || ((left.ty instanceof Types.INT) && (right.ty instanceof Types.INT)) || (left.ty instanceof Types.STRING) && (right.ty instanceof Types.STRING)) Error(e.pos, "Comparison between non-alike types."); return new ExpTy(null, new Types.INT()); default: Error(e.pos, "Illegal operator."); return new ExpTy(null, new Types.INT()); } } ExpTy transExp(Absyn.AssignExp e){ ExpTy var = transVar(e.var); if (var.ty instanceof Types.NAME) var.ty = var.ty.actual(); if (env.venv.get(((Absyn.SimpleVar)e.var).name) instanceof LoopVarEntry) { Error(e.var.pos, "Loop variable cannot be assigned."); return new ExpTy(null, new Types.VOID()); } ExpTy exp = transExp(e.exp); if (exp.ty instanceof Types.NAME) exp.ty = exp.ty.actual(); if (!(var.ty.coerceTo(exp.ty) || (var.ty instanceof Types.RECORD && exp.ty instanceof Types.NIL))){ Error(e.pos, "Type mismatch"); } return new ExpTy(null, new Types.VOID()); } ExpTy transExp(Absyn.BreakExp e) { return new ExpTy(null, new Types.VOID()); } ExpTy transExp(Absyn.CallExp e) { Entry call = (Entry)env.venv.get(e.func); if (call == null) { Error(e.pos, "Undefined function: " + e.func); return new ExpTy(null, new Types.VOID()); } if (call instanceof FunEntry) { FunEntry func = (FunEntry)call; Types.RECORD formals = func.formals; Absyn.ExpList explist = e.args; int index = 1; for(;formals!=null && explist!=null; formals = formals.tail, explist = explist.tail) { ExpTy type = transExp(explist.head); if (!type.ty.coerceTo(formals.fieldType)) Error(e.pos, "Mismatch on parameter " + index); index++; } if (!(formals == null && explist == null)) Error(e.pos, "Function parameter mismatch."); return new ExpTy(null, func.result); } else { Error(e.pos, "Unknown call to function."); return new ExpTy(null, ((VarEntry)call).ty); } } ExpTy transExp(Absyn.LetExp e){ env.venv.beginScope(); env.tenv.beginScope(); ArrayList<String> list = new ArrayList<String>(); for(Absyn.DecList temp = e.decs; temp != null; temp = temp.tail) { Absyn.Dec head = temp.head; if (head instanceof Absyn.TypeDec){ Absyn.TypeDec td=(Absyn.TypeDec)head; if (list.contains(td.name.toString())) env.errorMsg.error(td.pos, "type '"+td.name+"' has been already defined"); list.add(td.name.toString()); env.tenv.put(td.name,new Types.NAME(td.name)); } if (head instanceof Absyn.FunctionDec){ Absyn.FunctionDec fd=(Absyn.FunctionDec)head; Type result = transTy(fd.result); Types.RECORD rc = transTypeFields(fd.params); if (list.contains(fd.name.toString())) env.errorMsg.error(fd.pos, "function '"+fd.name+"' has been already defined"); else{ list.add(fd.name.toString()); env.venv.put(fd.name, new FunEntry(rc,result)); } } } for(Absyn.DecList temp = e.decs; temp != null; temp = temp.tail) { Absyn.Dec head = temp.head; if (head instanceof Absyn.TypeDec) { Absyn.TypeDec td=(Absyn.TypeDec)head; ((Types.NAME)env.tenv.get(td.name)).bind(transTy(td.ty)); } } list.clear(); for(Absyn.DecList p = e.decs; p != null; p = p.tail) transDec(p.head); ExpTy et = transExp(e.body); env.venv.endScope(); env.tenv.endScope(); if (e.body == null) return new ExpTy(null, new Types.VOID()); return new ExpTy(null, et.ty); } ExpTy transExp(Absyn.IfExp e) { ExpTy if_exp = transExp(e.test); if (!(if_exp.ty instanceof Types.INT)) Error(e.pos, "The test part must return an integer"); ExpTy then = transExp(e.thenclause); if (e.elseclause != null) { ExpTy else_clause = transExp(e.elseclause); if (!then.ty.coerceTo(else_clause.ty)) { if (!(then.ty instanceof Types.NIL || else_clause.ty instanceof Types.NIL)) Error(e.pos, "'if --then' expression must return same type"); } return else_clause; } if (!(then.ty instanceof Types.VOID)) Error(e.pos, "'if --then' expression must return the type Types.VOID"); return new ExpTy(null, new Types.VOID()); } ExpTy transExp(Absyn.WhileExp e) { ExpTy while_exp = transExp(e.test); if (!(while_exp.ty instanceof Types.INT)) Error(e.pos, "The test part must return an integer"); ExpTy t = transExp(e.body); if (!(t.ty instanceof Types.VOID)) Error(e.pos, "'while' expression must return the type Types.VOID"); return new ExpTy(null, new Types.VOID()); } ExpTy transExp(Absyn.ForExp e) { env.venv.beginScope(); transDec(e.var); Entry for_exp = (Entry)env.venv.get(e.var.name); if (!(for_exp instanceof VarEntry)) Error(e.pos, "'"+e.var.name+"' isn't a variable"); else { if (!(((VarEntry)for_exp).ty instanceof Types.INT)) Error(e.pos, "'"+e.var.name+"' must be an integer"); } ExpTy et = transExp(e.hi); if (!(et.ty instanceof Types.INT)) Error(e.pos, "An integer must follow 'to'"); ExpTy ey = transExp(e.body); env.venv.endScope(); if (!(ey.ty instanceof Types.VOID)) Error(e.pos, "'for' expression must return the type Types.VOID"); return new ExpTy(null,new Types.VOID()); } }
package com.plugin.core; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.text.TextUtils; import android.util.Base64; import com.plugin.core.stub.ui.PluginStubActivity; import com.plugin.util.LogUtil; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * stub */ public class PluginStubBinding { public static final String STUB_ACTIVITY_PRE = PluginStubActivity.class.getPackage().getName(); private static final String ACTION_LAUNCH_MODE = "com.plugin.core.LAUNCH_MODE"; private static final String ACTION_STUB_SERVICE = "com.plugin.core.STUB_SERVICE"; /** * key:stub Activity Name * value:plugin Activity Name */ private static HashMap<String, String> singleTaskMapping = new HashMap<String, String>(); private static HashMap<String, String> singleTopMapping = new HashMap<String, String>(); private static HashMap<String, String> singleInstanceMapping = new HashMap<String, String>(); /** * key:stub Service Name * value:plugin Service Name */ private static HashMap<String, String> serviceMapping = new HashMap<String, String>(); private static boolean isPoolInited = false; public static String bindLaunchModeStubActivity(String pluginActivityClassName, int launchMode) { initPool(); HashMap<String, String> bindingMapping = null; if (launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) { bindingMapping = singleTaskMapping; } else if (launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) { bindingMapping = singleTopMapping; } else if (launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) { bindingMapping = singleInstanceMapping; } if (bindingMapping != null) { Iterator<Map.Entry<String, String>> itr = bindingMapping.entrySet().iterator(); String idleStubActivityName = null; while (itr.hasNext()) { Map.Entry<String, String> entry = itr.next(); if (entry.getValue() == null) { if (idleStubActivityName == null) { idleStubActivityName = entry.getKey(); //stubactivitypluginActivityClassName } } else if (pluginActivityClassName.equals(entry.getValue())) { return entry.getKey(); } } //StubActivitystubActivity if (idleStubActivityName != null) { bindingMapping.put(idleStubActivityName, pluginActivityClassName); return idleStubActivityName; } } return PluginStubActivity.class.getName(); } private static void initPool() { if (isPoolInited) { return; } loadStubActivity(); loadStubService(); isPoolInited = true; } private static void loadStubActivity() { Intent launchModeIntent = new Intent(); launchModeIntent.setAction(ACTION_LAUNCH_MODE); launchModeIntent.setPackage(PluginLoader.getApplicatoin().getPackageName()); List<ResolveInfo> list = PluginLoader.getApplicatoin().getPackageManager().queryIntentActivities(launchModeIntent, PackageManager.MATCH_DEFAULT_ONLY); if (list != null && list.size() >0) { for (ResolveInfo resolveInfo: list) { if (resolveInfo.activityInfo.name.startsWith(STUB_ACTIVITY_PRE)) { if (resolveInfo.activityInfo.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) { singleTaskMapping.put(resolveInfo.activityInfo.name, null); } else if (resolveInfo.activityInfo.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) { singleTopMapping.put(resolveInfo.activityInfo.name, null); } else if (resolveInfo.activityInfo.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) { singleInstanceMapping.put(resolveInfo.activityInfo.name, null); } } } } } private static void loadStubService() { Intent launchModeIntent = new Intent(); launchModeIntent.setAction(ACTION_STUB_SERVICE); launchModeIntent.setPackage(PluginLoader.getApplicatoin().getPackageName()); List<ResolveInfo> list = PluginLoader.getApplicatoin().getPackageManager().queryIntentServices(launchModeIntent, PackageManager.MATCH_DEFAULT_ONLY); if (list != null && list.size() >0) { for (ResolveInfo resolveInfo: list) { serviceMapping.put(resolveInfo.serviceInfo.name, null); } HashMap<String, String> mapping = restore(); if (mapping != null) { serviceMapping.putAll(mapping); save(serviceMapping); } } } public static void unBindLaunchModeStubActivity(String activityName, Intent intent) { if (activityName.startsWith(PluginStubBinding.STUB_ACTIVITY_PRE)) { if (intent != null) { ComponentName cn = intent.getComponent(); if (cn != null) { String pluginActivityName = cn.getClassName(); if (pluginActivityName.equals(singleTaskMapping.get(activityName))) { singleTaskMapping.put(activityName, null); } else if (pluginActivityName.equals(singleInstanceMapping.get(activityName))) { singleInstanceMapping.put(activityName, null); } else { //standardsingleToplaunchmode } } } } } public static String getBindedPluginServiceName(String stubServiceName) { Iterator<Map.Entry<String, String>> itr = serviceMapping.entrySet().iterator(); while (itr.hasNext()) { Map.Entry<String, String> entry = itr.next(); if (entry.getKey().equals(stubServiceName)) { return entry.getValue(); } } HashMap<String, String> mapping = restore(); if (mapping != null) { itr = mapping.entrySet().iterator(); while (itr.hasNext()) { Map.Entry<String, String> entry = itr.next(); if (entry.getKey().equals(stubServiceName)) { serviceMapping.put(stubServiceName, entry.getValue()); save(serviceMapping); return entry.getValue(); } } } return null; } public static String bindStubService(String pluginServiceClassName) { initPool(); Iterator<Map.Entry<String, String>> itr = serviceMapping.entrySet().iterator(); String idleStubServiceName = null; while (itr.hasNext()) { Map.Entry<String, String> entry = itr.next(); if (entry.getValue() == null) { if (idleStubServiceName == null) { idleStubServiceName = entry.getKey(); //idleStubServiceNamepluginActivityClassName } } else if (pluginServiceClassName.equals(entry.getValue())) { LogUtil.d("", entry.getKey(), pluginServiceClassName); return entry.getKey(); } } //StubServiceStubService if (idleStubServiceName != null) { LogUtil.d("", idleStubServiceName, pluginServiceClassName); serviceMapping.put(idleStubServiceName, pluginServiceClassName); //serviceMappingserviceappcrashservicecrash save(serviceMapping); return idleStubServiceName; } return null; } public static void unBindStubService(String pluginServiceName) { Iterator<Map.Entry<String, String>> itr = serviceMapping.entrySet().iterator(); while (itr.hasNext()) { Map.Entry<String, String> entry = itr.next(); if (pluginServiceName.equals(entry.getValue())) { LogUtil.d("", entry.getKey(), entry.getValue()); serviceMapping.put(entry.getKey(), null); save(serviceMapping); entry.getKey(); } } } private static boolean save(HashMap<String, String> mapping) { ObjectOutputStream objectOutputStream = null; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try { objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(mapping); objectOutputStream.flush(); byte[] data = byteArrayOutputStream.toByteArray(); String list = Base64.encodeToString(data, Base64.DEFAULT); PluginLoader.getApplicatoin() .getSharedPreferences("plugins.serviceMapping", Context.MODE_PRIVATE) .edit().putString("plugins.serviceMapping.map", list).commit(); return true; } catch (Exception e) { e.printStackTrace(); } finally { if (objectOutputStream != null) { try { objectOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (byteArrayOutputStream != null) { try { byteArrayOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return false; } private static HashMap<String, String> restore() { String list = PluginLoader.getApplicatoin() .getSharedPreferences("plugins.serviceMapping", Context.MODE_PRIVATE) .getString("plugins.serviceMapping.map", ""); Serializable object = null; if (!TextUtils.isEmpty(list)) { ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( Base64.decode(list, Base64.DEFAULT)); ObjectInputStream objectInputStream = null; try { objectInputStream = new ObjectInputStream(byteArrayInputStream); object = (Serializable) objectInputStream.readObject(); } catch (Exception e) { e.printStackTrace(); } finally { if (objectInputStream != null) { try { objectInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (byteArrayInputStream != null) { try { byteArrayInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } if (object != null) { HashMap<String, String> mapping = (HashMap<String, String>) object; return mapping; } return null; } }
package com.dmdirc.addons.osd; import com.dmdirc.DMDircMBassador; import com.dmdirc.addons.ui_swing.UIUtilities; import com.dmdirc.addons.ui_swing.injection.MainWindow; import com.dmdirc.config.prefs.CategoryChangeListener; import com.dmdirc.config.prefs.PluginPreferencesCategory; import com.dmdirc.config.prefs.PreferencesCategory; import com.dmdirc.config.prefs.PreferencesDialogModel; import com.dmdirc.config.prefs.PreferencesInterface; import com.dmdirc.config.prefs.PreferencesSetting; import com.dmdirc.config.prefs.PreferencesType; import com.dmdirc.config.prefs.SettingChangeListener; import com.dmdirc.events.ClientPrefsOpenedEvent; import com.dmdirc.interfaces.config.IdentityController; import com.dmdirc.plugins.PluginDomain; import com.dmdirc.plugins.PluginInfo; import com.dmdirc.ui.messages.ColourManager; import com.dmdirc.ui.messages.ColourManagerFactory; import com.dmdirc.util.validators.NumericalValidator; import com.dmdirc.util.validators.OptionalValidator; import java.awt.Window; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import javax.inject.Inject; import net.engio.mbassy.listener.Handler; /** * Class to manage OSD Windows. */ public class OsdManager implements CategoryChangeListener, PreferencesInterface, SettingChangeListener { /** The frame the OSD will be associated with. */ private final Window mainFrame; /** List of OSD Windows. */ private final List<OsdWindow> windowList = new ArrayList<>(); /** List of messages to be queued. */ private final Queue<QueuedMessage> windowQueue = new LinkedList<>(); /** This plugin's settings domain. */ private final String domain; /** Config OSD Window. */ private OsdWindow osdWindow; /** X-axis position of OSD. */ private int x; /** Y-axis potion of OSD. */ private int y; /** Setting objects with registered change listeners. */ private PreferencesSetting fontSizeSetting; private PreferencesSetting backgroundSetting; private PreferencesSetting foregroundSetting; private PreferencesSetting widthSetting; private PreferencesSetting timeoutSetting; private PreferencesSetting maxWindowsSetting; /** This plugin's plugin info. */ private final PluginInfo pluginInfo; private final DMDircMBassador eventBus; /** The controller to read/write settings with. */ private final IdentityController identityController; /** The manager to use to parse colours. */ private final ColourManager colourManager; @Inject public OsdManager( @MainWindow final Window mainFrame, final DMDircMBassador eventBus, final IdentityController identityController, final ColourManagerFactory colourManagerFactory, @PluginDomain(OsdPlugin.class) final PluginInfo pluginInfo) { this.mainFrame = mainFrame; this.eventBus = eventBus; this.identityController = identityController; this.colourManager = colourManagerFactory.getColourManager(identityController.getGlobalConfiguration()); this.pluginInfo = pluginInfo; this.domain = pluginInfo.getDomain(); } /** * Add messages to the queue and call displayWindows. * * @param timeout Time message will be displayed * @param message Message to be displayed. */ public void showWindow(final int timeout, final String message) { windowQueue.add(new QueuedMessage(timeout, message)); displayWindows(); } /** * Displays as many windows as appropriate. */ private synchronized void displayWindows() { final Integer maxWindows = identityController.getGlobalConfiguration() .getOptionInt(domain, "maxWindows", false); QueuedMessage nextItem; while ((maxWindows == null || getWindowCount() < maxWindows) && (nextItem = windowQueue.poll()) != null) { displayWindow(nextItem.getTimeout(), nextItem.getMessage()); } } /** * Create a new OSD window with "message". * <p> * This method needs to be synchronised to ensure that the window list is not modified in * between the invocation of * {@link OsdPolicy#getYPosition(OsdManager, int)} and the point at which * the {@link OsdWindow} is added to the windowList. * * @see OsdPolicy#getYPosition(OsdManager, int) * @param message Text to display in the OSD window. */ private synchronized void displayWindow(final int timeout, final String message) { final OsdPolicy policy = OsdPolicy.valueOf( identityController.getGlobalConfiguration().getOption(domain, "newbehaviour") .toUpperCase()); final int startY = identityController.getGlobalConfiguration() .getOptionInt(domain, "locationY"); windowList.add(UIUtilities.invokeAndWait(() -> new OsdWindow( mainFrame, identityController, this, colourManager, timeout, message, false, identityController.getGlobalConfiguration().getOptionInt( domain, "locationX"), policy.getYPosition(this, startY), domain))); } /** * Destroy the given OSD Window and check if the Queue has items, if so Display them. * * @param window The window that we are destroying. */ public synchronized void closeWindow(final OsdWindow window) { final OsdPolicy policy = OsdPolicy.valueOf( identityController.getGlobalConfiguration() .getOption(domain, "newbehaviour").toUpperCase()); int oldY = window.getDesiredY(); final int closedIndex = windowList.indexOf(window); if (closedIndex == -1) { return; } windowList.remove(window); UIUtilities.invokeLater(window::dispose); final List<OsdWindow> newList = getWindowList(); for (OsdWindow otherWindow : newList.subList(closedIndex, newList.size())) { final int currentY = otherWindow.getDesiredY(); if (policy.changesPosition()) { otherWindow.setDesiredLocation(otherWindow.getDesiredX(), oldY); oldY = currentY; } } displayWindows(); } /** * Destroy all OSD Windows. */ public void closeAll() { getWindowList().forEach(this::closeWindow); } /** * Get the list of current OSDWindows. * * @return a List of all currently open OSDWindows. */ public List<OsdWindow> getWindowList() { return new ArrayList<>(windowList); } /** * Get the count of open windows. * * @return Current number of OSD Windows open. */ public int getWindowCount() { return windowList.size(); } @Handler public void showConfig(final ClientPrefsOpenedEvent event) { final PreferencesDialogModel manager = event.getModel(); x = identityController.getGlobalConfiguration() .getOptionInt(domain, "locationX"); y = identityController.getGlobalConfiguration() .getOptionInt(domain, "locationY"); final PreferencesCategory category = new PluginPreferencesCategory( pluginInfo, "OSD", "General configuration for OSD plugin.", "category-osd"); fontSizeSetting = new PreferencesSetting(PreferencesType.INTEGER, domain, "fontSize", "Font size", "Changes the font " + "size of the OSD", manager.getConfigManager(), manager.getIdentity()).registerChangeListener(this); backgroundSetting = new PreferencesSetting(PreferencesType.COLOUR, domain, "bgcolour", "Background colour", "Background colour for the OSD", manager.getConfigManager(), manager.getIdentity()).registerChangeListener(this); foregroundSetting = new PreferencesSetting(PreferencesType.COLOUR, domain, "fgcolour", "Foreground colour", "Foreground colour for the OSD", manager.getConfigManager(), manager.getIdentity()).registerChangeListener(this); widthSetting = new PreferencesSetting(PreferencesType.INTEGER, domain, "width", "OSD Width", "Width of the OSD Window", manager.getConfigManager(), manager.getIdentity()) .registerChangeListener(this); timeoutSetting = new PreferencesSetting(PreferencesType.OPTIONALINTEGER, new OptionalValidator(new NumericalValidator(1, Integer.MAX_VALUE)), domain, "timeout", "Timeout", "Length of time in " + "seconds before the OSD window closes", manager.getConfigManager(), manager.getIdentity()); maxWindowsSetting = new PreferencesSetting(PreferencesType.OPTIONALINTEGER, new OptionalValidator(new NumericalValidator(1, Integer.MAX_VALUE)), domain, "maxWindows", "Maximum open windows", "Maximum number of OSD windows that will be displayed at any given time", manager.getConfigManager(), manager.getIdentity()); category.addSetting(fontSizeSetting); category.addSetting(backgroundSetting); category.addSetting(foregroundSetting); category.addSetting(widthSetting); category.addSetting(timeoutSetting); category.addSetting(maxWindowsSetting); final Map<String, String> posOptions = new HashMap<>(); //Populate policy MULTICHOICE for (OsdPolicy policy : OsdPolicy.values()) { posOptions.put(policy.name(), policy.getDescription()); } category.addSetting(new PreferencesSetting(domain, "newbehaviour", "New window policy", "What to do when an OSD Window " + "is opened when there are other, existing windows open", posOptions, manager.getConfigManager(), manager.getIdentity())); category.addChangeListener(this); manager.getCategory("Plugins").addSubCategory(category); manager.registerSaveListener(this); } @Override public void categorySelected(final PreferencesCategory category) { osdWindow = new OsdWindow(mainFrame, identityController, this, colourManager, -1, "Please drag this OSD to position", true, x, y, domain); osdWindow.setBackgroundColour(backgroundSetting.getValue()); osdWindow.setForegroundColour(foregroundSetting.getValue()); osdWindow.setFontSize(Integer.parseInt(fontSizeSetting.getValue())); } @Override public void categoryDeselected(final PreferencesCategory category) { x = osdWindow.getLocationOnScreen().x; y = osdWindow.getLocationOnScreen().y; osdWindow.dispose(); osdWindow = null; } @Override public void save() { identityController.getUserSettings().setOption(domain, "locationX", x); identityController.getUserSettings().setOption(domain, "locationY", y); } @Override public void settingChanged(final PreferencesSetting setting) { if (osdWindow == null) { // They've changed categories but are somehow poking settings. // Ignore the request. return; } if (setting.equals(fontSizeSetting)) { osdWindow.setFontSize(Integer.parseInt(setting.getValue())); } else if (setting.equals(backgroundSetting)) { osdWindow.setBackgroundColour(setting.getValue()); } else if (setting.equals(foregroundSetting)) { osdWindow.setForegroundColour(setting.getValue()); } else if (setting.equals(widthSetting)) { int width = 500; try { width = Integer.parseInt(setting.getValue()); } catch (NumberFormatException e) { //Ignore } osdWindow.setSize(width, osdWindow.getHeight()); } } public void onLoad() { eventBus.subscribe(this); } public void onUnload() { eventBus.unsubscribe(this); } }
package biomodel.gui.comp; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URI; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import org.sbml.jsbml.ext.comp.CompModelPlugin; import org.sbml.jsbml.ext.comp.CompSBasePlugin; import org.sbml.jsbml.ext.comp.Deletion; import org.sbml.jsbml.ext.comp.ReplacedBy; import org.sbml.jsbml.ext.comp.ReplacedElement; import org.sbml.jsbml.ext.comp.CompConstants; import org.sbml.jsbml.SBase; import org.sbml.jsbml.ext.comp.Submodel; import biomodel.annotation.AnnotationUtility; import biomodel.annotation.SBOLAnnotation; import biomodel.gui.sbol.SBOLField; import biomodel.gui.schematic.ModelEditor; import biomodel.gui.util.PropertyField; import biomodel.gui.util.PropertyList; import biomodel.parser.BioModel; import biomodel.util.GlobalConstants; import biomodel.util.SBMLutilities; import biomodel.util.Utility; import main.Gui; public class ComponentsPanel extends JPanel implements ActionListener { private static final long serialVersionUID = 1L; private String selected = ""; private String[] options = { "Ok", "Cancel" }; private ArrayList<String> portIds = null; private ArrayList<String> idRefs = null; private ArrayList<String> types = null; private ArrayList<JComboBox> portmapBox = null; private ArrayList<JComboBox> directionBox = null; private ArrayList<JComboBox> convBox = null; private BioModel bioModel = null; private PropertyList componentsList = null; private HashMap<String, PropertyField> fields = null; private SBOLField sbolField; private String selectedComponent, oldPort; private ModelEditor modelEditor; private String subModelId; private JComboBox timeConvFactorBox; private JComboBox extentConvFactorBox; private boolean paramsOnly; private BioModel subBioModel; public ComponentsPanel(String selected, PropertyList componentsList, BioModel bioModel, BioModel subBioModel, ArrayList<String> ports, String selectedComponent, String oldPort, boolean paramsOnly, ModelEditor gcmEditor) { super(new GridLayout(ports.size() + 6, 1)); this.selected = selected; this.componentsList = componentsList; this.bioModel = bioModel; this.modelEditor = gcmEditor; this.selectedComponent = selectedComponent; this.oldPort = oldPort; this.paramsOnly = paramsOnly; this.subBioModel = subBioModel; //this.setPreferredSize(new Dimension(800, 600)); fields = new HashMap<String, PropertyField>(); portIds = new ArrayList<String>(); idRefs = new ArrayList<String>(); types = new ArrayList<String>(); portmapBox = new ArrayList<JComboBox>(); directionBox = new ArrayList<JComboBox>(); convBox = new ArrayList<JComboBox>(); String[] directions = new String[2]; directions[0] = "< directions[1] = " if (bioModel.isGridEnabled()) { subModelId = "GRID__" + selectedComponent.replace(".xml",""); } else { subModelId = selected; } ArrayList <String> constParameterList = bioModel.getConstantUserParameters(); Collections.sort(constParameterList); String[] parameters = new String[constParameterList.size()+1]; parameters[0] = "(none)"; for (int l = 1; l < parameters.length; l++) { parameters[l] = constParameterList.get(l-1); } timeConvFactorBox = new JComboBox(parameters); extentConvFactorBox = new JComboBox(parameters); ArrayList <String> compartmentList = bioModel.getCompartments(); Collections.sort(compartmentList); String[] compsWithNone = new String[compartmentList.size() + 2]; compsWithNone[0] = "--none compsWithNone[1] = "--delete for (int l = 2; l < compsWithNone.length; l++) { compsWithNone[l] = compartmentList.get(l - 2); } for (int i = 0; i < ports.size(); i++) { String type = ports.get(i).split(":")[0]; String portId = ports.get(i).split(":")[1]; String idRef = ports.get(i).split(":")[2]; if (type.equals(GlobalConstants.COMPARTMENT)) { portIds.add(portId); idRefs.add(idRef); types.add(type); JComboBox port = new JComboBox(compsWithNone); portmapBox.add(port); JComboBox dirport = new JComboBox(directions); directionBox.add(dirport); JComboBox convFactor = new JComboBox(parameters); convBox.add(convFactor); } } ArrayList <String> parameterList = bioModel.getParameters(); Collections.sort(parameterList); String[] paramsWithNone = new String[parameterList.size() + 2]; paramsWithNone[0] = "--none paramsWithNone[1] = "--delete for (int l = 2; l < paramsWithNone.length; l++) { paramsWithNone[l] = parameterList.get(l - 2); } for (int i = 0; i < ports.size(); i++) { String type = ports.get(i).split(":")[0]; String portId = ports.get(i).split(":")[1]; String idRef = ports.get(i).split(":")[2]; if (type.equals(GlobalConstants.PARAMETER) || type.equals(GlobalConstants.LOCALPARAMETER)) { portIds.add(portId); idRefs.add(idRef); types.add(type); JComboBox port = new JComboBox(paramsWithNone); portmapBox.add(port); JComboBox dirport = new JComboBox(directions); directionBox.add(dirport); JComboBox convFactor = new JComboBox(parameters); convBox.add(convFactor); } } ArrayList <String> booleanList = bioModel.getBooleans(); Collections.sort(booleanList); String[] boolsWithNone = new String[booleanList.size() + 2]; boolsWithNone[0] = "--none boolsWithNone[1] = "--delete for (int l = 2; l < boolsWithNone.length; l++) { boolsWithNone[l] = booleanList.get(l - 2); } for (int i = 0; i < ports.size(); i++) { String type = ports.get(i).split(":")[0]; String portId = ports.get(i).split(":")[1]; String idRef = ports.get(i).split(":")[2]; if (type.equals(GlobalConstants.BOOLEAN)) { portIds.add(portId); idRefs.add(idRef); types.add(type); JComboBox port = new JComboBox(boolsWithNone); portmapBox.add(port); JComboBox dirport = new JComboBox(directions); directionBox.add(dirport); JComboBox convFactor = new JComboBox(parameters); convBox.add(convFactor); } } ArrayList <String> placeList = bioModel.getPlaces(); Collections.sort(placeList); String[] placesWithNone = new String[placeList.size() + 2]; placesWithNone[0] = "--none placesWithNone[1] = "--delete for (int l = 2; l < placesWithNone.length; l++) { placesWithNone[l] = placeList.get(l - 2); } for (int i = 0; i < ports.size(); i++) { String type = ports.get(i).split(":")[0]; String portId = ports.get(i).split(":")[1]; String idRef = ports.get(i).split(":")[2]; if (type.equals(GlobalConstants.PLACE)) { portIds.add(portId); idRefs.add(idRef); types.add(type); JComboBox port = new JComboBox(placesWithNone); portmapBox.add(port); JComboBox dirport = new JComboBox(directions); directionBox.add(dirport); JComboBox convFactor = new JComboBox(parameters); convBox.add(convFactor); } } ArrayList <String> speciesList = bioModel.getSpecies(); Collections.sort(speciesList); String[] specsWithNone = new String[speciesList.size() + 2]; specsWithNone[0] = "--none specsWithNone[1] = "--delete for (int l = 2; l < specsWithNone.length; l++) { specsWithNone[l] = speciesList.get(l - 2); } for (int i = 0; i < ports.size(); i++) { String type = ports.get(i).split(":")[0]; String portId = ports.get(i).split(":")[1]; String idRef = ports.get(i).split(":")[2]; if (type.equals(GlobalConstants.SBMLSPECIES)) { portIds.add(portId); idRefs.add(idRef); types.add(type); JComboBox port = new JComboBox(specsWithNone); portmapBox.add(port); JComboBox dirport = new JComboBox(directions); directionBox.add(dirport); JComboBox convFactor = new JComboBox(parameters); convBox.add(convFactor); } } ArrayList <String> promoterList = bioModel.getPromoters(); Collections.sort(promoterList); String[] promsWithNone = new String[promoterList.size() + 2]; promsWithNone[0] = "--none promsWithNone[1] = "--delete for (int l = 2; l < promsWithNone.length; l++) { promsWithNone[l] = promoterList.get(l - 2); } for (int i = 0; i < ports.size(); i++) { String type = ports.get(i).split(":")[0]; String portId = ports.get(i).split(":")[1]; String idRef = ports.get(i).split(":")[2]; if (type.equals(GlobalConstants.PROMOTER)) { portIds.add(portId); idRefs.add(idRef); types.add(type); JComboBox port = new JComboBox(promsWithNone); portmapBox.add(port); JComboBox dirport = new JComboBox(directions); directionBox.add(dirport); JComboBox convFactor = new JComboBox(parameters); convBox.add(convFactor); } } ArrayList <String> reactionList = bioModel.getReactions(); Collections.sort(reactionList); String[] reactionsWithNone = new String[reactionList.size() + 2]; reactionsWithNone[0] = "--none reactionsWithNone[1] = "--delete for (int l = 2; l < reactionsWithNone.length; l++) { reactionsWithNone[l] = reactionList.get(l - 2); } for (int i = 0; i < ports.size(); i++) { String type = ports.get(i).split(":")[0]; String portId = ports.get(i).split(":")[1]; String idRef = ports.get(i).split(":")[2]; if (type.equals(GlobalConstants.SBMLREACTION)) { portIds.add(portId); idRefs.add(idRef); types.add(type); JComboBox port = new JComboBox(reactionsWithNone); portmapBox.add(port); JComboBox dirport = new JComboBox(directions); directionBox.add(dirport); JComboBox convFactor = new JComboBox(parameters); convBox.add(convFactor); } } ArrayList <String> functionList = bioModel.getFunctions(); Collections.sort(functionList); String[] functionsWithNone = new String[functionList.size() + 2]; functionsWithNone[0] = "--none functionsWithNone[1] = "--delete for (int l = 2; l < functionsWithNone.length; l++) { functionsWithNone[l] = functionList.get(l - 2); } for (int i = 0; i < ports.size(); i++) { String type = ports.get(i).split(":")[0]; String portId = ports.get(i).split(":")[1]; String idRef = ports.get(i).split(":")[2]; if (type.equals(GlobalConstants.FUNCTION)) { portIds.add(portId); idRefs.add(idRef); types.add(type); JComboBox port = new JComboBox(functionsWithNone); portmapBox.add(port); JComboBox dirport = new JComboBox(directions); directionBox.add(dirport); JComboBox convFactor = new JComboBox(parameters); convBox.add(convFactor); } } ArrayList <String> unitList = bioModel.getUnits(); Collections.sort(unitList); String[] unitsWithNone = new String[unitList.size() + 2]; unitsWithNone[0] = "--none unitsWithNone[1] = "--delete for (int l = 2; l < unitsWithNone.length; l++) { unitsWithNone[l] = unitList.get(l - 2); } for (int i = 0; i < ports.size(); i++) { String type = ports.get(i).split(":")[0]; String portId = ports.get(i).split(":")[1]; String idRef = ports.get(i).split(":")[2]; if (type.equals(GlobalConstants.UNIT)) { portIds.add(portId); idRefs.add(idRef); types.add(type); JComboBox port = new JComboBox(unitsWithNone); portmapBox.add(port); JComboBox dirport = new JComboBox(directions); directionBox.add(dirport); JComboBox convFactor = new JComboBox(parameters); convBox.add(convFactor); } } ArrayList <String> ruleList = bioModel.getAlgebraicRules(); Collections.sort(ruleList); String[] rulesWithNone = new String[ruleList.size() + 2]; rulesWithNone[0] = "--none rulesWithNone[1] = "--delete for (int l = 2; l < rulesWithNone.length; l++) { rulesWithNone[l] = ruleList.get(l - 2); } for (int i = 0; i < ports.size(); i++) { String type = ports.get(i).split(":")[0]; String portId = ports.get(i).split(":")[1]; String idRef = ports.get(i).split(":")[2]; if (type.equals(GlobalConstants.ALGEBRAIC_RULE)) { portIds.add(portId); idRefs.add(idRef); types.add(type); JComboBox port = new JComboBox(rulesWithNone); portmapBox.add(port); JComboBox dirport = new JComboBox(directions); directionBox.add(dirport); JComboBox convFactor = new JComboBox(parameters); convFactor.setEnabled(false); convBox.add(convFactor); } } ruleList = bioModel.getAssignmentRules(); Collections.sort(ruleList); rulesWithNone = new String[ruleList.size() + 2]; rulesWithNone[0] = "--none rulesWithNone[1] = "--delete for (int l = 2; l < rulesWithNone.length; l++) { rulesWithNone[l] = ruleList.get(l - 2); } for (int i = 0; i < ports.size(); i++) { String type = ports.get(i).split(":")[0]; String portId = ports.get(i).split(":")[1]; String idRef = ports.get(i).split(":")[2]; if (type.equals(GlobalConstants.ASSIGNMENT_RULE)) { portIds.add(portId); idRefs.add(idRef); types.add(type); JComboBox port = new JComboBox(rulesWithNone); portmapBox.add(port); JComboBox dirport = new JComboBox(directions); directionBox.add(dirport); JComboBox convFactor = new JComboBox(parameters); convFactor.setEnabled(false); convBox.add(convFactor); } } ruleList = bioModel.getRateRules(); Collections.sort(ruleList); rulesWithNone = new String[ruleList.size() + 2]; rulesWithNone[0] = "--none rulesWithNone[1] = "--delete for (int l = 2; l < rulesWithNone.length; l++) { rulesWithNone[l] = ruleList.get(l - 2); } for (int i = 0; i < ports.size(); i++) { String type = ports.get(i).split(":")[0]; String portId = ports.get(i).split(":")[1]; String idRef = ports.get(i).split(":")[2]; if (type.equals(GlobalConstants.RATE_RULE)) { portIds.add(portId); idRefs.add(idRef); types.add(type); JComboBox port = new JComboBox(rulesWithNone); portmapBox.add(port); JComboBox dirport = new JComboBox(directions); directionBox.add(dirport); JComboBox convFactor = new JComboBox(parameters); convFactor.setEnabled(false); convBox.add(convFactor); } } ArrayList <String> constraintList = bioModel.getConstraints(); Collections.sort(constraintList); String[] constraintsWithNone = new String[constraintList.size() + 2]; constraintsWithNone[0] = "--none constraintsWithNone[1] = "--delete for (int l = 2; l < constraintsWithNone.length; l++) { constraintsWithNone[l] = constraintList.get(l - 2); } for (int i = 0; i < ports.size(); i++) { String type = ports.get(i).split(":")[0]; String portId = ports.get(i).split(":")[1]; String idRef = ports.get(i).split(":")[2]; if (type.equals(GlobalConstants.CONSTRAINT)) { portIds.add(portId); idRefs.add(idRef); types.add(type); JComboBox port = new JComboBox(constraintsWithNone); portmapBox.add(port); JComboBox dirport = new JComboBox(directions); directionBox.add(dirport); JComboBox convFactor = new JComboBox(parameters); convFactor.setEnabled(false); convBox.add(convFactor); } } ArrayList <String> eventList = bioModel.getEvents(); Collections.sort(eventList); String[] eventsWithNone = new String[eventList.size() + 2]; eventsWithNone[0] = "--none eventsWithNone[1] = "--delete for (int l = 2; l < eventsWithNone.length; l++) { eventsWithNone[l] = eventList.get(l - 2); } for (int i = 0; i < ports.size(); i++) { String type = ports.get(i).split(":")[0]; String portId = ports.get(i).split(":")[1]; String idRef = ports.get(i).split(":")[2]; if (type.equals(GlobalConstants.EVENT)) { portIds.add(portId); idRefs.add(idRef); types.add(type); JComboBox port = new JComboBox(eventsWithNone); portmapBox.add(port); JComboBox dirport = new JComboBox(directions); directionBox.add(dirport); JComboBox convFactor = new JComboBox(parameters); convFactor.setEnabled(false); convBox.add(convFactor); } } ArrayList <String> transitionList = bioModel.getTransitions(); Collections.sort(transitionList); String[] transWithNone = new String[transitionList.size() + 2]; transWithNone[0] = "--none transWithNone[1] = "--delete for (int l = 2; l < transWithNone.length; l++) { transWithNone[l] = transitionList.get(l - 2); } for (int i = 0; i < ports.size(); i++) { String type = ports.get(i).split(":")[0]; String portId = ports.get(i).split(":")[1]; String idRef = ports.get(i).split(":")[2]; if (type.equals(GlobalConstants.TRANSITION)) { portIds.add(portId); idRefs.add(idRef); types.add(type); JComboBox port = new JComboBox(transWithNone); portmapBox.add(port); JComboBox dirport = new JComboBox(directions); directionBox.add(dirport); JComboBox convFactor = new JComboBox(parameters); convFactor.setEnabled(false); convBox.add(convFactor); } } String[] Choices = new String[2]; Choices[0] = "--include Choices[1] = "--delete for (int i = 0; i < ports.size(); i++) { String type = ports.get(i).split(":")[0]; String portId = ports.get(i).split(":")[1]; String idRef = ports.get(i).split(":")[2]; if (!type.equals(GlobalConstants.COMPARTMENT) && !type.equals(GlobalConstants.PARAMETER) && !type.equals(GlobalConstants.LOCALPARAMETER) && !type.equals(GlobalConstants.EVENT) && !type.equals(GlobalConstants.SBMLSPECIES) && !type.equals(GlobalConstants.SBMLREACTION) && !type.equals(GlobalConstants.FUNCTION) && !type.equals(GlobalConstants.UNIT) && !type.equals(GlobalConstants.ASSIGNMENT_RULE) && !type.equals(GlobalConstants.RATE_RULE) && !type.equals(GlobalConstants.ALGEBRAIC_RULE) && !type.equals(GlobalConstants.CONSTRAINT) && !type.equals(GlobalConstants.PROMOTER) && !type.equals(GlobalConstants.BOOLEAN) && !type.equals(GlobalConstants.PLACE) && !type.equals(GlobalConstants.TRANSITION)) { portIds.add(portId); idRefs.add(idRef.replace("init__","")); types.add(type); JComboBox port = new JComboBox(Choices); portmapBox.add(port); JComboBox dirport = new JComboBox(directions); dirport.setEnabled(false); directionBox.add(dirport); JComboBox convFactor = new JComboBox(parameters); convBox.add(convFactor); } } Submodel instance = bioModel.getSBMLCompModel().getListOfSubmodels().get(subModelId); // ID field PropertyField field = new PropertyField(GlobalConstants.ID, "", null, null, Utility.IDDimString, paramsOnly, "default", false); fields.put(GlobalConstants.ID, field); add(field); // Name field if (instance != null) { field = new PropertyField(GlobalConstants.NAME, instance.getName(), null, null, Utility.NAMEstring, paramsOnly, "default", false); } else { field = new PropertyField(GlobalConstants.NAME, "", null, null, Utility.NAMEstring, paramsOnly, "default", false); } fields.put(GlobalConstants.NAME, field); add(field); JLabel timeConvFactorLabel = new JLabel("Time Conversion Factor"); JLabel extentConvFactorLabel = new JLabel("Extent Conversion Factor"); JPanel timePanel = new JPanel(); timePanel.setLayout(new GridLayout(1, 2)); JPanel extentPanel = new JPanel(); extentPanel.setLayout(new GridLayout(1, 2)); timePanel.add(timeConvFactorLabel); timePanel.add(timeConvFactorBox); extentPanel.add(extentConvFactorLabel); extentPanel.add(extentConvFactorBox); if (instance != null && instance.isSetTimeConversionFactor()) { timeConvFactorBox.setSelectedItem(instance.getTimeConversionFactor()); } if (instance != null && instance.isSetExtentConversionFactor()) { extentConvFactorBox.setSelectedItem(instance.getExtentConversionFactor()); } add(timePanel); add(extentPanel); // Parse out SBOL annotations and add to SBOL field if(!paramsOnly) { // Field for annotating submodel with SBOL DNA components List<URI> sbolURIs = new LinkedList<URI>(); String sbolStrand = AnnotationUtility.parseSBOLAnnotation(instance, sbolURIs); sbolField = new SBOLField(sbolURIs, sbolStrand, GlobalConstants.SBOL_DNA_COMPONENT, gcmEditor, 2, false); add(sbolField); } // Port Map field JPanel headingPanel = new JPanel(); JLabel typeLabel = new JLabel("Type"); JLabel portLabel = new JLabel("Port"); JLabel dirLabel = new JLabel("Direction"); JLabel replLabel = new JLabel("Replacement"); JLabel convLabel = new JLabel("Conversion"); headingPanel.setLayout(new GridLayout(1, 5)); headingPanel.add(typeLabel); headingPanel.add(portLabel); headingPanel.add(dirLabel); headingPanel.add(replLabel); headingPanel.add(convLabel); if (portIds.size()>0) { add(headingPanel); } //add(new JLabel("Ports")); for (int i = 0; i < portIds.size(); i++) { JPanel tempPanel = new JPanel(); JLabel tempLabel = new JLabel(idRefs.get(i)); JLabel tempLabel2 = new JLabel(types.get(i)); tempPanel.setLayout(new GridLayout(1, 5)); tempPanel.add(tempLabel2); tempPanel.add(tempLabel); tempPanel.add(directionBox.get(i)); tempPanel.add(portmapBox.get(i)); tempPanel.add(convBox.get(i)); add(tempPanel); directionBox.get(i).addActionListener(this); portmapBox.get(i).addActionListener(this); } if (instance!=null) { for (int j = 0; j < instance.getListOfDeletions().size(); j++) { Deletion deletion = instance.getListOfDeletions().get(j); int l = portIds.indexOf(deletion.getPortRef()); if (l >= 0) { portmapBox.get(l).setSelectedItem("--delete } } } ArrayList<SBase> elements = SBMLutilities.getListOfAllElements(bioModel.getSBMLDocument().getModel()); for (int j = 0; j < elements.size(); j++) { SBase sbase = elements.get(j); CompSBasePlugin sbmlSBase = (CompSBasePlugin)sbase.getExtension(CompConstants.namespaceURI); if (sbmlSBase!=null) { if (sbase.getElementName().equals(GlobalConstants.ASSIGNMENT_RULE)|| sbase.getElementName().equals(GlobalConstants.RATE_RULE)|| sbase.getElementName().equals(GlobalConstants.ALGEBRAIC_RULE)|| sbase.getElementName().equals(GlobalConstants.CONSTRAINT)) { getPortMap(sbmlSBase,sbase.getMetaId()); } else { getPortMap(sbmlSBase,SBMLutilities.getId(sbase)); } } } updateComboBoxEnabling(); String oldName = null; if (selected != null) { oldName = selected; fields.get(GlobalConstants.ID).setValue(selected); } boolean display = false; while (!display) { display = openGui(oldName); } } private void updateComboBoxEnabling() { for (int i = 0; i < portmapBox.size(); i++) { if (portmapBox.get(i).getSelectedIndex()<2 && (directionBox.get(i).getSelectedIndex()!=0 || convBox.get(i).getSelectedIndex()!=0)) { directionBox.get(i).setSelectedIndex(0); directionBox.get(i).setEnabled(false); convBox.get(i).setSelectedIndex(0); convBox.get(i).setEnabled(false); } else if (portmapBox.get(i).getSelectedIndex()<2) { directionBox.get(i).setEnabled(false); convBox.get(i).setEnabled(false); } else if (directionBox.get(i).getSelectedIndex()==1 && convBox.get(i).getSelectedIndex()!=0) { directionBox.get(i).setEnabled(true); convBox.get(i).setSelectedIndex(0); convBox.get(i).setEnabled(false); } else if (directionBox.get(i).getSelectedIndex()==1) { directionBox.get(i).setEnabled(true); convBox.get(i).setEnabled(false); } else { directionBox.get(i).setEnabled(true); convBox.get(i).setEnabled(true); } } } private void getPortMap(CompSBasePlugin sbmlSBase,String id) { for (int k = 0; k < sbmlSBase.getListOfReplacedElements().size(); k++) { ReplacedElement replacement = sbmlSBase.getListOfReplacedElements().get(k); if (replacement.getSubmodelRef().equals(subModelId)) { if (replacement.isSetPortRef()) { int l = portIds.indexOf(replacement.getPortRef()); if (l >= 0) { portmapBox.get(l).setSelectedItem(id); if (!portmapBox.get(l).getSelectedItem().equals(id)) { portmapBox.get(l).addItem(id); portmapBox.get(l).setSelectedItem(id); } directionBox.get(l).setSelectedIndex(0); convBox.get(l).setSelectedIndex(0); if (replacement.isSetConversionFactor()) { convBox.get(l).setSelectedItem(replacement.getConversionFactor()); } } } else if (replacement.isSetDeletion()) { Deletion deletion = bioModel.getSBMLCompModel().getListOfSubmodels().get(subModelId).getListOfDeletions().get(replacement.getDeletion()); if (deletion!=null) { int l = portIds.indexOf(deletion.getPortRef()); if (l >= 0) { portmapBox.get(l).setSelectedItem(id); if (!portmapBox.get(l).getSelectedItem().equals(id)) { portmapBox.get(l).addItem(id); portmapBox.get(l).setSelectedItem(id); } directionBox.get(l).setSelectedIndex(0); convBox.get(l).setSelectedIndex(0); } } } } } if (sbmlSBase.isSetReplacedBy()) { ReplacedBy replacement = sbmlSBase.getReplacedBy(); if (replacement.getSubmodelRef().equals(subModelId)) { if (replacement.isSetPortRef()) { int l = portIds.indexOf(replacement.getPortRef()); if (l >= 0) { portmapBox.get(l).setSelectedItem(id); if (!portmapBox.get(l).getSelectedItem().equals(id)) { portmapBox.get(l).addItem(id); portmapBox.get(l).setSelectedItem(id); } directionBox.get(l).setSelectedIndex(1); convBox.get(l).setSelectedIndex(0); } } } } } private boolean checkValues() { for (PropertyField f : fields.values()) { if (!f.isValidValue()) { return false; } } return true; } private boolean removePortMaps(CompSBasePlugin sbmlSBase) { int j = 0; boolean result = false; while (j < sbmlSBase.getListOfReplacedElements().size()) { ReplacedElement replacement = sbmlSBase.getListOfReplacedElements().get(j); if (replacement.getSubmodelRef().equals(subModelId) && ((replacement.isSetPortRef())||(replacement.isSetDeletion()))) { sbmlSBase.removeReplacedElement(replacement); result = true; } j++; } if (sbmlSBase.isSetReplacedBy()) { ReplacedBy replacement = sbmlSBase.getReplacedBy(); if (replacement.getSubmodelRef().equals(subModelId) && (replacement.isSetPortRef())) { sbmlSBase.unsetReplacedBy(); result = true; } } return result; } private boolean openGui(String oldName) { int value = JOptionPane.showOptionDialog(Gui.frame, this, "Component Editor", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { if (!checkValues()) { Utility.createErrorMessage("Error", "Illegal values entered."); return false; } // TODO: extract id plus dimensios using checkSizeParameters String id = fields.get(GlobalConstants.ID).getValue(); if (oldName == null) { if (bioModel.isSIdInUse(id)) { Utility.createErrorMessage("Error", "Id already exists."); return false; } } else if (!oldName.equals(id)) { if (bioModel.isSIdInUse(id)) { Utility.createErrorMessage("Error", "Id already exists."); return false; } } // Checks whether SBOL annotation on model needs to be deleted later when annotating component with SBOL // boolean removeModelSBOLAnnotationFlag = false; // if (!paramsOnly && sbolField.getSBOLURIs().size() > 0 && // bioModel.getElementSBOLCount() == 0 && bioModel.getModelSBOLAnnotationFlag()) { // Object[] options = { "OK", "Cancel" }; // int choice = JOptionPane.showOptionDialog(null, // "SBOL associated to model elements can't coexist with SBOL associated to model itself unless" + // " the latter was previously generated from the former. Remove SBOL associated to model?", // "Warning", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]); // if (choice == JOptionPane.OK_OPTION) // removeModelSBOLAnnotationFlag = true; // else // return false; Submodel instance = bioModel.getSBMLCompModel().getListOfSubmodels().get(subModelId); if (instance != null) { instance.setName(fields.get(GlobalConstants.NAME).getValue()); // TODO: add/remove dimensions from the instance //long k = 0; while (instance.getListOfDeletions().size()>0) { Deletion deletion = instance.getListOfDeletions().get(0); instance.removeDeletion(deletion); /* if (deletion.isSetPortRef() && portIds.contains(deletion.getPortRef())) { } else { k++; } */ } if (timeConvFactorBox.getSelectedItem().equals("(none)")) { instance.unsetTimeConversionFactor(); } else { instance.setTimeConversionFactor((String)timeConvFactorBox.getSelectedItem()); } if (extentConvFactorBox.getSelectedItem().equals("(none)")) { instance.unsetExtentConversionFactor(); } else { instance.setExtentConversionFactor((String)extentConvFactorBox.getSelectedItem()); } } else { Utility.createErrorMessage("Error", "Submodel is missing."); return false; } ArrayList<SBase> elements = SBMLutilities.getListOfAllElements(bioModel.getSBMLDocument().getModel()); for (int j = 0; j < elements.size(); j++) { SBase sbase = elements.get(j); CompSBasePlugin sbmlSBase = (CompSBasePlugin)sbase.getExtension(CompConstants.namespaceURI); if (sbmlSBase!=null) { if (removePortMaps(sbmlSBase)) { elements = SBMLutilities.getListOfAllElements(bioModel.getSBMLDocument().getModel()); } } } for (int i = 0; i < portIds.size(); i++) { String subId = id; if (subModelId.startsWith("GRID__")) subId = subModelId; String portId = portIds.get(i); //String type = types.get(i); String portmapId = (String)portmapBox.get(i).getSelectedItem(); if (!portmapId.equals("--none--")&&!portmapId.equals("--delete--")&&!portmapId.equals("--include--")) { CompSBasePlugin sbmlSBase = null; SBase sbase = SBMLutilities.getElementBySId(bioModel.getSBMLDocument().getModel(), portmapId); if (sbase!=null) { sbmlSBase = (CompSBasePlugin)sbase.getExtension(CompConstants.namespaceURI); if (sbmlSBase != null) { if (directionBox.get(i).getSelectedIndex()==0) { ReplacedElement replacement = sbmlSBase.createReplacedElement(); replacement.setSubmodelRef(subId); replacement.setPortRef(portId); if (!convBox.get(i).getSelectedItem().equals("(none)")) { replacement.setConversionFactor((String)convBox.get(i).getSelectedItem()); } } else { boolean skip = false; if (sbmlSBase.isSetReplacedBy()) { ReplacedBy replacement = sbmlSBase.getReplacedBy(); if (!replacement.getSubmodelRef().equals(subId) || !replacement.getPortRef().equals(portId)) { Utility.createErrorMessage("Error", portmapId + " is already replaced by " + replacement.getPortRef().replace(GlobalConstants.INPUT+"__", "").replace(GlobalConstants.OUTPUT+"__", "") + " from subModel " + replacement.getSubmodelRef() + "\nCannot also replace with " + portId.replace(GlobalConstants.INPUT+"__", "").replace(GlobalConstants.OUTPUT+"__", "") + " from subModel " + subId); skip = true; } } if (!skip) { ReplacedBy replacement = sbmlSBase.createReplacedBy(); replacement.setSubmodelRef(subId); replacement.setPortRef(portId); } } } } else { sbase = SBMLutilities.getElementByMetaId(bioModel.getSBMLDocument().getModel(), portmapId); sbmlSBase = (CompSBasePlugin)sbase.getExtension(CompConstants.namespaceURI); if (sbmlSBase != null) { if (directionBox.get(i).getSelectedIndex()==0) { /* TODO: Code below uses just a replacement */ ReplacedElement replacement = sbmlSBase.createReplacedElement(); replacement.setSubmodelRef(subId); replacement.setPortRef(portId); if (!convBox.get(i).getSelectedItem().equals("(none)")) { replacement.setConversionFactor((String)convBox.get(i).getSelectedItem()); } String speciesId = portId.replace(GlobalConstants.INPUT+"__", "").replace(GlobalConstants.OUTPUT+"__", ""); CompModelPlugin subCompModel = subBioModel.getSBMLCompModel(); Submodel submodel = bioModel.getSBMLCompModel().getListOfSubmodels().get(subId); BioModel.addImplicitDeletions(subCompModel, submodel, speciesId); /* Code below using replacement and deletion */ /* ReplacedElement replacement = sbmlSBase.createReplacedElement(); replacement.setSubmodelRef(subId); Submodel submodel = bioModel.getSBMLCompModel().getListOfSubmodels().get(subId); Deletion deletion = submodel.createDeletion(); deletion.setPortRef(portId); deletion.setId("delete_"+portId); replacement.setDeletion("delete_"+portId); */ } else { ReplacedBy replacement = sbmlSBase.createReplacedBy(); replacement.setSubmodelRef(subId); replacement.setPortRef(portId); String speciesId = portId.replace(GlobalConstants.INPUT+"__", "").replace(GlobalConstants.OUTPUT+"__", ""); CompModelPlugin subCompModel = subBioModel.getSBMLCompModel(); Submodel submodel = bioModel.getSBMLCompModel().getListOfSubmodels().get(subId); bioModel.addImplicitReplacedBys(subCompModel,submodel,speciesId,SBMLutilities.getId(sbase)); } } } } else if (portmapId.equals("--delete Submodel submodel = bioModel.getSBMLCompModel().getListOfSubmodels().get(subId); Deletion deletion = submodel.createDeletion(); deletion.setPortRef(portId); String speciesId = portId.replace(GlobalConstants.INPUT+"__", "").replace(GlobalConstants.OUTPUT+"__", ""); CompModelPlugin subCompModel = subBioModel.getSBMLCompModel(); BioModel.addImplicitDeletions(subCompModel, submodel, speciesId); } } if (selected != null && oldName != null && !oldName.equals(id)) { bioModel.changeComponentName(oldName, id); } String newPort = bioModel.getComponentPortMap(id); componentsList.removeItem(oldName + " " + selectedComponent.replace(".xml", "") + " " + oldPort); componentsList.addItem(id + " " + selectedComponent.replace(".xml", "") + " " + newPort); componentsList.setSelectedValue(id + " " + selectedComponent.replace(".xml", "") + " " + newPort, true); if (!paramsOnly) { // Add SBOL annotation to submodel if (sbolField.getSBOLURIs().size() > 0 || sbolField.getSBOLStrand().equals(GlobalConstants.SBOL_ASSEMBLY_MINUS_STRAND)) { SBOLAnnotation sbolAnnot = new SBOLAnnotation(instance.getMetaId(), sbolField.getSBOLURIs(), sbolField.getSBOLStrand()); AnnotationUtility.setSBOLAnnotation(instance, sbolAnnot); } else AnnotationUtility.removeSBOLAnnotation(instance); } modelEditor.setDirty(true); } else if (value == JOptionPane.NO_OPTION) { return true; } return true; } @Override public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("comboBoxChanged")) { updateComboBoxEnabling(); } } }
package example; //-*- mode:java; encoding:utf8n; coding:utf-8 -*- // vim:set fileencoding=utf-8: //@homepage@ import java.awt.*; import java.awt.event.*; import java.util.*; import java.util.List; import javax.swing.*; import javax.swing.event.EventListenerList; public class MainPanel extends JPanel{ private Box northBox = Box.createVerticalBox(); private Box centerBox = Box.createVerticalBox(); private Box southBox = Box.createVerticalBox(); public MainPanel() { super(new BorderLayout()); JPanel panel = new JPanel(new BorderLayout()); final List<ExpansionPanel> panelList = makeList(); ExpansionListener rl = new ExpansionListener() { public void expansionStateChanged(ExpansionEvent e) { initComps(panelList, e); } }; for(ExpansionPanel exp: panelList) { northBox.add(exp); exp.addExpansionListener(rl); } panel.add(northBox, BorderLayout.NORTH); panel.add(centerBox); panel.add(southBox, BorderLayout.SOUTH); panel.setMinimumSize(new Dimension(120, 0)); JSplitPane sp = new JSplitPane(); sp.setLeftComponent(panel); sp.setRightComponent(new JScrollPane(new JTree())); add(sp); setPreferredSize(new Dimension(320, 240)); } public void initComps(List<ExpansionPanel> list, ExpansionEvent e) { setVisible(false); centerBox.removeAll(); northBox.removeAll(); southBox.removeAll(); ExpansionPanel es = (ExpansionPanel) e.getSource(); boolean insertSouth = false; for(ExpansionPanel exp: list) { if(exp==es && exp.isSelected()) { centerBox.add(exp); insertSouth = true; }else if(insertSouth) { exp.setSelected(false); southBox.add(exp); }else{ exp.setSelected(false); northBox.add(exp); } } setVisible(true); } private List<ExpansionPanel> makeList() { return Arrays.<ExpansionPanel>asList( new ExpansionPanel("Panel1") { public Container makePanel() { Box p = Box.createVerticalBox(); p.setBorder(BorderFactory.createEmptyBorder(5, 15, 5, 15)); p.add(new JCheckBox("aaaa")); p.add(new JCheckBox("bbbbbbbbb")); return p; } }, new ExpansionPanel("Panel2") { public Container makePanel() { Box p = Box.createVerticalBox(); p.setBorder(BorderFactory.createEmptyBorder(5, 15, 5, 15)); for(int i=0;i<16;i++) p.add(new JLabel(String.format("%02d", i))); return p; } }, new ExpansionPanel("Panel3") { public Container makePanel() { Box p = Box.createVerticalBox(); p.setBorder(BorderFactory.createEmptyBorder(5, 15, 5, 15)); ButtonGroup bg = new ButtonGroup(); for(JRadioButton b: Arrays.<JRadioButton>asList( new JRadioButton("aa"), new JRadioButton("bb"), new JRadioButton("cc"))) { p.add(b); bg.add(b); b.setSelected(true); } return p; } }); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowGUI(); } }); } public static void createAndShowGUI() { try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }catch(Exception e) { e.printStackTrace(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } abstract class ExpansionPanel extends JPanel { abstract public Container makePanel(); private final JButton button; private final Container panel; private final JScrollPane scroll; private final String title; private boolean openFlag = false; public ExpansionPanel(String title) { super(new BorderLayout()); this.title = title; button = new JButton(new AbstractAction(title) { @Override public void actionPerformed(ActionEvent e) { setSelected(!isSelected()); fireExpansionEvent(); } }); panel = makePanel(); scroll = new JScrollPane(panel); scroll.getVerticalScrollBar().setUnitIncrement(25); add(button, BorderLayout.NORTH); } public boolean isSelected() { return openFlag; } public void setSelected(boolean flg) { openFlag = flg; if(openFlag) { add(scroll); }else{ remove(scroll); } } /*/ //*/
package org.zstack.compute.host; import org.springframework.beans.factory.annotation.Autowired; import org.zstack.core.componentloader.PluginRegistry; import org.zstack.header.Component; import org.zstack.header.core.Completion; import org.zstack.header.errorcode.ErrorCode; import org.zstack.header.errorcode.OperationFailureException; import org.zstack.header.host.*; import org.zstack.utils.CollectionUtils; import org.zstack.utils.Utils; import org.zstack.utils.function.ForEachFunction; import org.zstack.utils.logging.CLogger; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class HostExtensionPointEmitter implements Component { private static final CLogger logger = Utils.getLogger(HostExtensionPointEmitter.class); @Autowired private PluginRegistry pluginRgty; private List<HostPingTaskExtensionPoint> pingTaskExts = new ArrayList<>(); private List<HostDeleteExtensionPoint> deleteHostExts = new ArrayList<>(); private List<HostChangeStateExtensionPoint> changeStateExts = new ArrayList<>(); private List<HostConnectionReestablishExtensionPoint> connetionReestablishExts = new ArrayList<>(); private List<HostAddExtensionPoint> addHostExts = new ArrayList<>(); public void preDelete(HostInventory hinv) throws HostException { for (HostDeleteExtensionPoint extp : deleteHostExts) { extp.preDeleteHost(hinv); } } public void preChange(HostVO vo, HostStateEvent event) throws HostException { HostState next = vo.getState().nextState(event); HostInventory hinv = HostInventory.valueOf(vo); for (HostChangeStateExtensionPoint extp : changeStateExts) { extp.preChangeHostState(hinv, event, next); } } public void preChange(List<HostVO> vos, HostStateEvent event) throws HostException { for (HostVO vo : vos) { preChange(vo, event); } } public void beforeChange(HostVO vo, final HostStateEvent event) { final HostInventory hinv = HostInventory.valueOf(vo); final HostState next = vo.getState().nextState(event); CollectionUtils.safeForEach(changeStateExts, new ForEachFunction<HostChangeStateExtensionPoint>() { @Override public void run(HostChangeStateExtensionPoint extp) { extp.beforeChangeHostState(hinv, event, next); } }); } public void afterChange(HostVO vo, final HostStateEvent event, final HostState prevState) { final HostInventory hinv = HostInventory.valueOf(vo); CollectionUtils.safeForEach(changeStateExts, new ForEachFunction<HostChangeStateExtensionPoint>() { @Override public void run(HostChangeStateExtensionPoint extp) { extp.afterChangeHostState(hinv, event, prevState); } }); } public void beforeDelete(final HostInventory hinv) { CollectionUtils.safeForEach(deleteHostExts, new ForEachFunction<HostDeleteExtensionPoint>() { @Override public void run(HostDeleteExtensionPoint extp) { extp.beforeDeleteHost(hinv); } }); } public void afterDelete(final HostInventory hinv) { CollectionUtils.safeForEach(deleteHostExts, new ForEachFunction<HostDeleteExtensionPoint>() { @Override public void run(HostDeleteExtensionPoint extp) { extp.afterDeleteHost(hinv); } }); } public void hostPingTask(final HypervisorType type, final HostInventory inv) { CollectionUtils.safeForEach(pingTaskExts, new ForEachFunction<HostPingTaskExtensionPoint>() { @Override public void run(HostPingTaskExtensionPoint ext) { if (ext.getHypervisorType().equals(type)) { ext.executeTaskAlongWithPingTask(inv); } } }); } public void connectionReestablished(HypervisorType hvType, HostInventory host) throws HostException { for (HostConnectionReestablishExtensionPoint ext : connetionReestablishExts) { if (ext.getHypervisorTypeForReestablishExtensionPoint().equals(hvType)) { ext.connectionReestablished(host); } } } private void beforeAddHost(final Iterator<HostAddExtensionPoint> it, final HostInventory host, final Completion completion) { if (!it.hasNext()) { completion.success(); return; } HostAddExtensionPoint ext = it.next(); ext.beforeAddHost(host, new Completion(completion) { @Override public void success() { beforeAddHost(it, host, completion); } @Override public void fail(ErrorCode errorCode) { completion.fail(errorCode); } }); } public void beforeAddHost(HostInventory host, Completion completion) { if (addHostExts.isEmpty()) { completion.success(); return; } beforeAddHost(addHostExts.iterator(), host, completion); } public void afterAddHost(HostInventory host, Completion completion) { if (addHostExts.isEmpty()) { completion.success(); return; } afterAddHost(addHostExts.iterator(), host, completion); } private void afterAddHost(final Iterator<HostAddExtensionPoint> it, final HostInventory host, final Completion completion) { if (!it.hasNext()) { completion.success(); return; } HostAddExtensionPoint ext = it.next(); ext.afterAddHost(host, new Completion(completion) { @Override public void success() { afterAddHost(it, host, completion); } @Override public void fail(ErrorCode errorCode) { completion.fail(errorCode); } }); } private void populateExtensions() { pingTaskExts = pluginRgty.getExtensionList(HostPingTaskExtensionPoint.class); deleteHostExts = pluginRgty.getExtensionList(HostDeleteExtensionPoint.class); changeStateExts = pluginRgty.getExtensionList(HostChangeStateExtensionPoint.class); connetionReestablishExts = pluginRgty.getExtensionList(HostConnectionReestablishExtensionPoint.class); addHostExts = pluginRgty.getExtensionList(HostAddExtensionPoint.class); } @Override public boolean start() { populateExtensions(); return true; } @Override public boolean stop() { return true; } }
package com.eegeo.flurry; import java.util.Map; import java.util.HashMap; import com.eegeo.entrypointinfrastructure.MainActivity; import com.flurry.android.FlurryAgent; public class FlurryWrapper { public static void begin(MainActivity activity, String apiKey, String appVersion) { if (apiKey.isEmpty()) return; FlurryAgent.setCaptureUncaughtExceptions(true); FlurryAgent.init(activity, apiKey); FlurryAgent.setVersionName(appVersion); } public static void setPosition(float latitude, float longitude) { FlurryAgent.setLocation(latitude, longitude); } public static void setEvent(String eventString) { FlurryAgent.logEvent(eventString); } public static void setEvent(String eventString, String key1, String value1) { Map<String, String> parameterMap = new HashMap<String, String>(); parameterMap.put(key1, value1); FlurryAgent.logEvent(eventString, parameterMap); } public static void setEvent(String eventString, String key1, String value1, String key2, String value2) { Map<String, String> parameterMap = new HashMap<String, String>(); parameterMap.put(key1, value1); parameterMap.put(key2, value2); FlurryAgent.logEvent(eventString, parameterMap); } public static void setEvent(String eventString, String key1, String value1, String key2, String value2, String key3, String value3) { Map<String, String> parameterMap = new HashMap<String, String>(); parameterMap.put(key1, value1); parameterMap.put(key2, value2); parameterMap.put(key3, value3); FlurryAgent.logEvent(eventString, parameterMap); } public static void beginTimedEvent(String eventString) { boolean isTimed = true; FlurryAgent.logEvent(eventString, isTimed); } public static void beginTimedEvent(String eventString, String key1, String value1) { boolean isTimed = true; Map<String, String> parameterMap = new HashMap<String, String>(); parameterMap.put(key1, value1); FlurryAgent.logEvent(eventString, parameterMap, isTimed); } public static void endTimedEvent(String eventString) { FlurryAgent.endTimedEvent(eventString); } public static void endTimedEvent(String eventString, String key1, String value1) { Map<String, String> parameterMap = new HashMap<String, String>(); parameterMap.put(key1, value1); FlurryAgent.endTimedEvent(eventString, parameterMap); } }
package com.mapswithme.maps; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceScreen; import android.util.Log; public class DownloadUI extends PreferenceActivity { private static String TAG = "DownloadUI"; private native int countriesCount(int group, int country, int region); private native int countryStatus(int group, int country, int region); private native long countryLocalSizeInBytes(int group, int country, int region); private native long countryRemoteSizeInBytes(int group, int country, int region); private native String countryName(int group, int country, int region); private native void nativeCreate(); private native void nativeDestroy(); private native void downloadCountry(int group, int country, int region); private native void deleteCountry(int group, int country, int region); private AlertDialog.Builder m_alert; private DialogInterface.OnClickListener m_alertCancelHandler = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dlg, int which) { dlg.dismiss(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Root PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this); setPreferenceScreen(createCountriesHierarchy(root, -1, -1, -1)); m_alert = new AlertDialog.Builder(this); m_alert.setCancelable(false); nativeCreate(); } @Override public void onDestroy() { super.onDestroy(); nativeDestroy(); } private String formatSizeString(long sizeInBytes) { if (sizeInBytes > 1024 * 1024) return sizeInBytes / (1024 * 1024) + "Mb"; else if ((sizeInBytes + 1023) / 1024 > 999) return "1Mb"; else return (sizeInBytes + 1023) / 1024 + "Kb"; } private void updateCountryCell(final Preference cell, int group, int country, int region) { final int status = countryStatus(group, country, region); switch (status) { case 0: // EOnDisk cell.setSummary("Downloaded (" + formatSizeString(countryLocalSizeInBytes(group, country, region)) + "), touch to delete"); break; case 1: // ENotDownloaded cell.setSummary("Touch to download");// + formatSizeString(countryRemoteSizeInBytes(group, country, region))); break; case 2: // EDownloadFailed cell.setSummary("Download has failed, touch again for one more try"); break; case 3: // EDownloading cell.setSummary("Downloading..."); break; case 4: // EInQueue cell.setSummary("Marked for downloading, touch to cancel"); break; case 5: // EUnknown cell.setSummary("Unknown state :("); break; } } public void onChangeCountry(int group, int country, int region) { final Preference cell = findPreference(group + " " + country + " " + region); if (cell == null) { Log.d(TAG, String.format("no preference found for %d %d %d", group, country, region)); return; } updateCountryCell(cell, group, country, region); } public void onProgress(int group, int country, int region, long current, long total) { final Preference c = findPreference(group + " " + country + " " + region); if (c == null) Log.d(TAG, String.format("no preference found for %d %d %d", group, country, region)); else c.setSummary("Downloading " + current * 100 / total + "%, touch to cancel"); } private Preference createElement(int group, int country, int region) { final String name = countryName(group, country, region); if (countriesCount(group, country, region) == 0) { // it's downloadable country element final CheckBoxPreference cell = new CheckBoxPreference(this); cell.setKey(group + " " + country + " " + region); cell.setTitle(name); updateCountryCell(cell, group, country, region); return cell; } else { // it's parent element for downloadable countries PreferenceScreen parent = getPreferenceManager().createPreferenceScreen(this); // parent.setKey(group + " " + country + " " + region); parent.setTitle(name); // parent.setSummary(""); return createCountriesHierarchy(parent, group, country, region); } } private PreferenceScreen createCountriesHierarchy(PreferenceScreen root, int group, int country, int region) { final int count = countriesCount(group, country, region); for (int i = 0; i < count; ++i) { if (group == -1) root.addPreference(createElement(i, country, region)); else if (country == -1) root.addPreference(createElement(group, i, region)); else if (region == -1) root.addPreference(createElement(group, country, i)); } return root; } @Override public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { if (preference.hasKey()) { final String[] keys = preference.getKey().split(" "); final int group = Integer.parseInt(keys[0]); final int country = Integer.parseInt(keys[1]); final int region = Integer.parseInt(keys[2]); switch (countryStatus(group, country, region)) { case 0: // EOnDisk m_alert.setTitle(countryName(group, country, region)); m_alert.setPositiveButton("Delete", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dlg, int which) { deleteCountry(group, country, region); dlg.dismiss(); } }); m_alert.setNegativeButton("Cancel", m_alertCancelHandler); m_alert.create().show(); break; case 1: // ENotDownloaded m_alert.setTitle(countryName(group, country, region)); m_alert.setPositiveButton("Download " + formatSizeString(countryRemoteSizeInBytes(group, country, region)), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dlg, int which) { downloadCountry(group, country, region); dlg.dismiss(); } }); m_alert.setNegativeButton("Cancel", m_alertCancelHandler); m_alert.create().show(); break; case 2: // EDownloadFailed // Do not confirm download if status is failed, just start it downloadCountry(group, country, region); break; case 3: // EDownloading /// Confirm canceling m_alert.setTitle(countryName(group, country, region)); m_alert.setPositiveButton("Cancel download", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dlg, int which) { deleteCountry(group, country, region); dlg.dismiss(); } }); m_alert.setNegativeButton("Do nothing", m_alertCancelHandler); m_alert.create().show(); break; case 4: // EInQueue // Silently discard country from the queue deleteCountry(group, country, region); break; case 5: // EUnknown Log.d(TAG, "Unknown country state"); break; } } return super.onPreferenceTreeClick(preferenceScreen, preference); } }
package it.innove; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothManager; import android.bluetooth.le.ScanRecord; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Build; import android.support.annotation.Nullable; import android.util.Log; import com.facebook.react.bridge.ActivityEventListener; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.WritableArray; import com.facebook.react.bridge.WritableMap; import com.facebook.react.modules.core.RCTNativeAppEventEmitter; import java.lang.reflect.Method; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import static android.app.Activity.RESULT_OK; import static android.bluetooth.BluetoothProfile.GATT; import static android.os.Build.VERSION_CODES.LOLLIPOP; class BleManager extends ReactContextBaseJavaModule implements ActivityEventListener { public static final String LOG_TAG = "ReactNativeBleManager"; private static final int ENABLE_REQUEST = 539; private class BondRequest { private String uuid; private Callback callback; BondRequest(String _uuid, Callback _callback) { uuid = _uuid; callback = _callback; } } private BluetoothAdapter bluetoothAdapter; private BluetoothManager bluetoothManager; private Context context; private ReactApplicationContext reactContext; private Callback enableBluetoothCallback; private ScanManager scanManager; private BondRequest bondRequest; private BondRequest removeBondRequest; // key is the MAC Address private final Map<String, Peripheral> peripherals = new LinkedHashMap<>(); // scan session id public BleManager(ReactApplicationContext reactContext) { super(reactContext); context = reactContext; this.reactContext = reactContext; reactContext.addActivityEventListener(this); Log.d(LOG_TAG, "BleManager created"); } @Override public String getName() { return "BleManager"; } private BluetoothAdapter getBluetoothAdapter() { if (bluetoothAdapter == null) { BluetoothManager manager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); bluetoothAdapter = manager.getAdapter(); } return bluetoothAdapter; } private BluetoothManager getBluetoothManager() { if (bluetoothManager == null) { bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); } return bluetoothManager; } public void sendEvent(String eventName, @Nullable WritableMap params) { getReactApplicationContext() .getJSModule(RCTNativeAppEventEmitter.class) .emit(eventName, params); } @ReactMethod public void start(ReadableMap options, Callback callback) { Log.d(LOG_TAG, "start"); if (getBluetoothAdapter() == null) { Log.d(LOG_TAG, "No bluetooth support"); callback.invoke("No bluetooth support"); return; } boolean forceLegacy = false; if (options.hasKey("forceLegacy")) { forceLegacy = options.getBoolean("forceLegacy"); } if (Build.VERSION.SDK_INT >= LOLLIPOP && !forceLegacy) { scanManager = new LollipopScanManager(reactContext, this); } else { scanManager = new LegacyScanManager(reactContext, this); } IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED); filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED); context.registerReceiver(mReceiver, filter); callback.invoke(); Log.d(LOG_TAG, "BleManager initialized"); } @ReactMethod public void enableBluetooth(Callback callback) { if (getBluetoothAdapter() == null) { Log.d(LOG_TAG, "No bluetooth support"); callback.invoke("No bluetooth support"); return; } if (!getBluetoothAdapter().isEnabled()) { enableBluetoothCallback = callback; Intent intentEnable = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); if (getCurrentActivity() == null) callback.invoke("Current activity not available"); else getCurrentActivity().startActivityForResult(intentEnable, ENABLE_REQUEST); } else callback.invoke(); } @ReactMethod public void scan(ReadableArray serviceUUIDs, final int scanSeconds, boolean allowDuplicates, ReadableMap options, Callback callback) { Log.d(LOG_TAG, "scan"); if (getBluetoothAdapter() == null) { Log.d(LOG_TAG, "No bluetooth support"); callback.invoke("No bluetooth support"); return; } if (!getBluetoothAdapter().isEnabled()) { return; } synchronized (peripherals) { for (Iterator<Map.Entry<String, Peripheral>> iterator = peripherals.entrySet().iterator(); iterator.hasNext(); ) { Map.Entry<String, Peripheral> entry = iterator.next(); if (!entry.getValue().isConnected()) { iterator.remove(); } } } if (scanManager != null) scanManager.scan(serviceUUIDs, scanSeconds, options, callback); } @ReactMethod public void stopScan(Callback callback) { Log.d(LOG_TAG, "Stop scan"); if (getBluetoothAdapter() == null) { Log.d(LOG_TAG, "No bluetooth support"); callback.invoke("No bluetooth support"); return; } if (!getBluetoothAdapter().isEnabled()) { callback.invoke(); return; } if (scanManager != null) scanManager.stopScan(callback); } @ReactMethod public void createBond(String peripheralUUID, Callback callback) { Log.d(LOG_TAG, "Request bond to: " + peripheralUUID); Set<BluetoothDevice> deviceSet = getBluetoothAdapter().getBondedDevices(); for (BluetoothDevice device : deviceSet) { if (peripheralUUID.equalsIgnoreCase(device.getAddress())) { callback.invoke(); return; } } Peripheral peripheral = retrieveOrCreatePeripheral(peripheralUUID); if (peripheral == null) { callback.invoke("Invalid peripheral uuid"); } else if (bondRequest != null) { callback.invoke("Only allow one bond request at a time"); } else if (peripheral.getDevice().createBond()) { bondRequest = new BondRequest(peripheralUUID, callback); // request bond success, waiting for boradcast return; } callback.invoke("Create bond request fail"); } @ReactMethod private void removeBond(String peripheralUUID, Callback callback) { Log.d(LOG_TAG, "Remove bond to: " + peripheralUUID); Peripheral peripheral = retrieveOrCreatePeripheral(peripheralUUID); if (peripheral == null) { callback.invoke("Invalid peripheral uuid"); return; } else { try { Method m = peripheral.getDevice().getClass().getMethod("removeBond", (Class[]) null); m.invoke(peripheral.getDevice(), (Object[]) null); removeBondRequest = new BondRequest(peripheralUUID, callback); return; } catch (Exception e) { Log.d(LOG_TAG, "Error in remove bond: " + peripheralUUID, e); callback.invoke("Remove bond request fail"); } } } @ReactMethod public void connect(String peripheralUUID, Callback callback) { Log.d(LOG_TAG, "Connect to: " + peripheralUUID); Peripheral peripheral = retrieveOrCreatePeripheral(peripheralUUID); if (peripheral == null) { callback.invoke("Invalid peripheral uuid"); return; } peripheral.connect(callback, getCurrentActivity()); } @ReactMethod public void disconnect(String peripheralUUID, boolean force, Callback callback) { Log.d(LOG_TAG, "Disconnect from: " + peripheralUUID); Peripheral peripheral = peripherals.get(peripheralUUID); if (peripheral != null) { peripheral.disconnect(force); callback.invoke(); } else callback.invoke("Peripheral not found"); } @ReactMethod public void startNotification(String deviceUUID, String serviceUUID, String characteristicUUID, Callback callback) { Log.d(LOG_TAG, "startNotification"); Peripheral peripheral = peripherals.get(deviceUUID); if (peripheral != null) { peripheral.registerNotify(UUIDHelper.uuidFromString(serviceUUID), UUIDHelper.uuidFromString(characteristicUUID), callback); } else callback.invoke("Peripheral not found"); } @ReactMethod public void stopNotification(String deviceUUID, String serviceUUID, String characteristicUUID, Callback callback) { Log.d(LOG_TAG, "stopNotification"); Peripheral peripheral = peripherals.get(deviceUUID); if (peripheral != null) { peripheral.removeNotify(UUIDHelper.uuidFromString(serviceUUID), UUIDHelper.uuidFromString(characteristicUUID), callback); } else callback.invoke("Peripheral not found"); } @ReactMethod public void write(String deviceUUID, String serviceUUID, String characteristicUUID, ReadableArray message, Integer maxByteSize, Callback callback) { Log.d(LOG_TAG, "Write to: " + deviceUUID); Peripheral peripheral = peripherals.get(deviceUUID); if (peripheral != null) { byte[] decoded = new byte[message.size()]; for (int i = 0; i < message.size(); i++) { decoded[i] = new Integer(message.getInt(i)).byteValue(); } Log.d(LOG_TAG, "Message(" + decoded.length + "): " + bytesToHex(decoded)); peripheral.write(UUIDHelper.uuidFromString(serviceUUID), UUIDHelper.uuidFromString(characteristicUUID), decoded, maxByteSize, null, callback, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT); } else callback.invoke("Peripheral not found"); } @ReactMethod public void writeWithoutResponse(String deviceUUID, String serviceUUID, String characteristicUUID, ReadableArray message, Integer maxByteSize, Integer queueSleepTime, Callback callback) { Log.d(LOG_TAG, "Write without response to: " + deviceUUID); Peripheral peripheral = peripherals.get(deviceUUID); if (peripheral != null) { byte[] decoded = new byte[message.size()]; for (int i = 0; i < message.size(); i++) { decoded[i] = new Integer(message.getInt(i)).byteValue(); } Log.d(LOG_TAG, "Message(" + decoded.length + "): " + bytesToHex(decoded)); peripheral.write(UUIDHelper.uuidFromString(serviceUUID), UUIDHelper.uuidFromString(characteristicUUID), decoded, maxByteSize, queueSleepTime, callback, BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE); } else callback.invoke("Peripheral not found"); } @ReactMethod public void read(String deviceUUID, String serviceUUID, String characteristicUUID, Callback callback) { Log.d(LOG_TAG, "Read from: " + deviceUUID); Peripheral peripheral = peripherals.get(deviceUUID); if (peripheral != null) { peripheral.read(UUIDHelper.uuidFromString(serviceUUID), UUIDHelper.uuidFromString(characteristicUUID), callback); } else callback.invoke("Peripheral not found", null); } @ReactMethod public void retrieveServices(String deviceUUID, ReadableArray services, Callback callback) { Log.d(LOG_TAG, "Retrieve services from: " + deviceUUID); Peripheral peripheral = peripherals.get(deviceUUID); if (peripheral != null) { peripheral.retrieveServices(callback); } else callback.invoke("Peripheral not found", null); } @ReactMethod public void refreshCache(String deviceUUID, Callback callback) { Log.d(LOG_TAG, "Refershing cache for: " + deviceUUID); Peripheral peripheral = peripherals.get(deviceUUID); if (peripheral != null) { peripheral.refreshCache(callback); } else callback.invoke("Peripheral not found"); } @ReactMethod public void readRSSI(String deviceUUID, Callback callback) { Log.d(LOG_TAG, "Read RSSI from: " + deviceUUID); Peripheral peripheral = peripherals.get(deviceUUID); if (peripheral != null) { peripheral.readRSSI(callback); } else callback.invoke("Peripheral not found", null); } private Peripheral savePeripheral(BluetoothDevice device) { String address = device.getAddress(); synchronized (peripherals) { if (!peripherals.containsKey(address)) { Peripheral peripheral = new Peripheral(device, reactContext); peripherals.put(device.getAddress(), peripheral); } } return peripherals.get(address); } Peripheral savePeripheral(BluetoothDevice device, int rssi, byte[] scanRecord) { String address = device.getAddress(); synchronized (peripherals) { if (!peripherals.containsKey(address)) { Peripheral peripheral = new Peripheral(device, rssi, scanRecord, reactContext); peripherals.put(device.getAddress(), peripheral); } else { Peripheral peripheral = peripherals.get(address); peripheral.updateRssi(rssi); peripheral.updateData(scanRecord); } } return peripherals.get(address); } Peripheral savePeripheral(BluetoothDevice device, int rssi, ScanRecord scanRecord) { String address = device.getAddress(); synchronized (peripherals) { if (!peripherals.containsKey(address)) { Peripheral peripheral = new Peripheral(device, rssi, scanRecord, reactContext); peripherals.put(device.getAddress(), peripheral); } else { Peripheral peripheral = peripherals.get(address); peripheral.updateRssi(rssi); peripheral.updateData(scanRecord); } } return peripherals.get(address); } @ReactMethod public void checkState() { Log.d(LOG_TAG, "checkState"); BluetoothAdapter adapter = getBluetoothAdapter(); String state = "off"; if (adapter != null) { switch (adapter.getState()) { case BluetoothAdapter.STATE_ON: state = "on"; break; case BluetoothAdapter.STATE_OFF: state = "off"; } } WritableMap map = Arguments.createMap(); map.putString("state", state); Log.d(LOG_TAG, "state:" + state); sendEvent("BleManagerDidUpdateState", map); } private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.d(LOG_TAG, "onReceive"); final String action = intent.getAction(); if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) { final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR); String stringState = ""; switch (state) { case BluetoothAdapter.STATE_OFF: stringState = "off"; break; case BluetoothAdapter.STATE_TURNING_OFF: stringState = "turning_off"; break; case BluetoothAdapter.STATE_ON: stringState = "on"; break; case BluetoothAdapter.STATE_TURNING_ON: stringState = "turning_on"; break; } WritableMap map = Arguments.createMap(); map.putString("state", stringState); Log.d(LOG_TAG, "state: " + stringState); sendEvent("BleManagerDidUpdateState", map); } else if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) { final int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR); final int prevState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR); BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); String bondStateStr = "UNKNOWN"; switch (bondState) { case BluetoothDevice.BOND_BONDED: bondStateStr = "BOND_BONDED"; break; case BluetoothDevice.BOND_BONDING: bondStateStr = "BOND_BONDING"; break; case BluetoothDevice.BOND_NONE: bondStateStr = "BOND_NONE"; break; } Log.d(LOG_TAG, "bond state: " + bondStateStr); if (bondRequest != null && bondRequest.uuid.equals(device.getAddress())) { if (bondState == BluetoothDevice.BOND_BONDED) { bondRequest.callback.invoke(); bondRequest = null; } else if (bondState == BluetoothDevice.BOND_NONE || bondState == BluetoothDevice.ERROR) { bondRequest.callback.invoke("Bond request has been denied"); bondRequest = null; } } if (removeBondRequest != null && removeBondRequest.uuid.equals(device.getAddress()) && bondState == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED) { removeBondRequest.callback.invoke(); removeBondRequest = null; } } } }; @ReactMethod public void getDiscoveredPeripherals(Callback callback) { Log.d(LOG_TAG, "Get discovered peripherals"); WritableArray map = Arguments.createArray(); Map<String, Peripheral> peripheralsCopy = new LinkedHashMap<>(peripherals); for (Map.Entry<String, Peripheral> entry : peripheralsCopy.entrySet()) { Peripheral peripheral = entry.getValue(); WritableMap jsonBundle = peripheral.asWritableMap(); map.pushMap(jsonBundle); } callback.invoke(null, map); } @ReactMethod public void getConnectedPeripherals(ReadableArray serviceUUIDs, Callback callback) { Log.d(LOG_TAG, "Get connected peripherals"); WritableArray map = Arguments.createArray(); if (getBluetoothAdapter() == null) { Log.d(LOG_TAG, "No bluetooth support"); callback.invoke("No bluetooth support"); return; } List<BluetoothDevice> periperals = getBluetoothManager().getConnectedDevices(GATT); for (BluetoothDevice entry : periperals) { Peripheral peripheral = savePeripheral(entry); WritableMap jsonBundle = peripheral.asWritableMap(); map.pushMap(jsonBundle); } callback.invoke(null, map); } @ReactMethod public void getBondedPeripherals(Callback callback) { Log.d(LOG_TAG, "Get bonded peripherals"); WritableArray map = Arguments.createArray(); Set<BluetoothDevice> deviceSet = getBluetoothAdapter().getBondedDevices(); for (BluetoothDevice device : deviceSet) { Peripheral peripheral = new Peripheral(device, reactContext); WritableMap jsonBundle = peripheral.asWritableMap(); map.pushMap(jsonBundle); } callback.invoke(null, map); } @ReactMethod public void removePeripheral(String deviceUUID, Callback callback) { Log.d(LOG_TAG, "Removing from list: " + deviceUUID); Peripheral peripheral = peripherals.get(deviceUUID); if (peripheral != null) { synchronized (peripherals) { if (peripheral.isConnected()) { callback.invoke("Peripheral can not be removed while connected"); } else { peripherals.remove(deviceUUID); callback.invoke(); } } } else callback.invoke("Peripheral not found"); } @ReactMethod public void requestConnectionPriority(String deviceUUID, int connectionPriority, Callback callback) { Log.d(LOG_TAG, "Request connection priority of " + connectionPriority + " from: " + deviceUUID); Peripheral peripheral = peripherals.get(deviceUUID); if (peripheral != null) { peripheral.requestConnectionPriority(connectionPriority, callback); } else { callback.invoke("Peripheral not found", null); } } @ReactMethod public void requestMTU(String deviceUUID, int mtu, Callback callback) { Log.d(LOG_TAG, "Request MTU of " + mtu + " bytes from: " + deviceUUID); Peripheral peripheral = peripherals.get(deviceUUID); if (peripheral != null) { peripheral.requestMTU(mtu, callback); } else { callback.invoke("Peripheral not found", null); } } private final static char[] hexArray = "0123456789ABCDEF".toCharArray(); public static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for (int j = 0; j < bytes.length; j++) { int v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } public static WritableArray bytesToWritableArray(byte[] bytes) { WritableArray value = Arguments.createArray(); for (int i = 0; i < bytes.length; i++) value.pushInt((bytes[i] & 0xFF)); return value; } @Override public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) { Log.d(LOG_TAG, "onActivityResult"); if (requestCode == ENABLE_REQUEST && enableBluetoothCallback != null) { if (resultCode == RESULT_OK) { enableBluetoothCallback.invoke(); } else { enableBluetoothCallback.invoke("User refused to enable"); } enableBluetoothCallback = null; } } @Override public void onNewIntent(Intent intent) { } private Peripheral retrieveOrCreatePeripheral(String peripheralUUID) { Peripheral peripheral = peripherals.get(peripheralUUID); if (peripheral == null) { synchronized (peripherals) { if (peripheralUUID != null) { peripheralUUID = peripheralUUID.toUpperCase(); } if (BluetoothAdapter.checkBluetoothAddress(peripheralUUID)) { BluetoothDevice device = bluetoothAdapter.getRemoteDevice(peripheralUUID); peripheral = new Peripheral(device, reactContext); peripherals.put(peripheralUUID, peripheral); } } } return peripheral; } }
package core.framework.test.search; import core.framework.impl.search.ElasticSearchImpl; import core.framework.util.StopWatch; import org.elasticsearch.client.Client; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.network.NetworkService; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.discovery.DiscoveryModule; import org.elasticsearch.env.Environment; import org.elasticsearch.node.NodeValidationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.file.Path; /** * @author neo */ public class MockElasticSearch extends ElasticSearchImpl { private final Logger logger = LoggerFactory.getLogger(MockElasticSearch.class); private final Path dataPath; public MockElasticSearch(Path dataPath) { this.dataPath = dataPath; } @Override protected Client createClient() { StopWatch watch = new StopWatch(); try { Settings.Builder settings = Settings.builder(); settings.put(Environment.PATH_HOME_SETTING.getKey(), dataPath) .put(NetworkModule.HTTP_ENABLED.getKey(), false) .put(NetworkService.GLOBAL_NETWORK_BINDHOST_SETTING.getKey(), "_local_") .put(DiscoveryModule.DISCOVERY_TYPE_SETTING.getKey(), "single-node"); MockNode node = new MockNode(settings.build()); node.start(); return node.client(); } catch (NodeValidationException e) { throw new Error(e); } finally { logger.info("create local elasticsearch node, dataPath={}, elapsedTime={}", dataPath, watch.elapsedTime()); } } }
package org.eclipse.rdf4j.rio.turtle; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.lang.reflect.GenericArrayType; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import org.eclipse.rdf4j.common.io.IndentingWriter; import org.eclipse.rdf4j.model.BNode; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Model; import org.eclipse.rdf4j.model.Resource; import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; import org.eclipse.rdf4j.model.impl.LinkedHashModel; import org.eclipse.rdf4j.model.impl.SimpleValueFactory; import org.eclipse.rdf4j.model.util.Literals; import org.eclipse.rdf4j.model.vocabulary.RDF; import org.eclipse.rdf4j.model.vocabulary.XMLSchema; import org.eclipse.rdf4j.rio.RDFFormat; import org.eclipse.rdf4j.rio.RDFHandlerException; import org.eclipse.rdf4j.rio.RDFWriter; import org.eclipse.rdf4j.rio.helpers.AbstractRDFWriter; import org.eclipse.rdf4j.rio.helpers.BasicParserSettings; import org.eclipse.rdf4j.rio.helpers.BasicWriterSettings; public class TurtleWriter extends AbstractRDFWriter implements RDFWriter { protected IndentingWriter writer; protected boolean writingStarted; /** * Flag indicating whether the last written statement has been closed. */ protected boolean statementClosed; protected Resource lastWrittenSubject; protected IRI lastWrittenPredicate; /** * A {@link Model} that is only used if pretty printing is enabled before startRDF is called; */ protected Model prettyPrintModel = null; /** * Creates a new TurtleWriter that will write to the supplied OutputStream. * * @param out * The OutputStream to write the Turtle document to. */ public TurtleWriter(OutputStream out) { this(new OutputStreamWriter(out, Charset.forName("UTF-8"))); } /** * Creates a new TurtleWriter that will write to the supplied Writer. * * @param writer * The Writer to write the Turtle document to. */ public TurtleWriter(Writer writer) { this.writer = new IndentingWriter(writer); namespaceTable = new LinkedHashMap<String, String>(); writingStarted = false; statementClosed = true; lastWrittenSubject = null; lastWrittenPredicate = null; } @Override public RDFFormat getRDFFormat() { return RDFFormat.TURTLE; } @Override public void startRDF() throws RDFHandlerException { if (writingStarted) { throw new RuntimeException("Document writing has already started"); } writingStarted = true; if (getWriterConfig().get(BasicWriterSettings.PRETTY_PRINT)) { prettyPrintModel = new LinkedHashModel(); } try { // Write namespace declarations for (Map.Entry<String, String> entry : namespaceTable.entrySet()) { String name = entry.getKey(); String prefix = entry.getValue(); writeNamespace(prefix, name); if (prettyPrintModel != null) { prettyPrintModel.setNamespace(prefix, name); } } if (!namespaceTable.isEmpty()) { writer.writeEOL(); } } catch (IOException e) { throw new RDFHandlerException(e); } } @Override public void endRDF() throws RDFHandlerException { if (!writingStarted) { throw new RuntimeException("Document writing has not yet started"); } try { if (prettyPrintModel != null) { // Note: We can't guarantee ordering at this point because Resource doesn't implement Comparable<Resource> for (Resource nextContext : prettyPrintModel.contexts()) { for (Resource nextSubject : prettyPrintModel.subjects()) { boolean canShortenSubject = true; // We can almost always shorten subject IRIs, // with some known corner cases that are already embedded in the algorithm // So just need to do checking for BNode subjects if (nextSubject instanceof BNode) { if (getRDFFormat().equals(RDFFormat.TRIG) && prettyPrintModel.filter(nextSubject, null, null, (Resource)null).contexts().size() > 1) { // TriG section 2.3.1 specifies that we cannot shorten blank nodes shared across contexts, // and this code is shared with TriG. canShortenSubject = false; } if (!prettyPrintModel.contains(null, null, nextSubject)) { // Cannot shorten this blank node as it is used as the object of a statement somewhere // so must be written in a non-anonymous form canShortenSubject = false; } } for (IRI nextPredicate : prettyPrintModel.filter(nextSubject, null, null, nextContext).predicates()) { for (Statement nextSt : prettyPrintModel.filter(nextSubject, nextPredicate, null, nextContext)) { handleStatementInternal(nextSt, true); } } } } } closePreviousStatement(); writer.flush(); } catch (IOException e) { throw new RDFHandlerException(e); } finally { writingStarted = false; } } @Override public void handleNamespace(String prefix, String name) throws RDFHandlerException { try { if (!namespaceTable.containsKey(name)) { // Namespace not yet mapped to a prefix, try to give it the // specified prefix boolean isLegalPrefix = prefix.length() == 0 || TurtleUtil.isPN_PREFIX(prefix); if (!isLegalPrefix || namespaceTable.containsValue(prefix)) { // use, if (prefix.length() == 0 || !isLegalPrefix) { prefix = "ns"; } int number = 1; while (namespaceTable.containsValue(prefix + number)) { number++; } prefix += number; } namespaceTable.put(name, prefix); if (writingStarted) { closePreviousStatement(); writeNamespace(prefix, name); } } } catch (IOException e) { throw new RDFHandlerException(e); } } @Override public void handleStatement(Statement st) throws RDFHandlerException { if (!writingStarted) { throw new RuntimeException("Document writing has not yet been started"); } // If we are pretty-printing, all writing is buffered until endRDF is // called if (prettyPrintModel != null) { prettyPrintModel.add(st); } else { handleStatementInternal(st, false); } } /** * Internal method that differentiates between the pretty-print and streaming writer cases. * * @param st * The next statement to write * @param endRDFCalled */ protected void handleStatementInternal(Statement st, boolean endRDFCalled) { // Avoid accidentally writing statements early, but don't lose track of // them if they are sent here if (prettyPrintModel != null && !endRDFCalled) { prettyPrintModel.add(st); return; } Resource subj = st.getSubject(); IRI pred = st.getPredicate(); Value obj = st.getObject(); try { if (subj.equals(lastWrittenSubject)) { if (pred.equals(lastWrittenPredicate)) { // Identical subject and predicate writer.write(" , "); } else { // Identical subject, new predicate writer.write(" ;"); writer.writeEOL(); // Write new predicate writePredicate(pred); writer.write(" "); lastWrittenPredicate = pred; } } else { // New subject closePreviousStatement(); // Write new subject: writer.writeEOL(); writeResource(subj); writer.write(" "); lastWrittenSubject = subj; // Write new predicate writePredicate(pred); writer.write(" "); lastWrittenPredicate = pred; statementClosed = false; writer.increaseIndentation(); } writeValue(obj); // Don't close the line just yet. Maybe the next // statement has the same subject and/or predicate. } catch (IOException e) { throw new RDFHandlerException(e); } } @Override public void handleComment(String comment) throws RDFHandlerException { try { closePreviousStatement(); if (comment.indexOf('\r') != -1 || comment.indexOf('\n') != -1) { // Comment is not allowed to contain newlines or line feeds. // Split comment in individual lines and write comment lines // for each of them. StringTokenizer st = new StringTokenizer(comment, "\r\n"); while (st.hasMoreTokens()) { writeCommentLine(st.nextToken()); } } else { writeCommentLine(comment); } } catch (IOException e) { throw new RDFHandlerException(e); } } protected void writeCommentLine(String line) throws IOException { writer.write(" writer.write(line); writer.writeEOL(); } protected void writeNamespace(String prefix, String name) throws IOException { writer.write("@prefix "); writer.write(prefix); writer.write(": <"); writer.write(TurtleUtil.encodeURIString(name)); writer.write("> ."); writer.writeEOL(); } protected void writePredicate(IRI predicate) throws IOException { if (predicate.equals(RDF.TYPE)) { // Write short-cut for rdf:type writer.write("a"); } else { writeURI(predicate); } } protected void writeValue(Value val) throws IOException { if (val instanceof Resource) { writeResource((Resource)val); } else { writeLiteral((Literal)val); } } protected void writeResource(Resource res) throws IOException { if (res instanceof IRI) { writeURI((IRI)res); } else { writeBNode((BNode)res); } } protected void writeURI(IRI uri) throws IOException { String uriString = uri.toString(); // Try to find a prefix for the URI's namespace String prefix = null; int splitIdx = TurtleUtil.findURISplitIndex(uriString); if (splitIdx > 0) { String namespace = uriString.substring(0, splitIdx); prefix = namespaceTable.get(namespace); } if (prefix != null) { // Namespace is mapped to a prefix; write abbreviated URI writer.write(prefix); writer.write(":"); writer.write(uriString.substring(splitIdx)); } else { // Write full URI writer.write("<"); writer.write(TurtleUtil.encodeURIString(uriString)); writer.write(">"); } } protected void writeBNode(BNode bNode) throws IOException { writer.write("_:"); String id = bNode.getID(); if (id.isEmpty()) { if (this.getWriterConfig().get(BasicParserSettings.PRESERVE_BNODE_IDS)) { throw new IOException( "Cannot consistently write blank nodes with empty internal identifiers"); } writer.write("genid-hash-"); writer.write(Integer.toHexString(System.identityHashCode(bNode))); } else { if (!TurtleUtil.isNameStartChar(id.charAt(0))) { writer.write("genid-start-"); writer.write(Integer.toHexString(id.charAt(0))); } else { writer.write(id.charAt(0)); } for (int i = 1; i < id.length() - 1; i++) { if (TurtleUtil.isPN_CHARS(id.charAt(i))) { writer.write(id.charAt(i)); } else { writer.write(Integer.toHexString(id.charAt(i))); } } if (id.length() > 1) { if (!TurtleUtil.isNameEndChar(id.charAt(id.length() - 1))) { writer.write(Integer.toHexString(id.charAt(id.length() - 1))); } else { writer.write(id.charAt(id.length() - 1)); } } } } protected void writeLiteral(Literal lit) throws IOException { String label = lit.getLabel(); IRI datatype = lit.getDatatype(); if (getWriterConfig().get(BasicWriterSettings.PRETTY_PRINT)) { if (XMLSchema.INTEGER.equals(datatype) || XMLSchema.DECIMAL.equals(datatype) || XMLSchema.DOUBLE.equals(datatype) || XMLSchema.BOOLEAN.equals(datatype)) { try { writer.write(XMLDatatypeUtil.normalize(label, datatype)); return; // done } catch (IllegalArgumentException e) { // not a valid numeric typed literal. ignore error and write // quoted string instead. } } } if (label.indexOf('\n') != -1 || label.indexOf('\r') != -1 || label.indexOf('\t') != -1) { // Write label as long string writer.write("\"\"\""); writer.write(TurtleUtil.encodeLongString(label)); writer.write("\"\"\""); } else { // Write label as normal string writer.write("\""); writer.write(TurtleUtil.encodeString(label)); writer.write("\""); } if (Literals.isLanguageLiteral(lit)) { // Append the literal's language writer.write("@"); writer.write(lit.getLanguage().get()); } else if (!XMLSchema.STRING.equals(datatype) || !xsdStringToPlainLiteral()) { // Append the literal's datatype (possibly written as an abbreviated // URI) writer.write("^^"); writeURI(datatype); } } protected void closePreviousStatement() throws IOException { if (!statementClosed) { // The previous statement still needs to be closed: writer.write(" ."); writer.writeEOL(); writer.decreaseIndentation(); statementClosed = true; lastWrittenSubject = null; lastWrittenPredicate = null; } } private boolean xsdStringToPlainLiteral() { return getWriterConfig().get(BasicWriterSettings.XSD_STRING_TO_PLAIN_LITERAL); } }
package com.headstartech.scheelite; import com.google.common.base.Optional; import java.util.Set; /** * The configuration of the state machine (states and their super state, transitions and initial transitions). * * @since 2.0 */ public class StateMachineConfiguration<T, U> { private final StateTree<T, U> stateTree; private final TransitionMap<T, U> transitionMap; StateMachineConfiguration(StateTree<T, U> stateTree, TransitionMap<T, U> transitionMap) { this.stateTree = stateTree; this.transitionMap = transitionMap; } /** * Gets the states in the state machine * * @return the states * * @see com.headstartech.scheelite.State */ public Set<State<T, U>> getStates() { return stateTree.getStates(); } /** * Gets the transitions in the state machine * * @return the transitions * * @see com.headstartech.scheelite.Transition */ public Set<Transition<T, U>> getTransitions() { return transitionMap.getTransitions(); } /** * Gets the super state of the specified {@link com.headstartech.scheelite.State}. * * @param state * @return the super state or <code>null</code> if the argument is the root state */ public State<T, U> getSuperState(State<T, U> state) { Optional<State<T, U>> superState = stateTree.getParent(state); if(superState.isPresent()) { return superState.get(); } else { return null; } } /** * Gets the implicit root state. * * The id of the root state is <code>null</code>. * * @return the root state. */ public State<T, U> getRootState() { return stateTree.getRootState(); } }
package com.jukusoft.libgdx.rpg.game.screen; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.scenes.scene2d.Event; import com.badlogic.gdx.scenes.scene2d.EventListener; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.*; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.jukusoft.libgdx.rpg.engine.font.BitmapFontFactory; import com.jukusoft.libgdx.rpg.engine.game.ScreenBasedGame; import com.jukusoft.libgdx.rpg.engine.hud.ImageWidget; import com.jukusoft.libgdx.rpg.engine.hud.WidgetGroup; import com.jukusoft.libgdx.rpg.engine.input.InputPriority; import com.jukusoft.libgdx.rpg.engine.input.listener.KeyListener; import com.jukusoft.libgdx.rpg.engine.lighting.LightingEnvironment; import com.jukusoft.libgdx.rpg.engine.screen.impl.BaseScreen; import com.jukusoft.libgdx.rpg.engine.skin.SkinFactory; import com.jukusoft.libgdx.rpg.engine.time.GameTime; import com.jukusoft.libgdx.rpg.game.data.CharacterData; import com.jukusoft.libgdx.rpg.engine.hud.HUD; import com.jukusoft.libgdx.rpg.engine.hud.FilledIconBar; import com.jukusoft.libgdx.rpg.game.shared.SharedDataConst; import com.jukusoft.libgdx.rpg.game.utils.AssetPathUtils; import com.jukusoft.libgdx.rpg.game.world.GameWorld; import javax.swing.*; import javax.swing.filechooser.FileFilter; import java.io.File; public class HUDOverlayScreen extends BaseScreen { protected static final String HEART_ICON_PATH = AssetPathUtils.getImagePath("icons/heart/heart_32.png"); protected static final String DIAMOND_ICON_PATH = AssetPathUtils.getImagePath("icons/diamond/diamond_32.png"); protected static final String LOGO_PATH = AssetPathUtils.getImagePath("general/icon_transparency_smallest.png"); protected CharacterData characterData = null; protected ShapeRenderer shapeRenderer = null; //HUD protected HUD hud = null; protected static final int FONT_SIZE = 18; protected FilledIconBar healthBar = null; protected FilledIconBar manaBar = null; protected ImageWidget logoImageWidget = null; //assets protected BitmapFont font = null; protected Texture heartTexture = null; protected Texture diamondTexture = null; protected Texture logoTexture = null; //lighting environment protected LightingEnvironment lightingEnvironment = null; protected Skin uiSkin = null; protected Stage stage = null; protected VerticalGroup verticalGroup = null; @Override protected void onInit(ScreenBasedGame game, AssetManager assetManager) { this.font = BitmapFontFactory .createFont(AssetPathUtils.getFontPath("arial/arial.ttf"), FONT_SIZE, Color.WHITE); //load assets game.getAssetManager().load(HEART_ICON_PATH, Texture.class); game.getAssetManager().load(DIAMOND_ICON_PATH, Texture.class); game.getAssetManager().load(LOGO_PATH, Texture.class); //wait while all assets was loaded game.getAssetManager().finishLoading(); this.heartTexture = game.getAssetManager().get(HEART_ICON_PATH, Texture.class); this.diamondTexture = game.getAssetManager().get(DIAMOND_ICON_PATH, Texture.class); this.logoTexture = game.getAssetManager().get(LOGO_PATH, Texture.class); //create and load ui skin from json file this.uiSkin = SkinFactory.createSkin(AssetPathUtils.getUISkinPath("create_character", "uiskin.json")); } @Override public void onResume () { this.characterData = game.getSharedData().get("character_data", CharacterData.class); if (this.characterData == null) { throw new IllegalStateException("character data wasnt initialized yet."); } this.shapeRenderer = new ShapeRenderer(); //get lighting environment this.lightingEnvironment = game.getSharedData().get(SharedDataConst.LIGHTING_ENV, LightingEnvironment.class); //create new Head-up-Display (HUD) this.hud = new HUD(); //create new widget group for health bar this.healthBar = new FilledIconBar(this.heartTexture, this.font); this.healthBar.setPosition(game.getViewportWidth() - 540, game.getViewportHeight() - /*106*/60); this.healthBar.setMaxValue(this.characterData.getMaxHealth()); this.healthBar.setValue(this.characterData.getHealth()); this.hud.addWidget(this.healthBar); //create new mana bar this.manaBar = new FilledIconBar(this.diamondTexture, this.font); this.manaBar.setPosition(game.getViewportWidth() - 680, game.getViewportHeight() - /*156*/60); this.manaBar.setMaxValue(this.characterData.getMaxMana()); this.manaBar.setValue(this.characterData.getMana()); this.hud.addWidget(this.manaBar); //add logo image widget this.logoImageWidget = new ImageWidget(this.logoTexture); this.logoImageWidget.setPosition(20, game.getViewportHeight() - 70); this.hud.addWidget(this.logoImageWidget); //create stage this.stage = new Stage(); //set stage input processor game.getInputManager().addCustomInputProcessor(stage); game.getInputManager().getGameInputProcessor().addKeyListener(new KeyListener() { @Override public boolean keyDown(int keycode) { return false; } @Override public boolean keyUp(int keycode) { return false; } @Override public boolean keyTyped(char character) { if (character == 'o') { toggleControlsVisible(); } return false; } @Override public InputPriority getInputOrder() { return null; } @Override public int compareTo(KeyListener o) { return 0; } }); //add lighting controls this.addLightingControls(this.hud); } @Override public void onPause () { if (this.shapeRenderer != null) { this.shapeRenderer.dispose(); this.shapeRenderer = null; } if (this.stage != null) { this.stage.dispose(); this.stage = null; } } @Override public void update(ScreenBasedGame game, GameTime time) { //update health bar this.healthBar.setMaxValue(this.characterData.getMaxHealth()); this.healthBar.setValue(this.characterData.getHealth()); this.healthBar.setText(this.healthBar.getPercent() + "%"); //update mana bar this.manaBar.setMaxValue(this.characterData.getMaxMana()); this.manaBar.setValue(this.characterData.getMana()); this.manaBar.setText(this.manaBar.getPercent() + "%"); this.hud.update(game, time); } @Override public void draw(GameTime time, SpriteBatch batch) { //set user interface camera batch.setProjectionMatrix(game.getUICamera().combined); //reset shader, so default shader will be used //batch.setShader(null); this.hud.drawLayer0(time, batch); batch.end(); //draw stage this.stage.draw(); //set camera matrix to shape renderer this.shapeRenderer.setProjectionMatrix(game.getUICamera().combined); shapeRenderer.begin(ShapeRenderer.ShapeType.Filled); this.hud.drawLayer1(time, shapeRenderer); shapeRenderer.end(); batch.begin(); this.hud.drawLayer2(time, batch); } @Override public void destroy() { this.heartTexture.dispose(); this.heartTexture = null; this.diamondTexture.dispose(); this.diamondTexture = null; this.logoTexture.dispose(); this.logoTexture = null; } protected void addLightingControls (HUD hud) { //create and add new widget group to HUD /*WidgetGroup controlGroup = new WidgetGroup(); controlGroup.setPosition(400, 400); hud.addWidget(controlGroup);*/ this.verticalGroup = new VerticalGroup(); verticalGroup.setPosition(1000, 400); //add checkbox to enable lighting CheckBox checkBox = new CheckBox("Lighting enabled", this.uiSkin); //checkBox.setPosition(0, 0); checkBox.addCaptureListener(new EventListener() { @Override public boolean handle(Event event) { if (checkBox.isChecked()) { lightingEnvironment.setLightingEnabled(true); } else { lightingEnvironment.setLightingEnabled(false); } return false; } }); verticalGroup.addActor(checkBox); if (lightingEnvironment.isLightingEnabled()) { checkBox.setChecked(true); } Label label = new Label("Light Intensity", this.uiSkin); verticalGroup.addActor(label); Slider slider = new Slider(0, 3, 0.01f, false, this.uiSkin); slider.setValue(lightingEnvironment.getAmbientIntensity()); slider.addCaptureListener(event -> { lightingEnvironment.setAmbientIntensity(slider.getValue()); return true; }); verticalGroup.addActor(slider); Label redLabel = new Label("Red Color: " + lightingEnvironment.getAmbientColor().x, this.uiSkin); verticalGroup.addActor(redLabel); Slider redSlider = new Slider(0, 1, 0.01f, false, this.uiSkin); redSlider.setValue(lightingEnvironment.getAmbientColor().x); redSlider.addCaptureListener(event -> { Vector3 oldColor = lightingEnvironment.getAmbientColor(); lightingEnvironment.setAmbientColor(redSlider.getValue(), oldColor.y, oldColor.z); redLabel.setText("Red Color: " + lightingEnvironment.getAmbientColor().x); return true; }); verticalGroup.addActor(redSlider); Label greenLabel = new Label("Green Color: " + lightingEnvironment.getAmbientColor().y, this.uiSkin); verticalGroup.addActor(greenLabel); Slider greenSlider = new Slider(0, 1, 0.01f, false, this.uiSkin); greenSlider.setValue(lightingEnvironment.getAmbientColor().y); greenSlider.addCaptureListener(event -> { Vector3 oldColor = lightingEnvironment.getAmbientColor(); lightingEnvironment.setAmbientColor(oldColor.x, greenSlider.getValue(), oldColor.z); greenLabel.setText("Green Color: " + lightingEnvironment.getAmbientColor().y); return true; }); verticalGroup.addActor(greenSlider); Label blueLabel = new Label("Blue Color: " + lightingEnvironment.getAmbientColor().z, this.uiSkin); verticalGroup.addActor(blueLabel); Slider blueSlider = new Slider(0, 1, 0.01f, false, this.uiSkin); blueSlider.setValue(lightingEnvironment.getAmbientColor().z); blueSlider.addCaptureListener(event -> { Vector3 oldColor = lightingEnvironment.getAmbientColor(); lightingEnvironment.setAmbientColor(oldColor.x, oldColor.y, blueSlider.getValue()); blueLabel.setText("Blue Color: " + lightingEnvironment.getAmbientColor().z); return true; }); verticalGroup.addActor(blueSlider); TextButton button = new TextButton("Reset", this.uiSkin); button.addCaptureListener(new ClickListener() { public void clicked (InputEvent event, float x, float y) { System.out.println("reset lighting control."); lightingEnvironment.setAmbientIntensity(0.7f); lightingEnvironment.setAmbientColor(0.3f, 0.3f, 0.7f); slider.setValue(0.7f); redSlider.setValue(0.3f); greenSlider.setValue(0.3f); blueSlider.setValue(0.7f); } }); verticalGroup.addActor(button); //only developer mode TextButton loadMapButton = new TextButton("Load own map", this.uiSkin); loadMapButton.addCaptureListener(new ClickListener() { public void clicked (InputEvent event, float x, float y) { System.out.println("load own map"); Thread thread = new Thread(new Runnable() { @Override public void run() { // JFileChooser-Objekt erstellen JFileChooser chooser = new JFileChooser(); chooser.setFileFilter(new FileFilter() { @Override public boolean accept(File f) { return f.getName().endsWith(".tmx") || f.isDirectory(); } @Override public String getDescription() { return "TMX Map"; } }); chooser.setDialogType(JFileChooser.OPEN_DIALOG); // Dialog zum Speichern von Dateien anzeigen int i = chooser.showDialog(null, "Choose tmx map"); //check, if OPEN was clicked if (i == JFileChooser.APPROVE_OPTION) { // Ausgabe der ausgewaehlten Datei System.out.println("open tmx map: " + chooser.getSelectedFile().getAbsolutePath()); game.runOnUIThread(() -> { GameWorld gameWorld = game.getSharedData().get(SharedDataConst.GAME_WORLD, GameWorld.class); gameWorld.devOptionLoadMap(chooser.getSelectedFile().getAbsolutePath()); }); } else { System.out.println("No open button clicked."); } } }); thread.start(); } }); verticalGroup.addActor(loadMapButton); //only developer mode TextButton loadSkyBoxButton = new TextButton("Load own SkyBox", this.uiSkin); loadSkyBoxButton.addCaptureListener(new ClickListener() { public void clicked (InputEvent event, float x, float y) { System.out.println("load own map"); Thread thread = new Thread(new Runnable() { @Override public void run() { // JFileChooser-Objekt erstellen JFileChooser chooser = new JFileChooser(); chooser.setFileFilter(new FileFilter() { @Override public boolean accept(File f) { return f.getName().endsWith(".png") || f.isDirectory(); } @Override public String getDescription() { return "PNG Graphics File"; } }); chooser.setDialogType(JFileChooser.OPEN_DIALOG); // Dialog zum Speichern von Dateien anzeigen int i = chooser.showDialog(null, "Choose PNG Graphic for SkyBox"); //check, if OPEN was clicked if (i == JFileChooser.APPROVE_OPTION) { // Ausgabe der ausgewaehlten Datei System.out.println("open skybox: " + chooser.getSelectedFile().getAbsolutePath()); final String filePath = chooser.getSelectedFile().getAbsolutePath(); if (!(new File(filePath).exists())) { System.err.println("PNG graphic doesnt exists."); return; } game.runOnUIThread(() -> { GameWorld gameWorld = game.getSharedData().get(SharedDataConst.GAME_WORLD, GameWorld.class); //load texture game.getAssetManager().load(filePath, Texture.class); game.getAssetManager().finishLoadingAsset(filePath); Texture skyBoxTexture = game.getAssetManager().get(filePath, Texture.class); gameWorld.getSkyBox().setTexture(skyBoxTexture); }); } else { System.out.println("No open button clicked."); } } }); thread.start(); } }); verticalGroup.addActor(loadSkyBoxButton); stage.addActor(verticalGroup); } protected void setControlsVisible (boolean visible) { this.verticalGroup.setVisible(visible); } protected void toggleControlsVisible () { this.verticalGroup.setVisible(!this.verticalGroup.isVisible()); } }
package org.mskcc.cbio.portal.servlet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.simple.JSONArray; import org.json.simple.JSONValue; import org.mskcc.cbio.cgds.dao.DaoCancerStudy; import org.mskcc.cbio.cgds.dao.DaoException; import org.mskcc.cbio.cgds.dao.DaoGeneticProfile; import org.mskcc.cbio.cgds.dao.DaoMutation; import org.mskcc.cbio.cgds.model.CancerStudy; import org.mskcc.cbio.cgds.model.GeneticAlterationType; import org.mskcc.cbio.cgds.model.GeneticProfile; import org.owasp.validator.html.PolicyException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; /** * @author Gideon Dresdner <dresdnerg@cbio.mskcc.org> * */ public class PancancerMutationsJSON extends HttpServlet { private ServletXssUtil servletXssUtil; private static Log log = LogFactory.getLog(PancancerMutationsJSON.class); /** * Initializes the servlet. * * @throws ServletException */ public void init() throws ServletException { super.init(); try { servletXssUtil = ServletXssUtil.getInstance(); } catch (PolicyException e) { throw new ServletException(e); } } /** * the request requires a parameter "mutation_keys" which is a JSON list of strings. * * @param request * @param response * @throws ServletException * @throws IOException */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Collection<String> hugos = new ArrayList<String>(); hugos.add("EGFR"); Collection<Integer> profileIds = new ArrayList<Integer>(); profileIds.add(5); try { Collection<Map<String, Object>> data = DaoMutation.countSamplesWithGenes(hugos, profileIds); System.out.println(data); } catch (DaoException e) { throw new ServletException(e); } String mutationKeysRawJson = request.getParameter("mutation_keys"); if (mutationKeysRawJson == null || mutationKeysRawJson.equals("")) { throw new ServletException("no mutation_keys parameter provided"); } JSONArray mutationKeys = (JSONArray) JSONValue.parse(mutationKeysRawJson); // iterate over all cancer studies, for each one grab all the genetic profiles, // only grab the ones that are mutation profiles, // and for each mutation profile count samples by mutation keyword List<CancerStudy> allCancerStudies = DaoCancerStudy.getAllCancerStudies(); Collection<Integer> internalGeneticProfileIds = new ArrayList<Integer>(); for (CancerStudy cancerStudy : allCancerStudies) { Integer internalId = cancerStudy.getInternalId(); List<GeneticProfile> geneticProfiles = DaoGeneticProfile.getAllGeneticProfiles(internalId); for (GeneticProfile geneticProfile : geneticProfiles) { if (geneticProfile.getGeneticAlterationType().equals(GeneticAlterationType.MUTATION_EXTENDED)) { internalGeneticProfileIds.add(geneticProfile.getGeneticProfileId()); } } } if (internalGeneticProfileIds.isEmpty()) { throw new ServletException("no genetic_profile_ids found"); } Collection<Map<String, Object>> data; try { data = DaoMutation.countSamplesWithKeywords(mutationKeys, internalGeneticProfileIds); } catch (DaoException e) { throw new ServletException(e); } PrintWriter writer = response.getWriter(); response.setContentType("application/json"); JSONArray.writeJSONString((List) data, writer); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package thirtytwo.degrees.halfpipe; import static thirtytwo.degrees.halfpipe.Halfpipe.*; import static thirtytwo.degrees.halfpipe.HalfpipeConfiguration.*; import com.netflix.config.DynamicPropertyFactory; import com.netflix.config.DynamicStringProperty; import com.sun.jersey.api.core.PackagesResourceConfig; import com.sun.jersey.api.json.JSONConfiguration; import com.sun.jersey.spi.container.servlet.ServletContainer; import com.sun.jersey.spi.spring.container.servlet.SpringServlet; import com.yammer.metrics.web.DefaultWebappMetricsFilter; import org.apache.catalina.servlets.DefaultServlet; import org.springframework.util.Assert; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.filter.DelegatingFilterProxy; import org.springframework.web.servlet.DispatcherServlet; import thirtytwo.degrees.halfpipe.configuration.Configuration; import thirtytwo.degrees.halfpipe.jersey.HalfpipeResourceConfig; import javax.servlet.*; import java.util.Set; public class HalfpipeWebAppInitializer implements WebApplicationInitializer { static Object lock = new Object(); static boolean initialized = false; public HalfpipeWebAppInitializer() { } /*protected abstract Class<?> getConfigClass(); protected abstract Class<?> getViewConfigClass();*/ @Override public void onStartup(ServletContext sc) throws ServletException { try { synchronized (lock) { if (initialized) return; initialized = true; createConfig((sc.getNamedDispatcher("default") == null)); // Create the root appcontext AnnotationConfigWebApplicationContext rootCtx = createWebContext(Application.serverContextClass); rootCtx.refresh(); // rather than sc.addListener(new ContextLoaderListener(rootCtx)); // set the required servletcontext attribute to avoid loading beans twice sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, rootCtx); Configuration config = rootCtx.getBean(Configuration.class); // Filters addFilter(sc, "springSecurityFilterChain", new DelegatingFilterProxy(), ROOT_URL_PATTERN); addFilter(sc, "webappMetricsFilter", new DefaultWebappMetricsFilter(), ROOT_URL_PATTERN); // now the context for the Dispatcher servlet AnnotationConfigWebApplicationContext webCtx = createWebContext(Application.serverViewContextClass); webCtx.setParent(rootCtx); //TODO: does setParent need to be done? // The main Spring MVC servlet. ServletRegistration.Dynamic viewServlet = addServlet(sc, "viewServlet", new DispatcherServlet(webCtx), 1, getStringProp(PROP_VIEW_URL_PATTERN, ROOT_URL_PATTERN)); if (DynamicPropertyFactory.getInstance().getBooleanProperty(PROP_INSTALL_DEFAULT_SERVLET, false).get()) { addServlet(sc, HALFPIPE_DEFAULT_SERVLET, new DefaultServlet(), 1, ROOT_URL_PATTERN); } // Jersey Servlet ServletRegistration.Dynamic jersey = addServlet(sc, "jersey-servlet", new SpringServlet(), 1, getStringProp(HALFPIPE_URL_PATTERN, RESOURCE_URL_PATTERN)); jersey.setInitParameter(ServletContainer.RESOURCE_CONFIG_CLASS, HalfpipeResourceConfig.class.getName()); jersey.setInitParameter(PackagesResourceConfig.PROPERTY_PACKAGES, config.resourcePackages.get()); jersey.setInitParameter(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE.toString()); } } catch (Exception e) { e.printStackTrace(); sc.log("Unable to initialize Halfpipe web application", e); throw new ServletException("Unable to initialize Halfpipe web application", e); } } private AnnotationConfigWebApplicationContext createWebContext(Class<?> appConfigClass) { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); ctx.register(appConfigClass); return ctx; } private ServletRegistration.Dynamic addServlet(ServletContext servletContext, String servletName, Servlet servlet, int loadOnStartup, DynamicStringProperty urlPattern) { return addServlet(servletContext, servletName, servlet, loadOnStartup, urlPattern.get()); } private ServletRegistration.Dynamic addServlet(ServletContext servletContext, String servletName, Servlet servlet, int loadOnStartup, String... urlPatterns) { ServletRegistration.Dynamic reg = servletContext.addServlet(servletName, servlet); Assert.notNull(reg, "Unable to create servlet " + servletName); reg.setLoadOnStartup(loadOnStartup); Set<String> mappingConflicts = reg.addMapping(urlPatterns); if (!mappingConflicts.isEmpty()) { for (String s : mappingConflicts) { System.err.println("Mapping conflict: " + s); } throw new IllegalStateException( "'"+servletName+"' cannot be mapped to '/' under Tomcat versions <= 7.0.14"); } return reg; } private FilterRegistration.Dynamic addFilter(ServletContext servletContext, String filterName, Filter filter, String urlPattern) { FilterRegistration.Dynamic fr = servletContext.addFilter(filterName, filter); Assert.notNull(fr, "Unable to create filter "+filterName); //fr.setInitParameter("name", "value"); fr.addMappingForUrlPatterns(null, true, urlPattern); return fr; } }
package com.continuuity.data; import com.continuuity.common.conf.Constants; import com.continuuity.common.guice.LocationRuntimeModule; import com.continuuity.data.runtime.DataFabricLevelDBModule; import com.continuuity.data2.dataset.api.DataSetClient; import com.continuuity.data2.dataset.lib.table.BufferingOcTableClient; import com.continuuity.data2.dataset.lib.table.OrderedColumnarTable; import com.google.inject.Guice; import com.google.inject.Injector; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.rules.TemporaryFolder; public class LocalDataSetAccessorTest extends NamespacingDataSetAccessorTest { @ClassRule public static TemporaryFolder tmpFolder = new TemporaryFolder(); private static DataSetAccessor dsAccessor; @BeforeClass public static void beforeClass() throws Exception { NamespacingDataSetAccessorTest.beforeClass(); conf.set(Constants.CFG_LOCAL_DATA_DIR, tmpFolder.newFolder().getAbsolutePath()); Injector injector = Guice.createInjector( new LocationRuntimeModule().getSingleNodeModules(), new DataFabricLevelDBModule(conf)); dsAccessor = injector.getInstance(DataSetAccessor.class); } @Override protected DataSetAccessor getDataSetAccessor() { return dsAccessor; } @Override protected String getRawName(DataSetClient dsClient) { if (dsClient instanceof OrderedColumnarTable) { return ((BufferingOcTableClient) dsClient).getTableName(); } throw new RuntimeException("Unknown DataSetClient type: " + dsClient.getClass()); } }
package com.firebase.ui.database; import android.support.annotation.CallSuper; import android.support.annotation.NonNull; import android.support.annotation.RestrictTo; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.concurrent.CopyOnWriteArrayList; /** * Exposes a collection of items in Firebase as a {@link List} of {@link DataSnapshot}. To observe * the list attach a {@link com.google.firebase.database.ChildEventListener}. * * @param <E> a POJO class to which the DataSnapshots can be converted. */ public abstract class ObservableSnapshotArray<E> extends ImmutableList<DataSnapshot> { protected final List<ChangeEventListener> mListeners = new CopyOnWriteArrayList<>(); protected final SnapshotParser<E> mParser; /** * Create an ObservableSnapshotArray where snapshots are parsed as objects of a particular * class. * * @param clazz the class as which DataSnapshots should be parsed. * @see ClassSnapshotParser */ public ObservableSnapshotArray(@NonNull Class<E> clazz) { this(new ClassSnapshotParser<>(clazz)); } /** * Create an ObservableSnapshotArray with a custom {@link SnapshotParser}. * * @param parser the {@link SnapshotParser} to use */ public ObservableSnapshotArray(@NonNull SnapshotParser<E> parser) { mParser = Preconditions.checkNotNull(parser); } /** * Attach a {@link ChangeEventListener} to this array. The listener will receive one {@link * ChangeEventListener.EventType#ADDED} event for each item that already exists in the array at * the time of attachment, and then receive all future child events. */ @CallSuper public ChangeEventListener addChangeEventListener(@NonNull ChangeEventListener listener) { Preconditions.checkNotNull(listener); mListeners.add(listener); for (int i = 0; i < size(); i++) { listener.onChildChanged(ChangeEventListener.EventType.ADDED, get(i), i, -1); } listener.onDataChanged(); return listener; } /** * Detach a {@link com.google.firebase.database.ChildEventListener} from this array. */ @CallSuper public void removeChangeEventListener(@NonNull ChangeEventListener listener) { mListeners.remove(listener); } /** * Removes all {@link ChangeEventListener}s. The list will be empty after this call returns. * * @see #removeChangeEventListener(ChangeEventListener) */ @CallSuper public void removeAllListeners() { for (ChangeEventListener listener : mListeners) { removeChangeEventListener(listener); } } protected abstract List<DataSnapshot> getSnapshots(); protected final void notifyChangeEventListeners(ChangeEventListener.EventType type, DataSnapshot snapshot, int index) { notifyChangeEventListeners(type, snapshot, index, -1); } protected final void notifyChangeEventListeners(ChangeEventListener.EventType type, DataSnapshot snapshot, int index, int oldIndex) { for (ChangeEventListener listener : mListeners) { listener.onChildChanged(type, snapshot, index, oldIndex); } } protected final void notifyListenersOnDataChanged() { for (ChangeEventListener listener : mListeners) { listener.onDataChanged(); } } protected final void notifyListenersOnCancelled(DatabaseError error) { for (ChangeEventListener listener : mListeners) { listener.onCancelled(error); } } /** * @return true if {@link FirebaseArray} is listening for change events from the Firebase * database, false otherwise */ public final boolean isListening() { return !mListeners.isEmpty(); } /** * @return true if the provided {@link ChangeEventListener} is listening for changes */ public final boolean isListening(ChangeEventListener listener) { return mListeners.contains(listener); } /** * Get the {@link DataSnapshot} at a given position converted to an object of the parametrized * type. This uses the {@link SnapshotParser} passed to the constructor. If the parser was not * initialized this will throw an unchecked exception. */ public E getObject(int index) { return mParser.parseSnapshot(get(index)); } @Override public int size() { return getSnapshots().size(); } @Override public boolean isEmpty() { return getSnapshots().isEmpty(); } @Override public boolean contains(Object o) { return getSnapshots().contains(o); } @Override public Iterator<DataSnapshot> iterator() { return new ImmutableIterator(getSnapshots().iterator()); } @Override public DataSnapshot[] toArray() { return getSnapshots().toArray(new DataSnapshot[getSnapshots().size()]); } @Override public boolean containsAll(Collection<?> c) { return getSnapshots().containsAll(c); } @Override public DataSnapshot get(int index) { return getSnapshots().get(index); } @Override public int indexOf(Object o) { return getSnapshots().indexOf(o); } @Override public int lastIndexOf(Object o) { return getSnapshots().lastIndexOf(o); } @Override public ListIterator<DataSnapshot> listIterator() { return new ImmutableListIterator(getSnapshots().listIterator()); } @Override public ListIterator<DataSnapshot> listIterator(int index) { return new ImmutableListIterator(getSnapshots().listIterator(index)); } /** * Guaranteed to throw an exception. Use {@link #toArray()} instead to get an array of {@link * DataSnapshot}s. * * @throws UnsupportedOperationException always */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) @Override public final <T> T[] toArray(T[] a) { throw new UnsupportedOperationException(); } }
package bisq.desktop.components; import bisq.desktop.components.controlsfx.control.PopOver; import bisq.desktop.main.offer.offerbook.OfferBookListItem; import bisq.desktop.util.FormBuilder; import bisq.desktop.util.GUIUtil; import bisq.core.account.sign.SignedWitnessService; import bisq.core.locale.Res; import bisq.core.offer.OfferRestrictions; import bisq.core.util.coin.CoinFormatter; import de.jensd.fx.fontawesome.AwesomeIcon; import javafx.scene.Node; import javafx.scene.control.ContentDisplay; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; import javafx.scene.layout.VBox; import javafx.geometry.Insets; import javafx.geometry.Pos; public class AccountStatusTooltipLabel extends AutoTooltipLabel { public static final int DEFAULT_WIDTH = 300; private final Node textIcon; private final PopOverWrapper popoverWrapper = new PopOverWrapper(); private final OfferBookListItem.WitnessAgeData witnessAgeData; private final String popupTitle; public AccountStatusTooltipLabel(OfferBookListItem.WitnessAgeData witnessAgeData, CoinFormatter formatter) { super(witnessAgeData.getDisplayString()); this.witnessAgeData = witnessAgeData; this.textIcon = FormBuilder.getIcon(witnessAgeData.getIcon()); this.popupTitle = witnessAgeData.isLimitLifted() ? Res.get("offerbook.timeSinceSigning.tooltip.accountLimitLifted") : Res.get("offerbook.timeSinceSigning.tooltip.accountLimit", formatter.formatCoinWithCode(OfferRestrictions.TOLERATED_SMALL_TRADE_AMOUNT)); positionAndActivateIcon(); } private void positionAndActivateIcon() { textIcon.setOpacity(0.4); textIcon.getStyleClass().add("tooltip-icon"); textIcon.setOnMouseEntered(e -> popoverWrapper.showPopOver(this::createPopOver)); textIcon.setOnMouseExited(e -> popoverWrapper.hidePopOver()); setGraphic(textIcon); setContentDisplay(ContentDisplay.RIGHT); } private PopOver createPopOver() { Label titleLabel = new Label(popupTitle); titleLabel.setMaxWidth(DEFAULT_WIDTH); titleLabel.setWrapText(true); titleLabel.setPadding(new Insets(10, 10, 2, 10)); titleLabel.getStyleClass().add("bold-text"); titleLabel.getStyleClass().add("default-text"); Label infoLabel = new Label(witnessAgeData.getInfo()); infoLabel.setMaxWidth(DEFAULT_WIDTH); infoLabel.setWrapText(true); infoLabel.setPadding(new Insets(2, 10, 2, 10)); infoLabel.getStyleClass().add("default-text"); Label buyLabel = createDetailsItem( Res.get("offerbook.timeSinceSigning.tooltip.checkmark.buyBtc"), witnessAgeData.isAccountSigned() ); Label waitLabel = createDetailsItem( Res.get("offerbook.timeSinceSigning.tooltip.checkmark.wait", SignedWitnessService.SIGNER_AGE_DAYS), witnessAgeData.isLimitLifted() ); Hyperlink learnMoreLink = new Hyperlink(Res.get("offerbook.timeSinceSigning.tooltip.learnMore")); learnMoreLink.setMaxWidth(DEFAULT_WIDTH); learnMoreLink.setWrapText(true); learnMoreLink.setPadding(new Insets(10, 10, 2, 10)); learnMoreLink.getStyleClass().add("very-small-text"); learnMoreLink.setOnAction((e) -> { GUIUtil.openWebPage("https://bisq.wiki/Account_limits"); }); VBox vBox = new VBox(2, titleLabel, infoLabel, buyLabel, waitLabel, learnMoreLink); vBox.setPadding(new Insets(2, 0, 2, 0)); vBox.setAlignment(Pos.CENTER_LEFT); PopOver popOver = new PopOver(vBox); if (textIcon.getScene() != null) { popOver.setDetachable(false); popOver.setArrowLocation(PopOver.ArrowLocation.LEFT_CENTER); popOver.show(textIcon, -10); } return popOver; } private Label createDetailsItem(String text, boolean active) { Label icon = FormBuilder.getIcon(active ? AwesomeIcon.OK_SIGN : AwesomeIcon.REMOVE_SIGN); icon.setLayoutY(4); icon.getStyleClass().add("icon"); if (active) { icon.getStyleClass().add("highlight"); } else { icon.getStyleClass().add("text-gray-ddd"); } Label label = new Label(text, icon); label.setMaxWidth(DEFAULT_WIDTH); label.setWrapText(true); label.setPadding(new Insets(0, 10, 0, 10)); label.getStyleClass().addAll("small-text"); if (active) { label.getStyleClass().add("success-text"); } else { label.getStyleClass().add("text-gray-ddd"); } return label; } }
package bisq.desktop.main.funds.withdrawal; import bisq.desktop.common.view.ActivatableView; import bisq.desktop.common.view.FxmlView; import bisq.desktop.components.AutoTooltipCheckBox; import bisq.desktop.components.AutoTooltipLabel; import bisq.desktop.components.ExternalHyperlink; import bisq.desktop.components.HyperlinkWithIcon; import bisq.desktop.components.TitledGroupBg; import bisq.desktop.main.overlays.popups.Popup; import bisq.desktop.main.overlays.windows.WalletPasswordWindow; import bisq.desktop.util.GUIUtil; import bisq.desktop.util.Layout; import bisq.core.btc.exceptions.AddressEntryException; import bisq.core.btc.exceptions.InsufficientFundsException; import bisq.core.btc.listeners.BalanceListener; import bisq.core.btc.model.AddressEntry; import bisq.core.btc.setup.WalletsSetup; import bisq.core.btc.wallet.BtcWalletService; import bisq.core.btc.wallet.Restrictions; import bisq.core.locale.Res; import bisq.core.trade.Trade; import bisq.core.trade.TradeManager; import bisq.core.user.Preferences; import bisq.core.util.FormattingUtils; import bisq.core.util.ParsingUtils; import bisq.core.util.coin.CoinFormatter; import bisq.core.util.coin.CoinUtil; import bisq.core.util.validation.BtcAddressValidator; import bisq.network.p2p.P2PService; import bisq.common.UserThread; import bisq.common.util.Tuple3; import bisq.common.util.Tuple4; import org.bitcoinj.core.AddressFormatException; import org.bitcoinj.core.Coin; import org.bitcoinj.core.InsufficientMoneyException; import org.bitcoinj.core.Transaction; import org.bitcoinj.wallet.Wallet; import javax.inject.Inject; import javax.inject.Named; import com.google.common.util.concurrent.FutureCallback; import org.apache.commons.lang3.StringUtils; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; import javafx.scene.control.RadioButton; import javafx.scene.control.SelectionMode; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import javafx.scene.control.Tooltip; import javafx.scene.layout.GridPane; import javafx.scene.layout.VBox; import javafx.geometry.Pos; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.value.ChangeListener; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.collections.transformation.SortedList; import javafx.util.Callback; import org.bouncycastle.crypto.params.KeyParameter; import java.util.ArrayList; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.jetbrains.annotations.NotNull; import static bisq.desktop.util.FormBuilder.*; import static com.google.common.base.Preconditions.checkNotNull; @FxmlView public class WithdrawalView extends ActivatableView<VBox, Void> { @FXML GridPane gridPane; @FXML TableView<WithdrawalListItem> tableView; @FXML TableColumn<WithdrawalListItem, WithdrawalListItem> addressColumn, balanceColumn, selectColumn; private RadioButton useAllInputsRadioButton, useCustomInputsRadioButton, feeExcludedRadioButton, feeIncludedRadioButton; private Label amountLabel; private TextField amountTextField, withdrawFromTextField, withdrawToTextField, withdrawMemoTextField; private final BtcWalletService btcWalletService; private final TradeManager tradeManager; private final P2PService p2PService; private final WalletsSetup walletsSetup; private final CoinFormatter formatter; private final Preferences preferences; private final BtcAddressValidator btcAddressValidator; private final WalletPasswordWindow walletPasswordWindow; private final ObservableList<WithdrawalListItem> observableList = FXCollections.observableArrayList(); private final SortedList<WithdrawalListItem> sortedList = new SortedList<>(observableList); private final Set<WithdrawalListItem> selectedItems = new HashSet<>(); private BalanceListener balanceListener; private Set<String> fromAddresses = new HashSet<>(); private Coin totalAvailableAmountOfSelectedItems = Coin.ZERO; private Coin amountAsCoin = Coin.ZERO; private Coin sendersAmount = Coin.ZERO; private ChangeListener<String> amountListener; private ChangeListener<Boolean> amountFocusListener; private ChangeListener<Toggle> feeToggleGroupListener, inputsToggleGroupListener; private ToggleGroup feeToggleGroup, inputsToggleGroup; private final BooleanProperty useAllInputs = new SimpleBooleanProperty(true); private boolean feeExcluded; private int rowIndex = 0; // Constructor, lifecycle @Inject private WithdrawalView(BtcWalletService btcWalletService, TradeManager tradeManager, P2PService p2PService, WalletsSetup walletsSetup, @Named(FormattingUtils.BTC_FORMATTER_KEY) CoinFormatter formatter, Preferences preferences, BtcAddressValidator btcAddressValidator, WalletPasswordWindow walletPasswordWindow) { this.btcWalletService = btcWalletService; this.tradeManager = tradeManager; this.p2PService = p2PService; this.walletsSetup = walletsSetup; this.formatter = formatter; this.preferences = preferences; this.btcAddressValidator = btcAddressValidator; this.walletPasswordWindow = walletPasswordWindow; } @Override public void initialize() { final TitledGroupBg titledGroupBg = addTitledGroupBg(gridPane, rowIndex, 4, Res.get("funds.deposit.withdrawFromWallet")); titledGroupBg.getStyleClass().add("last"); inputsToggleGroup = new ToggleGroup(); inputsToggleGroupListener = (observable, oldValue, newValue) -> { useAllInputs.set(newValue == useAllInputsRadioButton); updateInputSelection(); }; final Tuple3<Label, RadioButton, RadioButton> labelRadioButtonRadioButtonTuple3 = addTopLabelRadioButtonRadioButton(gridPane, rowIndex, inputsToggleGroup, Res.get("funds.withdrawal.inputs"), Res.get("funds.withdrawal.useAllInputs"), Res.get("funds.withdrawal.useCustomInputs"), Layout.FIRST_ROW_DISTANCE); useAllInputsRadioButton = labelRadioButtonRadioButtonTuple3.second; useCustomInputsRadioButton = labelRadioButtonRadioButtonTuple3.third; feeToggleGroup = new ToggleGroup(); final Tuple4<Label, TextField, RadioButton, RadioButton> feeTuple3 = addTopLabelTextFieldRadioButtonRadioButton(gridPane, ++rowIndex, feeToggleGroup, Res.get("funds.withdrawal.receiverAmount", Res.getBaseCurrencyCode()), "", Res.get("funds.withdrawal.feeExcluded"), Res.get("funds.withdrawal.feeIncluded"), 0); amountLabel = feeTuple3.first; amountTextField = feeTuple3.second; amountTextField.setMinWidth(180); feeExcludedRadioButton = feeTuple3.third; feeIncludedRadioButton = feeTuple3.fourth; withdrawFromTextField = addTopLabelTextField(gridPane, ++rowIndex, Res.get("funds.withdrawal.fromLabel", Res.getBaseCurrencyCode())).second; withdrawToTextField = addTopLabelInputTextField(gridPane, ++rowIndex, Res.get("funds.withdrawal.toLabel", Res.getBaseCurrencyCode())).second; withdrawMemoTextField = addTopLabelInputTextField(gridPane, ++rowIndex, Res.get("funds.withdrawal.memoLabel", Res.getBaseCurrencyCode())).second; final Button withdrawButton = addButton(gridPane, ++rowIndex, Res.get("funds.withdrawal.withdrawButton"), 15); withdrawButton.setOnAction(event -> onWithdraw()); addressColumn.setGraphic(new AutoTooltipLabel(Res.get("shared.address"))); balanceColumn.setGraphic(new AutoTooltipLabel(Res.get("shared.balanceWithCur", Res.getBaseCurrencyCode()))); selectColumn.setGraphic(new AutoTooltipLabel(Res.get("shared.select"))); tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY); tableView.setMaxHeight(Double.MAX_VALUE); tableView.setPlaceholder(new AutoTooltipLabel(Res.get("funds.withdrawal.noFundsAvailable"))); tableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); setAddressColumnCellFactory(); setBalanceColumnCellFactory(); setSelectColumnCellFactory(); addressColumn.setComparator(Comparator.comparing(WithdrawalListItem::getAddressString)); balanceColumn.setComparator(Comparator.comparing(WithdrawalListItem::getBalance)); balanceColumn.setSortType(TableColumn.SortType.DESCENDING); tableView.getSortOrder().add(balanceColumn); balanceListener = new BalanceListener() { @Override public void onBalanceChanged(Coin balance, Transaction tx) { updateList(); } }; amountListener = (observable, oldValue, newValue) -> { if (amountTextField.focusedProperty().get()) { try { amountAsCoin = ParsingUtils.parseToCoin(amountTextField.getText(), formatter); } catch (Throwable t) { log.error("Error at amountTextField input. " + t.toString()); } } }; amountFocusListener = (observable, oldValue, newValue) -> { if (oldValue && !newValue) { if (amountAsCoin.isPositive()) amountTextField.setText(formatter.formatCoin(amountAsCoin)); else amountTextField.setText(""); } }; feeExcludedRadioButton.setToggleGroup(feeToggleGroup); feeIncludedRadioButton.setToggleGroup(feeToggleGroup); feeToggleGroupListener = (observable, oldValue, newValue) -> { feeExcluded = newValue == feeExcludedRadioButton; amountLabel.setText(feeExcluded ? Res.get("funds.withdrawal.receiverAmount") : Res.get("funds.withdrawal.senderAmount")); }; } private void updateInputSelection() { observableList.forEach(item -> { item.setSelected(useAllInputs.get()); selectForWithdrawal(item); }); tableView.refresh(); } @Override protected void activate() { sortedList.comparatorProperty().bind(tableView.comparatorProperty()); tableView.setItems(sortedList); updateList(); reset(); amountTextField.textProperty().addListener(amountListener); amountTextField.focusedProperty().addListener(amountFocusListener); btcWalletService.addBalanceListener(balanceListener); feeToggleGroup.selectedToggleProperty().addListener(feeToggleGroupListener); inputsToggleGroup.selectedToggleProperty().addListener(inputsToggleGroupListener); if (feeToggleGroup.getSelectedToggle() == null) feeToggleGroup.selectToggle(feeIncludedRadioButton); if (inputsToggleGroup.getSelectedToggle() == null) inputsToggleGroup.selectToggle(useAllInputsRadioButton); updateInputSelection(); GUIUtil.requestFocus(withdrawToTextField); } @Override protected void deactivate() { sortedList.comparatorProperty().unbind(); observableList.forEach(WithdrawalListItem::cleanup); btcWalletService.removeBalanceListener(balanceListener); amountTextField.textProperty().removeListener(amountListener); amountTextField.focusedProperty().removeListener(amountFocusListener); feeToggleGroup.selectedToggleProperty().removeListener(feeToggleGroupListener); inputsToggleGroup.selectedToggleProperty().removeListener(inputsToggleGroupListener); } // UI handlers private void onWithdraw() { if (GUIUtil.isReadyForTxBroadcastOrShowPopup(p2PService, walletsSetup)) { try { // We do not know sendersAmount if senderPaysFee is true. We repeat fee calculation after first attempt if senderPaysFee is true. Transaction feeEstimationTransaction = btcWalletService.getFeeEstimationTransactionForMultipleAddresses(fromAddresses, amountAsCoin); if (feeExcluded && feeEstimationTransaction != null) { sendersAmount = amountAsCoin.add(feeEstimationTransaction.getFee()); feeEstimationTransaction = btcWalletService.getFeeEstimationTransactionForMultipleAddresses(fromAddresses, sendersAmount); } checkNotNull(feeEstimationTransaction, "feeEstimationTransaction must not be null"); Coin dust = btcWalletService.getDust(feeEstimationTransaction); Coin fee = feeEstimationTransaction.getFee().add(dust); Coin receiverAmount; // amountAsCoin is what the user typed into the withdrawal field. // this can be interpreted as either the senders amount or receivers amount depending // on a radio button "fee excluded / fee included". // therefore we calculate the actual sendersAmount and receiverAmount as follows: if (feeExcluded) { receiverAmount = amountAsCoin; sendersAmount = receiverAmount.add(fee); } else { sendersAmount = amountAsCoin.add(dust); // sendersAmount bumped up to UTXO size when dust is in play receiverAmount = sendersAmount.subtract(fee); } if (dust.isPositive()) { log.info("Dust output ({} satoshi) was detected, the dust amount has been added to the fee (was {}, now {})", dust.value, feeEstimationTransaction.getFee(), fee.value); } if (areInputsValid()) { int txVsize = feeEstimationTransaction.getVsize(); log.info("Fee for tx with size {}: {} " + Res.getBaseCurrencyCode() + "", txVsize, fee.toPlainString()); if (receiverAmount.isPositive()) { double feePerVbyte = CoinUtil.getFeePerVbyte(fee, txVsize); double vkb = txVsize / 1000d; String messageText = Res.get("shared.sendFundsDetailsWithFee", formatter.formatCoinWithCode(sendersAmount), withdrawFromTextField.getText(), withdrawToTextField.getText(), formatter.formatCoinWithCode(fee), feePerVbyte, vkb, formatter.formatCoinWithCode(receiverAmount)); if (dust.isPositive()) { messageText = Res.get("shared.sendFundsDetailsDust", dust.value, dust.value > 1 ? "s" : "") + messageText; } new Popup().headLine(Res.get("funds.withdrawal.confirmWithdrawalRequest")) .confirmation(messageText) .actionButtonText(Res.get("shared.yes")) .onAction(() -> doWithdraw(sendersAmount, fee, new FutureCallback<>() { @Override public void onSuccess(@javax.annotation.Nullable Transaction transaction) { if (transaction != null) { log.debug("onWithdraw onSuccess tx ID:{}", transaction.getTxId().toString()); } else { log.error("onWithdraw transaction is null"); } List<Trade> trades = new ArrayList<>(tradeManager.getObservableList()); trades.stream() .filter(Trade::isPayoutPublished) .forEach(trade -> btcWalletService.getAddressEntry(trade.getId(), AddressEntry.Context.TRADE_PAYOUT) .ifPresent(addressEntry -> { if (btcWalletService.getBalanceForAddress(addressEntry.getAddress()).isZero()) tradeManager.onTradeCompleted(trade); })); } @Override public void onFailure(@NotNull Throwable t) { log.error("onWithdraw onFailure"); } })) .closeButtonText(Res.get("shared.cancel")) .show(); } else { new Popup().warning(Res.get("portfolio.pending.step5_buyer.amountTooLow")).show(); } } } catch (InsufficientFundsException e) { new Popup().warning(Res.get("funds.withdrawal.warn.amountExceeds") + "\n\nError message:\n" + e.getMessage()).show(); } catch (Throwable e) { e.printStackTrace(); log.error(e.toString()); new Popup().warning(e.toString()).show(); } } } private void selectForWithdrawal(WithdrawalListItem item) { if (item.isSelected()) selectedItems.add(item); else selectedItems.remove(item); fromAddresses = selectedItems.stream() .map(WithdrawalListItem::getAddressString) .collect(Collectors.toSet()); if (!selectedItems.isEmpty()) { totalAvailableAmountOfSelectedItems = Coin.valueOf(selectedItems.stream().mapToLong(e -> e.getBalance().getValue()).sum()); if (totalAvailableAmountOfSelectedItems.isPositive()) { amountAsCoin = totalAvailableAmountOfSelectedItems; amountTextField.setText(formatter.formatCoin(amountAsCoin)); } else { amountAsCoin = Coin.ZERO; totalAvailableAmountOfSelectedItems = Coin.ZERO; amountTextField.setText(""); withdrawFromTextField.setText(""); } if (selectedItems.size() == 1) { withdrawFromTextField.setText(selectedItems.stream().findAny().get().getAddressEntry().getAddressString()); withdrawFromTextField.setTooltip(null); } else { int abbr = Math.max(10, 66 / selectedItems.size()); String addressesShortened = selectedItems.stream() .map(e -> StringUtils.abbreviate(e.getAddressString(), abbr)) .collect(Collectors.joining(", ")); String text = Res.get("funds.withdrawal.withdrawMultipleAddresses", addressesShortened); withdrawFromTextField.setText(text); String addresses = selectedItems.stream() .map(WithdrawalListItem::getAddressString) .collect(Collectors.joining(",\n")); String tooltipText = Res.get("funds.withdrawal.withdrawMultipleAddresses.tooltip", addresses); withdrawFromTextField.setTooltip(new Tooltip(tooltipText)); } } else { reset(); } } private void openBlockExplorer(WithdrawalListItem item) { if (item.getAddressString() != null) GUIUtil.openWebPage(preferences.getBlockChainExplorer().addressUrl + item.getAddressString(), false); } // Private private void updateList() { observableList.forEach(WithdrawalListItem::cleanup); observableList.setAll(btcWalletService.getAddressEntriesForAvailableBalanceStream() .map(addressEntry -> new WithdrawalListItem(addressEntry, btcWalletService, formatter)) .collect(Collectors.toList())); updateInputSelection(); } private void doWithdraw(Coin amount, Coin fee, FutureCallback<Transaction> callback) { if (btcWalletService.isEncrypted()) { UserThread.runAfter(() -> walletPasswordWindow.onAesKey(aesKey -> sendFunds(amount, fee, aesKey, callback)) .show(), 300, TimeUnit.MILLISECONDS); } else { sendFunds(amount, fee, null, callback); } } private void sendFunds(Coin amount, Coin fee, KeyParameter aesKey, FutureCallback<Transaction> callback) { try { String memo = withdrawMemoTextField.getText(); if (memo.isEmpty()) { memo = null; } Transaction transaction = btcWalletService.sendFundsForMultipleAddresses(fromAddresses, withdrawToTextField.getText(), amount, fee, null, aesKey, memo, callback); reset(); updateList(); } catch (AddressFormatException e) { new Popup().warning(Res.get("validation.btc.invalidAddress")).show(); } catch (Wallet.DustySendRequested e) { new Popup().warning(Res.get("validation.amountBelowDust", formatter.formatCoinWithCode(Restrictions.getMinNonDustOutput()))).show(); } catch (AddressEntryException e) { new Popup().error(e.getMessage()).show(); } catch (InsufficientMoneyException e) { log.warn(e.getMessage()); new Popup().warning(Res.get("funds.withdrawal.notEnoughFunds") + "\n\nError message:\n" + e.getMessage()).show(); } catch (Throwable e) { log.warn(e.toString()); new Popup().warning(e.toString()).show(); } } private void reset() { withdrawFromTextField.setText(""); withdrawFromTextField.setPromptText(Res.get("funds.withdrawal.selectAddress")); withdrawFromTextField.setTooltip(null); totalAvailableAmountOfSelectedItems = Coin.ZERO; amountAsCoin = Coin.ZERO; sendersAmount = Coin.ZERO; amountTextField.setText(""); amountTextField.setPromptText(Res.get("funds.withdrawal.setAmount")); withdrawToTextField.setText(""); withdrawToTextField.setPromptText(Res.get("funds.withdrawal.fillDestAddress")); withdrawMemoTextField.setText(""); withdrawMemoTextField.setPromptText(Res.get("funds.withdrawal.memo")); selectedItems.clear(); tableView.getSelectionModel().clearSelection(); } private boolean areInputsValid() { if (!sendersAmount.isPositive()) { new Popup().warning(Res.get("validation.negative")).show(); return false; } if (!btcAddressValidator.validate(withdrawToTextField.getText()).isValid) { new Popup().warning(Res.get("validation.btc.invalidAddress")).show(); return false; } if (!totalAvailableAmountOfSelectedItems.isPositive()) { new Popup().warning(Res.get("funds.withdrawal.warn.noSourceAddressSelected")).show(); return false; } if (sendersAmount.compareTo(totalAvailableAmountOfSelectedItems) > 0) { new Popup().warning(Res.get("funds.withdrawal.warn.amountExceeds")).show(); return false; } return true; } // ColumnCellFactories private void setAddressColumnCellFactory() { addressColumn.setCellValueFactory((addressListItem) -> new ReadOnlyObjectWrapper<>(addressListItem.getValue())); addressColumn.setCellFactory( new Callback<>() { @Override public TableCell<WithdrawalListItem, WithdrawalListItem> call(TableColumn<WithdrawalListItem, WithdrawalListItem> column) { return new TableCell<>() { private HyperlinkWithIcon hyperlinkWithIcon; @Override public void updateItem(final WithdrawalListItem item, boolean empty) { super.updateItem(item, empty); if (item != null && !empty) { String address = item.getAddressString(); hyperlinkWithIcon = new ExternalHyperlink(address); hyperlinkWithIcon.setOnAction(event -> openBlockExplorer(item)); hyperlinkWithIcon.setTooltip(new Tooltip(Res.get("tooltip.openBlockchainForAddress", address))); setAlignment(Pos.CENTER); setGraphic(hyperlinkWithIcon); } else { setGraphic(null); if (hyperlinkWithIcon != null) hyperlinkWithIcon.setOnAction(null); } } }; } }); } private void setBalanceColumnCellFactory() { balanceColumn.getStyleClass().add("last-column"); balanceColumn.setCellValueFactory((addressListItem) -> new ReadOnlyObjectWrapper<>(addressListItem.getValue())); balanceColumn.setCellFactory( new Callback<>() { @Override public TableCell<WithdrawalListItem, WithdrawalListItem> call(TableColumn<WithdrawalListItem, WithdrawalListItem> column) { return new TableCell<>() { @Override public void updateItem(final WithdrawalListItem item, boolean empty) { super.updateItem(item, empty); setGraphic((item != null && !empty) ? item.getBalanceLabel() : null); } }; } }); } private void setSelectColumnCellFactory() { selectColumn.getStyleClass().add("first-column"); selectColumn.setCellValueFactory((addressListItem) -> new ReadOnlyObjectWrapper<>(addressListItem.getValue())); selectColumn.setCellFactory( new Callback<>() { @Override public TableCell<WithdrawalListItem, WithdrawalListItem> call(TableColumn<WithdrawalListItem, WithdrawalListItem> column) { return new TableCell<>() { CheckBox checkBox = new AutoTooltipCheckBox(); @Override public void updateItem(final WithdrawalListItem item, boolean empty) { super.updateItem(item, empty); if (item != null && !empty) { checkBox.setOnAction(e -> { item.setSelected(checkBox.isSelected()); selectForWithdrawal(item); // If all are selected we select useAllInputsRadioButton if (observableList.size() == selectedItems.size()) { inputsToggleGroup.selectToggle(useAllInputsRadioButton); } else { // We don't want to get deselected all when we activate the useCustomInputsRadioButton // so we temporarily disable the listener inputsToggleGroup.selectedToggleProperty().removeListener(inputsToggleGroupListener); inputsToggleGroup.selectToggle(useCustomInputsRadioButton); useAllInputs.set(false); inputsToggleGroup.selectedToggleProperty().addListener(inputsToggleGroupListener); } }); setGraphic(checkBox); checkBox.setSelected(item.isSelected()); } else { checkBox.setOnAction(null); setGraphic(null); } } }; } }); } }
package org.dspace.curate; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.sql.SQLException; import java.util.Map; import org.apache.log4j.Logger; import org.dspace.content.DSpaceObject; import org.dspace.content.Item; import org.dspace.doi.CDLDataCiteService; import org.dspace.doi.DryadDOIRegistrationHelper; import org.jdom.input.SAXBuilder; import org.apache.xerces.parsers.SAXParser; import org.dspace.content.DCValue; import org.dspace.core.ConfigurationManager; import org.jdom.Document; import org.jdom.JDOMException; /** * Generates a report of Dryad items with invalid DataCite XML, resulting in * failed DOI Registration. * @author Dan Leehr <dan.leehr@nescent.org> */ @Distributive public class DataCiteXMLValidator extends AbstractCurationTask { private static final Logger log = Logger.getLogger(DataCiteXMLValidator.class); private static final String HEADERS = "\"DOI\",\"Status\",\"Result\",\"Detail\""; private static SAXBuilder builder = new SAXBuilder("org.apache.xerces.parsers.SAXParser", true); private void report(Item item, Integer status, String result, String detail) { //TODO: Do something with the result. // DOI, status code, result, detail DCValue[] dcdoi = item.getMetadata("dc.identifier"); String doi = ""; if (dcdoi.length > 0) { doi = dcdoi[0].value; } String message = String.format("\"%s\",%d,\"%s\",\"%s\"", doi, status, result, detail); report(message); } @Override public int perform(DSpaceObject dso) throws IOException { builder.setFeature("http://apache.org/xml/features/validation/schema", true); // This is stored locally to keep the validation quick. // If we change the datacite schema we must change this as well. String xsdFilePath = ConfigurationManager.getProperty("dspace.dir") + "/config/external-schema/datacite-kernel-2.2/metadata.xsd"; builder.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation", "http://datacite.org/schema/kernel-2.2 file://" + xsdFilePath); report(HEADERS); distribute(dso); return Curator.CURATE_SUCCESS; } /** * Check an individual item and report its XML validation status * @param item * @throws SQLException * @throws IOException */ @Override protected void performItem(Item item) throws SQLException, IOException { // Get the item // Determine if it should be registered Boolean shouldCheck = ( item.isArchived() || DryadDOIRegistrationHelper.isDataPackageInPublicationBlackout(item) ); if(shouldCheck == false) { report(item, Curator.CURATE_SKIP, "not archived or in blackout",null); return; } // crosswalk it to get xml Map<String,String> metadata = CDLDataCiteService.createMetadataListXML(item); // get doi and target? String dataCiteXmlMetadata = metadata.get(CDLDataCiteService.DATACITE); // validate xml against datacite schema // from http://www.jdom.org/docs/faq.html#a0370 try { InputStream in = new ByteArrayInputStream(dataCiteXmlMetadata.getBytes("UTF-8")); Document doc = builder.build(in); report(item, Curator.CURATE_SUCCESS, "Validated", null); } catch (JDOMException ex) { // There was an exception validating String cause = ex.getCause().getMessage(); report(item, Curator.CURATE_FAIL, "Failed", cause); } } }
package org.ethereum.jsontestsuite; import org.ethereum.config.SystemProperties; import org.ethereum.config.blockchain.FrontierConfig; import org.ethereum.config.blockchain.HomesteadConfig; import org.ethereum.config.net.AbstractNetConfig; import org.ethereum.config.net.MainNetConfig; import org.ethereum.jsontestsuite.suite.JSONReader; import org.json.simple.parser.ParseException; import org.junit.*; import org.junit.runners.MethodSorters; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import static org.ethereum.jsontestsuite.suite.JSONReader.getFileNamesForTreeSha; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class GitHubStateTest { //SHACOMMIT of tested commit, ethereum/tests.git public String shacommit = "97066e40ccd061f727deb5cd860e4d9135aa2551"; private long oldForkValue; @Before public void setup() { // TODO remove this after Homestead launch and shacommit update with actual block number // for this JSON test commit the Homestead block was defined as 900000 SystemProperties.getDefault().setBlockchainConfig(new AbstractNetConfig() {{ add(0, new FrontierConfig()); add(1_150_000, new HomesteadConfig()); }}); } @After public void clean() { SystemProperties.getDefault().setBlockchainConfig(MainNetConfig.INSTANCE); } @Ignore @Test // this method is mostly for hands-on convenient testing public void stSingleTest() throws ParseException, IOException { String json = JSONReader.loadJSONFromCommit("StateTests/Homestead/stTransactionTest.json", shacommit); GitHubJSONTestSuite.runStateTest(json, "TransactionSendingToZero"); } @Test public void stExample() throws ParseException, IOException { Set<String> excluded = new HashSet<>(); String json = JSONReader.loadJSONFromCommit("StateTests/stExample.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); } @Test public void stCallCodes() throws ParseException, IOException { Set<String> excluded = new HashSet<>(); String json = JSONReader.loadJSONFromCommit("StateTests/stCallCodes.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); json = JSONReader.loadJSONFromCommit("StateTests/Homestead/stCallCodes.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); } @Test public void stCallDelegateCodes() throws ParseException, IOException { Set<String> excluded = new HashSet<>(); String json = JSONReader.loadJSONFromCommit("StateTests/Homestead/stCallDelegateCodes.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); } @Test public void stCallDelegateCodesCallCode() throws ParseException, IOException { Set<String> excluded = new HashSet<>(); String json = JSONReader.loadJSONFromCommit("StateTests/Homestead/stCallDelegateCodesCallCode.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); } @Test public void stHomeSteadSpecific() throws ParseException, IOException { Set<String> excluded = new HashSet<>(); String json = JSONReader.loadJSONFromCommit("StateTests/Homestead/stHomeSteadSpecific.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); } @Test public void stCallCreateCallCodeTest() throws ParseException, IOException { Set<String> excluded = new HashSet<>(); excluded.add("CallRecursiveBombPreCall"); // Max Gas value is pending to be < 2^63 String json = JSONReader.loadJSONFromCommit("StateTests/stCallCreateCallCodeTest.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); json = JSONReader.loadJSONFromCommit("StateTests/Homestead/stCallCreateCallCodeTest.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); } @Test public void stDelegatecallTest() throws ParseException, IOException { Set<String> excluded = new HashSet<>(); // String json = JSONReader.loadJSONFromCommit("StateTests/stDelegatecallTest.json", shacommit); // GitHubJSONTestSuite.runStateTest(json, excluded); String json = JSONReader.loadJSONFromCommit("StateTests/Homestead/stDelegatecallTest.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); } @Test public void stInitCodeTest() throws ParseException, IOException { Set<String> excluded = new HashSet<>(); String json = JSONReader.loadJSONFromCommit("StateTests/stInitCodeTest.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); json = JSONReader.loadJSONFromCommit("StateTests/Homestead/stInitCodeTest.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); } @Test public void stLogTests() throws ParseException, IOException { Set<String> excluded = new HashSet<>(); String json = JSONReader.loadJSONFromCommit("StateTests/stLogTests.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); json = JSONReader.loadJSONFromCommit("StateTests/Homestead/stLogTests.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); } @Test public void stPreCompiledContracts() throws ParseException, IOException { Set<String> excluded = new HashSet<>(); String json = JSONReader.loadJSONFromCommit("StateTests/stPreCompiledContracts.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); json = JSONReader.loadJSONFromCommit("StateTests/Homestead/stPreCompiledContracts.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); } @Ignore @Test public void stMemoryStressTest() throws ParseException, IOException { Set<String> excluded = new HashSet<>(); excluded.add("mload32bitBound_return2");// The test extends memory to 4Gb which can't be handled with Java arrays excluded.add("mload32bitBound_return"); // The test extends memory to 4Gb which can't be handled with Java arrays excluded.add("mload32bitBound_Msize"); // The test extends memory to 4Gb which can't be handled with Java arrays String json = JSONReader.loadJSONFromCommit("StateTests/stMemoryStressTest.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); json = JSONReader.loadJSONFromCommit("StateTests/Homestead/stMemoryStressTest.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); } @Test public void stMemoryTest() throws ParseException, IOException { Set<String> excluded = new HashSet<>(); String json = JSONReader.loadJSONFromCommit("StateTests/stMemoryTest.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); json = JSONReader.loadJSONFromCommit("StateTests/Homestead/stMemoryTest.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); } @Test public void stQuadraticComplexityTest() throws ParseException, IOException { Set<String> excluded = new HashSet<>(); // leaving only Homestead version since the test runs too long // String json = JSONReader.loadJSONFromCommit("StateTests/stQuadraticComplexityTest.json", shacommit); // GitHubJSONTestSuite.runStateTest(json, excluded); String json = JSONReader.loadJSONFromCommit("StateTests/Homestead/stQuadraticComplexityTest.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); } @Test public void stSolidityTest() throws ParseException, IOException { Set<String> excluded = new HashSet<>(); String json = JSONReader.loadJSONFromCommit("StateTests/stSolidityTest.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); } @Test public void stRecursiveCreate() throws ParseException, IOException { Set<String> excluded = new HashSet<>(); String json = JSONReader.loadJSONFromCommit("StateTests/stRecursiveCreate.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); json = JSONReader.loadJSONFromCommit("StateTests/Homestead/stRecursiveCreate.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); } @Test public void stRefundTest() throws ParseException, IOException { Set<String> excluded = new HashSet<>(); String json = JSONReader.loadJSONFromCommit("StateTests/stRefundTest.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); json = JSONReader.loadJSONFromCommit("StateTests/Homestead/stRefundTest.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); } @Test public void stSpecialTest() throws ParseException, IOException { Set<String> excluded = new HashSet<>(); String json = JSONReader.loadJSONFromCommit("StateTests/stSpecialTest.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); json = JSONReader.loadJSONFromCommit("StateTests/Homestead/stSpecialTest.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); } @Test public void stBlockHashTest() throws ParseException, IOException { String json = JSONReader.loadJSONFromCommit("StateTests/stBlockHashTest.json", shacommit); GitHubJSONTestSuite.runStateTest(json); } @Test public void stSystemOperationsTest() throws IOException { Set<String> excluded = new HashSet<>(); String json = JSONReader.loadJSONFromCommit("StateTests/stSystemOperationsTest.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); json = JSONReader.loadJSONFromCommit("StateTests/Homestead/stSystemOperationsTest.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); } @Test public void stTransactionTest() throws ParseException, IOException { Set<String> excluded = new HashSet<>(); String json = JSONReader.loadJSONFromCommit("StateTests/stTransactionTest.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); json = JSONReader.loadJSONFromCommit("StateTests/Homestead/stTransactionTest.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); } @Test public void stTransitionTest() throws ParseException, IOException { Set<String> excluded = new HashSet<>(); String json = JSONReader.loadJSONFromCommit("StateTests/stTransitionTest.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); } @Test public void stWalletTest() throws ParseException, IOException { Set<String> excluded = new HashSet<>(); String json = JSONReader.loadJSONFromCommit("StateTests/stWalletTest.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); json = JSONReader.loadJSONFromCommit("StateTests/Homestead/stWalletTest.json", shacommit); GitHubJSONTestSuite.runStateTest(json, excluded); } @Test // testing full suite public void testRandomStateGitHub() throws ParseException, IOException { String sha = "99db6f4f5fea3aa5cfbe8436feba8e213d06d1e8"; List<String> fileNames = getFileNamesForTreeSha(sha); List<String> includedFiles = Arrays.asList( "st201504081841JAVA.json", "st201504081842JAVA.json", "st201504081843JAVA.json" ); for (String fileName : fileNames) { if (includedFiles.contains(fileName)) { System.out.println("Running: " + fileName); String json = JSONReader.loadJSON("StateTests//RandomTests/" + fileName); GitHubJSONTestSuite.runStateTest(json); } } } }
package eu.scasefp7.eclipse.umlrec; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.multipart.BodyPart; import com.sun.jersey.multipart.MultiPart; import eu.scasefp7.eclipse.umlrec.parser.ActivityParser; import eu.scasefp7.eclipse.umlrec.parser.UseCaseParser; import eu.scasefp7.eclipse.umlrec.parser.XMIActivityNode; import eu.scasefp7.eclipse.umlrec.parser.XMIEdge; import eu.scasefp7.eclipse.umlrec.parser.XMIUseCaseNode; import javax.imageio.ImageIO; import javax.ws.rs.core.MediaType; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.Path; import org.eclipse.swt.widgets.Display; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import java.awt.Point; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; public class UMLRecognizer { /** Store the image file name */ protected String _fileName = null; /** The UML Server url */ final String BASE_URI = "http://109.231.121.171:8080/UMLServer/"; // TODO - get this from preferences private Image image = new Image(); private String xmi; private boolean isUseCase; private String sourceUMLType; private Display disp; private List<XMIActivityNode> sourceUMLActivityNodes = new ArrayList<XMIActivityNode>(); private List<XMIUseCaseNode> sourceUMLUseCaseNodes = new ArrayList<XMIUseCaseNode>(); private List<XMIEdge> sourceUMLEdges = new ArrayList<XMIEdge>(); private static Map<String, Point> layoutController = new HashMap<String, Point>(); public static final boolean SHOW_IMAGES = false; public static final int THRESH = 200; public static final double SIZE_RATE = 15.0; public static final double DIST_NEIGHBOR_OBJECTS = 5.0; public static final double COVER_AREA_THR = 40.0; public UMLRecognizer(Display disp) { this.disp = disp; } public void setIsUseCase(boolean isUseCase) { this.isUseCase = isUseCase; } public void setImage(String fileName) throws RecognitionException { image.setName(fileName); String[] split = fileName.split("\\."); image.setFormat(split[split.length - 1]); } public void process() throws MissingRecognizerDataException, RecognitionException, IOException { // The process function returns // 0 for a successful run, // -2 if TessData files are missing OR the program failed to analyse the // text of the diagram and // -1 if an unknown error occurred. Client c = Client.create(); WebResource service = c.resource(BASE_URI); ByteArrayOutputStream bas = new ByteArrayOutputStream(); URL url = new File(image.getName()).toURI().toURL(); BufferedImage bi = ImageIO.read(url); ImageIO.write(bi, image.getFormat(), bas); byte[] logo = bas.toByteArray(); // Construct a MultiPart with two body parts MultiPart multiPart = new MultiPart().bodyPart(new BodyPart(image, MediaType.APPLICATION_XML_TYPE)) .bodyPart(new BodyPart(logo, MediaType.APPLICATION_OCTET_STREAM_TYPE)); try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); if (isUseCase) { sourceUMLType = "uml:Use Case"; // POST the request ClientResponse response = service.path("/usecase").type("multipart/mixed").post(ClientResponse.class, multiPart); xmi = response.getEntity(String.class); Document doc = docBuilder.parse(new InputSource(new StringReader(xmi))); UseCaseParser uCaseParser = new UseCaseParser(); uCaseParser.Parsexmi(doc); ArrayList<XMIUseCaseNode> nodes = uCaseParser.getNodes(); ArrayList<XMIEdge> edges = uCaseParser.getEdges(); if (uCaseParser.checkParsedXmiForPapyrus(disp)) { sourceUMLUseCaseNodes = nodes; sourceUMLEdges = edges; } } else { sourceUMLType = "uml:Activity"; // POST the request ClientResponse response = service.path("/activity").type("multipart/mixed").post(ClientResponse.class, multiPart); xmi = response.getEntity(String.class); Document doc = docBuilder.parse(new InputSource(new StringReader(xmi))); ActivityParser activityParser = new ActivityParser(); activityParser.Parsexmi(doc); ArrayList<XMIActivityNode> nodes = activityParser.getNodes(); ArrayList<XMIEdge> edges = activityParser.getEdges(); if (activityParser.checkParsedXmiForPapyrus(disp)) { sourceUMLActivityNodes = nodes; sourceUMLEdges = edges; } } makePapyrusCompliantUML(); } catch (ParserConfigurationException | SAXException | IOException e) { e.printStackTrace(); throw new RuntimeException(e); } return; } public String getXMIcontent() { return this.xmi; } public void setParameters(boolean isUseCase, boolean showImages, int thresh, double sizeRate, double distNeightborObjects, double coverAreaThr) { this.isUseCase = isUseCase; image.setImageThreshold(thresh); image.setRectangleRate(sizeRate); image.setMinDistance(distNeightborObjects); image.setMinRate(coverAreaThr); } public Image getImage() { return image; } public void setXmi(String xmi) { this.xmi = xmi; } /** * Generates a Papyrus compliant UML file from the original UML edges and nodes. * @throws ParserConfigurationException * @throws TransformerException */ private void makePapyrusCompliantUML() { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // uml:Model element Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("uml:Model"); doc.appendChild(rootElement); rootElement.setAttribute("xmi:version","20131001"); rootElement.setAttribute("xmlns:xmi","http: rootElement.setAttribute("xmlns:uml","http: rootElement.setAttribute("xmi:id", getUniqueId()); rootElement.setAttribute("name","model"); if (sourceUMLType.equalsIgnoreCase("uml:Activity")) { // packagedElement element Element packagedElement = doc.createElement("packagedElement"); rootElement.appendChild(packagedElement); packagedElement.setAttribute("xmi:type", "uml:Activity"); packagedElement.setAttribute("xmi:id", getUniqueId()); packagedElement.setAttribute("name", "RootElement"); StringBuilder nodesStringJoiner = new StringBuilder(); if (sourceUMLType.equalsIgnoreCase("uml:Activity")) { for (XMIActivityNode node : sourceUMLActivityNodes) { nodesStringJoiner.append(node.getId() + " "); } } else if (sourceUMLType.equalsIgnoreCase("uml:Use Case")) { for (XMIUseCaseNode node : sourceUMLUseCaseNodes) { nodesStringJoiner.append(node.getId() + " "); } } String nodesString = nodesStringJoiner.toString(); if (nodesString.length() > 0) packagedElement.setAttribute("node", nodesString.substring(0, nodesString.length() - 1)); else packagedElement.setAttribute("node", nodesString); // edge elements for (XMIEdge edge : sourceUMLEdges) { Element edgeElement = doc.createElement("edge"); packagedElement.appendChild(edgeElement); edgeElement.setAttribute("xmi:type",edge.getType()); edgeElement.setAttribute("xmi:id",edge.getId()); String edgeName = edge.getName(); if(edgeName!=null && edgeName.isEmpty()==false) { edgeElement.setAttribute("name", edgeName); } edgeElement.setAttribute("target",edge.getTarget()); edgeElement.setAttribute("source",edge.getSource()); } // node elements for (XMIActivityNode node : sourceUMLActivityNodes) { Element nodeElement = doc.createElement("node"); packagedElement.appendChild(nodeElement); nodeElement.setAttribute("xmi:type",node.getType()); String nodeId = node.getId(); nodeElement.setAttribute("xmi:id", nodeId); String nodeName = node.getName(); if(nodeName!=null && nodeName.isEmpty()==false){ nodeElement.setAttribute("name", nodeName); } nodeElement.setAttribute("incoming",getNodeIncomingEdgeIds(nodeId, node.getIncoming())); nodeElement.setAttribute("outgoing",getNodeOutgoingEdgeIds(nodeId, node.getOutgoing())); List<Point> coordinates = node.getCoordinates(); if(coordinates!=null && coordinates.isEmpty()==false && coordinates.get(0)!=null) { Point nodePoint = coordinates.get(0); layoutController.put(nodeId, nodePoint); } } } else if (sourceUMLType.equalsIgnoreCase("uml:Use Case")) { for (XMIUseCaseNode node : sourceUMLUseCaseNodes) { Element packagedElement = doc.createElement("packagedElement"); rootElement.appendChild(packagedElement); String nodeType = node.getType(); switch(nodeType) { case "uml:UserNode": packagedElement.setAttribute("xmi:type", "uml:Actor"); break; case "uml:UseCaseNode": packagedElement.setAttribute("xmi:type", "uml:UseCase"); break; default: packagedElement.setAttribute("xmi:type", nodeType); break; } String nodeId = node.getId(); packagedElement.setAttribute("xmi:id", nodeId); String nodeName = node.getName(); if(nodeName!=null && nodeName.isEmpty()==false){ packagedElement.setAttribute("name", nodeName); } // generalizations List<String> outgoingSolidNodesIds = node.getOutgoingSolidNodes(); if(outgoingSolidNodesIds!=null && outgoingSolidNodesIds.isEmpty()==false) { for (String outgoingNodeId : outgoingSolidNodesIds) { if(outgoingNodeId.isEmpty()==false) { for (XMIEdge edge : sourceUMLEdges){ if(outgoingNodeId.equals(edge.getTarget()) && edge.getSource().equals(nodeId)) { Element generalization = doc.createElement("generalization"); generalization.setAttribute("xmi:type", "uml:Generalization"); generalization.setAttribute("xmi:id", getUniqueId()); generalization.setAttribute("general", outgoingNodeId); packagedElement.appendChild(generalization); } } } } } // associations List<String> connectedSolidNodesIds = node.getConnectedSolidNodes(); if(connectedSolidNodesIds!=null && connectedSolidNodesIds.isEmpty()==false) { for (String connectedNodeId : connectedSolidNodesIds) { if(connectedNodeId.isEmpty()==false) { for (XMIEdge edge : sourceUMLEdges) { if(connectedNodeId.equals(edge.getTarget()) && edge.getSource().equals(nodeId)) { Element association = doc.createElement("packagedElement"); association.setAttribute("xmi:type", "uml:Association"); String associationId = getUniqueId(); association.setAttribute("xmi:id", associationId); Element ownedEnd1 = doc.createElement("ownedEnd"); ownedEnd1.setAttribute("xmi:type","uml:Property"); String ownedEnd1Id = getUniqueId(); ownedEnd1.setAttribute("xmi:id", ownedEnd1Id); ownedEnd1.setAttribute("name", ""); ownedEnd1.setAttribute("type", nodeId); ownedEnd1.setAttribute("association", associationId); Element ownedEnd2 = doc.createElement("ownedEnd"); ownedEnd2.setAttribute("xmi:type","uml:Property"); String ownedEnd2Id = getUniqueId(); ownedEnd2.setAttribute("xmi:id", ownedEnd2Id); ownedEnd2.setAttribute("name", ""); ownedEnd2.setAttribute("type", connectedNodeId); ownedEnd2.setAttribute("association", associationId); association.setAttribute("memberEnd", ownedEnd1Id+" "+ownedEnd2Id); association.appendChild(ownedEnd1); association.appendChild(ownedEnd2); rootElement.appendChild(association); } } } } } // include - extend List<String> outgoingDashedNodesIds = node.getOutgoingDashedNodes(); if(outgoingDashedNodesIds!=null && outgoingDashedNodesIds.isEmpty()==false) { for (String outgoingNodeId : outgoingDashedNodesIds) { if(outgoingNodeId.isEmpty()==false) { for (XMIEdge edge : sourceUMLEdges) { if(outgoingNodeId.equals(edge.getTarget()) && edge.getSource().equals(nodeId)) { if(edge.getName().equalsIgnoreCase("include")) { Element include = doc.createElement("include"); include.setAttribute("xmi:type", "uml:Include"); String includeId = getUniqueId(); include.setAttribute("xmi:id", includeId); include.setAttribute("addition", outgoingNodeId); packagedElement.appendChild(include); } else if(edge.getName().equalsIgnoreCase("extend")) { Element extend = doc.createElement("extend"); extend.setAttribute("xmi:type", "uml:Extend"); String extendId = getUniqueId(); extend.setAttribute("xmi:id", extendId); extend.setAttribute("extendedCase", outgoingNodeId); packagedElement.appendChild(extend); } } } } } } List<Point> coordinates = node.getCoordinates(); if(coordinates!=null && coordinates.isEmpty()==false && coordinates.get(0)!=null) { Point nodePoint = coordinates.get(0); layoutController.put(node.getId(), nodePoint); } } } // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(2)); StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(doc.getDocumentElement()); transformer.transform(source, result); xmi = sw.toString(); } catch (ParserConfigurationException | TransformerException e) { e.printStackTrace(); throw new RuntimeException(e); } } /** * Generates a unique ID string to use for xmi:id. * @return The resulting unique ID string */ private String getUniqueId() { return "_"+UUID.randomUUID().toString().toUpperCase(); } /** * Gets the correct string for the node incoming property, containing * the incoming edge ids and not the node ids. * @param nodeId - The node's xmi:id * @param incomingNodesIds - The list with the xmi:ids of the incoming nodes * @return incomingEdgeIdsString - The resulting string */ private String getNodeIncomingEdgeIds(String nodeId, List<String> incomingNodesIds) { String incomingEdgeIdsString = ""; if(incomingNodesIds!=null && incomingNodesIds.isEmpty()==false) { List<String> incomingEdgeIds = new ArrayList<String>(); for (String incomingNodeId : incomingNodesIds) { for (XMIEdge edge : sourceUMLEdges){ if(incomingNodeId.equals(edge.getSource()) && edge.getTarget().equals(nodeId)) { incomingEdgeIds.add(edge.getId()); } } } StringBuilder stringJoiner = new StringBuilder(); for (String incomingEdgeId : incomingEdgeIds) { stringJoiner.append(incomingEdgeId + " "); } String string = stringJoiner.toString(); if (string.length() > 0) incomingEdgeIdsString = string.substring(0, string.length() - 1); else incomingEdgeIdsString = string; } return incomingEdgeIdsString; } /** * Gets the correct string for the node outgoing property, containing * the outgoing edge ids and not the node ids. * @param nodeId - The node's xmi:id * @param outgoingNodesIds - The list with the xmi:ids of the outgoing nodes * @return outgoingEdgeIdsString - The resulting string. */ private String getNodeOutgoingEdgeIds(String nodeId, List<String> outgoingNodesIds) { String outgoingEdgeIdsString = ""; if(outgoingNodesIds!=null && outgoingNodesIds.isEmpty()==false) { List<String> outgoingEdgeIds = new ArrayList<String>(); for (String outgoingNodeId : outgoingNodesIds) { for (XMIEdge edge : sourceUMLEdges){ if(outgoingNodeId.equals(edge.getTarget()) && edge.getSource().equals(nodeId)) { outgoingEdgeIds.add(edge.getId()); } } } StringBuilder stringJoiner = new StringBuilder(); for (String outgoingEdgeId : outgoingEdgeIds) { stringJoiner.append(outgoingEdgeId + " "); } String string = stringJoiner.toString(); if (string.length() > 0) outgoingEdgeIdsString = string.substring(0, string.length() - 1); else outgoingEdgeIdsString = string; } return outgoingEdgeIdsString; } public static Map<String, Point> getLayoutController() { return layoutController; } }
package remonsinnema.blog.fizzbuzz; import static org.junit.Assert.assertEquals; import org.junit.Test; public class WhenFizzingAndBuzzing { private final FizzBuzz fizzbuzz = new FizzBuzz(); @Test public void shouldReplaceWithFizzAndBuzz() { assertFizzBuzz("1", 1); } private void assertFizzBuzz(String expected, int n) { assertEquals(Integer.toString(n), expected, fizzbuzz.get(n)); } }
import java.util.HashMap; import java.util.Map; public class UMTP_Sample { public <T, C> C getT(String s, int i, Class<C> cls) { T t = (T) getFoo(); System.out.println(t); return (C) new Object(); } public <T> String fpUseClass(T t) { return t.toString(); } public <T> String fpUseClass(Class<T> c) { return c.getName().toString(); } public <T> String fpUseArray(T[] t) { return t[0].toString(); } private <K, V> Map<V, K> fpKVReverseMap(Map<K, V> map) { Map<V, K> m = new HashMap<V, K>(); for (Map.Entry<K, V> entry : map.entrySet()) { m.put(entry.getValue(), entry.getKey()); } return m; } public <X, Y> void fpEmbedded(Map<X, Map<String, Y>> x) { } public Object getFoo() { return null; } }
package net.katsuster.strview.ui; import java.util.*; import java.io.*; import java.awt.HeadlessException; import javax.swing.*; import net.katsuster.strview.io.*; import net.katsuster.strview.gui.*; import net.katsuster.strview.media.ts.*; public class Main { protected Main() { //do nothing } public static void main(String[] args) { FileDropWindow w = null; if (args.length > 0) { String fname = args[0]; List<File> flist = new ArrayList<File>(); flist.add(new File(fname)); LargeBitList blist = new ByteToBitList(new FileByteList(fname)); TSPacketList tslist = new TSPacketList(blist); //tslist.count(); for (TSPacket a : tslist) { System.out.println(a); } } try { //Look and Feel try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception ex) { ex.printStackTrace(); return; } w = new FileDropWindow(); w.setTitle("bined"); w.setSize(300, 100); w.setVisible(true); } catch (HeadlessException ex) { } } }
package lpn.parser.LpnDecomposition; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Random; import lpn.parser.LhpnFile; import lpn.parser.Place; import lpn.parser.Transition; import lpn.parser.Variable; import verification.platu.lpn.DualHashMap; public class LpnProcess extends LhpnFile { private ArrayList<Transition> processTrans = new ArrayList<Transition>(); private ArrayList<Place> processPlaces = new ArrayList<Place>(); private ArrayList<Variable> processInput = new ArrayList<Variable>(); private ArrayList<Variable> processOutput = new ArrayList<Variable>(); private ArrayList<Variable> processInternal = new ArrayList<Variable>(); private int id; private boolean isStateMachine; public LpnProcess(Integer procId) { id = procId; isStateMachine = true; } public int getProcessId() { return id; } public void addTranToProcess(Transition curTran) { processTrans.add(curTran); } public void addPlaceToProcess(Place curPlace) { processPlaces.add(curPlace); } // /** // * This method assigns at least one sticky transition to each process. Transitions whose preset places are marked are considered to be sticky // * for each process. The purpose of assigning sticky transitions is to break all cycles in each process. In general, one sticky transition is // * sufficient to break the cycle. However, Floyd's all-pairs shortest-path algorithm (binary) is used to find additional transition(s) that can // * help to cut the cycle(s). // */ // @SuppressWarnings("unchecked") // public void assignStickyTransitions() { // // Assign transition(s) with marked post to be sticky // for (Place p : processPlaces) { // if (p.isMarked()) { // if (p.getPreset() != null && p.getPreset().length > 0) { // Transition[] transitions = p.getPreset(); // for (int i=0; i<transitions.length; i++) { // transitions[i].setSticky(true); // else { // Integer selectedTran; // Random rand = new Random(); // selectedTran = rand.nextInt(processTrans.size()); // while (processTrans.get(selectedTran).getName().contains("_dummy")); // processTrans.get(selectedTran).setSticky(true); // ArrayList<Transition> processTransCopy = (ArrayList<Transition>) processTrans.clone(); // ArrayList<Transition> transToRemove = new ArrayList<Transition>(); // DualHashMap<Transition, Integer> tranIndexInMatrixMap = new DualHashMap<Transition, Integer>(); // int index = -1; // for (Iterator<Transition> processTransCopyIter = processTransCopy.iterator(); processTransCopyIter.hasNext();) { // Transition curTran = processTransCopyIter.next(); // if (curTran.isSticky() || curTran.getName().contains("_dummy")) { // transToRemove.add(curTran); // continue; // index++; // tranIndexInMatrixMap.put(curTran, index); // processTransCopy.removeAll(transToRemove); // // Floyd's all-pairs shortest path // ArrayList<ArrayList<Boolean>> matrix = new ArrayList<ArrayList<Boolean>>(); // Integer numCycles = 0; // if (processTransCopy.size() == 0) { // continue; // ArrayList<Boolean> row = new ArrayList<Boolean>(); // for (int i=0; i<processTransCopy.size(); i++) { // for (int j=0; j<processTransCopy.size(); j++) { // row.add(j, false); // matrix.add(i, (ArrayList<Boolean>) row.clone()); // row.clear(); // // find the next reachable transition(s) from the current transition // for (int i=0; i<processTransCopy.size(); i++) { // Transition curTran = processTransCopy.get(i); // for (Place p : curTran.getPostset()) { // for (Transition tran : p.getPostset()) { // if (processTransCopy.contains(tran)) { // Integer tranIndexInMatrix = tranIndexInMatrixMap.get(tran); // Integer curTranIndexInMatrix = tranIndexInMatrixMap.get(curTran); // matrix.get(curTranIndexInMatrix).set(tranIndexInMatrix, true); // // update reachability // for (int k=0; k<processTransCopy.size(); k++) { // for (int i=0; i<processTransCopy.size(); i++) { // for (int j=0; j<processTransCopy.size(); j++) { // if (matrix.get(i).get(k) && matrix.get(k).get(j)) { // matrix.get(i).set(j, true); // // Check to see if there is still any cycles left. If a transition can reach itself, then there is a loop. // Transition tranWithBiggestPreset = new Transition(); // for (int i=0; i<matrix.size(); i++) { // if (matrix.get(i).get(i)) { // numCycles ++; // if (tranIndexInMatrixMap.getKey(i).getPreset().length > tranWithBiggestPreset.getPreset().length) { // tranWithBiggestPreset = tranIndexInMatrixMap.getKey(i); // tranWithBiggestPreset.setSticky(true); // // Remove the sticky transition in the matrix. // Integer tranWithBiggestPresetIndex = tranIndexInMatrixMap.getValue(tranWithBiggestPreset); // processTransCopy.remove(tranWithBiggestPreset); // for (int i=0; i<matrix.size(); i++) { // matrix.get(i).remove(tranWithBiggestPresetIndex); // matrix.remove(tranWithBiggestPresetIndex); // numCycles --; // while (numCycles > 0 && processTransCopy.size() > 0); // public void printProcWithStickyTrans() { // System.out.println("Process ID:" + this.getProcessId()); // for (int i=0; i < this.processTrans.size(); i++) { // if (processTrans.get(i).isSticky()) { // System.out.println(processTrans.get(i).getName() + " " + processTrans.get(i).getIndex()); /** * This method assigns at least one sticky transition to each process. Transitions whose preset places are marked are considered to be sticky * for each process. The purpose of assigning sticky transitions is to break all cycles in each process. In general, one sticky transition is * sufficient to break the cycle. However, Floyds all-pairs shortest-path algorithm (binary) is used to find additional transition(s) that can * help to cut the cycle(s). */ @SuppressWarnings("unchecked") public void assignStickyTransitions() { // Assign transition(s) with marked post to be sticky for (Place p : processPlaces) { if (p.isMarked()) { if (p.getPreset() != null && p.getPreset().length > 0) { Transition[] transitions = p.getPreset(); for (int i=0; i<transitions.length; i++) { transitions[i].setSticky(true); } } else { Integer selectedTran; do { Random rand = new Random(); selectedTran = rand.nextInt(processTrans.size()); } while (processTrans.get(selectedTran).getName().contains("_dummy")); processTrans.get(selectedTran).setSticky(true); } } } ArrayList<Transition> processTransCopy = (ArrayList<Transition>) processTrans.clone(); ArrayList<Transition> transToRemove = new ArrayList<Transition>(); DualHashMap<Transition, Integer> tranIndexInMatrixMap = new DualHashMap<Transition, Integer>(); int index = -1; for (Iterator<Transition> processTransCopyIter = processTransCopy.iterator(); processTransCopyIter.hasNext();) { Transition curTran = processTransCopyIter.next(); if (curTran.isSticky() || curTran.getName().contains("_dummy")) { transToRemove.add(curTran); continue; } index++; tranIndexInMatrixMap.put(curTran, index); } processTransCopy.removeAll(transToRemove); // Floyd's all-pairs shortest path ArrayList<ArrayList<Boolean>> matrix = new ArrayList<ArrayList<Boolean>>(); Integer numCycles = 0; do { if (processTransCopy.size() == 0) { continue; } ArrayList<Boolean> row = new ArrayList<Boolean>(); for (int i=0; i<processTransCopy.size(); i++) { for (int j=0; j<processTransCopy.size(); j++) { row.add(j, false); } matrix.add(i, (ArrayList<Boolean>) row.clone()); row.clear(); } // find the next reachable transition(s) from the current transition for (int i=0; i<processTransCopy.size(); i++) { Transition curTran = processTransCopy.get(i); for (Place p : curTran.getPostset()) { for (Transition tran : p.getPostset()) { if (processTransCopy.contains(tran)) { Integer tranIndexInMatrix = tranIndexInMatrixMap.get(tran); Integer curTranIndexInMatrix = tranIndexInMatrixMap.get(curTran); matrix.get(curTranIndexInMatrix).set(tranIndexInMatrix, true); } } } } // update reachability for (int k=0; k<processTransCopy.size(); k++) { for (int i=0; i<processTransCopy.size(); i++) { for (int j=0; j<processTransCopy.size(); j++) { if (matrix.get(i).get(k) && matrix.get(k).get(j)) { matrix.get(i).set(j, true); } } } } // Check to see if there is still any cycles left. If a transition can reach itself, then there is a loop. Transition tranWithBiggestPreset = new Transition(); for (int i=0; i<matrix.size(); i++) { if (matrix.get(i).get(i)) { numCycles ++; if (tranIndexInMatrixMap.getKey(i).getPreset().length > tranWithBiggestPreset.getPreset().length) { tranWithBiggestPreset = tranIndexInMatrixMap.getKey(i); } } } tranWithBiggestPreset.setSticky(true); // Remove the sticky transition in the matrix. Integer tranWithBiggestPresetIndex = tranIndexInMatrixMap.getValue(tranWithBiggestPreset); processTransCopy.remove(tranWithBiggestPreset); for (int i=0; i<matrix.size(); i++) { matrix.get(i).remove(tranWithBiggestPresetIndex); } matrix.remove(tranWithBiggestPresetIndex); numCycles } while (numCycles > 0 && processTransCopy.size() > 0); } // public void printProcWithStickyTrans() { // System.out.println("Process ID:" + this.getProcessId()); // for (int i=0; i < this.processTrans.size(); i++) { // if (processTrans.get(i).isSticky()) { // System.out.println(processTrans.get(i).getName() + " " + processTrans.get(i).getIndex()); public void print() { System.out.print("Process ID: " + this.getProcessId() + "\n"); ArrayList<Transition> trans = this.getProcessTransitions(); System.out.println("Transitions:"); for (Iterator<Transition> transIter = trans.iterator(); transIter.hasNext();) { System.out.print(transIter.next() + " "); } System.out.print("\n"); System.out.println("Places:"); ArrayList<Place> places = this.getProcessPlaces(); for (Iterator<Place> placesIter = places.iterator(); placesIter.hasNext();) { System.out.print(placesIter.next() + " "); } System.out.print("\n"); System.out.println("Inputs:"); ArrayList<Variable> input = this.getProcessInput(); for (Iterator<Variable> inputIter = input.iterator(); inputIter.hasNext();) { System.out.println(inputIter.next() + " "); } System.out.print("\n"); System.out.println("Outputs:"); ArrayList<Variable> output = this.getProcessOutput(); for (Iterator<Variable> outputIter = output.iterator(); outputIter.hasNext();) { System.out.println(outputIter.next() + " "); } System.out.print("\n"); System.out.println("Internals:"); ArrayList<Variable> internal = this.getProcessInternal(); for (Iterator<Variable> internalIter = internal.iterator(); internalIter.hasNext();) { System.out.println(internalIter.next() + " "); } System.out.print("\n"); System.out.println(" } public ArrayList<Place> getProcessPlaces() { return processPlaces; } public ArrayList<Transition> getProcessTransitions() { return processTrans; } public ArrayList<Variable> getProcessInput() { return processInput; } public ArrayList<Variable> getProcessOutput() { return processOutput; } public ArrayList<Variable> getProcessInternal() { return processInternal; } public ArrayList<Variable> getProcessVariables() { ArrayList<Variable> variables = new ArrayList<Variable>(); variables.addAll(processInput); variables.addAll(processOutput); variables.addAll(processInternal); return variables; } public int getProcessVarSize() { return processInternal.size() + processInput.size() + processOutput.size(); } public LhpnFile buildLPN(LhpnFile lpnProc) { // Places for (int i=0; i< this.getProcessPlaces().size(); i++) { Place p = this.getProcessPlaces().get(i); lpnProc.addPlace(p.getName(), p.isMarked()); } // Transitions for (int i=0; i< this.getProcessTransitions().size(); i++) { Transition t = this.getProcessTransitions().get(i); lpnProc.addTransition(t); } // Inputs for (int i=0; i< this.getProcessInput().size(); i++) { Variable var = this.getProcessInput().get(i); lpnProc.addInput(var.getName(), var.getType(), var.getInitValue()); } // Outputs for (int i=0; i< this.getProcessOutput().size(); i++) { Variable var = this.getProcessOutput().get(i); lpnProc.addOutput(var.getName(), var.getType(), var.getInitValue()); } // Internal for (int i=0; i< this.getProcessInternal().size(); i++) { Variable var = this.getProcessInternal().get(i); lpnProc.addInternal(var.getName(), var.getType(), var.getInitValue()); } return lpnProc; } public void setStateMachineFlag(boolean isSM) { isStateMachine = isSM; } public boolean getStateMachineFlag() { return isStateMachine; } }
package water.automl; import water.api.AbstractRegister; import water.api.RequestServer; import water.automl.api.AutoMLBuilderHandler; import water.automl.api.AutoMLHandler; import water.automl.api.LeaderboardsHandler; import water.util.Log; public class Register extends AbstractRegister{ @Override public void register(String relativeResourcePath) throws ClassNotFoundException { RequestServer.registerEndpoint("automl_build", "POST /99/AutoMLBuilder", AutoMLBuilderHandler.class, "build", "Start an AutoML build process."); RequestServer.registerEndpoint("fetch", "GET /99/AutoML/{automl_id}", AutoMLHandler.class, "fetch", "Fetch the specified AutoML object."); RequestServer.registerEndpoint("list", "GET /99/Leaderboards", LeaderboardsHandler.class, "list", "Return all the AutoML leaderboards."); RequestServer.registerEndpoint("fetch", "GET /99/Leaderboards/{project}", LeaderboardsHandler.class, "fetch", "Return the AutoML leaderboard for the given project."); /* RequestServer.registerEndpoint("automl_schema", "GET /3/AutoMLJSONSchemaHandler", AutoMLJSONSchemaHandler.class, "getJSONSchema", "Get the json schema for the AutoML input fields."); */ Log.info("H2O AutoML extensions enabled."); } }
package water.api; import water.*; import water.fvec.Frame; import water.fvec.Vec; class FramesHandler extends Handler<FramesHandler, FramesBase> { // TODO: handlers should return an object that has the result as well as the needed http headers including status code @Override protected int min_ver() { return 2; } @Override protected int max_ver() { return Integer.MAX_VALUE; } Key key; Frame[] frames; String column; // NOTE: this is needed for request handling, but isn't really part of // state. We should be able to have verb request params that aren't part // of the state. Another example: find_compatible_models is not part of // the Schema. // /2/Frames backward compatibility protected void list_or_fetch() { //if (this.version != 2) if (null != key) { fetch(); } else { list(); } } protected void list() { final Key[] frameKeys = KeySnapshot.globalSnapshot().filter(new KeySnapshot.KVFilter() { @Override public boolean filter(KeySnapshot.KeyInfo k) { return k._type == TypeMap.FRAME; } }).keys(); frames = new Frame[frameKeys.length]; for (int i = 0; i < frameKeys.length; i++) { Frame frame = getFromDKV(frameKeys[i]); frames[i] = frame; } } /** NOTE: We really want to return a different schema here! */ protected void columns() { // TODO: return *only* the columns. . . fetch(); } public static Frame getFromDKV(String key_str) { return getFromDKV(Key.make(key_str)); } public static Frame getFromDKV(Key key) { if (null == key) throw new IllegalArgumentException("Got null key."); Value v = DKV.get(key); if (null == v) throw new IllegalArgumentException("Did not find key: " + key.toString()); Iced ice = v.get(); if (! (ice instanceof Frame)) throw new IllegalArgumentException("Expected a Frame for key: " + key.toString() + "; got a: " + ice.getClass()); return (Frame)ice; } protected void column() { Frame frame = getFromDKV(key); // NOTE: We really want to return a different schema here! Vec vec = frame.vec(column); if (null == vec) throw new IllegalArgumentException("Did not find column: " + column + " in frame: " + key.toString()); Vec[] vecs = { vec }; String[] names = { column }; Frame f = new Frame(names, vecs); frames = new Frame[1]; frames[0] = f; } protected void fetch() { Frame frame = getFromDKV(key); frames = new Frame[1]; frames[0] = frame; } @Override protected FramesBase schema(int version) { switch (version) { case 2: return new FramesV2(); case 3: return new FramesV3(); default: throw H2O.fail("Bad version for Frames schema: " + version); } } // Need to stub this because it's required by H2OCountedCompleter: @Override public void compute2() { throw H2O.fail(); } }
package water.persist; import java.io.*; //import java.net.SocketTimeoutException; //import java.util.Arrays; //import java.util.Properties; import water.Key; import water.Value; import water.H2O; import water.Job; //import water.fvec.Vec; import water.util.Log; //import water.util.RIStream; //import com.amazonaws.ClientConfiguration; //import com.amazonaws.Protocol; //import com.amazonaws.services.s3.AmazonS3; //import com.amazonaws.services.s3.AmazonS3Client; //import com.amazonaws.services.s3.model.*; /** Persistence backend for S3 */ public final class PersistS3 extends Persist { // FIXME: back port here authorization chain from h2o1 private static final String HELP = "You can specify a credentials properties file with the -aws_credentials command line switch."; private static final String KEY_PREFIX = "s3: private static final int KEY_PREFIX_LEN = KEY_PREFIX.length(); private static final Object _lock = new Object(); private static volatile AmazonS3 _s3; private static class AmazonS3 { } /** Initialize the AWS S3 client */ public static AmazonS3 getClient() { if( _s3 == null ) { synchronized( _lock ) { if( _s3 == null ) { try { //_s3 = new AmazonS3Client(H2O.getAWSCredentials(), s3ClientCfg()); throw H2O.unimpl(); } catch( Throwable e ) { StringBuilder msg = new StringBuilder(); msg.append(e.getMessage() + "\n"); msg.append("Unable to load S3 credentials."); if( H2O.ARGS.aws_credentials == null ) msg.append(HELP); Log.throwErr(new RuntimeException(msg.toString())); } } } } return _s3; } //public static final class H2SO3InputStream extends RIStream { // Key _k; // long _to; // String[] _bk; // protected InputStream open(long offset) { // return getClient().getObject(new GetObjectRequest(_bk[0], _bk[1]).withRange(offset, _to)).getObjectContent(); // public H2SO3InputStream(Key k, ProgressMonitor pmon) { // this(k, pmon, 0, Long.MAX_VALUE); // public H2SO3InputStream(Key k, ProgressMonitor pmon, long from, long to) { // super(from, pmon); // _k = k; // _to = Math.min(DKV.get(k).length() - 1, to); // _bk = decodeKey(k); // open(); /** InputStream from a S3-based Key */ public static InputStream openStream(Key k, Job pmon) throws IOException { throw H2O.unimpl(); // return new H2SO3InputStream(k, pmon); } //public static Key loadKey(S3ObjectSummary obj) throws IOException { // Key k = encodeKey(obj.getBucketName(), obj.getKey()); // long size = obj.getSize(); // Value val = null; // if( obj.getKey().endsWith(Extensions.HEX) ) { // Hex file? // int sz = (int) Math.min(ValueArray.CHUNK_SZ, size); // byte[] mem = MemoryManager.malloc1(sz); // May stall a long time to get memory // S3ObjectInputStream is = getObjectForKey(k, 0, ValueArray.CHUNK_SZ).getObjectContent(); // int off = 0; // while( off < sz ) // off += is.read(mem, off, sz - off); // ValueArray ary = new ValueArray(k, sz).read(new AutoBuffer(mem)); // val = new Value(k, ary, Value.S3); // } else if( size >= 2 * ValueArray.CHUNK_SZ ) { // // ValueArray byte wrapper over a large file // val = new Value(k, new ValueArray(k, size), Value.S3); // } else { // val = new Value(k, (int) size, Value.S3); // Plain Value // val.setdsk(); // DKV.put(k, val); // return k; @Override public byte[] load(Value v) { throw H2O.unimpl(); // long start_io_ms = System.currentTimeMillis(); // byte[] b = MemoryManager.malloc1(v._max); // Key k = v._key; // long skip = 0; // // Convert an arraylet chunk into a long-offset from the base file. // if( k._kb[0] == Key.ARRAYLET_CHUNK ) { // skip = ValueArray.getChunkOffset(k); // The offset // k = ValueArray.getArrayKey(k); // From the base file key // if( k.toString().endsWith(Extensions.HEX) ) { // Hex file? // int value_len = DKV.get(k).memOrLoad().length; // How long is the ValueArray header? // skip += value_len; // Skip header // // Too complicate matters, S3 likes to reset connections when H2O hits it // // too hard. We "fix" this by just trying again, assuming we're getting // // hit with a bogus resource limit (H2O doing a parse looks like a DDOS to // // Amazon S3). // S3ObjectInputStream s = null; // while( true ) { // Loop, in case we get premature EOF's // try { // long start_ns = System.nanoTime(); // Blocking i/o call timing - without counting repeats // s = getObjectForKey(k, skip, v._max).getObjectContent(); // ByteStreams.readFully(s, b); // delegate work to Google (it reads the byte buffer in a cycle as we did) // assert v.isPersisted(); // TimeLine.record_IOclose(start_ns, start_io_ms, 1/* read */, v._max, Value.S3); // return b; // // Explicitly ignore the following exceptions but // // fail on the rest IOExceptions // } catch( EOFException e ) { // ignoreAndWait(e, false); // } catch( SocketTimeoutException e ) { // ignoreAndWait(e, false); // } catch( IOException e ) { // ignoreAndWait(e, true); // } finally { // try { // if( s != null ) s.close(); // } catch( IOException e ) {} } //private static void ignoreAndWait(final Exception e, boolean printException) { // H2O.ignore(e, "Hit the S3 reset problem, waiting and retrying...", printException); // try { // Thread.sleep(500); // } catch( InterruptedException ie ) {} @Override public void store(Value v) { throw H2O.unimpl(); // if( !v._key.home() ) return; // // Never store arraylets on S3, instead we'll store the entire array. // assert !v.isArray(); // Key dest = PersistS3Task.init(v); // PersistS3Task.run(dest, v, null, null); } ///** // * Creates the key for given S3 bucket and key. Returns the H2O key, or null if the key cannot be // * created. // * // * @param bucket // * Bucket name // * @param key // * Key name (S3) // * @return H2O key pointing to the given bucket and key. // */ //public static Key encodeKey(String bucket, String key) { // Key res = encodeKeyImpl(bucket, key); //// assert checkBijection(res, bucket, key); // return res; ///** // * Decodes the given H2O key to the S3 bucket and key name. Returns the array of two strings, // * first one is the bucket name and second one is the key name. // * // * @param k // * Key to be decoded. // * @return Pair (array) of bucket name and key name. // */ //public static String[] decodeKey(Key k) { // return decodeKeyImpl(k); //// assert checkBijection(k, res[0], res[1]); //// return res; //// private static boolean checkBijection(Key k, String bucket, String key) { //// Key en = encodeKeyImpl(bucket, key); //// String[] de = decodeKeyImpl(k); //// boolean res = Arrays.equals(k._kb, en._kb) && bucket.equals(de[0]) && key.equals(de[1]); //// assert res : "Bijection failure:" + "\n\tKey 1:" + k + "\n\tKey 2:" + en + "\n\tBkt 1:" + bucket + "\n\tBkt 2:" //// + de[0] + "\n\tStr 1:" + key + "\n\tStr 2:" + de[1] + ""; //// return res; //private static Key encodeKeyImpl(String bucket, String key) { // return Key.make(KEY_PREFIX + bucket + '/' + key); //private static String[] decodeKeyImpl(Key k) { // String s = new String((k._kb[0] == Key.CHK)?Arrays.copyOfRange(k._kb, Vec.KEY_PREFIX_LEN, k._kb.length):k._kb); // assert s.startsWith(KEY_PREFIX) && s.indexOf('/') >= 0 : "Attempting to decode non s3 key: " + k; // s = s.substring(KEY_PREFIX_LEN); // int dlm = s.indexOf('/'); // String bucket = s.substring(0, dlm); // String key = s.substring(dlm + 1); // return new String[] { bucket, key }; //// Gets the S3 object associated with the key that can read length bytes from offset //private static S3Object getObjectForKey(Key k, long offset, long length) throws IOException { // String[] bk = decodeKey(k); // GetObjectRequest r = new GetObjectRequest(bk[0], bk[1]); // r.setRange(offset, offset + length - 1); // Range is *inclusive* according to docs??? // return getClient().getObject(r); //// Gets the object metadata associated with given key. //private static ObjectMetadata getObjectMetadataForKey(Key k) { // String[] bk = decodeKey(k); // assert (bk.length == 2); // return getClient().getObjectMetadata(bk[0], bk[1]); ///** S3 socket timeout property name */ //public final static String S3_SOCKET_TIMEOUT_PROP = "water.s3.socketTimeout"; ///** S3 connection timeout property name */ //public final static String S3_CONNECTION_TIMEOUT_PROP = "water.s3.connectionTimeout"; ///** S3 maximal error retry number */ //public final static String S3_MAX_ERROR_RETRY_PROP = "water.s3.maxErrorRetry"; ///** S3 maximal http connections */ //public final static String S3_MAX_HTTP_CONNECTIONS_PROP = "water.s3.maxHttpConnections"; //static ClientConfiguration s3ClientCfg() { // ClientConfiguration cfg = new ClientConfiguration(); // Properties prop = System.getProperties(); // if( prop.containsKey(S3_SOCKET_TIMEOUT_PROP) ) cfg.setSocketTimeout(Integer.getInteger(S3_SOCKET_TIMEOUT_PROP)); // if( prop.containsKey(S3_CONNECTION_TIMEOUT_PROP) ) cfg.setConnectionTimeout(Integer // .getInteger(S3_CONNECTION_TIMEOUT_PROP)); // if( prop.containsKey(S3_MAX_ERROR_RETRY_PROP) ) cfg.setMaxErrorRetry(Integer.getInteger(S3_MAX_ERROR_RETRY_PROP)); // if( prop.containsKey(S3_MAX_HTTP_CONNECTIONS_PROP) ) cfg.setMaxConnections(Integer // .getInteger(S3_MAX_HTTP_CONNECTIONS_PROP)); // cfg.setProtocol(Protocol.HTTP); // return cfg; @Override public void delete(Value v) { throw H2O.fail(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package benchmarks.dataStatistics; import benchmarks.DatabaseEngineInterfaces.CassandraInterface; import benchmarks.helpers.Pair; import java.io.*; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; /** * @author pedro */ public class ResultHandler { private int testsamples = 100; String test_name; //pair(time,result) private HashMap<String, ArrayList<Pair<Long,Long>>> results; private HashMap<String, HashMap<String, Long>> events; /** * @param run_data_divisions the division in the data by runs. If -1 all will be inserted un the same run; */ public ResultHandler(String name, int run_data_divisions) { this.test_name = name; testsamples = run_data_divisions; results = new HashMap<String, ArrayList<Pair<Long,Long>>>(); events = new HashMap<String, HashMap<String, Long>>(); } public void logResult(String operation, long result) { Pair<Long,Long> resultPair = new Pair<Long, Long>(System.currentTimeMillis(), result); if (!results.containsKey(operation)) { results.put(operation, new ArrayList<Pair<Long, Long>>()); } results.get(operation).add(resultPair); } public void countEvent(String eventType, String event, long number) { if (!events.containsKey(eventType)) { HashMap<String, Long> new_events = new HashMap<String, Long>(); new_events.put(event, number); events.put(eventType, new_events); } else { if (!events.get(eventType).containsKey(event)) { events.get(eventType).put(event, number); } else { long count = events.get(eventType).get(event) + number; events.get(eventType).put(event, count); } } } public void cleanResults() { results.clear(); System.gc(); } public void addResults(ResultHandler other_results) { Map<String, ArrayList<Pair<Long,Long>>> new_results = other_results.results; for (String event_name : new_results.keySet()) { if (!this.results.containsKey(event_name)) { this.results.put(event_name, new_results.get(event_name)); } else { for (Pair<Long,Long> l : new_results.get(event_name)) { this.results.get(event_name).add(l); } } } Map<String, HashMap<String, Long>> new_events = other_results.events; for (String event_name : new_events.keySet()) { if (!this.events.containsKey(event_name)) { this.events.put(event_name, new_events.get(event_name)); } else { HashMap<String, Long> new_event_count = new_events.get(event_name); HashMap<String, Long> this_event_count = this.events.get(event_name); for (String event_count_name : new_event_count.keySet()) { if (this_event_count.containsKey(event_count_name)) { this_event_count.put(event_count_name, this_event_count.get(event_count_name) + new_event_count.get(event_count_name)); } else { this_event_count.put(event_count_name, new_event_count.get(event_count_name)); } } } } } public void listDataToSOutput() { System.out.println("\n\n System.out.println("--runs: " + testsamples); for (String dataOperation : results.keySet()) { System.out.println("OPERATION: " + dataOperation); ArrayList<Pair<Long,Long>> result_data = results.get(dataOperation); boolean do_multipleruns = testsamples < 0 ? false : true; int total_amount = 0; int currrent_amount = 0; int current_run = 0; int run = 0; ArrayList<Long> run_result = new ArrayList<Long>(); for (Pair<Long,Long> res : result_data) { run_result.add(res.right); total_amount += res.right; currrent_amount += res.right; current_run += 1; if (do_multipleruns && current_run == testsamples) { System.out.println("--RESULTS FOR RUN " + run + ""); double average = (currrent_amount * 1.0d) / (testsamples * 1.0d); System.out.println("Average: " + average); double variance = 0.0; long aux = 0; for (Long run_res : run_result) { aux += Math.pow((run_res - average), 2); } variance = aux * (1d / (run_result.size() - 1d)); System.out.println("Variance: " + variance); run++; currrent_amount = 0; current_run = 0; run_result = new ArrayList<Long>(); } } if (!result_data.isEmpty()) { System.out.println(" double average = (total_amount * 1.0d) / (result_data.size() * 1.0d); System.out.println("Average: " + average); double variance = 0.0; long aux = 0; for (Pair<Long,Long> run_res : result_data) { aux += Math.pow((run_res.right - average), 2); } variance = aux * (1d / (result_data.size() - 1d)); System.out.println("Variance: " + variance + "\n\n"); } } if (!events.isEmpty()) { System.out.println("****EVENT COUNT****"); for (String eventType : events.keySet()) { System.out.println("+EVENT TYPE: " + eventType); for (String event : events.get(eventType).keySet()) { System.out.println("\t>>" + event + " : " + events.get(eventType).get(event)); } } } } public void listDataToFile(String filename) { } public void listDataToFile(File filename) { } public void listDatatoFiles(String folder_name, String perfix, boolean doMultiple) { System.out.println("\n\n File enclosing_folder = new File(folder_name); if (!enclosing_folder.isDirectory()) { System.out.println("NOT A FOLDER: ENCLOSING FOLDER USED"); enclosing_folder = enclosing_folder.getParentFile(); } GregorianCalendar date = new GregorianCalendar(); String suffix = date.get(GregorianCalendar.YEAR) + "_" + date.get(GregorianCalendar.MONTH) + "_" + date.get(GregorianCalendar.DAY_OF_MONTH) + "_" + date.get(GregorianCalendar.HOUR_OF_DAY) + "_" + date.get(GregorianCalendar.MINUTE) + ""; File folder = new File(enclosing_folder.getAbsolutePath()+"/"+ test_name + suffix); if (!folder.exists()) { boolean created = folder.mkdir(); if (!created) { System.out.println("RESULT FOLDER DOES NOT EXISTS AND CANT BE CREATED"); return; } } System.out.println("OUTPUT FOLDER: " + folder.getName()); resultComparator comparator = new resultComparator(); for (String dataOperation : results.keySet()) { System.out.println("OPERATION: " + dataOperation); ArrayList<Pair<Long,Long>> result_data = results.get(dataOperation); boolean do_multipleruns = (testsamples < 0 && doMultiple) ? false : true; int current_run = 0; int run = 0; File operation_results_file = new File(folder.getPath() +"/"+ dataOperation); FileOutputStream out = null; BufferedOutputStream stream = null; try { out = new FileOutputStream(operation_results_file); stream = new BufferedOutputStream(out); } catch (FileNotFoundException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } try { if(!do_multipleruns) { stream.write(("results , time \n").getBytes()); } else{ stream.write(("results , time , run\n").getBytes()); } } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } int length = result_data.size(); for (int z =0;z<length;z++) { Pair<Long,Long> res = result_data.get(z); current_run += 1; String result_line = res.right + " , "+res.left+""; if (do_multipleruns) { result_line = result_line + " , " + run; } result_line = result_line + "\n"; if (do_multipleruns && current_run == testsamples) { run++; } try { stream.write(result_line.getBytes()); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } try { stream.flush(); stream.close(); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } finally { try { out.close(); } catch (IOException ex) { Logger.getLogger(CassandraInterface.class.getName()).log(Level.SEVERE, null, ex); } } } if (!events.isEmpty()) { System.out.println("****WRITING EVENT COUNT****"); for (String eventType : events.keySet()) { File event_results_file = new File(folder.getPath() +"/" + eventType); FileOutputStream out = null; BufferedOutputStream stream = null; try { out = new FileOutputStream(event_results_file); stream = new BufferedOutputStream(out); } catch (FileNotFoundException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } System.out.println("+EVENT TYPE: " + eventType); for (String event : events.get(eventType).keySet()) { // System.out.println("\t>>" + event + " : " + events.get(eventType).get(event)); try { out.write((event + " , " + events.get(eventType).get(event) + "").getBytes()); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } try { stream.flush(); stream.close(); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } finally { try { out.close(); } catch (IOException ex) { Logger.getLogger(CassandraInterface.class.getName()).log(Level.SEVERE, null, ex); } } } } } public void doRstatistcs(String filePerfix) { } class resultComparator implements Comparator { public int compare(Object o1, Object o2) { if(!(o1 instanceof Pair) ||!(o2 instanceof Pair)) return 0; Pair<Long,Long> p1 = (Pair<Long, Long>) o1; Pair<Long,Long> p2 = (Pair<Long, Long>) o2; if (p1.left > p2.left) return 1; else if (p1.left < p2.left) return -1; else return 0; } } }
///import java.util.ArrayList; import java.lang.reflect.Array; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; /** * GradeMap was suppose to be a simple hashmap / array list combo but it seems that the concept does not scale, * once passing 100 entries, there was a slight performance drop, which seem to cause too much lag. Thus I decided to drop * the arraylist and do a hashmap within a hashmap. Furthermore, I decided to treat each test as its own object, known as * Grade. * * Previously it was StudentID, {ArrayList<Grade>()} but the scaling with entries was not that effective.... * thus I decided to rewrite it using the below.. * * GradeData => {StudentID}, {HashMap<TestID, Grade()>} * * * * * * @author h0lybyte * This is for my CS102 class... */ public class GradeMap { // public static HashMap<Integer,ArrayList<Grade>> GradeData = new HashMap<Integer,ArrayList<Grade>>(); public static HashMap<Integer, HashMap<Integer, Grade>> GradeData = new HashMap<Integer, HashMap<Integer, Grade>>(); /** Inserts a grade into the GradeData hashmap, if the studentID is not in the system, it will add the student id and * repeat itself. (semi-recursion). * * => Check if studentID is in the GradeData * if not, then .put(studentID, empty ArrayList<Grade) and recursion * else * if, then check if ArrayList is there or check if the Arraylist is null. * if the array list is null, then it will create a temp arraylist and add the new grade. * if the array list is there, it will check if the testid exists OR it will add the grade. * @param studentID * @param testID * @param grade * @return */ @SuppressWarnings("unused") public static Boolean insertGrade(int studentID, int testID , int grade) { // Temp Variables to play with have to be added, they will be used as a temp reference, hence the variable name.. temp. // First check if the GradeData has the studentID if(GradeData.containsKey(studentID)) { /** // Check if the GradeData has a valid object * * */ if(GradeData.get(studentID) == null) { // ArrayList<Grade> temp = new ArrayList<Grade>(); // It returns null, so we have to add a new personal Map, with the first entry being that testID. HashMap<Integer, Grade> temp = new HashMap<Integer, Grade>(); temp.put(testID, new Grade(studentID, testID, grade)); GradeData.remove(studentID); GradeData.put(studentID, temp); //"Personal Grade was made and the first entry was this test grade. System.out.println("Personal Grade was made and the first entry was this test grade."); return true; } else { // personal gradeData map exists for the user... now there are 2 areas... // First we must check to see if the testID already exists if(GradeData.get(studentID).get(testID) != null) { System.out.println("testID is already in the system, please use the update method"); return false; } // Since its not in the system, we will go ahead and add the new Grade.. else { System.out.println("Grade as been inserted"); GradeData.get(studentID).put(testID, new Grade(studentID, testID, grade)); // After some trimming, I was able to reduce the actual insert operation to 1 line. // GradeData.get(studentID) fetches the personal HashMap<testID, Grade()> // put(testID, new Grade(studentID, testID, grade) inserts the testID and the new grade. return true; } } } else /** If the studentID is not in the system, then we will go ahead and automatically add the studentID and their test * * */ { HashMap<Integer, Grade> temp = new HashMap<Integer, Grade>(); // New temp map temp.put(testID, new Grade(studentID, testID, grade)); // insert the first test scores GradeData.remove(studentID); // remove any old information, to prevent collisions GradeData.put(studentID, temp); // insert the student id and their first test. // GradeData.put(studentID, new ArrayList<Grade>()); System.out.println("StudentID was not in the system... automatically inserting"); return true; } } @SuppressWarnings({ "unused", "rawtypes" }) public static void fetchGrades(int studentID) { // Checks if the student is in the system, if null, then system.out that he is not there. if(GradeData.get(studentID) == null) { System.out.println("The student is not in the system"); } else { //ArrayList<Grade> temp = GradeData.get(studentID); Iterator<Entry<Integer, Grade>> it = GradeData.get(studentID).entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry)it.next(); System.out.println(pairs.getKey() + " = " + pairs.getValue()); //it.remove(); // avoids a ConcurrentModificationException } } } @SuppressWarnings({ "unused", "rawtypes" }) public static void fetchAverage(int studentID) { int temp_test = 0; int temp_total = 0; // Checks if the student is in the system, if null, then system.out that he is not there. if(GradeData.get(studentID) == null) { System.out.println("The student is not in the system"); } else { //ArrayList<Grade> temp = GradeData.get(studentID); Iterator<Entry<Integer, Grade>> it = GradeData.get(studentID).entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry)it.next(); // System.out.println(pairs.getKey() + " = " + pairs.getValue()); temp_test++; temp_total = temp_total + ((Grade)pairs.getValue()).getgrade(); //it.remove(); // avoids a ConcurrentModificationException } System.out.println("StudentID " + studentID + " : Average => " + temp_total/temp_test); } } public static int getScore(int studentID, int testID) { if(GradeData.get(studentID) == null) { System.out.println("The student is not in the system"); } else { Iterator<Entry<Integer, Grade>> it = GradeData.get(studentID).entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry)it.next(); if(pairs.getKey().equals(testID)) { //System.out.println(((Grade)pairs.getValue()).getgrade()); return ((Grade)pairs.getValue()).getgrade(); } } } return -1; } // This method returns true or false based on the removal of the testID from the personal Hashmap for the studentID public static Boolean removeGrade(int studentID, int testID) { // Checks if the student is in the GradeData Map if(GradeData.get(studentID) == null) { //StudentID's Personal Grade map was not in the system. System.out.println("StudentID's Personal Grade map was not in the system."); return false; } else { // If the student is in the map, check if they have taken the test. if(!GradeData.get(studentID).containsKey(testID)) { System.out.println("Student: "+studentID + " has no records of " + testID); return false; } else { GradeData.get(studentID).remove(testID); System.out.println("Removed " + testID + " from StudentID " + studentID); return true; } } //return false; } // Simple function to convert an integer to a Letter (char) public static char score2letter(int score) { char result; if (score >= 90) { result = 'A'; } else if (score >= 80) { result = 'B'; } else if (score >= 70) { result = 'C'; } else if (score >= 60) { result = 'D'; } else { result = 'F'; } return result; } public Array getArray(int studentID) { return null; } public static void main(String [] args) { // Lets do some basic debuging // Insert 2 tests and fetch user insertGrade(1,1,100); System.out.println(score2letter(getScore(1,1))); } }
package net.runelite.http.service.cache; import java.io.IOException; import java.util.ArrayList; import java.util.List; import net.runelite.cache.fs.Archive; import net.runelite.cache.fs.Index; import net.runelite.cache.fs.Storage; import net.runelite.cache.fs.Store; import net.runelite.cache.index.FileData; import net.runelite.http.service.cache.beans.ArchiveEntry; import net.runelite.http.service.cache.beans.CacheEntry; import net.runelite.http.service.cache.beans.FileEntry; import net.runelite.http.service.cache.beans.IndexEntry; import org.sql2o.Connection; import org.sql2o.ResultSetIterable; public class CacheStorage implements Storage { private CacheEntry cacheEntry; private final CacheDAO cacheDao; private final Connection con; public CacheStorage(CacheEntry cacheEntry, CacheDAO cacheDao, Connection con) { this.cacheEntry = cacheEntry; this.cacheDao = cacheDao; this.con = con; } public CacheEntry getCacheEntry() { return cacheEntry; } public void setCacheEntry(CacheEntry cacheEntry) { this.cacheEntry = cacheEntry; } @Override public void init(Store store) throws IOException { } @Override public void close() throws IOException { } @Override public void load(Store store) throws IOException { List<IndexEntry> indexes = cacheDao.findIndexesForCache(con, cacheEntry); List<FileData> fileData = new ArrayList<>(); for (IndexEntry indexEntry : indexes) { Index index = store.addIndex(indexEntry.getIndexId()); index.setCrc(indexEntry.getCrc()); index.setRevision(indexEntry.getRevision()); try (ResultSetIterable<ArchiveEntry> archives = cacheDao.findArchivesForIndex(con, indexEntry)) { for (ArchiveEntry archiveEntry : archives) { Archive archive = index.addArchive(archiveEntry.getArchiveId()); archive.setNameHash(archiveEntry.getNameHash()); archive.setCrc(archiveEntry.getCrc()); archive.setRevision(archiveEntry.getRevision()); archive.setHash(archiveEntry.getHash()); // File data is not necessary for cache updating } } } } @Override public void save(Store store) throws IOException { for (Index index : store.getIndexes()) { IndexEntry entry = cacheDao.findOrCreateIndex(con, cacheEntry, index.getId(), index.getCrc(), index.getRevision()); // this assumes nothing is associated to the cache yet cacheDao.associateIndexToCache(con, cacheEntry, entry); for (Archive archive : index.getArchives()) { ArchiveEntry archiveEntry = cacheDao.findArchive(con, entry, archive.getArchiveId(), archive.getNameHash(), archive.getCrc(), archive.getRevision()); if (archiveEntry == null) { byte[] hash = archive.getHash(); archiveEntry = cacheDao.createArchive(con, entry, archive.getArchiveId(), archive.getNameHash(), archive.getCrc(), archive.getRevision(), hash); for (FileData file : archive.getFileData()) { cacheDao.associateFileToArchive(con, archiveEntry, file.getId(), file.getNameHash()); } } cacheDao.associateArchiveToIndex(con, archiveEntry, entry); } } } @Override public byte[] loadArchive(Archive archive) throws IOException { throw new UnsupportedOperationException(); } @Override public void saveArchive(Archive archive, byte[] data) throws IOException { throw new UnsupportedOperationException(); } }
package com.exedio.cope.instrument; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.Reader; import java.io.Writer; import java.util.ArrayList; import java.util.Iterator; import java.util.zip.CRC32; import java.util.zip.CheckedInputStream; import java.util.zip.CheckedOutputStream; import com.exedio.cope.NestingRuntimeException; public final class Main { /** * @return whether the output file is different to the input file */ static boolean inject(final File inputfile, final File outputfile, final JavaRepository repository) throws IOException, InjectorParseException { //System.out.println("injecting from "+inputfile+" to "+outputfile); if(!inputfile.exists()) throw new RuntimeException("error: input file " + inputfile.getAbsolutePath() + " does not exist."); if(!inputfile.isFile()) throw new RuntimeException("error: input file " + inputfile.getAbsolutePath() + " is not a regular file."); if(outputfile.exists()) { if(inputfile.getCanonicalPath().equals(outputfile.getCanonicalPath())) throw new RuntimeException("error: input file and output file are the same."); if(!outputfile.isFile()) throw new RuntimeException("error: output file is not a regular file."); } final CRC32 inputCRC = new CRC32(); final CRC32 outputCRC = new CRC32(); Reader input=null; Writer output=null; try { input =new InputStreamReader(new CheckedInputStream(new FileInputStream(inputfile), inputCRC)); output=new OutputStreamWriter(new CheckedOutputStream(new FileOutputStream(outputfile), outputCRC)); (new Injector(input, output, new Instrumentor(), repository)).parseFile(); input.close(); output.close(); } catch(InjectorParseException e) { e.printStackTrace(); throw new InjectorParseException(inputfile.getAbsolutePath() + " does not exist"); } finally { if(input!=null) input.close(); if(output!=null) output.close(); } return inputCRC.getValue() != outputCRC.getValue(); } private static final String TEMPFILE_SUFFIX=".temp_cope_injection"; private void inject(final File tobemodifiedfile, final JavaRepository repository) throws IOException, InjectorParseException { final File outputfile=new File(tobemodifiedfile.getAbsolutePath()+TEMPFILE_SUFFIX); if(inject(tobemodifiedfile, outputfile, repository)) { logInstrumented(tobemodifiedfile); if(!outputfile.exists()) throw new RuntimeException("not exists "+outputfile+"."); if(!tobemodifiedfile.delete()) throw new RuntimeException("deleting "+tobemodifiedfile+" failed."); if(!outputfile.renameTo(tobemodifiedfile)) throw new RuntimeException("renaming "+outputfile+" to "+tobemodifiedfile+" failed."); } else { logSkipped(tobemodifiedfile); if(!outputfile.exists()) throw new RuntimeException("not exists "+outputfile+"."); if(!outputfile.delete()) throw new RuntimeException("deleting "+tobemodifiedfile+" failed."); } } public static void main(final String[] args) { try { (new Main()).run(new File("."), args, true); } catch(RuntimeException e) { e.printStackTrace(); throw e; } catch(IllegalParameterException e) { e.printStackTrace(); throw new NestingRuntimeException(e); } catch(InjectorParseException e) { e.printStackTrace(); throw new NestingRuntimeException(e); } catch(IOException e) { e.printStackTrace(); throw new NestingRuntimeException(e); } } Main() {} private void printUsage(PrintStream o) { o.println("usage:"); o.print("java "); o.print(getClass().getName()); o.println(" tobemodified1.java ..."); } final void run(final File dir, final String[] args, final boolean verbose) throws IllegalParameterException, InjectorParseException, IOException { final ArrayList sourcefiles = new ArrayList(); for(int i=0; i<args.length; i++) sourcefiles.add(new File(dir, args[i])); if(sourcefiles.isEmpty()) throw new IllegalParameterException("nothing to do."); final JavaRepository repository = new JavaRepository(); this.verbose = verbose; instrumented = 0; skipped = 0; for(Iterator i=sourcefiles.iterator(); i.hasNext(); ) inject((File)i.next(), repository); if(verbose || instrumented>0) System.out.println("Instrumented " + instrumented + ' ' + (instrumented==1 ? "file" : "files") + ", skipped " + skipped + " in " + dir); } boolean verbose; int skipped; int instrumented; private void logSkipped(final File file) { if(verbose) System.out.println("Instrumented " + file); skipped++; } private void logInstrumented(final File file) { if(verbose) System.out.println("Skipped " + file); instrumented++; } }
package info.limpet.impl; import info.limpet.IChangeListener; import info.limpet.ICommand; import info.limpet.IDocument; import info.limpet.IStoreGroup; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.UUID; import javax.measure.unit.Unit; import org.eclipse.january.DatasetException; import org.eclipse.january.dataset.DatasetUtils; import org.eclipse.january.dataset.IDataset; import org.eclipse.january.dataset.ILazyDataset; import org.eclipse.january.dataset.DoubleDataset; import org.eclipse.january.metadata.AxesMetadata; abstract public class Document<T extends Object> implements IDocument<T> { // TODO: long-term, find a better place for this public static enum InterpMethod { Linear, Nearest, Before, After }; /** * _dataset isn't final, sincew we replace it when the document is re-calculated */ protected IDataset dataset; final protected ICommand predecessor; final private List<IChangeListener> changeListeners = new ArrayList<IChangeListener>(); private transient List<IChangeListener> transientChangeListeners = new ArrayList<IChangeListener>(); private IStoreGroup parent; final private UUID uuid; final private List<ICommand> dependents = new ArrayList<ICommand>(); private Unit<?> indexUnits; public Document(IDataset dataset, ICommand predecessor) { this.dataset = dataset; this.predecessor = predecessor; uuid = UUID.randomUUID(); } @UIProperty(name = "IndexUnits", category = "Label", visibleWhen = "indexed == true") @Override public Unit<?> getIndexUnits() { return indexUnits; } /** * set the units for the index data * * @param units */ public void setIndexUnits(Unit<?> units) { if (!isIndexed()) { throw new IllegalArgumentException( "Index not present, cannot set index units"); } indexUnits = units; } public IDataset getDataset() { return dataset; } public void setDataset(IDataset dataset) { this.dataset = dataset; } /* * (non-Javadoc) * * @see info.limpet.IDocument#beingDeleted() */ @Override public void beingDeleted() { final List<IChangeListener> listeners = new ArrayList<IChangeListener>(); listeners.addAll(getListeners()); for (final IChangeListener s : listeners) { s.collectionDeleted(this); } } /** * collate a list of the listeners for this document * * @return */ private List<IChangeListener> getListeners() { final List<IChangeListener> listeners = new ArrayList<IChangeListener>(); listeners.addAll(changeListeners); listeners.addAll(dependents); // since the TCLs are (by definition) transient, we may not have any // (such as after file restore). So, first check that they're present if (transientChangeListeners != null) { listeners.addAll(transientChangeListeners); } return listeners; } /* * (non-Javadoc) * * @see info.limpet.IDocument#getName() */ @Override @UIProperty(name = "Name", category = UIProperty.CATEGORY_LABEL) public String getName() { final String res; if (dataset != null) { res = dataset.getName(); } else { res = null; } return res; } /* * (non-Javadoc) * * @see info.limpet.IDocument#setName(java.lang.String) */ @Override public void setName(String name) { dataset.setName(name); fireDataChanged(); } /* * (non-Javadoc) * * @see info.limpet.IDocument#getParent() */ @Override public IStoreGroup getParent() { return parent; } /* * (non-Javadoc) * * @see info.limpet.IDocument#setParent(info.limpet.IStoreGroup) */ @Override public void setParent(IStoreGroup parent) { this.parent = parent; } /* * (non-Javadoc) * * @see info.limpet.IDocument#addChangeListener(info.limpet.IChangeListener) */ @Override public void addChangeListener(IChangeListener listener) { changeListeners.add(listener); } /* * (non-Javadoc) * * @see info.limpet.IDocument#addChangeListener(info.limpet.IChangeListener) */ @Override public void addTransientChangeListener(IChangeListener listener) { // we may need to re-create it, if we've been restored from file if (transientChangeListeners == null) { transientChangeListeners = new ArrayList<IChangeListener>(); } transientChangeListeners.add(listener); } /* * (non-Javadoc) * * @see info.limpet.IDocument#removeChangeListener(info.limpet.IChangeListener) */ @Override public void removeChangeListener(IChangeListener listener) { changeListeners.remove(listener); } @Override public void removeTransientChangeListener( IChangeListener collectionChangeListener) { transientChangeListeners.remove(collectionChangeListener); } /* * (non-Javadoc) * * @see info.limpet.IDocument#fireDataChanged() */ @Override public void fireDataChanged() { final List<IChangeListener> listeners = getListeners(); for (final IChangeListener s : listeners) { s.dataChanged(this); } } @Override public void fireMetadataChanged() { final List<IChangeListener> listeners = getListeners(); for (final IChangeListener s : listeners) { s.metadataChanged(this); } } /* * (non-Javadoc) * * @see info.limpet.IDocument#getUUID() */ @Override public UUID getUUID() { return uuid; } /* * (non-Javadoc) * * @see info.limpet.IDocument#size() */ @Override @UIProperty(name = "Size", category = UIProperty.CATEGORY_LABEL) public int size() { return dataset.getSize(); } /* * (non-Javadoc) * * @see info.limpet.IDocument#isIndexed() */ @Override @UIProperty(name = "Indexed", category = UIProperty.CATEGORY_LABEL) public boolean isIndexed() { // is there an axis? final AxesMetadata am = dataset.getFirstMetadata(AxesMetadata.class); // is it a time axis? return am != null; } private static class DoubleIterator implements Iterator<Double> { private double[] _data; private int _ctr; private DoubleIterator(double[] data) { _data = data; _ctr = 0; } @Override public boolean hasNext() { return _ctr < _data.length; } @Override public Double next() { return _data[_ctr++]; } @Override public void remove() { throw new IllegalArgumentException( "Remove operation not provided for this iterator"); } } /* * (non-Javadoc) * * @see info.limpet.IDocument#getIndices() */ @Override public Iterator<Double> getIndex() { DoubleIterator res = null; if (isIndexed()) { final AxesMetadata am = dataset.getFirstMetadata(AxesMetadata.class); ILazyDataset ds = am.getAxes()[0]; try { DoubleDataset dd = (DoubleDataset) DatasetUtils.sliceAndConvertLazyDataset(ds); double[] items = dd.getData(); res = new DoubleIterator(items); } catch (DatasetException e) { throw new IllegalArgumentException(e); } } return res; } /* * (non-Javadoc) * * @see info.limpet.IDocument#isQuantity() */ @Override @UIProperty(name = "Quantity", category = UIProperty.CATEGORY_LABEL) public boolean isQuantity() { return false; } /* * (non-Javadoc) * * @see info.limpet.IDocument#getPrecedent() */ @Override public ICommand getPrecedent() { return predecessor; } /* * (non-Javadoc) * * @see info.limpet.IDocument#addDependent(info.limpet.ICommand) */ @Override public void addDependent(ICommand command) { dependents.add(command); } /* * (non-Javadoc) * * @see info.limpet.IDocument#removeDependent(info.limpet.ICommand) */ @Override public void removeDependent(ICommand command) { dependents.remove(command); } /* * (non-Javadoc) * * @see info.limpet.IDocument#getDependents() */ @Override public List<ICommand> getDependents() { return dependents; } /** * temporarily use this - until we're confident about replacing child Dataset objects * */ @Override public void clearQuiet() { dataset = null; } @Override final public String toString() { return getName(); } /** * produce this document as a listing * * @return */ abstract public String toListing(); }
package de.lebk.verein.member; import de.lebk.verein.lease.Lease; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; import java.util.Random; /** * * @author raddatz * @date 15.12.2016 */ public class Member { private String firstName; private String lastName; private String password; private String username; private char sex; private GregorianCalendar entered; private List<Lease> leases; public Member(String firstName, String lastName, String password, char sex, GregorianCalendar entered) { this.firstName = firstName; this.lastName = lastName; this.password = password; this.username = generateUsername(firstName, lastName); this.sex = sex; this.entered = entered; } public String getFullName() { return firstName + " " + lastName; } public String getDateTimeEntered() { return entered.get(Calendar.DATE) + "." + entered.get(Calendar.MONTH) + "." + entered.get(Calendar.YEAR); } private String generateUsername(String fName, String lName) { // TODO make usernames unique Random uniqueNumber = new Random(); return fName.toLowerCase().substring(0, 2) + (lName.toLowerCase().contains(" ") ? lName.toLowerCase().substring(0, lName.toLowerCase().indexOf(" ")) : lName.toLowerCase()) + uniqueNumber.nextInt(Integer.MAX_VALUE); } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public char getSex() { return sex; } public void setSex(char sex) { this.sex = sex; } public GregorianCalendar getEntered() { return entered; } public void setEntered(GregorianCalendar entered) { this.entered = entered; } public List<Lease> getLeases() { return leases; } public void setLeases(List<Lease> leases) { this.leases = leases; } }
package jade; //#MIDP_EXCLUDE_BEGIN import jade.core.Runtime; import jade.core.Profile; import jade.core.ProfileImpl; import jade.core.ProfileException; import jade.core.Specifier; import jade.util.leap.ArrayList; import jade.util.leap.Iterator; import jade.util.leap.List; import jade.util.leap.Properties; import jade.util.Logger; import java.util.StringTokenizer; import java.util.Stack; import java.util.Enumeration; import java.io.*; /** * Boots <B><em>JADE</em></b> system, parsing command line arguments. * * @author Giovanni Rimassa - Universita` di Parma * @version $Date$ $Revision$ * */ public class Boot { private static final String DEFAULT_FILENAME = "leap.properties"; /** * Fires up the <b><em>JADE</em></b> system. * This method initializes the Profile Manager and then starts the * bootstrap process for the <B><em>JADE</em></b> * agent platform. */ public static void main(String args[]) { try { // Create the Profile ProfileImpl p = null; if (args.length > 0) { if (args[0].startsWith("-")) { // Settings specified as command line arguments p = new ProfileImpl(parseCmdLineArgs(args)); } else { // Settings specified in a property file p = new ProfileImpl(args[0]); } } else { // Settings specified in the default property file p = new ProfileImpl(DEFAULT_FILENAME); } // Start a new JADE runtime system Runtime.instance().startUp(p); } catch (ProfileException pe) { System.err.println("Error creating the Profile ["+pe.getMessage()+"]"); pe.printStackTrace(); printUsage(); //System.err.println("Usage: java jade.Boot <filename>"); System.exit(-1); } catch (IllegalArgumentException iae) { System.err.println("Command line arguments format error. "+iae.getMessage()); iae.printStackTrace(); printUsage(); //System.err.println("Usage: java jade.Boot <filename>"); System.exit(-1); } } private static Properties parseCmdLineArgs(String[] args) throws IllegalArgumentException { Properties props = new Properties(); int i = 0; while (i < args.length) { if (args[i].startsWith("-")) { // Parse next option if (args[i].equalsIgnoreCase("-container")) { props.setProperty(Profile.MAIN, "false"); } else if (args[i].equalsIgnoreCase("-gui")) { props.setProperty("gui", "true"); } else if (args[i].equalsIgnoreCase("-name")) { if (++i < args.length) { props.setProperty(Profile.PLATFORM_ID, args[i]); } else { throw new IllegalArgumentException("No platform name specified after \"-name\" option"); } } else if (args[i].equalsIgnoreCase("-host")) { if (++i < args.length) { props.setProperty(Profile.MAIN_HOST, args[i]); } else { throw new IllegalArgumentException("No host name specified after \"-host\" option"); } } else if (args[i].equalsIgnoreCase("-port")) { if (++i < args.length) { props.setProperty(Profile.MAIN_PORT, args[i]); } else { throw new IllegalArgumentException("No port number specified after \"-port\" option"); } } else if (args[i].equalsIgnoreCase("-conf")) { if (++i < args.length) { // Some parameters are specified in a properties file try { Properties pp = new Properties(); pp.load(args[i]); Enumeration kk = pp.keys(); while (kk.hasMoreElements()) { String key = (String) kk.nextElement(); props.setProperty(key, pp.getProperty(key)); } } catch (Exception e) { Logger.println("WARNING: error loading properties from file "+args[i]+". "+e); } } else { throw new IllegalArgumentException("No configuration file name specified after \"-conf\" option"); } } else if (args[i].equalsIgnoreCase("-mtp")) { if (++i < args.length) { props.setProperty(Profile.MTPS, args[i]); } else { throw new IllegalArgumentException("No mtps specified after \"-mtp\" option"); } if (props.getProperty("nomtp") != null) { Logger.println("WARNING: both \"-mtp\" and \"-nomtp\" options specified. The latter will be ignored"); } } else if (args[i].equalsIgnoreCase("-nomtp")) { props.setProperty("nomtp", "true"); if (props.getProperty(Profile.MTPS) != null) { Logger.println("WARNING: both \"-mtp\" and \"-nomtp\" options specified. The latter will be ignored"); } } else if (args[i].equalsIgnoreCase("-agents")) { if (++i < args.length) { props.setProperty(Profile.AGENTS, args[i]); } else { throw new IllegalArgumentException("No agents specified after \"-agents\" option"); } } else { String name = args[i].substring(1); if (++i < args.length) { props.setProperty(name, args[i]); } else { throw new IllegalArgumentException("No value specified for property \""+name+"\""); } } ++i; } else { // Get agents at the end of command line if (props.getProperty(Profile.AGENTS) != null) { Logger.println("WARNING: overriding agents specification set with the \"-agents\" option"); } String agents = args[i]; props.setProperty(Profile.AGENTS, args[i]); if (++i < args.length) { Logger.println("WARNING: ignoring command line argument "+args[i]+" occurring after agents specification"); if (agents != null && agents.indexOf('(') != -1 && !agents.endsWith(")")) { Logger.println("Note that agent arguments specifications must not contain spaces"); } if (args[i].indexOf(':') != -1) { Logger.println("Note that agent specifications must be separated by a semicolon character \";\" without spaces"); } } break; } } return props; } private static void printUsage() { System.out.println("Usage 1:"); System.out.println("java -cp <classpath> jade.Boot <property-file-name>"); System.out.println("\nUsage 2:"); System.out.println("java -cp <classpath> jade.Boot [options] [agents]"); System.out.println("Options:"); System.out.println(" -container"); System.out.println(" -gui"); System.out.println(" -name <platform-name>"); System.out.println(" -host <main-host>"); System.out.println(" -port <main-port>"); System.out.println(" -mtp <semicolon-separated mtp-specifiers>"); System.out.println(" where mtp-specifier = [in-address:]<mtp-class>[(comma-separated args)]"); System.out.println(" -nomtp"); System.out.println(" -<property-name> <property-value>"); System.out.println("Agents: [-agents] <semicolon-separated agent-specifiers>"); System.out.println(" where agent-specifier = <agent-name>:<agent-class>[(comma separated args)]"); System.out.println(); } //#MIDP_EXCLUDE_END }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Vector; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import sopc2dts.Logger; import sopc2dts.generators.DTSGenerator; import sopc2dts.generators.KernelHeadersGenerator; import sopc2dts.generators.SopcCreateHeaderFilesImitator; import sopc2dts.lib.BoardInfo; import sopc2dts.lib.SopcInfoSystem; import sopc2dts.lib.components.SopcInfoComponent; public class Sopc2DTS { protected Vector<CommandLineOption> vOptions = new Vector<CommandLineOption>(); protected CLParameter showHelp = new CLParameter(""+false); protected CLParameter showVersion = new CLParameter("" + false); protected CLParameter verbose = new CLParameter("" + false); protected CLParameter mimicAlteraTools = new CLParameter("" + false); protected CLParameter inputFileName = new CLParameter(""); protected CLParameter boardFileName = new CLParameter(""); protected CLParameter outputFileName = new CLParameter(""); protected CLParameter outputType = new CLParameter("dts"); protected CLParameter pov = new CLParameter(""); protected CLParameter bootargs = new CLParameter(""); protected CLParameter sopcParameters = new CLParameter("none"); SopcInfoComponent.parameter_action dumpParameters = SopcInfoComponent.parameter_action.NONE; protected String programName; /** * @param args */ public static void main(String[] args) { Sopc2DTS s2d = new Sopc2DTS("sopc2dts"); try { if(s2d.parseCmdLine(args)) { s2d.go(); } } catch(Exception e) { System.err.println(e); s2d.printUsage(); } } public Sopc2DTS(String pName) { programName = pName; vOptions.add(new CommandLineOption("board", "b", boardFileName, true, false,"The board description file", "boardinfo file")); vOptions.add(new CommandLineOption("help" ,"h", showHelp, false,false,"Show this usage info and exit",null)); vOptions.add(new CommandLineOption("verbose" ,"v", verbose, false,false,"Show Lots of debugging info", null)); vOptions.add(new CommandLineOption("version" ,null,showVersion, false,false,"Show version information and exit", null)); vOptions.add(new CommandLineOption("mimic-sopc-create-header-files" ,"m", mimicAlteraTools, false,false,"Try to (mis)behave like sopc-create-header-files does", null)); vOptions.add(new CommandLineOption("input", "i", inputFileName, true, true, "The sopcinfo file (if not supplied the current dir is scanned for one)", "sopcinfo file")); vOptions.add(new CommandLineOption("output", "o", outputFileName, true, false,"The output filename","filename")); vOptions.add(new CommandLineOption("pov", "p", pov, true, false,"The point of view to generate from. Defaults to the first cpu found", "component name")); vOptions.add(new CommandLineOption("type", "t", outputType, true, false,"The type of output to generate", "{dts,uboot,kernel,kernel-full}")); vOptions.add(new CommandLineOption("bootargs", null,bootargs, true, false,"Default kernel arguments for the \"chosen\" section of the DTS", "kernel-args")); vOptions.add(new CommandLineOption("sopc-parameters", null,sopcParameters, true, false,"What sopc-parameters to include in DTS: none, cmacro or all.", "choice")); } protected void go() { BoardInfo bInfo = null; File f; if(inputFileName.value.length()==0) { System.out.println("No input file specified!"); printUsage(); } if(boardFileName.value.length()>0) { f = new File(boardFileName.value); if(f.exists()) { try { bInfo = new BoardInfo(new InputSource(new BufferedReader(new FileReader(f)))); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } f = null; } if(bInfo==null) { bInfo = new BoardInfo(); } if(pov.value.length()>0) { bInfo.setPov(pov.value); } f = new File(inputFileName.value); if(f.exists()) { try { SopcInfoSystem sys = new SopcInfoSystem(new InputSource(new BufferedReader(new FileReader(f)))); if(bInfo.getPov().length()==0) { for(int i=0; (i<sys.getSystemComponents().size()) && (bInfo.getPov().length()==0); i++) { if(sys.getSystemComponents().get(i).getScd().getGroup().equalsIgnoreCase("cpu")) { bInfo.setPov(sys.getSystemComponents().get(i).getInstanceName()); } } } if(Boolean.parseBoolean(mimicAlteraTools.value)) { SopcCreateHeaderFilesImitator fake = new SopcCreateHeaderFilesImitator(sys); Vector<SopcInfoComponent> vMasters = sys.getMasterComponents(); for(SopcInfoComponent master : vMasters) { BufferedWriter out = new BufferedWriter(new FileWriter(master.getInstanceName()+".h")); bInfo.setPov(master.getInstanceName()); out.write(fake.getOutput(bInfo)); out.close(); } } else { String generatedData = null; if(bootargs.value.length()>0) { bInfo.setBootArgs(bootargs.value); } if(outputType.value.equalsIgnoreCase("dts")) { DTSGenerator dGen = new DTSGenerator(sys); generatedData = dGen.getOutput(bInfo, dumpParameters); } else if(outputType.value.equalsIgnoreCase("uboot")) { generatedData = "Whoops, I guess I was bluffing. uboot support is not yet done"; } else if(outputType.value.equalsIgnoreCase("kernel")) { KernelHeadersGenerator kGen = new KernelHeadersGenerator(sys); generatedData = kGen.getOutput(null); } else if(outputType.value.equalsIgnoreCase("kernel-full")) { SopcCreateHeaderFilesImitator fake = new SopcCreateHeaderFilesImitator(sys); generatedData = fake.getOutput(bInfo); } else { System.out.println("Unsupported output type: " + outputType.value); } if(generatedData!=null) { if(outputFileName.value.length()==0) { System.out.println(generatedData); } else { BufferedWriter out = new BufferedWriter(new FileWriter(outputFileName.value)); out.write(generatedData); out.close(); } } } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { System.out.println("Inputfile " + inputFileName.value + " not found"); } } protected String[] intelliSplit(String inp, int splitChar) { Vector<String> vRes = new Vector<String>(); boolean escape=false; boolean quoted=false; String tmp = ""; int i=0; while(i<inp.length()) { if(inp.charAt(i) == '\"') { if(!escape) quoted = !quoted; tmp+=inp.charAt(i); escape=false; } else if(inp.charAt(i) == '\\') { escape=true; tmp += inp.charAt(i); } else if((inp.charAt(i) == splitChar)&& !escape && !quoted) { if(tmp.length()>0) { vRes.add(tmp); tmp = ""; } } else { tmp += inp.charAt(i); escape=false; } i++; } if(tmp.length()>0) { vRes.add(tmp); } return vRes.toArray(new String[0]); } protected boolean parseCmdLine(String[] args) throws Exception { int argPos = 0; int oldPos = 0; String cmdLine = ""; while(argPos<args.length) { cmdLine += args[argPos++] + ' '; } argPos=0; args=intelliSplit(cmdLine, ' '); while(argPos<args.length) { oldPos = argPos; for(int iHandler=0; (iHandler<vOptions.size()) && (argPos<args.length); iHandler++) { argPos = vOptions.get(iHandler).scanCmdLine(args, argPos); } if(oldPos == argPos) { //No parser found!!! System.out.println("Option " + args[argPos] +" not understood."); printUsage(); return false; } } if(Boolean.parseBoolean(showHelp.value)) { printUsage(); return false; } if(Boolean.parseBoolean(showVersion.value)) { printVersion(); return false; } Logger.setVerbose(Boolean.parseBoolean(verbose.value)); if(sopcParameters.value.equalsIgnoreCase("none")) { dumpParameters = SopcInfoComponent.parameter_action.NONE; } else if(sopcParameters.value.equalsIgnoreCase("cmacro")) { dumpParameters = SopcInfoComponent.parameter_action.CMACRCO; } else if(sopcParameters.value.equalsIgnoreCase("all")) { dumpParameters = SopcInfoComponent.parameter_action.ALL; } return true; } protected void printUsage() { printVersion(); System.out.println("Usage: " + programName + " <arguments>"); System.out.println("Required Arguments:"); String longOpts = ""; String shortOpts = ""; for(int i=0; i<vOptions.size(); i++) { if(vOptions.get(i).isRequired()) { longOpts += vOptions.get(i).getDesc(); shortOpts += vOptions.get(i).getShortDesc(); } } System.out.println(longOpts); System.out.println(shortOpts); System.out.println("Optional Arguments:"); longOpts = ""; shortOpts = ""; for(int i=0; i<vOptions.size(); i++) { if(!vOptions.get(i).isRequired()) { longOpts += vOptions.get(i).getDesc(); shortOpts += vOptions.get(i).getShortDesc(); } } System.out.println(longOpts); System.out.println(shortOpts); } public void printVersion() { System.out.println(programName + " - 0.1"); } protected class CLParameter { public String value; public CLParameter(String val) { value = val; } } protected class CommandLineOption { String option; String shortOption; String helpDesc; CLParameter parameter; String parameterDesc; boolean isRequired; boolean hasValue; public CommandLineOption(String opt, String shortOpt, CLParameter param, boolean hasVal, boolean req, String help, String paramDesc) { option = opt; shortOption = shortOpt; helpDesc = help; parameter = param; parameterDesc = paramDesc; isRequired = req; hasValue = hasVal; if(isRequired) { helpDesc += (" (Required)"); } else { helpDesc += (" (Optional)"); } } int scanCmdLine(String[] opts, int index) throws Exception { if(opts[index].charAt(0)!='-') { //Assume it's the sopcinfo file inputFileName.value = opts[index]; index++; } else { String[] tmpOpts = intelliSplit(opts[index],'='); if((tmpOpts[0].equals("--" + option)) || ((shortOption!=null)&&(tmpOpts[0].equals('-' + shortOption)))) { if(parameter!=null) { if(hasValue) { String val; if(tmpOpts.length==1) { if(index<(opts.length-1)) { index++; } else { throw new Exception("Missing argument"); } val = opts[index]; } else { val = tmpOpts[1]; } parameter.value = val; } else { parameter.value = "" + true; } } if(parameter==verbose) { Logger.setVerbose(Boolean.parseBoolean(parameter.value)); } Logger.log("Scanned option " + option + '(' + shortOption + ") with"); if(hasValue) { Logger.logln(" value " + parameter.value); } else { Logger.logln("out value."); } index++; } } return index; } boolean isRequired() { return isRequired; } String getDesc() { return " --" + option + ((!hasValue ?"\t\t" : " <" + parameterDesc + ">\t")) + helpDesc + "\n"; } String getShortDesc() { if(shortOption!=null) { return " -" + shortOption + ((!hasValue ? "\t\t" : " <" + parameterDesc + ">\t")) + "Short for --" + option + "\n"; } else { return ""; } } } }
package pupila; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.border.TitledBorder; import javax.swing.JSeparator; import javax.swing.JEditorPane; import java.awt.Font; public class Janela { private JFrame frmD; public JTextField txtKjh; private JTextField textField_1; private ButtonGroup group; /** * Launch the application. */ public static void main(String[] args) { try { // Set cross-platform Java L&F (also called "Metal") UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); } catch (UnsupportedLookAndFeelException e) { // handle exception } catch (ClassNotFoundException e) { // handle exception } catch (InstantiationException e) { // handle exception } catch (IllegalAccessException e) { // handle exception } EventQueue.invokeLater(new Runnable() { public void run() { try { Janela window = new Janela(); window.frmD.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public Janela() throws Exception{ initialize(); } /** * Initialize the contents of the frame. */ private void initialize() throws Exception { frmD = new JFrame(); frmD.setResizable(false); frmD.setTitle("Pupilometria - Tratamento de resultados"); frmD.setBounds(100, 100, 537, 457); frmD.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frmD.getContentPane().setLayout(null); JButton btnNewButton = new JButton("Buscar..."); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { LeitorTXT leitura = new LeitorTXT(); try {leitura.LerOlho(0);}catch(Exception e) {} txtKjh.setText(leitura.getArq()); } }); btnNewButton.setBounds(304, 34, 77, 23); frmD.getContentPane().add(btnNewButton); txtKjh = new JTextField(); txtKjh.setText(""); txtKjh.setEditable(false); txtKjh.setBounds(10, 35, 282, 20); frmD.getContentPane().add(txtKjh); txtKjh.setColumns(10); JLabel lblLocalDoArquivo = new JLabel("Arquivo de dados original:"); lblLocalDoArquivo.setBounds(10, 11, 245, 23); frmD.getContentPane().add(lblLocalDoArquivo); JPanel panel = new JPanel(); panel.setBorder(new TitledBorder(null, "Olho examinado", TitledBorder.LEADING, TitledBorder.TOP, null, null)); panel.setBounds(402, 29, 116, 84); frmD.getContentPane().add(panel); panel.setLayout(null); JRadioButton rdbtnDireito = new JRadioButton("Direito"); rdbtnDireito.setSelected(true); rdbtnDireito.setBounds(6, 23, 57, 23); panel.add(rdbtnDireito); JRadioButton rdbtnEsquerdo = new JRadioButton("Esquerdo"); rdbtnEsquerdo.setSelected(false); rdbtnEsquerdo.setBounds(6, 54, 71, 23); panel.add(rdbtnEsquerdo); group = new ButtonGroup(); group.add(rdbtnDireito); group.add(rdbtnEsquerdo); textField_1 = new JTextField(); textField_1.setBounds(10, 388, 508, 23); frmD.getContentPane().add(textField_1); textField_1.setColumns(10); JLabel lblVetorCorrigidoseparado = new JLabel("Vetor corrigido (separado por tabula\u00E7\u00F5es):"); lblVetorCorrigidoseparado.setBounds(10, 363, 211, 14); frmD.getContentPane().add(lblVetorCorrigidoseparado); JButton btnExecutar = new JButton("EXECUTAR LIMPEZA"); btnExecutar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { LeitorTXT le = new LeitorTXT(); Limpeza lim = new Limpeza(); Grava grv = new Grava(); le.mediaLargAlt(); lim.Limpa(); lim.Suaviza(); grv.Gravar("vetor",le.getPasta(),lim.getSuave()); textField_1.setText(grv.getVetorTab()); textField_1.selectAll(); textField_1.copy(); } }); btnExecutar.setBounds(10, 80, 231, 33); frmD.getContentPane().add(btnExecutar); JButton btnSalvar = new JButton("SALVAR"); btnSalvar.setBounds(251, 80, 130, 33); frmD.getContentPane().add(btnSalvar); JSeparator separator = new JSeparator(); separator.setBounds(10, 135, 511, 20); frmD.getContentPane().add(separator); JEditorPane editorPane = new JEditorPane(); editorPane.setBounds(10, 191, 238, 146); frmD.getContentPane().add(editorPane); JEditorPane editorPane_1 = new JEditorPane(); editorPane_1.setBounds(275, 191, 231, 146); frmD.getContentPane().add(editorPane_1); JLabel lblOriginal = new JLabel("ORIGINAL"); lblOriginal.setFont(new Font("Tahoma", Font.BOLD, 11)); lblOriginal.setBounds(10, 166, 77, 14); frmD.getContentPane().add(lblOriginal); JLabel lblCorrigido = new JLabel("CORRIGIDO"); lblCorrigido.setFont(new Font("Tahoma", Font.BOLD, 11)); lblCorrigido.setBounds(275, 166, 84, 14); frmD.getContentPane().add(lblCorrigido); } public void setTxt(String txt) { txtKjh.setText(txt); JOptionPane.showMessageDialog(null, txt); } }
import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; public class Window extends JPanel{ public static void main(String[] args) { // TODO Auto-generated method stub SwingUtilities.invokeLater(new Runnable(){ @Override public void run() { JFrame restaurantFrame = new JFrame("restaurant"); restaurantFrame.setSize(800,800); restaurantFrame.setResizable(false); restaurantFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); restaurantFrame.add(new Window()); restaurantFrame.setVisible(true); } }); } private BufferedImage tableImage=null; public Window(){ File imageFile = new File("img/s.png"); try { tableImage = ImageIO.read(imageFile); } catch (IOException e) { System.err.println("Blad odczytu obrazka"); e.printStackTrace(); } new RestaurationManager().start(); } @Override public void paintComponent(Graphics g){ Graphics2D g2 = (Graphics2D) g; g2.drawImage(tableImage, 0,0, this); } }
it package concurrency; import java.util.LinkedList; import java.util.Queue; /** * Implement add() and remove() methods for the queue data structure. * * The queue should be a bounded queue i.e. at any point of time, it can only * hold a specified number of elements. * * The queue should be blocking i.e. if a thread is trying to read from the * queue, and does not find any elements left to read, then it should wait until * an element becomes available. Similarly, if a thread is trying to write to * the queue, and finds the queue to be full, then it should wait until an * element is removed from the queue. * * The queue should be fair i.e. if there are 10 readers waiting to read from * the queue, and if a queue element becomes available for reading, then the * reader thread that arrived earliest in time should be allowed access to read * the element, and other reader threads should continue to remain blocked. * Similarly, if there are 10 writers waiting to write to the queue, and if * slots become available in the queue for writing, then the writer thread that * arrived earliest in time should be allowed access to write to the free slot, * and the other writer threads should continue to remain blocked. */ public class BoundedBlockingQueue<T> { private final Queue<T> elementQueue; private final Queue<Long> readerQueue; private final Queue<Long> writerQueue; private final int capacity; public BoundedBlockingQueue(int capacity) { if (capacity < 0) { throw new IllegalArgumentException(String.format( "Queue size cannot be negative. You passed: %d", capacity)); } this.capacity = capacity; this.elementQueue = new LinkedList<T>(); this.readerQueue = new LinkedList<Long>(); this.writerQueue = new LinkedList<Long>(); } public synchronized void add(T element) throws InterruptedException { long threadId = Thread.currentThread().getId(); writerQueue.add(threadId); while (writerQueue.size() == capacity || writerQueue.peek() != threadId) { wait(); } writerQueue.remove(); elementQueue.add(element); notifyAll(); // notify all waiting readers as well as writers. } public synchronized T remove() throws InterruptedException { long threadId = Thread.currentThread().getId(); readerQueue.add(threadId); while (elementQueue.isEmpty() || readerQueue.peek() != threadId) { wait(); } readerQueue.remove(); T toReturn = elementQueue.remove(); notifyAll(); // notify all waiting readers as well as writers. return toReturn; } }
package com.pubnub.api; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static com.pubnub.api.matchers.JSONAssert.assertJSONArrayHas; import static com.pubnub.api.matchers.JSONAssert.assertJSONArrayHasNo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; public class NamespaceTest { Pubnub pubnub = new Pubnub("demo", "demo"); String random; @Before public void setUp() { pubnub.setCacheBusting(false); random = UUID.randomUUID().toString().substring(0, 8); } @Test public void testGetAllNamespacesAndRemoveThem() throws InterruptedException, JSONException, PubnubException { JSONObject result; JSONArray resultNamespaces; final CountDownLatch latch1 = new CountDownLatch(3); final CountDownLatch latch2 = new CountDownLatch(1); final CountDownLatch latch3 = new CountDownLatch(3); final CountDownLatch latch4 = new CountDownLatch(1); final TestHelper.SimpleCallback cb1 = new TestHelper.SimpleCallback(latch1); final TestHelper.SimpleCallback cb2 = new TestHelper.SimpleCallback(latch2); final TestHelper.SimpleCallback cb3 = new TestHelper.SimpleCallback(latch3); final TestHelper.SimpleCallback cb4 = new TestHelper.SimpleCallback(latch4); String[] groups = new String[]{"jtest1" + random, "jtest2" + random, "jtest3" + random}; String[] namespaces = new String[]{"jspace1" + random, "jspace2" + random, "jspace13" + random}; // add for (int i = 0; i < groups.length; i++) { String group = groups[i]; String namespace = namespaces[i]; pubnub.channelGroupAddChannel(namespace + ":" + group, "ch1", cb1); } latch1.await(10, TimeUnit.SECONDS); // get pubnub.channelGroupListNamespaces(cb2); latch2.await(10, TimeUnit.SECONDS); result = (JSONObject) cb2.getResponse(); resultNamespaces = result.getJSONArray("namespaces"); assertFalse("Error is thrown", cb1.responseIsError()); assertEquals("OK", cb1.getResponse()); assertJSONArrayHas(namespaces[0], resultNamespaces); assertJSONArrayHas(namespaces[1], resultNamespaces); assertJSONArrayHas(namespaces[2], resultNamespaces); // remove pubnub.channelGroupRemoveNamespace(namespaces[0], cb3); pubnub.channelGroupRemoveNamespace(namespaces[1], cb3); pubnub.channelGroupRemoveNamespace(namespaces[2], cb3); latch3.await(10, TimeUnit.SECONDS); Thread.sleep(1000); // get again pubnub.channelGroupListNamespaces(cb4); latch4.await(10, TimeUnit.SECONDS); result = (JSONObject) cb4.getResponse(); resultNamespaces = result.getJSONArray("namespaces"); assertFalse("Error is thrown", cb3.responseIsError()); assertEquals("OK", cb3.getResponse()); assertJSONArrayHasNo(namespaces[0], resultNamespaces); assertJSONArrayHasNo(namespaces[1], resultNamespaces); assertJSONArrayHasNo(namespaces[2], resultNamespaces); } }
package org.jpos.iso; import java.io.*; import java.util.*; import org.jpos.iso.packager.XMLPackager; /** * implements <b>Leaf</b> for binary fields * * See the * <a href="API_users_guide.html">API User's Guide</a> * for details. * * @author apr@cs.com.uy * @version $Id$ * @see ISOComponent */ public class ISOBinaryField extends ISOComponent implements Cloneable { protected int fieldNumber; protected byte[] value; /** * @param n - the FieldNumber */ public ISOBinaryField(int n) { fieldNumber = n; } /** * @param n - fieldNumber * @param v - fieldValue */ public ISOBinaryField(int n, byte[] v) { fieldNumber = n; value = v; } /** * @param n - fieldNumber * @param v - fieldValue * @param offset - starting offset * @param len - field length */ public ISOBinaryField(int n, byte[] v, int offset, int len) { byte[] b = new byte[len]; System.arraycopy (v, offset, b, 0, len); fieldNumber = n; value = b; } /** * not available on Leaf - always throw ISOException * @exception ISOException */ public byte[] pack() throws ISOException { throw new ISOException ("Not available on Leaf"); } /** * not available on Leaf - always throw ISOException * @exception ISOException */ public int unpack(byte[] b) throws ISOException { throw new ISOException ("Not available on Leaf"); } /** * @return Object representing this field number */ public Object getKey() { return new Integer(fieldNumber); } /** * @return Object representing this field value */ public Object getValue() { return value; } /** * @param obj - Object representing this field value * @exception ISOException */ public void setValue(Object obj) throws ISOException { value = (byte[]) obj; } /** * @return byte[] representing this field */ public byte[] getBytes() { return value; } /** * dump this field to PrintStream. The output is sorta * XML, intended to be easily parsed. * @param p - print stream * @param indent - optional indent string */ public void dump (PrintStream p, String indent) { p.println (indent +"<"+XMLPackager.ISOFIELD_TAG + " " + XMLPackager.ID_ATTR +"=\"" +fieldNumber +"\" "+ XMLPackager.VALUE_ATTR +"=\"" +this.toString() + "\" " + XMLPackager.TYPE_ATTR +"=\"" + XMLPackager.TYPE_BINARY + "\"/>" ); } public String toString() { return ISOUtil.hexString(value); } }
package Parser; import java.security.InvalidParameterException; import org.joda.time.DateTime; import taskDo.SearchType; import taskDo.Task; import taskDo.TaskType; import commandFactory.CommandType; import commonClasses.Constants; import commonClasses.SummaryReport; public class OptionalCommandInterpreter extends CommandInterpreter { enum OptionalCommand { DUE, FROM, TO, CATEGORY, IMPT, TASK, NOTE } // Members OptionalCommand currentCommand; public OptionalCommandInterpreter() { } public void identifyAndSetCommand(String command) throws InvalidParameterException { switch (command) { case "due": currentCommand = OptionalCommand.DUE; break; case "from": currentCommand = OptionalCommand.FROM; break; case "to": currentCommand = OptionalCommand.TO; break; case "category": currentCommand = OptionalCommand.CATEGORY; break; case "impt": currentCommand = OptionalCommand.IMPT; break; case "task": currentCommand = OptionalCommand.TASK; break; case "note": currentCommand = OptionalCommand.NOTE; break; default: SummaryReport .setFeedBackMsg(Constants.MESSAGE_INVALID_OPTIONAL_COMMAND); throw new InvalidParameterException(); } } public String removeCommandWord(String remainingInput) { switch (currentCommand) { case DUE: return remainingInput.substring(4); // Length of word "due " case FROM: return remainingInput.substring(5); case TO: return remainingInput.substring(3); case IMPT: return remainingInput.substring(5); case CATEGORY: return remainingInput.substring(9); case TASK: return remainingInput.substring(5); case NOTE: return remainingInput.substring(5); default: return ""; } } public ParsedResult updateResults(ParsedResult result, String commandParam) throws InvalidParameterException { Task task = result.getTaskDetails(); switch (currentCommand) { case DUE: updateDueCase(commandParam, task); break; case FROM: updateFromCase(commandParam, task); break; case TO: updateToCase(result, commandParam); break; case CATEGORY: task.setCategory(commandParam); break; case TASK: task.setDescription(commandParam); break; case IMPT: updateImportantCase(commandParam, task); break; case NOTE: task.setTaskNote(commandParam); default:// do nothing } return result; } private void updateImportantCase(String commandParam, Task task) throws InvalidParameterException { if (commandParam.equals(Constants.IMPT_YES)) { task.setImportant(true); } else if (commandParam.equals(Constants.IMPT_NO)) { task.setImportant(false); } else { SummaryReport .setFeedBackMsg(Constants.MESSAGE_INVALID_IMPORTANCE_PARAM); throw new InvalidParameterException(); } } private void updateToCase(ParsedResult result, String commandParam) throws InvalidParameterException { DateTime date; date = CommonInterpreterMethods.getDate(commandParam); Task task = result.getTaskDetails(); if (date == null) { SummaryReport.setFeedBackMsg(Constants.MESSAGE_INVALID_DATE); throw new InvalidParameterException(); } if(result.getCommandType() == CommandType.DISPLAY) { task.setStartDate(task.getDueDate()); if(task.getStartDate().isAfter(date)) { SummaryReport.setFeedBackMsg(Constants.MESSAGE_END_DATE_EARLIER_THAN_START_DATE); throw new InvalidParameterException(); } result.setSearchMode(SearchType.RANGEOFDATES); } else if(result.getTaskDetails().getStartDate() == null) { SummaryReport.setFeedBackMsg(Constants.MESSAGE_MISSING_START_DATE_FOR_TASK); throw new InvalidParameterException(); } task.setDueDate(date); } private void updateFromCase(String commandParam, Task task) throws InvalidParameterException { DateTime date; date = CommonInterpreterMethods.getDate(commandParam); if (date == null) { SummaryReport.setFeedBackMsg(Constants.MESSAGE_INVALID_DATE); throw new InvalidParameterException(); } if(task.getTaskType() == TaskType.DEADLINE) { //Means previously already used due optional command SummaryReport.setFeedBackMsg(Constants.MESSAGE_INVALID_COMBINATION_DUE_AND_FROMTO); throw new InvalidParameterException(); } task.setStartDate(date); task.setTaskType(TaskType.TIMED); } private void updateDueCase(String commandParam, Task task) throws InvalidParameterException { DateTime date; if (CommonInterpreterMethods.noDeadLine(commandParam)) { task.setDueDate(Constants.SOMEDAY); task.setStartDate(null); } else { date = CommonInterpreterMethods.getDate(commandParam); if (date == null) { SummaryReport .setFeedBackMsg(Constants.MESSAGE_INVALID_DATE); throw new InvalidParameterException(); } if(task.getTaskType() == TaskType.TIMED) { //Means previously used from to command SummaryReport.setFeedBackMsg(Constants.MESSAGE_INVALID_COMBINATION_DUE_AND_FROMTO); throw new InvalidParameterException(); } task.setDueDate(date); task.setStartDate(null); task.setTaskType(TaskType.DEADLINE); } } }
package ris.projekt.knjiznica; import java.util.*; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import ris.projekt.knjiznica.beans.*; //vir: Crunchify.com public class Email { static Properties mailServerProperties; static Session getMailSession; static MimeMessage generateMailMessage; public static boolean posljiEmailZamudnina(String email, List<StoritevZaIzpis> zamujenoGradivo){ boolean uspesnoPoslano = false; try { generateAndSendEmail(email, zamujenoGradivo); uspesnoPoslano = true; } catch (AddressException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return uspesnoPoslano; } private static void generateAndSendEmail(String email, List<StoritevZaIzpis> zamujenoGradivo) throws AddressException, MessagingException { //Step1 System.out.println("\n 1st ===> setup Mail Server Properties.."); mailServerProperties = System.getProperties(); mailServerProperties.put("mail.smtp.port", "587"); mailServerProperties.put("mail.smtp.auth", "true"); mailServerProperties.put("mail.smtp.starttls.enable", "true"); System.out.println("Mail Server Properties have been setup successfully.."); //Step2 System.out.println("\n\n 2nd ===> get Mail Session.."); getMailSession = Session.getDefaultInstance(mailServerProperties, null); generateMailMessage = new MimeMessage(getMailSession); generateMailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(email)); //uporabnik.ris@gmail.com generateMailMessage.setSubject("Zamujen rok vrnitve izposojenega gradiva", "UTF-8"); StringBuilder sb = new StringBuilder(); sb.append("Spotovani! <br /> Obveamo vas, da ste zamudili rok vrnitve izposojenega gradiva." +" Prosimo vas, da gradivo imprej vrnete."); if(zamujenoGradivo.size()!=0){ //tabela izposoj sb.append("<table>"); sb.append("<tr><td>Izposojeno gradivo</td></tr>"); sb.append("<tr><th>#</th><th>Naslov</th><th>Datum izposoje</th><th>Rok vrnitve</th></tr>"); StoritevZaIzpis s = new StoritevZaIzpis(); for(int i=1;i<=zamujenoGradivo.size();i++){ s = zamujenoGradivo.get(i-1); sb.append("<tr><td>"+i+"</td><td>"+s.getGradivo().getNaslov()+"</td><td>"+ s.getStoritev().getDatumIzposoje()+"</td><td>"+s.getStoritev().getRokVrnitve()+"</td></tr>"); } sb.append("</table>"); } sb.append("<br><br>Lep pozdrav, <br>Vaa Knjinica"); generateMailMessage.setContent(sb.toString(), "text/html; charset=UTF-8"); System.out.println("Mail Session has been created successfully.."); //Step3 System.out.println("\n\n 3rd ===> Get Session and Send mail"); Transport transport = getMailSession.getTransport("smtp"); transport.connect("smtp.gmail.com", "knjiznicaris", "projektRIS"); transport.sendMessage(generateMailMessage, generateMailMessage.getAllRecipients()); transport.close(); } }
package VASSAL.launch; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BoxLayout; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTree; import javax.swing.ListSelectionModel; import javax.swing.UIManager; import javax.swing.border.TitledBorder; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeWillExpandListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.text.html.HTMLEditorKit; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreePath; import org.jdesktop.swingx.JXTreeTable; import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode; import org.jdesktop.swingx.treetable.DefaultTreeTableModel; import VASSAL.Info; import VASSAL.build.module.AbstractMetaData; import VASSAL.build.module.Documentation; import VASSAL.build.module.ExtensionMetaData; import VASSAL.build.module.ExtensionsManager; import VASSAL.build.module.ModuleMetaData; import VASSAL.build.module.SaveMetaData; import VASSAL.chat.CgiServerStatus; import VASSAL.chat.ui.ServerStatusView; import VASSAL.configure.BooleanConfigurer; import VASSAL.configure.DirectoryConfigurer; import VASSAL.configure.ShowHelpAction; import VASSAL.configure.StringArrayConfigurer; import VASSAL.configure.TranslateVassalAction; import VASSAL.i18n.Resources; import VASSAL.preferences.Prefs; import VASSAL.tools.BrowserSupport; import VASSAL.tools.ComponentSplitter; import VASSAL.tools.ErrorLog; import VASSAL.tools.SequenceEncoder; import VASSAL.tools.filechooser.FileChooser; import VASSAL.tools.menu.CheckBoxMenuItemProxy; import VASSAL.tools.menu.MenuBarProxy; import VASSAL.tools.menu.MenuManager; import VASSAL.tools.menu.MenuProxy; public class ModuleManagerWindow extends JFrame { private static final long serialVersionUID = 1L; private static final String SHOW_STATUS_KEY = "showServerStatus"; private static final int COLUMNS = 3; private static final int KEY_COLUMN = 0; private static final int VERSION_COLUMN = 1; private static final int SPARE_COLUMN = 2; private static final String[] columnHeadings = new String[COLUMNS]; private final ImageIcon moduleIcon; private final ImageIcon activeExtensionIcon; private final ImageIcon inactiveExtensionIcon; private final ImageIcon openGameFolderIcon; private final ImageIcon closedGameFolderIcon; private final ImageIcon fileIcon; private StringArrayConfigurer recentModuleConfig; private File selectedModule; private CardLayout modulePanelLayout; private JPanel moduleView; private ComponentSplitter.SplitPane serverStatusView; private MyTreeNode rootNode; private JXTreeTable tree; private MyTreeTableModel treeModel; private MyTreeNode selectedNode; private long lastExpansionTime; private TreePath lastExpansionPath; private static final long doubleClickInterval; static { final Object dci = Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval"); doubleClickInterval = dci instanceof Integer ? (Integer) dci : 200L; } public static ModuleManagerWindow getInstance() { return instance; } private static final ModuleManagerWindow instance = new ModuleManagerWindow(); public ModuleManagerWindow() { setTitle("VASSAL"); setLayout(new BoxLayout(getContentPane(), BoxLayout.X_AXIS)); final AbstractAction shutDownAction = new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { if (!AbstractLaunchAction.shutDown()) return; try { Prefs.getGlobalPrefs().write(); Prefs.getGlobalPrefs().close(); } catch (IOException ex) { ErrorLog.warn(ex); } System.exit(0); } }; shutDownAction.putValue(Action.NAME, Resources.getString(Resources.QUIT)); setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { shutDownAction.actionPerformed(null); } }); // setup menubar and actions final MenuManager mm = MenuManager.getInstance(); final MenuBarProxy mb = mm.getMenuBarProxyFor(this); // file menu final MenuProxy fileMenu = new MenuProxy(Resources.getString("General.file")); fileMenu.add(mm.addKey("Main.play_module")); fileMenu.add(mm.addKey("Main.edit_module")); fileMenu.add(mm.addKey("Main.new_module")); fileMenu.add(mm.addKey("Editor.import_module")); if (!Info.isMacOSX()) { fileMenu.addSeparator(); fileMenu.add(mm.addKey("General.quit")); } // tools menu final MenuProxy toolsMenu = new MenuProxy(Resources.getString("General.tools")); final BooleanConfigurer serverStatusConfig = new BooleanConfigurer(SHOW_STATUS_KEY, null, Boolean.FALSE); Prefs.getGlobalPrefs().addOption(null, serverStatusConfig); toolsMenu.add(new CheckBoxMenuItemProxy(new AbstractAction( Resources.getString("Chat.server_status")) { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { serverStatusView.toggleVisibility(); serverStatusConfig.setValue( serverStatusConfig.booleanValue() ? Boolean.FALSE : Boolean.TRUE); } }, serverStatusConfig.booleanValue())); toolsMenu.add(mm.addKey("Editor.ModuleEditor.translate_vassal")); // help menu final MenuProxy helpMenu = new MenuProxy(Resources.getString("General.help")); helpMenu.add(mm.addKey("General.help")); helpMenu.add(mm.addKey("Main.tour")); if (!Info.isMacOSX()) { helpMenu.addSeparator(); helpMenu.add(mm.addKey("AboutScreen.about_vassal")); } mb.add(fileMenu); mb.add(toolsMenu); mb.add(helpMenu); // add actions mm.addAction("Main.play_module", new Player.PromptLaunchAction(this)); mm.addAction("Main.edit_module", new Editor.PromptLaunchAction(this)); mm.addAction("Main.new_module", new Editor.NewModuleLaunchAction(this)); mm.addAction("Editor.import_module", new Editor.PromptImportLaunchAction(this)); mm.addAction("General.quit", shutDownAction); mm.addAction("Editor.ModuleEditor.translate_vassal", new TranslateVassalAction(this)); URL url = null; try { url = new File(Documentation.getDocumentationBaseDir(), "README.html").toURI().toURL(); } catch (MalformedURLException e) { ErrorLog.warn(e); } mm.addAction("General.help", new ShowHelpAction(url, null)); mm.addAction("Main.tour", new LaunchTourAction(this)); mm.addAction("AboutScreen.about_vassal", AboutVASSAL.getAction()); setJMenuBar(mm.getMenuBarFor(this)); // Load Icons moduleIcon = new ImageIcon( getClass().getResource("/images/mm-module.png")); activeExtensionIcon = new ImageIcon( getClass().getResource("/images/mm-extension-active.png")); inactiveExtensionIcon = new ImageIcon( getClass().getResource("/images/mm-extension-inactive.png")); openGameFolderIcon = new ImageIcon( getClass().getResource("/images/mm-gamefolder-open.png")); closedGameFolderIcon = new ImageIcon( getClass().getResource("/images/mm-gamefolder-closed.png")); fileIcon = new ImageIcon(getClass().getResource("/images/mm-file.png")); // build module controls final JPanel moduleControls = new JPanel(new BorderLayout()); modulePanelLayout = new CardLayout(); moduleView = new JPanel(modulePanelLayout); buildTree(); JScrollPane scroll = new JScrollPane(tree); moduleView.add(scroll, "modules"); final JEditorPane l = new JEditorPane("text/html", Resources.getString("ModuleManager.quickstart")); l.setEditable(false); // pick up background color and font from JLabel l.setBackground(UIManager.getColor("control")); final Font font = UIManager.getFont("Label.font"); ((HTMLEditorKit) l.getEditorKit()).getStyleSheet().addRule( "body { font: " + font.getFamily() + " " + font.getSize() + "pt }"); l.addHyperlinkListener(new HyperlinkListener() { public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { BrowserSupport.openURL(e.getURL().toString()); } } }); // this is necessary to get proper vertical alignment final JPanel p = new JPanel(new GridBagLayout()); final GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; c.anchor = GridBagConstraints.CENTER; p.add(l, c); moduleView.add(p, "quickStart"); modulePanelLayout.show( moduleView, getModuleCount() == 0 ? "quickStart" : "modules"); moduleControls.add(moduleView, BorderLayout.CENTER); moduleControls.setBorder(new TitledBorder( Resources.getString("ModuleManager.recent_modules"))); add(moduleControls); // build server status controls final ServerStatusView serverStatusControls = new ServerStatusView(new CgiServerStatus()); serverStatusControls.setBorder( new TitledBorder(Resources.getString("Chat.server_status"))); serverStatusView = new ComponentSplitter().splitRight( moduleControls, serverStatusControls, false); serverStatusView.revalidate(); // show the server status controls according to the prefs if (serverStatusConfig.booleanValue()) serverStatusView.showComponent(); final Rectangle r = Info.getScreenBounds(this); serverStatusControls.setPreferredSize( new Dimension((int) (r.width / 3.5), 0)); setSize(3 * r.width / 4, 3 * r.height / 4); } protected void buildTree() { recentModuleConfig = new StringArrayConfigurer("RecentModules", null); Prefs.getGlobalPrefs().addOption(null, recentModuleConfig); final List<String> missingModules = new ArrayList<String>(); final List<ModuleInfo> moduleList = new ArrayList<ModuleInfo>(); for (String s : recentModuleConfig.getStringArray()) { final ModuleInfo module = new ModuleInfo(s); if (module.getFile().exists() && module.isValid()) { moduleList.add(module); } else { missingModules.add(s); } } for (String s : missingModules) { moduleList.remove(s); recentModuleConfig.removeValue(s); } Collections.sort(moduleList, new Comparator<ModuleInfo>() { public int compare(ModuleInfo f1, ModuleInfo f2) { return f1.compareTo(f2); } }); rootNode = new MyTreeNode (new RootInfo()); for (ModuleInfo moduleInfo : moduleList) { final MyTreeNode moduleNode = new MyTreeNode(moduleInfo); for (ExtensionInfo ext : moduleInfo.getExtensions()) { final MyTreeNode extensionNode = new MyTreeNode(ext); moduleNode.add(extensionNode); } for (File f : moduleInfo.getFolders()) { final GameFolderInfo folderInfo = new GameFolderInfo(f, moduleInfo); final MyTreeNode folderNode = new MyTreeNode(folderInfo); moduleNode.add(folderNode); final ArrayList<File> l = new ArrayList<File>(); final File[] files = f.listFiles(); if (files == null) continue; for (File f1 : files) { if (f1.isFile()) { l.add(f1); } } Collections.sort(l); for (File f2 : l) { final SaveFileInfo fileInfo = new SaveFileInfo(f2, folderInfo); if (fileInfo.isValid() && fileInfo.belongsToModule()) { final MyTreeNode fileNode = new MyTreeNode(fileInfo); folderNode.add(fileNode); } } } rootNode.add(moduleNode); } treeModel = new MyTreeTableModel(rootNode); tree = new JXTreeTable(treeModel); tree.setRootVisible(false); tree.setEditable(false); tree.setTreeCellRenderer(new MyTreeCellRenderer()); tree.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { final TreePath path = tree.getPathForLocation(e.getPoint().x, e.getPoint().y); // do nothing if not on a node, or if this node was expanded // or collapsed during the past doubleClickInterval milliseconds if (path == null || (lastExpansionPath == path && e.getWhen() - lastExpansionTime <= doubleClickInterval)) return; selectedNode = (MyTreeNode) path.getLastPathComponent(); final int row = tree.getRowForPath(path); if (row < 0) return; final AbstractInfo target = (AbstractInfo) selectedNode.getUserObject(); // launch module or load save, otherwise expand or collapse node if (target instanceof ModuleInfo) { ((ModuleInfo) target).play(); } else if (target instanceof SaveFileInfo) { ((SaveFileInfo) target).play(); } else if (tree.isExpanded(row)) { tree.collapseRow(row); } else { tree.expandRow(row); } } } @Override public void mouseReleased(MouseEvent e) { final TreePath path = tree.getPathForLocation(e.getPoint().x, e.getPoint().y); if (path == null) return; selectedNode = (MyTreeNode) path.getLastPathComponent(); if (e.isMetaDown()) { final int row = tree.getRowForPath(path); if (row >= 0) { tree.clearSelection(); tree.addRowSelectionInterval(row, row); final AbstractInfo target = (AbstractInfo) selectedNode.getUserObject(); target.buildPopup(row).show(tree, e.getX(), e.getY()); } } } }); // We capture the time and location of clicks which would cause // expansion in order to distinguish these from clicks which // might launch a module or game. tree.addTreeWillExpandListener(new TreeWillExpandListener() { public void treeWillCollapse(TreeExpansionEvent e) { lastExpansionTime = System.currentTimeMillis(); lastExpansionPath = e.getPath(); } public void treeWillExpand(TreeExpansionEvent e) { lastExpansionTime = System.currentTimeMillis(); lastExpansionPath = e.getPath(); } }); // This ensures that double-clicks always start the module but // doesn't prevent single-clicks on the handles from working. tree.setToggleClickCount(3); tree.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { final MyTreeNode node = (MyTreeNode) e.getPath().getLastPathComponent(); final AbstractInfo target = node.getNodeInfo(); if (target instanceof ModuleInfo) { setSelectedModule(target.getFile()); } else { if (node.getParent() != null) { setSelectedModule(node.getParentModuleFile()); } } } }); columnHeadings[KEY_COLUMN] = ""; columnHeadings[VERSION_COLUMN] = Resources.getString("ModuleManager.version"); columnHeadings[SPARE_COLUMN] = ""; // FIXME: Width handling needs improvement. Also save in prefs tree.getColumnModel().getColumn(KEY_COLUMN).setMinWidth(250); tree.getColumnModel().getColumn(VERSION_COLUMN) .setCellRenderer(new VersionCellRenderer()); tree.getColumnModel().getColumn(VERSION_COLUMN).setMinWidth(75); tree.getColumnModel().getColumn(SPARE_COLUMN).setMinWidth(10); tree.getColumnModel().getColumn(SPARE_COLUMN).setPreferredWidth(600); // FIXME: How to set alignment of individual header components? tree.getTableHeader().setAlignmentX(JComponent.CENTER_ALIGNMENT); } public String update(File f) { AbstractMetaData.FileType type = AbstractMetaData.getFileType(f); // Module. // If we already have this module added, just refresh it, otherwise add it in. if (type == AbstractMetaData.FileType.MODULE) { final MyTreeNode moduleNode = rootNode.findNode(f); if (moduleNode == null) { addModule(f); } else { moduleNode.refresh(); } } // Extension. // Check to see if it has been saved into one of the extension directories // for any module we already know of. Refresh the module else if (type == AbstractMetaData.FileType.EXTENSION) { for (int i = 0; i < rootNode.getChildCount(); i++) { final MyTreeNode moduleNode = rootNode.getChild(i); final ModuleInfo moduleInfo = (ModuleInfo) moduleNode.getNodeInfo(); for (ExtensionInfo ext : moduleInfo.getExtensions()) { if (ext.getFile().equals(f)) { moduleNode.refresh(); return "OK"; } } } } // Save Game or Log file. // If the parent of the save file is already recorded as a Game Folder, // pass the file off to the Game Folder to handle. Otherwise, ignore it. else if (type == AbstractMetaData.FileType.SAVE) { for (int i = 0; i < rootNode.getChildCount(); i++) { final MyTreeNode moduleNode = rootNode.getChild(i); final MyTreeNode folderNode = moduleNode.findNode(f.getParentFile()); if (folderNode != null && folderNode.getNodeInfo() instanceof GameFolderInfo) { ((GameFolderInfo) folderNode.getNodeInfo()).update(f); return "OK"; } } } tree.repaint(); return "OK"; } /** * Return the number of Modules added to the Module Manager * * @return Number of modules */ private int getModuleCount() { return rootNode.getChildCount(); } public File getSelectedModule() { return selectedModule; } private void setSelectedModule(File selectedModule) { this.selectedModule = selectedModule; } public void addModule(File f) { if (!rootNode.contains(f)) { final ModuleInfo moduleInfo = new ModuleInfo(f); final MyTreeNode moduleNode = new MyTreeNode(moduleInfo); treeModel.insertNodeInto(moduleNode, rootNode, rootNode.findInsertIndex(moduleInfo)); for (ExtensionInfo ext : moduleInfo.getExtensions()) { final MyTreeNode extensionNode = new MyTreeNode(ext); treeModel.insertNodeInto(extensionNode, moduleNode, moduleNode.findInsertIndex(ext)); } updateModuleList(); } } public void removeModule(File f) { final MyTreeNode moduleNode = rootNode.findNode(f); treeModel.removeNodeFromParent(moduleNode); updateModuleList(); } public File getModuleByName(String name) { if (name == null) return null; for (int i = 0; i < rootNode.getChildCount(); i++) { final ModuleInfo module = (ModuleInfo) rootNode.getChild(i).getNodeInfo(); if (name.equals(module.getModuleName())) return module.getFile(); } return null; } private void updateModuleList() { final List<String> l = new ArrayList<String>(); for (int i = 0; i < rootNode.getChildCount(); i++) { final ModuleInfo module = (ModuleInfo) (rootNode.getChild(i)).getNodeInfo(); l.add(module.encode()); } recentModuleConfig.setValue(l.toArray(new String[l.size()])); modulePanelLayout.show( moduleView, getModuleCount() == 0 ? "quickStart" : "modules"); } private class MyTreeTableModel extends DefaultTreeTableModel { public MyTreeTableModel(MyTreeNode rootNode) { super(rootNode); } public int getColumnCount() { return COLUMNS; } public String getColumnName(int col) { switch (col) { case VERSION_COLUMN : return Resources.getString("ModuleManager.version"); default: return ""; } } public Object getValueAt(Object node, int column) { return ((MyTreeNode) node).getValueAt(column); } } /** * Custom Tree cell renderer:- * - Add file name as tooltip * - Handle expanded display (some nodes use the same icon for expanded/unexpanded) * - Gray out inactve extensions * - Gray out Save Games that belong to other modules */ private class MyTreeCellRenderer extends DefaultTreeCellRenderer { private static final long serialVersionUID = 1L; public Component getTreeCellRendererComponent( JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { super.getTreeCellRendererComponent( tree, value, selected, expanded, leaf, row, hasFocus); final AbstractInfo info = ((MyTreeNode) value).getNodeInfo(); setText(info.toString()); setToolTipText(info.getToolTipText()); setIcon(info.getIcon(expanded)); setForeground(info.getTreeCellFgColor()); return this; } } private class VersionCellRenderer extends DefaultTableCellRenderer { private static final long serialVersionUID = 1L; public VersionCellRenderer() { super(); this.setHorizontalAlignment(CENTER); } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); return this; } } private static class MyTreeNode extends DefaultMutableTreeTableNode { public MyTreeNode(AbstractInfo nodeInfo) { super(nodeInfo); nodeInfo.setTreeNode(this); } public AbstractInfo getNodeInfo() { return (AbstractInfo) getUserObject(); } public File getFile() { return getNodeInfo().getFile(); } public void refresh() { getNodeInfo().refresh(); } @Override public void setValueAt(Object aValue, int column) { } @Override public Object getValueAt(int column) { return getNodeInfo().getValueAt(column); } public MyTreeNode getChild(int index) { return (MyTreeNode) super.getChildAt(index); } public MyTreeNode findNode(File f) { for (int i = 0; i < getChildCount(); i++) { final MyTreeNode moduleNode = getChild(i); // NB: we canonicalize because File.equals() does not // always return true when one File is a relative path. try { f = f.getCanonicalFile(); } catch (IOException e) { f = f.getAbsoluteFile(); } if (f.equals(moduleNode.getNodeInfo().getFile())) { return moduleNode; } } return null; } public boolean contains(File f) { return findNode(f) != null; } public int findInsertIndex(AbstractInfo info) { for (int i = 0; i < getChildCount(); i++) { final MyTreeNode childNode = getChild(i); if (childNode.getNodeInfo().compareTo(info) >= 0) { return i; } } return getChildCount(); } /** * Return the Module node enclosing this node * * @return Parent Tree Node */ public MyTreeNode getParentModuleNode() { final AbstractInfo info = getNodeInfo(); if (info instanceof RootInfo) { return null; } else if (info instanceof ModuleInfo) { return this; } else if ((MyTreeNode) getParent() == null) { return null; } else { return ((MyTreeNode) getParent()).getParentModuleNode(); } } /** * Return the Module file of the Module node enclosing this node * * @return Module File */ public File getParentModuleFile() { final MyTreeNode parentNode = getParentModuleNode(); return parentNode == null ? null : parentNode.getFile(); } } private abstract class AbstractInfo implements Comparable<AbstractInfo> { protected File file; protected Icon openIcon; protected Icon closedIcon; protected boolean valid = true; protected String error = ""; protected MyTreeNode node; public AbstractInfo(File f, Icon open, Icon closed) { setFile(f); setIcon(open, closed); } public AbstractInfo(File f, Icon i) { this (f, i, i); } public AbstractInfo(File f) { this(f, null); } public AbstractInfo() { } @Override public String toString() { return file == null ? "" : file.getName(); } public File getFile() { return file; } public void setFile(File f) { if (f == null) return; try { file = f.getCanonicalFile(); } catch (IOException e) { file = f.getAbsoluteFile(); } } public String getToolTipText() { if (file == null) { return ""; } else { return file.getPath(); } } /* * Sort by Type, then File name. */ public int compareTo(AbstractInfo info) { final int typeCompare = info.getSortKey().compareTo(getSortKey()); return typeCompare == 0 ? getFile().getName().toLowerCase().compareTo( info.getFile().getName().toLowerCase()) : typeCompare; } public JPopupMenu buildPopup(int row) { return null; } public Icon getIcon(boolean expanded) { return expanded ? openIcon : closedIcon; } public void setIcon(Icon i) { setIcon(i, i); } public void setIcon(Icon open, Icon closed) { openIcon = open; closedIcon = closed; } public String getValueAt(int column) { switch (column) { case KEY_COLUMN: return toString(); case VERSION_COLUMN: return getVersion(); default: return null; } } public void setValid(boolean b) { valid = b; } public boolean isValid() { return valid; } public void setError(String s) { error = s; } public String getError() { return error; } public String getVersion() { return ""; } public String getComments() { return ""; } public MyTreeNode getTreeNode() { return node; } public void setTreeNode(MyTreeNode n) { node = n; } /** * Return a String used to sort different types of AbstractInfo's that are * children of the same parent. * * @return sort key */ public String getSortKey() { return "5"; } /** * Return the color of the text used to display the name in column 1. * Over-ride this to change color depending on item state. * * @return cell text color */ public Color getTreeCellFgColor() { return Color.black; } /** * Refresh yourself and any children */ public void refresh() { refreshChildren(); } public void refreshChildren() { for (int i = 0; i < node.getChildCount(); i++) { (node.getChild(i)).refresh(); } } } private class RootInfo extends AbstractInfo { public RootInfo() { super(null); } } public class ModuleInfo extends AbstractInfo { private ExtensionsManager extMgr; private SortedSet<File> gameFolders = new TreeSet<File>(); private ModuleMetaData metadata; private Action newExtensionAction = new NewExtensionLaunchAction(ModuleManagerWindow.this); private AbstractAction addExtensionAction = new AbstractAction(Resources.getString("ModuleManager.add_extension")) { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { final FileChooser fc = FileChooser.createFileChooser( ModuleManagerWindow.this, (DirectoryConfigurer) Prefs.getGlobalPrefs().getOption(Prefs.MODULES_DIR_KEY)); if (fc.showOpenDialog() == FileChooser.APPROVE_OPTION) { final File selectedFile = fc.getSelectedFile(); final ExtensionInfo testExtInfo = new ExtensionInfo(selectedFile, true, null); if (testExtInfo.isValid()) { final File f = getExtensionsManager().setActive(fc.getSelectedFile(), true); final MyTreeNode moduleNode = rootNode.findNode(selectedModule); final ExtensionInfo extInfo = new ExtensionInfo(f, true, (ModuleInfo) moduleNode.getNodeInfo()); if (extInfo.isValid()) { final MyTreeNode extNode = new MyTreeNode(extInfo); treeModel.insertNodeInto(extNode, moduleNode, moduleNode.findInsertIndex(extInfo)); } } else { JOptionPane.showMessageDialog(null, testExtInfo.getError(), null, JOptionPane.ERROR_MESSAGE); } } } }; private AbstractAction addFolderAction = new AbstractAction( Resources.getString("ModuleManager.add_save_game_folder")) { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { final FileChooser fc = FileChooser.createFileChooser( ModuleManagerWindow.this, (DirectoryConfigurer) Prefs.getGlobalPrefs().getOption(Prefs.MODULES_DIR_KEY), FileChooser.DIRECTORIES_ONLY); if (fc.showOpenDialog() == FileChooser.APPROVE_OPTION) { addFolder(fc.getSelectedFile()); } } }; public ModuleInfo(File f) { super(f, moduleIcon); extMgr = new ExtensionsManager(f); loadMetaData(); } protected void loadMetaData() { AbstractMetaData data = AbstractMetaData.buildMetaData(file); if (data != null && data instanceof ModuleMetaData) { setValid(true); metadata = (ModuleMetaData) data; } else { setValid(false); return; } } /** * Initialise ModuleInfo based on a saved preference string. * See encode(). * * @param s Preference String */ public ModuleInfo(String s) { SequenceEncoder.Decoder sd = new SequenceEncoder.Decoder(s, ';'); setFile(new File(sd.nextToken())); setIcon(moduleIcon); loadMetaData(); extMgr = new ExtensionsManager(getFile()); while (sd.hasMoreTokens()) { gameFolders.add(new File(sd.nextToken())); } } /** * Refresh this module and all children */ public void refresh() { loadMetaData(); // Remove any missing children final MyTreeNode[] nodes = new MyTreeNode[getTreeNode().getChildCount()]; for (int i = 0; i < getTreeNode().getChildCount(); i++) { nodes[i] = getTreeNode().getChild(i); } for (int i = 0; i < nodes.length; i++) { if (!nodes[i].getFile().exists()) { treeModel.removeNodeFromParent(nodes[i]); } } // Refresh or add any existing children for (ExtensionInfo ext : getExtensions()) { MyTreeNode extNode = getTreeNode().findNode(ext.getFile()); if (extNode == null) { if (ext.isValid()) { extNode = new MyTreeNode(ext); treeModel.insertNodeInto(extNode, getTreeNode(), getTreeNode().findInsertIndex(ext)); } } else { extNode.refresh(); } } } /** * Encode any information which needs to be recorded in the Preference entry for this module:- * - Path to Module File * - Paths to any child Save Game Folders * * @return encoded data */ public String encode() { final SequenceEncoder se = new SequenceEncoder(file.getPath(), ';'); for (File f : gameFolders) { se.append(f.getPath()); } return se.getValue(); } public ExtensionsManager getExtensionsManager() { return extMgr; } public void addFolder(File f) { // try to create the directory if it doesn't exist if (!f.exists() && !f.mkdirs()) { JOptionPane.showMessageDialog( ModuleManagerWindow.this, Resources.getString("Install.error_unable_to_create", f.getPath()), "Error", JOptionPane.ERROR_MESSAGE ); return; } gameFolders.add(f); final MyTreeNode moduleNode = rootNode.findNode(selectedModule); final GameFolderInfo folderInfo = new GameFolderInfo(f, (ModuleInfo) moduleNode.getNodeInfo()); final MyTreeNode folderNode = new MyTreeNode(folderInfo); final int idx = moduleNode.findInsertIndex(folderInfo); treeModel.insertNodeInto(folderNode, moduleNode, idx); for (File file : f.listFiles()) { if (file.isFile()) { final SaveFileInfo fileInfo = new SaveFileInfo(file, folderInfo); if (fileInfo.isValid() && fileInfo.belongsToModule()) { final MyTreeNode fileNode = new MyTreeNode(fileInfo); treeModel.insertNodeInto(fileNode, folderNode, folderNode.findInsertIndex(fileInfo)); } } } updateModuleList(); } public void removeFolder(File f) { gameFolders.remove(f); } public SortedSet<File> getFolders() { return gameFolders; } public List<ExtensionInfo> getExtensions() { final List<ExtensionInfo> l = new ArrayList<ExtensionInfo>(); for (File f : extMgr.getActiveExtensions()) { l.add(new ExtensionInfo(f, true, this)); } for (File f : extMgr.getInactiveExtensions()) { l.add(new ExtensionInfo(f, false, this)); } Collections.sort(l); return l; } public void play() { new Player.LaunchAction( ModuleManagerWindow.this, file).actionPerformed(null); } @Override public JPopupMenu buildPopup(int row) { final JPopupMenu m = new JPopupMenu(); m.add(new Player.LaunchAction(ModuleManagerWindow.this, file)); m.add(new Editor.ListLaunchAction(ModuleManagerWindow.this, file)); m.add(new AbstractAction(Resources.getString("General.remove")) { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { removeModule(file); } }); m.addSeparator(); m.add(addFolderAction); m.addSeparator(); m.add(newExtensionAction); m.add(addExtensionAction); return m; } /* * Is the module currently being Played or Edited? */ public boolean isInUse() { return AbstractLaunchAction.isInUse(file) || AbstractLaunchAction.isEditing(file); } @Override public String getVersion() { return metadata.getVersion(); } public String getLocalizedDescription() { return metadata.getLocalizedDescription(); } public String getModuleName() { return metadata.getName(); } @Override public String toString() { return metadata.getLocalizedName(); } @Override public String getValueAt(int column) { return column == SPARE_COLUMN ? getLocalizedDescription() : super.getValueAt(column); } } private class ExtensionInfo extends AbstractInfo { private boolean active; private ModuleInfo moduleInfo; private ExtensionMetaData metadata; public ExtensionInfo(File file, boolean active, ModuleInfo module) { super(file, active ? activeExtensionIcon : inactiveExtensionIcon); this.active = active; moduleInfo = module; loadMetaData(); } protected void loadMetaData() { AbstractMetaData data = AbstractMetaData.buildMetaData(file); if (data != null && data instanceof ExtensionMetaData) { setValid(true); metadata = (ExtensionMetaData) data; } else { setError(Resources.getString("ModuleManager.invalid_extension")); setValid(false); } } @Override public void refresh() { loadMetaData(); setActive(getExtensionsManager().isExtensionActive(getFile())); tree.repaint(); } public boolean isActive() { return active; } public void setActive(boolean b) { active = b; setIcon(active ? activeExtensionIcon : inactiveExtensionIcon); } @Override public String getVersion() { return metadata == null ? "" : metadata.getVersion(); } public String getDescription() { return metadata == null ? "" : metadata.getDescription(); } public ExtensionsManager getExtensionsManager() { return moduleInfo == null ? null : moduleInfo.getExtensionsManager(); } @Override public String toString() { String s = getFile().getName(); String st = ""; if (metadata == null) { st = Resources.getString("ModuleManager.invalid"); } if (!active) { st += st.length() > 0 ? "," : ""; st += Resources.getString("ModuleManager.inactive"); } if (st.length() > 0) { s += " (" + st + ")"; } return s; } @Override public JPopupMenu buildPopup(int row) { final JPopupMenu m = new JPopupMenu(); m.add(new ActivateExtensionAction(Resources.getString(isActive() ? "ModuleManager.deactivate" : "ModuleManager.activate"))); m.add(new EditExtensionLaunchAction( ModuleManagerWindow.this, getFile(), getSelectedModule())); return m; } @Override public Color getTreeCellFgColor() { // FIXME: should get colors from LAF if (isActive()) { return metadata == null ? Color.red : Color.black; } else { return metadata == null ? Color.pink : Color.gray; } } @Override public String getValueAt(int column) { return column == SPARE_COLUMN ? getDescription() : super.getValueAt(column); } /* * Is the extension, or its owning module currently being Played or Edited? */ public boolean isInUse() { return AbstractLaunchAction.isInUse(file) || AbstractLaunchAction.isEditing(file); } private class ActivateExtensionAction extends AbstractAction { private static final long serialVersionUID = 1L; public ActivateExtensionAction (String s) { super(s); setEnabled(!isInUse() && ! moduleInfo.isInUse()); } public void actionPerformed(ActionEvent evt) { setFile(getExtensionsManager().setActive(getFile(), !isActive())); setActive(getExtensionsManager().isExtensionActive(getFile())); final TreePath path = tree.getPathForRow(tree.getSelectedRow()); final MyTreeNode extNode = (MyTreeNode) path.getLastPathComponent(); treeModel.setValueAt("", extNode, 0); } } } private class GameFolderInfo extends AbstractInfo { protected String comment; protected ModuleInfo moduleInfo; public GameFolderInfo(File f, ModuleInfo m) { super(f, openGameFolderIcon, closedGameFolderIcon); moduleInfo = m; } public JPopupMenu buildPopup(int row) { final JPopupMenu m = new JPopupMenu(); m.add(new AbstractAction(Resources.getString("General.refresh")) { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { refresh(); } }); m.addSeparator(); m.add(new AbstractAction(Resources.getString("General.remove")) { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { final MyTreeNode moduleNode = rootNode.findNode(moduleInfo.getFile()); final MyTreeNode folderNode = moduleNode.findNode(getFile()); treeModel.removeNodeFromParent(folderNode); moduleInfo.removeFolder(getFile()); updateModuleList(); } }); return m; } public ModuleInfo getModuleInfo() { return moduleInfo; } public void refresh() { // Remove any files that no longer exist for (int i = getTreeNode().getChildCount()-1; i >= 0; i final MyTreeNode fileNode = getTreeNode().getChild(i); final SaveFileInfo fileInfo = (SaveFileInfo) fileNode.getNodeInfo(); if (!fileInfo.getFile().exists()) { treeModel.removeNodeFromParent(fileNode); } } // Refresh any that are File[] files = getFile().listFiles(); for (int i = 0; i < files.length; i++) { update(files[i]); } } /** * Update the display for the specified save File, or add it in if * we don't already know about it. * @param f */ public void update(File f) { for (int i = 0; i < getTreeNode().getChildCount(); i++) { final SaveFileInfo fileInfo = (SaveFileInfo) (getTreeNode().getChild(i)).getNodeInfo(); if (fileInfo.getFile().equals(f)) { fileInfo.refresh(); return; } } final SaveFileInfo fileInfo = new SaveFileInfo(f, this); final MyTreeNode fileNode = new MyTreeNode(fileInfo); treeModel.insertNodeInto(fileNode, getTreeNode(), getTreeNode().findInsertIndex(fileInfo)); } /* * Force Game Folders to sort after extensions */ @Override public String getSortKey() { return "3"; } } private class SaveFileInfo extends AbstractInfo { protected GameFolderInfo folderInfo; // Owning Folder protected SaveMetaData metadata; // Save file metadata public SaveFileInfo(File f, GameFolderInfo folder) { super(f, fileIcon); folderInfo = folder; loadMetaData(); } protected void loadMetaData() { AbstractMetaData data = AbstractMetaData.buildMetaData(file); if (data != null && data instanceof SaveMetaData) { metadata = (SaveMetaData) data; setValid(true); } else { setValid(false); } } public void refresh() { loadMetaData(); tree.repaint(); } @Override public JPopupMenu buildPopup(int row) { final JPopupMenu m = new JPopupMenu(); m.add(new Player.LaunchAction( ModuleManagerWindow.this, getModuleFile(), file)); return m; } protected File getModuleFile() { return folderInfo.getModuleInfo().getFile(); } public void play() { new Player.LaunchAction( ModuleManagerWindow.this, getModuleFile(), file).actionPerformed(null); } @Override public String getValueAt(int column) { return column == SPARE_COLUMN ? buildComments() : super.getValueAt(column); } private String buildComments() { String comments = ""; if (!belongsToModule()) { if (metadata.getModuleName().length() > 0) { comments = "[" + metadata.getModuleName() + "] "; } } comments += metadata.getDescription(); return comments; } private boolean belongsToModule() { return metadata.getModuleName().length() == 0 || folderInfo.getModuleInfo().getModuleName().equals( metadata.getModuleName()); } @Override public Color getTreeCellFgColor() { // FIXME: should get colors from LAF return belongsToModule() ? Color.black : Color.gray; } @Override public String getVersion() { return metadata.getModuleVersion(); } } /** * Action to create a New Extension and edit it in another process. */ private class NewExtensionLaunchAction extends AbstractLaunchAction { private static final long serialVersionUID = 1L; public NewExtensionLaunchAction(Frame frame) { super(Resources.getString("ModuleManager.new_extension"), frame, Editor.class.getName(), new LaunchRequest(LaunchRequest.Mode.NEW_EXT) ); } @Override public void actionPerformed(ActionEvent e) { lr.module = getSelectedModule(); // register that this module is being used if (editing.contains(lr.module)) return; Integer count = using.get(lr.module); using.put(lr.module, count == null ? 1 : ++count); super.actionPerformed(e); } @Override protected LaunchTask getLaunchTask() { return new LaunchTask() { @Override protected void done() { super.done(); // reduce the using count Integer count = using.get(lr.module); if (count == 1) using.remove(lr.module); else using.put(lr.module, --count); } /* @Override protected void process(List<Void> chunks) { super.process(chunks); ((ModuleManagerWindow) frame).addModule(mod); } */ }; } } private class EditExtensionLaunchAction extends AbstractLaunchAction { private static final long serialVersionUID = 1L; public EditExtensionLaunchAction(Frame frame, File extension, File module) { super(Resources.getString("Editor.edit_extension"), frame, Editor.class.getName(), new LaunchRequest(LaunchRequest.Mode.EDIT_EXT, module, extension) ); setEnabled(!using.containsKey(module) && !editing.contains(module) && !editing.contains(extension) && !using.containsKey(extension)); } @Override public void actionPerformed(ActionEvent e) { // check that neither this module nor this extension is being edited if (editing.contains(lr.module) || editing.contains(lr.extension)) return; // register that this module is being used Integer count = using.get(lr.module); using.put(lr.module, count == null ? 1 : ++count); // register that this extension is being edited editing.add(lr.extension); super.actionPerformed(e); setEnabled(false); } @Override protected LaunchTask getLaunchTask() { return new LaunchTask() { @Override protected void done() { super.done(); // reduce the using count for module Integer count = using.get(lr.module); if (count == 1) using.remove(lr.module); else using.put(lr.module, --count); // reduce that this extension is done being edited editing.remove(lr.extension); setEnabled(true); } /* @Override protected void process(List<Void> chunks) { super.process(chunks); ((ModuleManagerWindow) frame).addModule(mod); } */ }; } } }
package api.web.gw2.mapping.v2.items; import api.web.gw2.mapping.core.CoinValue; import api.web.gw2.mapping.core.LocalizedResource; import api.web.gw2.mapping.core.OptionalValue; import api.web.gw2.mapping.v2.APIv2; import java.util.Optional; import java.util.OptionalInt; import java.util.Set; @APIv2(endpoint = "v2/items") // NOI18N. public interface Item { /** * Gets the id of this item. * @return An {@code int}. */ int getId(); /** * Gets the localized name of this item. * @return A {@code String} instance, never {@code null}. */ @LocalizedResource String getName(); /** * Gets the localized description of this item. * @return An {@code Optional<String>} instance, never {@code null}. */ @LocalizedResource @OptionalValue Optional<String> getDescription(); /** * Gets the type of this item. * @return An {@code ItemType} instance, never {@code null}. */ ItemType getType(); /** * Gets the required level to use this item. * @return A {@code short}. */ short getLevel(); /** * Gets the rarity of this item. * @return An {@code ItemRarity} instance, never {@code null}. */ ItemRarity getRarity(); /** * Gets the vendor value of this item in coins. * @return An {@code int}. */ @CoinValue int getVendorValue(); /** * Gets the id of the default skin of this item. * @return An {@code OptionalInt} instance, never {@code null}. */ OptionalInt getDefaultSkin(); /** * Get a set of flags on this items. * @return A non-modifiable {@code Set<ItemFlag>} instance, never {@code null}, set may be empty. */ Set<ItemFlag> getFlags(); /** * Get a set of game types on this items. * @return A non-modifiable {@code Set<ItemGameType>} instance, never {@code null}, set may be empty. */ Set<ItemGameType> getGameTypes(); /** * Get a set of restrictions on this items. * @return A non-modifiable {@code Set<ItemRestriction>} instance, never {@code null}, set may be empty. */ Set<ItemRestriction> getRestrictions(); /** * Gets the URL to the icon of this item. * @return A {@code String} instance, never {@code null}. */ String getIcon(); /** * Gets the details of this object. * @param <T> The type of the details. * @return An {@code Optional<T>} instance, never {@code null}. */ <T extends Details> Optional<T> getDetails(); }
package api.web.gw2.mapping.v2.raids; import api.web.gw2.mapping.core.IdValue; import api.web.gw2.mapping.core.SetValue; import api.web.gw2.mapping.v2.APIv2; import java.util.Set; @APIv2(endpoint = "v2/raids") // NOI18N. public interface Raid { /** * Gets the id of this raid. * @return A {@code String} instance, never {@code null}. */ @IdValue(flavor = IdValue.Flavor.STRING) String getId(); /** * Gets the set of wings in this raid. * @return A {@code Set<RaidWing>} instance, never {@code null}. May be * empty. */ @SetValue Set<RaidWing> getWings(); }
package blahbot; import battlecode.common.*; public class Soldier { static void debug_dump() { if (Clock.getRoundNum() % 10 > 0) return; combat.debug_dump(); } static void move(Direction dir) throws GameActionException { if (dir == Direction.NONE || dir == Direction.OMNI) { rc.breakpoint(); return; } final MapLocation pos = rc.getLocation(); boolean mySide = pos.distanceSquaredTo(Utils.myHq) <= pos.distanceSquaredTo(Utils.hisHq); if (mySide) rc.sneak(dir); else rc.move(dir); } static MapLocation reinforce() throws GameActionException { MapLocation[] spots = comm.spots(2); final MapLocation pos = rc.getLocation(); for (int i = 0; i < spots.length; ++i) { if (spots[i] != null && spots[i].distanceSquaredTo(pos) < 200) return spots[i]; } return null; } static boolean build() throws GameActionException { Robot[] allies = rc.senseNearbyGameObjects( Robot.class, RobotType.SOLDIER.sensorRadiusSquared, Utils.me); if (allies.length == 0) return false; MapLocation pastrPos = null; for (int i = allies.length; i RobotInfo info = rc.senseRobotInfo(allies[i]); if (info.type == RobotType.NOISETOWER) return false; if (info.type == RobotType.PASTR) pastrPos = info.location; else if (info.isConstructing) { if (info.constructingType == RobotType.PASTR) pastrPos = info.location; else return false; } } if (pastrPos == null) return false; return rc.getLocation().distanceSquaredTo(pastrPos) < 5; } public static void run(RobotController rc) throws GameActionException { Soldier.rc = rc; Soldier.comm = new Comm(rc); Soldier.combat = new SoldierCombat(rc, comm); Soldier.pathing = new BugPathing(rc); while (true) { // \todo Might want to do some calcs in our off turns. if (!rc.isActive()) { rc.yield(); continue; } ByteCode.Check bcCheck = new ByteCode.Check(rc); if (combat.isCombat() == SoldierCombat.CombatState.YES) { rc.setIndicatorString(0, "soldier.combat"); pathing.setTarget(combat.exterminate()); if (pathing.getTarget() != null) move(pathing.direction()); } else if (build()) rc.construct(RobotType.NOISETOWER); else { MapLocation pos; MapLocation myPos = rc.getLocation(); if ((pos = reinforce()) != null) { pathing.setTarget(pos); rc.setIndicatorString(0, "soldier.reinforce"); } else if (rc.getLocation().equals(comm.getRallyPoint())) { rc.construct(RobotType.PASTR); rc.setIndicatorString(0, "soldier.construct"); } else if (comm.hasGlobalOrder() && (pos = comm.globalOrderPos()) != null) { pathing.setTarget(pos); rc.setIndicatorString(0, "soldier.orders: " + pos.toString()); } else if (pathing.getTarget() == null || myPos.equals(pathing.getTarget())) { pathing.setTarget(pos = comm.getRallyPoint()); rc.setIndicatorString(0, "soldier.rally: " + pos.toString()); } Direction dir = pathing.direction(); rc.setIndicatorString(0, "soldier.move: " + myPos + ", " + pathing.getTarget() + " -> " + dir.toString()); move(dir); } debug_dump(); bcCheck.debug_check("Soldier.end"); rc.yield(); } } static RobotController rc; static BugPathing pathing; static Comm comm; static SoldierCombat combat; }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Emanuelle; import javax.swing.JOptionPane; /** * * @author aluno */ public class Util2 { public static void main(String args[]) { int x, y; String s, s2; Util u = new Util(); while (!u.isNumero((s = JOptionPane.showInputDialog("Digite valor para s")))) { JOptionPane.showMessageDialog(null, "Digite apenas numeros!!"); } while (!u.isNumero((s2 = JOptionPane.showInputDialog("Digite valor para s2")))) { JOptionPane.showMessageDialog(null, "Digite apenas numeros!!"); } x = Integer.parseInt(s); y = Integer.parseInt(s2); JOptionPane.showMessageDialog(null, "Soma = " + (x + y)); } }
package es.urjc.jer; import java.io.IOException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; public class PlayerHandler extends TextWebSocketHandler { private Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>(); private Map<Integer, Sala> salas = new ConcurrentHashMap<>(); private Map<String, Player> players = new ConcurrentHashMap<>(); private Map<Point, Entity> entities = new ConcurrentHashMap<>(); private ObjectMapper mapper = new ObjectMapper(); @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { System.out.println("New user: " + session.getId()); sessions.put(session.getId(), session); Player p = new Player(); p.setPlay(false); players.put(session.getId(), p); } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { System.out.println("Session closed: " + session.getId()); sessions.remove(session.getId()); players.remove(session.getId()); } @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { synchronized (message) { } System.out.println("Message received: " + message.getPayload()); JsonNode node = mapper.readTree(message.getPayload()); switch (node.get("protocolo").asText()) { case "createSala_msg": Sala s = new Sala (salas.size(), 0, 0); System.out.println(salas.size()); players.get(session.getId()).setPlay(true); players.get(session.getId()).setIdsala(s.getId()); System.out.println("" + players.get(session.getId()).getIdsala()); s.addPlayer(players.get(session.getId())); System.out.println("TAMAÑO ANTES" + salas.size()); salas.put(salas.size(), s); System.out.println("TAMAÑO AHORA" + salas.size()); notifySalaCreated(session, node, s.getNumJugadores()); break; case "joinSala_msg": players.get(session.getId()).setPlay(true); players.get(session.getId()).setIdsala(node.get("id").asInt()); salas.get(node.get("id").asInt()).addPlayer(players.get(session.getId())); notifyJ2(node, session); break; case "door_msg": // METODO DE CAMBIAR DE SALA (ROOM, MAZMORRA) // Lee el mensaje Point newroom = new Point(); newroom.setX(node.get("roomX").asInt()); newroom.setY(node.get("roomY").asInt()); players.get(session.getId()).setRoom(newroom); // Manda un mensaje al otro jugador ObjectNode newDoorNode = mapper.createObjectNode(); newDoorNode.put("protocolo", "door_msg"); newDoorNode.put("newroomX", newroom.getX()); newDoorNode.put("newroomY", newroom.getY()); sendOtherParticipants(session, newDoorNode); break; case "position_msg": // METODO PARA INTERCAMBIAR INFORMACION DE JUGADORES ESTANDO EN LA MISMA SALA // Lee el mensaje Point newpos = new Point(); newpos.setX(node.get("thisposX").asInt()); newpos.setY(node.get("thisposY").asInt()); players.get(session.getId()).setPos(newpos); int xscale = node.get("thisScale").asInt(); players.get(session.getId()).setXScale(xscale); // Manda respuesta al otro jugador ObjectNode newPosNode = mapper.createObjectNode(); newPosNode.put("protocolo", "position_msg"); newPosNode.put("otherposX", newpos.getX()); newPosNode.put("otherposY", newpos.getY()); newPosNode.put("otherScale", xscale); sendOtherParticipants(session, newPosNode); break; case "spawnentity_msg": // METODO PARA SPAWNEAR ENEMIGOS // Lee el mensaje y crea la entidad Entity newentity = new Entity(); newentity.setX(node.get("thisX").asInt()); newentity.setY(node.get("thisY").asInt()); newentity.setType(node.get("thistype").asText()); newentity.setVivo(true); // Envia la informacion de la entidad al otro jugador ObjectNode newEntNode = mapper.createObjectNode(); newEntNode.put("protocolo", "spawnentity_msg"); newEntNode.put("thisX", newentity.getX()); newEntNode.put("thisY", newentity.getY()); newEntNode.put("thistype", newentity.getType()); sendOtherParticipants(session, newEntNode); break; case "updateentity_msg": break; case "endgame_msg": // Envia la informacion de la entidad al otro jugador ObjectNode newEndNode = mapper.createObjectNode(); newEndNode.put("protocolo", "endgame_msg"); sendOtherParticipants(session, newEndNode); break; default: System.out.println("ERROR: Mensaje no soportado"); } } private void notifyJ2 (JsonNode node, WebSocketSession session) throws IOException { ObjectNode join = mapper.createObjectNode(); join.put("protocolo", "joinSala_msg"); join.put("salaId", players.get(session.getId()).getIdsala()); for(WebSocketSession participant : sessions.values()) { if(!participant.getId().equals(session.getId()) && (players.get(participant.getId()).getIdsala() == node.get("id").asInt())) { participant.sendMessage(new TextMessage(join.toString())); System.out.println("JOIN SALA: Message sent: " + join.toString()); } } } //notifica a todos los jugadores que no esten en una partida private void notifySalaCreated(WebSocketSession session, JsonNode node, int size) throws IOException { ObjectNode newNode = mapper.createObjectNode(); newNode.put("protocolo", "createSala_msg"); newNode.put("id", node.get("id").asInt()); newNode.put("numJugadores", size); newNode.put("status", 1); for(WebSocketSession participant : sessions.values()) { if(!participant.getId().equals(session.getId()) && !players.get(participant.getId()).isPlay()) { participant.sendMessage(new TextMessage(newNode.toString())); System.out.println("CREATE SALA: Message sent: " + newNode.toString()); } } } // Solo dentro de EL MISMO LOBBY private void sendOtherParticipants(WebSocketSession session, JsonNode node) throws IOException { System.out.println("Message sent: " + node.toString()); for(WebSocketSession participant : sessions.values()) { if(!participant.getId().equals(session.getId()) && (players.get(session.getId()).getIdsala() == players.get(participant.getId()).getIdsala())){ participant.sendMessage(new TextMessage(node.toString())); } } } }
package com.iterable.iterableapi; import android.graphics.Rect; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RestrictTo; import androidx.core.util.ObjectsCompat; import org.json.JSONException; import org.json.JSONObject; import java.util.Date; public class IterableInAppMessage { private static final String TAG = "IterableInAppMessage"; private final @NonNull String messageId; private final @NonNull Content content; private final @NonNull JSONObject customPayload; private final @NonNull Date createdAt; private final @NonNull Date expiresAt; private final @NonNull Trigger trigger; private final @Nullable Boolean saveToInbox; private final @Nullable InboxMetadata inboxMetadata; private final @Nullable Long campaignId; private boolean processed = false; private boolean consumed = false; private boolean read = false; private boolean loadedHtmlFromJson = false; private @Nullable IterableInAppStorage inAppStorageInterface; IterableInAppMessage(@NonNull String messageId, @NonNull Content content, @NonNull JSONObject customPayload, @NonNull Date createdAt, @NonNull Date expiresAt, @NonNull Trigger trigger, @Nullable Boolean saveToInbox, @Nullable InboxMetadata inboxMetadata, @Nullable Long campaignId) { this.messageId = messageId; this.content = content; this.customPayload = customPayload; this.createdAt = createdAt; this.expiresAt = expiresAt; this.trigger = trigger; this.saveToInbox = saveToInbox; this.inboxMetadata = inboxMetadata; this.campaignId = campaignId; } static class Trigger { enum TriggerType { IMMEDIATE, EVENT, NEVER } final @Nullable JSONObject triggerJson; final @NonNull TriggerType type; private Trigger(JSONObject triggerJson) { this.triggerJson = triggerJson; String typeString = triggerJson.optString(IterableConstants.ITERABLE_IN_APP_TRIGGER_TYPE); switch(typeString) { case "immediate": type = TriggerType.IMMEDIATE; break; case "never": type = TriggerType.NEVER; break; default: type = TriggerType.NEVER; } } Trigger(@NonNull TriggerType triggerType) { triggerJson = null; this.type = triggerType; } @NonNull static Trigger fromJSONObject(JSONObject triggerJson) { if (triggerJson == null) { // Default to 'immediate' if there is no trigger in the payload return new Trigger(TriggerType.IMMEDIATE); } else { return new Trigger(triggerJson); } } @Nullable JSONObject toJSONObject() { return triggerJson; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof Trigger)) { return false; } Trigger trigger = (Trigger) obj; return ObjectsCompat.equals(triggerJson, trigger.triggerJson); } @Override public int hashCode() { return ObjectsCompat.hash(triggerJson); } } public static class Content { public String html; public final Rect padding; public final double backgroundAlpha; Content(String html, Rect padding, double backgroundAlpha) { this.html = html; this.padding = padding; this.backgroundAlpha = backgroundAlpha; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof Content)) { return false; } Content content = (Content) obj; return ObjectsCompat.equals(html, content.html) && ObjectsCompat.equals(padding, content.padding) && backgroundAlpha == backgroundAlpha; } @Override public int hashCode() { return ObjectsCompat.hash(html, padding, backgroundAlpha); } } public static class InboxMetadata { public final @Nullable String title; public final @Nullable String subtitle; public final @Nullable String icon; public InboxMetadata(@Nullable String title, @Nullable String subtitle, @Nullable String icon) { this.title = title; this.subtitle = subtitle; this.icon = icon; } @Nullable static InboxMetadata fromJSONObject(@Nullable JSONObject inboxMetadataJson) { if (inboxMetadataJson == null) { return null; } String title = inboxMetadataJson.optString(IterableConstants.ITERABLE_IN_APP_INBOX_TITLE); String subtitle = inboxMetadataJson.optString(IterableConstants.ITERABLE_IN_APP_INBOX_SUBTITLE); String icon = inboxMetadataJson.optString(IterableConstants.ITERABLE_IN_APP_INBOX_ICON); return new InboxMetadata(title, subtitle, icon); } @NonNull JSONObject toJSONObject() { JSONObject inboxMetadataJson = new JSONObject(); try { inboxMetadataJson.putOpt(IterableConstants.ITERABLE_IN_APP_INBOX_TITLE, title); inboxMetadataJson.putOpt(IterableConstants.ITERABLE_IN_APP_INBOX_SUBTITLE, subtitle); inboxMetadataJson.putOpt(IterableConstants.ITERABLE_IN_APP_INBOX_ICON, icon); } catch (JSONException e) { IterableLogger.e(TAG, "Error while serializing inbox metadata", e); } return inboxMetadataJson; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof InboxMetadata)) { return false; } InboxMetadata inboxMetadata = (InboxMetadata) obj; return ObjectsCompat.equals(title, inboxMetadata.title) && ObjectsCompat.equals(subtitle, inboxMetadata.subtitle) && ObjectsCompat.equals(icon, inboxMetadata.icon); } @Override public int hashCode() { return ObjectsCompat.hash(title, subtitle, icon); } } @NonNull public String getMessageId() { return messageId; } @Nullable public Long getCampaignId() { return campaignId; } @NonNull public Date getCreatedAt() { return createdAt; } @NonNull Date getExpiresAt() { return expiresAt; } @NonNull public Content getContent() { if (content.html == null) { content.html = inAppStorageInterface.getHTML(messageId); } return content; } @NonNull public JSONObject getCustomPayload() { return customPayload; } boolean isProcessed() { return processed; } void setProcessed(boolean processed) { this.processed = processed; onChanged(); } boolean isConsumed() { return consumed; } void setConsumed(boolean consumed) { this.consumed = consumed; onChanged(); } Trigger.TriggerType getTriggerType() { return trigger.type; } public boolean isInboxMessage() { return saveToInbox != null ? saveToInbox : false; } @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public boolean isSilentInboxMessage() { return isInboxMessage() && getTriggerType() == IterableInAppMessage.Trigger.TriggerType.NEVER; } @Nullable public InboxMetadata getInboxMetadata() { return inboxMetadata; } public boolean isRead() { return read; } void setRead(boolean read) { this.read = read; onChanged(); } boolean hasLoadedHtmlFromJson() { return loadedHtmlFromJson; } void setLoadedHtmlFromJson(boolean loadedHtmlFromJson) { this.loadedHtmlFromJson = loadedHtmlFromJson; } static IterableInAppMessage fromJSONObject(@NonNull JSONObject messageJson, @Nullable IterableInAppStorage storageInterface) { if (messageJson == null) { return null; } JSONObject contentJson = messageJson.optJSONObject(IterableConstants.ITERABLE_IN_APP_CONTENT); if (contentJson == null) { return null; } String messageId = messageJson.optString(IterableConstants.KEY_MESSAGE_ID); final Long campaignId = IterableUtil.retrieveValidCampaignIdOrNull(messageJson, IterableConstants.KEY_CAMPAIGN_ID); long createdAtLong = messageJson.optLong(IterableConstants.ITERABLE_IN_APP_CREATED_AT); Date createdAt = createdAtLong != 0 ? new Date(createdAtLong) : null; long expiresAtLong = messageJson.optLong(IterableConstants.ITERABLE_IN_APP_EXPIRES_AT); Date expiresAt = expiresAtLong != 0 ? new Date(expiresAtLong) : null; String html = contentJson.optString(IterableConstants.ITERABLE_IN_APP_HTML, null); JSONObject paddingOptions = contentJson.optJSONObject(IterableConstants.ITERABLE_IN_APP_DISPLAY_SETTINGS); Rect padding = getPaddingFromPayload(paddingOptions); double backgroundAlpha = contentJson.optDouble(IterableConstants.ITERABLE_IN_APP_BACKGROUND_ALPHA, 0); JSONObject triggerJson = messageJson.optJSONObject(IterableConstants.ITERABLE_IN_APP_TRIGGER); Trigger trigger = Trigger.fromJSONObject(triggerJson); JSONObject customPayload = messageJson.optJSONObject(IterableConstants.ITERABLE_IN_APP_CUSTOM_PAYLOAD); if (customPayload == null) { customPayload = contentJson.optJSONObject(IterableConstants.ITERABLE_IN_APP_LEGACY_PAYLOAD); } if (customPayload == null) { customPayload = new JSONObject(); } Boolean saveToInbox = messageJson.has(IterableConstants.ITERABLE_IN_APP_SAVE_TO_INBOX) ? messageJson.optBoolean(IterableConstants.ITERABLE_IN_APP_SAVE_TO_INBOX) : null; JSONObject inboxPayloadJson = messageJson.optJSONObject(IterableConstants.ITERABLE_IN_APP_INBOX_METADATA); InboxMetadata inboxMetadata = InboxMetadata.fromJSONObject(inboxPayloadJson); IterableInAppMessage message = new IterableInAppMessage( messageId, new Content(html, padding, backgroundAlpha), customPayload, createdAt, expiresAt, trigger, saveToInbox, inboxMetadata, campaignId); message.inAppStorageInterface = storageInterface; if (html != null) { message.setLoadedHtmlFromJson(true); } message.processed = messageJson.optBoolean(IterableConstants.ITERABLE_IN_APP_PROCESSED, false); message.consumed = messageJson.optBoolean(IterableConstants.ITERABLE_IN_APP_CONSUMED, false); message.read = messageJson.optBoolean(IterableConstants.ITERABLE_IN_APP_READ, false); return message; } @NonNull JSONObject toJSONObject() { JSONObject messageJson = new JSONObject(); JSONObject contentJson = new JSONObject(); try { messageJson.putOpt(IterableConstants.KEY_MESSAGE_ID, messageId); if (campaignId != null && IterableUtil.isValidCampaignId(campaignId)) { messageJson.put(IterableConstants.KEY_CAMPAIGN_ID, campaignId); } if (createdAt != null) { messageJson.putOpt(IterableConstants.ITERABLE_IN_APP_CREATED_AT, createdAt.getTime()); } if (expiresAt != null) { messageJson.putOpt(IterableConstants.ITERABLE_IN_APP_EXPIRES_AT, expiresAt.getTime()); } messageJson.putOpt(IterableConstants.ITERABLE_IN_APP_TRIGGER, trigger.toJSONObject()); contentJson.putOpt(IterableConstants.ITERABLE_IN_APP_DISPLAY_SETTINGS, encodePaddingRectToJson(content.padding)); if (content.backgroundAlpha != 0) { contentJson.putOpt(IterableConstants.ITERABLE_IN_APP_BACKGROUND_ALPHA, content.backgroundAlpha); } messageJson.putOpt(IterableConstants.ITERABLE_IN_APP_CONTENT, contentJson); messageJson.putOpt(IterableConstants.ITERABLE_IN_APP_CUSTOM_PAYLOAD, customPayload); if (saveToInbox != null) { messageJson.putOpt(IterableConstants.ITERABLE_IN_APP_SAVE_TO_INBOX, saveToInbox); } if (inboxMetadata != null) { messageJson.putOpt(IterableConstants.ITERABLE_IN_APP_INBOX_METADATA, inboxMetadata.toJSONObject()); } messageJson.putOpt(IterableConstants.ITERABLE_IN_APP_PROCESSED, processed); messageJson.putOpt(IterableConstants.ITERABLE_IN_APP_CONSUMED, consumed); messageJson.putOpt(IterableConstants.ITERABLE_IN_APP_READ, read); } catch (JSONException e) { IterableLogger.e(TAG, "Error while serializing an in-app message", e); } return messageJson; } interface OnChangeListener { void onInAppMessageChanged(IterableInAppMessage message); } private OnChangeListener onChangeListener; void setOnChangeListener(OnChangeListener listener) { onChangeListener = listener; } private void onChanged() { if (onChangeListener != null) { onChangeListener.onInAppMessageChanged(this); } } /** * Returns a Rect containing the paddingOptions * @param paddingOptions * @return */ static Rect getPaddingFromPayload(JSONObject paddingOptions) { Rect rect = new Rect(); rect.top = decodePadding(paddingOptions.optJSONObject("top")); rect.left = decodePadding(paddingOptions.optJSONObject("left")); rect.bottom = decodePadding(paddingOptions.optJSONObject("bottom")); rect.right = decodePadding(paddingOptions.optJSONObject("right")); return rect; } /** * Returns a JSONObject containing the encoded padding options * @param rect Rect representing the padding options * @return JSON object with encoded padding values * @throws JSONException */ static JSONObject encodePaddingRectToJson(Rect rect) throws JSONException { JSONObject paddingJson = new JSONObject(); paddingJson.putOpt("top", encodePadding(rect.top)); paddingJson.putOpt("left", encodePadding(rect.left)); paddingJson.putOpt("bottom", encodePadding(rect.bottom)); paddingJson.putOpt("right", encodePadding(rect.right)); return paddingJson; } /** * Retrieves the padding percentage * @discussion -1 is returned when the padding percentage should be auto-sized * @param jsonObject * @return */ static int decodePadding(JSONObject jsonObject) { int returnPadding = 0; if (jsonObject != null) { if ("AutoExpand".equalsIgnoreCase(jsonObject.optString("displayOption"))) { returnPadding = -1; } else { returnPadding = jsonObject.optInt("percentage", 0); } } return returnPadding; } /** * Encodes the padding percentage to JSON * @param padding integer representation of the padding value * @return JSON object containing encoded padding data * @throws JSONException */ static JSONObject encodePadding(int padding) throws JSONException { JSONObject paddingJson = new JSONObject(); if (padding == -1) { paddingJson.putOpt("displayOption", "AutoExpand"); } else { paddingJson.putOpt("percentage", padding); } return paddingJson; } }
package net.iaeste.iws.migrate.migrators; import net.iaeste.iws.api.enums.Privacy; import net.iaeste.iws.migrate.daos.IWSDao; import net.iaeste.iws.migrate.entities.IW3FileEntity; import net.iaeste.iws.persistence.entities.FileEntity; import net.iaeste.iws.persistence.entities.FolderEntity; import net.iaeste.iws.persistence.entities.GroupEntity; import net.iaeste.iws.persistence.entities.UserEntity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.util.Date; import java.util.List; import java.util.UUID; public class FileMigrator implements Migrator<IW3FileEntity> { private static final Logger log = LoggerFactory.getLogger(FileMigrator.class); @Autowired private IWSDao iwsDao; public FileMigrator() { } public FileMigrator(final IWSDao iwsDao) { this.iwsDao = iwsDao; } /** * {@inheritDoc} */ @Override public MigrationResult migrate() { throw new IllegalArgumentException("This Migrator is not allowed here."); } /** * {@inheritDoc} */ @Override @Transactional(value = "transactionManagerIWS", propagation = Propagation.REQUIRES_NEW) public MigrationResult migrate(final List<IW3FileEntity> oldEntities) { int skipped = 0; int folders = 0; int files = 0; for (final IW3FileEntity oldFile : oldEntities) { if (skipThis(oldFile)) { skipped++; } else { if ("d".equals(oldFile.getFiletype())) { if (migrateFolder(oldFile)) { folders++; } else { skipped++; } } else { if (migrateFile(oldFile)) { files++; } else { skipped++; } } } } log.info("Completed migrating block with {} files and {} folders.", files, folders); return new MigrationResult(folders + files, skipped); } // Internal Countries Migration Methods private boolean skipThis(final IW3FileEntity entity) { boolean result = false; if (entity.getFileid() <= 2) { // Default Folders (root & library) is skipped result = true; } else if (entity.getGroupId() == 117) { result = true; } return result; } private boolean migrateFolder(final IW3FileEntity oldEntity) { final GroupEntity groupEntity = findGroup(oldEntity); final FolderEntity folderEntity = findFolder(oldEntity); final boolean persisted; if (groupEntity == null) { log.info("Skipping folder (missing Group): [" + oldEntity.getFileid() + "] " + oldEntity.getFilename()); persisted = false; } else { final FolderEntity entity = new FolderEntity(); entity.setExternalId(UUID.randomUUID().toString()); entity.setParentId(folderEntity != null ? folderEntity.getId() : null); entity.setGroup(findGroup(oldEntity)); entity.setFoldername(oldEntity.getFilename().trim()); entity.setOldIW3FileId(oldEntity.getFileid()); entity.setModified(readDate(oldEntity.getModified(), new Date())); entity.setCreated(readDate(entity.getCreated(), entity.getModified())); iwsDao.persist(entity); persisted = true; } return persisted; } private boolean migrateFile(final IW3FileEntity oldEntity) { final GroupEntity groupEntity = findGroup(oldEntity); final UserEntity userEntity = findUser(oldEntity); final boolean persisted; if (userEntity == null) { log.info("Skipping file (missing User): [" + oldEntity.getFileid() + "] " + oldEntity.getFilename()); persisted = false; } else if (groupEntity == null) { log.info("Skipping file (missing Group): [" + oldEntity.getFileid() + "] " + oldEntity.getFilename()); persisted = false; } else { final FileEntity entity = new FileEntity(); entity.setExternalId(UUID.randomUUID().toString()); // For now, we're assuming that all files are Protected. Later, we // can try to change that when we know more about them. entity.setPrivacy(Privacy.PROTECTED); entity.setGroup(findGroup(oldEntity)); entity.setUser(findUser(oldEntity)); entity.setFolder(findFolder(oldEntity)); entity.setFilename(oldEntity.getFilename().trim()); entity.setStoredFilename("files/" + oldEntity.getUserId() + '/' + oldEntity.getSystemname()); entity.setFilesize(oldEntity.getFilesize()); entity.setMimetype(oldEntity.getMimetype().getMimetype()); entity.setDescription(oldEntity.getDescription().trim()); entity.setKeywords(oldEntity.getKeywords().trim()); entity.setChecksum(convertChecksum(oldEntity.getChecksum())); entity.setOldIW3FileId(oldEntity.getFileid()); entity.setModified(readDate(oldEntity.getModified(), new Date())); entity.setCreated(readDate(oldEntity.getCreated(), oldEntity.getModified())); iwsDao.persist(entity); persisted = true; } return persisted; } private static Date readDate(final Date primary, final Date secondary) { final Date date; if (primary != null) { date = primary; } else if (secondary != null) { date = secondary; } else { date = new Date(); } return date; } private GroupEntity findGroup(final IW3FileEntity oldEntity) { final Integer iw3GroupId = oldEntity.getGroupId(); final GroupEntity entity = iwsDao.findGroupByIW3Id(iw3GroupId); return entity; } private UserEntity findUser(final IW3FileEntity oldEntity) { final Integer iw3UserId = oldEntity.getUserId(); UserEntity entity = iwsDao.findUserByIW3Id(iw3UserId); if (entity == null) { // Most documents which is also having a Group associated, should // also be migrated, so we will simply set it to the GroupOwner final GroupEntity group = findGroup(oldEntity); if (group != null) { entity = iwsDao.findGroupOwner(group); } } return entity; } private FolderEntity findFolder(final IW3FileEntity oldEntity) { // In IW3, the FolderId 1 is the same as a non-public root folder. In // IWS, it is simply set to null. The Library in IW3 has the FolderId 2, // which is mapped over in IWS, so it will work fine :-) final Integer iw3FolderId = oldEntity.getFolderid(); final FolderEntity entity; if (iw3FolderId == 1) { entity = null; } else { entity = iwsDao.findFolderByIW3Id(Long.valueOf(iw3FolderId)); } return entity; } private Long convertChecksum(final String checksum) { return null; } }
package com.kylinolap.job; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import org.apache.commons.io.IOUtils; import org.apache.hadoop.hbase.util.Pair; import org.apache.maven.model.Model; import org.apache.maven.model.io.xpp3.MavenXpp3Reader; import org.codehaus.plexus.util.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.kylinolap.common.KylinConfig; import com.kylinolap.common.persistence.ResourceTool; import com.kylinolap.common.util.AbstractKylinTestCase; import com.kylinolap.common.util.CliCommandExecutor; import com.kylinolap.cube.CubeInstance; import com.kylinolap.cube.CubeManager; import com.kylinolap.cube.dataGen.FactTableGenerator; import com.kylinolap.job.engine.JobEngineConfig; import com.kylinolap.job.hadoop.hive.SqlHiveDataTypeMapping; import com.kylinolap.job.tools.LZOSupportnessChecker; import com.kylinolap.metadata.MetadataManager; import com.kylinolap.metadata.model.schema.ColumnDesc; import com.kylinolap.metadata.model.schema.TableDesc; public class DeployUtil { @SuppressWarnings("unused") private static final Logger logger = LoggerFactory.getLogger(DeployUtil.class); public static void initCliWorkDir() throws IOException { execCliCommand("rm -rf " + getHadoopCliWorkingDir()); execCliCommand("mkdir -p " + config().getKylinJobLogDir()); } public static void deployMetadata() throws IOException { // install metadata to hbase ResourceTool.reset(config()); ResourceTool.copy(KylinConfig.createInstanceFromUri(AbstractKylinTestCase.LOCALMETA_TEST_DATA), config()); // update cube desc signature. for (CubeInstance cube : CubeManager.getInstance(config()).listAllCubes()) { cube.getDescriptor().setSignature(cube.getDescriptor().calculateSignature()); CubeManager.getInstance(config()).updateCube(cube); } } public static void overrideJobJarLocations() { Pair<File, File> files = getJobJarFiles(); File jobJar = files.getFirst(); File coprocessorJar = files.getSecond(); config().overrideKylinJobJarPath(jobJar.getAbsolutePath()); config().overrideCoprocessorLocalJar(coprocessorJar.getAbsolutePath()); } public static void deployJobJars() throws IOException { Pair<File, File> files = getJobJarFiles(); File jobJar = files.getFirst(); File coprocessorJar = files.getSecond(); File jobJarRemote = new File(config().getKylinJobJarPath()); File jobJarLocal = new File(jobJar.getParentFile(), jobJarRemote.getName()); if (jobJar.equals(jobJarLocal) == false) { FileUtils.copyFile(jobJar, jobJarLocal); } File coprocessorJarRemote = new File(config().getCoprocessorLocalJar()); File coprocessorJarLocal = new File(coprocessorJar.getParentFile(), coprocessorJarRemote.getName()); if (coprocessorJar.equals(coprocessorJarLocal) == false) { FileUtils.copyFile(coprocessorJar, coprocessorJarLocal); } CliCommandExecutor cmdExec = config().getCliCommandExecutor(); cmdExec.copyFile(jobJarLocal.getAbsolutePath(), jobJarRemote.getParent()); cmdExec.copyFile(coprocessorJar.getAbsolutePath(), coprocessorJarRemote.getParent()); } private static Pair<File, File> getJobJarFiles() { String version; try { MavenXpp3Reader pomReader = new MavenXpp3Reader(); Model model = pomReader.read(new FileReader("../pom.xml")); version = model.getVersion(); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } File jobJar = new File("../job/target", "kylin-job-" + version + "-job.jar"); File coprocessorJar = new File("../storage/target", "kylin-storage-" + version + "-coprocessor.jar"); return new Pair<File, File>(jobJar, coprocessorJar); } public static void overrideJobConf(String confDir) throws IOException { boolean enableLzo = LZOSupportnessChecker.getSupportness(); overrideJobConf(confDir, enableLzo); } public static void overrideJobConf(String confDir, boolean enableLzo) throws IOException { File src = new File(confDir, JobEngineConfig.HADOOP_JOB_CONF_FILENAME + (enableLzo ? ".lzo_enabled" : ".lzo_disabled") + ".xml"); File dst = new File(confDir, JobEngineConfig.HADOOP_JOB_CONF_FILENAME + ".xml"); FileUtils.copyFile(src, dst); } private static void execCliCommand(String cmd) throws IOException { config().getCliCommandExecutor().execute(cmd); } private static String getHadoopCliWorkingDir() { return config().getCliWorkingDir(); } private static KylinConfig config() { return KylinConfig.getInstanceFromEnv(); } static final String TABLE_CAL_DT = "test_cal_dt"; static final String TABLE_CATEGORY_GROUPINGS = "test_category_groupings"; static final String TABLE_KYLIN_FACT = "test_kylin_fact"; static final String TABLE_SELLER_TYPE_DIM = "test_seller_type_dim"; static final String TABLE_SITES = "test_sites"; static final String[] TABLE_NAMES = new String[] { TABLE_CAL_DT, TABLE_CATEGORY_GROUPINGS, TABLE_KYLIN_FACT, TABLE_SELLER_TYPE_DIM, TABLE_SITES }; public static void prepareTestData(String joinType, String cubeName) throws Exception { // data is generated according to cube descriptor and saved in resource store if (joinType.equalsIgnoreCase("inner")) { FactTableGenerator.generate(cubeName, "10000", "1", null, "inner"); } else if (joinType.equalsIgnoreCase("left")) { FactTableGenerator.generate(cubeName, "10000", "0.6", null, "left"); } else { throw new IllegalArgumentException("Unsupported join type : " + joinType); } deployHiveTables(); } private static void deployHiveTables() throws Exception { MetadataManager metaMgr = MetadataManager.getInstance(config()); // scp data files, use the data from hbase, instead of local files File temp = File.createTempFile("temp", ".csv"); temp.createNewFile(); for (String tablename : TABLE_NAMES) { tablename = tablename.toUpperCase(); File localBufferFile = new File(temp.getParent() + "/" + tablename + ".csv"); localBufferFile.createNewFile(); InputStream hbaseDataStream = metaMgr.getStore().getResource("/data/" + tablename + ".csv"); FileOutputStream localFileStream = new FileOutputStream(localBufferFile); IOUtils.copy(hbaseDataStream, localFileStream); hbaseDataStream.close(); localFileStream.close(); config().getCliCommandExecutor().copyFile(localBufferFile.getPath(), config().getCliWorkingDir()); localBufferFile.delete(); } temp.delete(); // create hive tables execHiveCommand(generateCreateTableHql(metaMgr.getTableDesc(TABLE_CAL_DT.toUpperCase()))); execHiveCommand(generateCreateTableHql(metaMgr.getTableDesc(TABLE_CATEGORY_GROUPINGS.toUpperCase()))); execHiveCommand(generateCreateTableHql(metaMgr.getTableDesc(TABLE_KYLIN_FACT.toUpperCase()))); execHiveCommand(generateCreateTableHql(metaMgr.getTableDesc(TABLE_SELLER_TYPE_DIM.toUpperCase()))); execHiveCommand(generateCreateTableHql(metaMgr.getTableDesc(TABLE_SITES.toUpperCase()))); // load data to hive tables // LOAD DATA LOCAL INPATH 'filepath' [OVERWRITE] INTO TABLE tablename execHiveCommand(generateLoadDataHql(TABLE_CAL_DT)); execHiveCommand(generateLoadDataHql(TABLE_CATEGORY_GROUPINGS)); execHiveCommand(generateLoadDataHql(TABLE_KYLIN_FACT)); execHiveCommand(generateLoadDataHql(TABLE_SELLER_TYPE_DIM)); execHiveCommand(generateLoadDataHql(TABLE_SITES)); } private static void execHiveCommand(String hql) throws IOException { String hiveCmd = "hive -e \"" + hql + "\""; config().getCliCommandExecutor().execute(hiveCmd); } private static String generateLoadDataHql(String tableName) { return "LOAD DATA LOCAL INPATH '" + config().getCliWorkingDir() + "/" + tableName.toUpperCase() + ".csv' OVERWRITE INTO TABLE " + tableName.toUpperCase(); } private static String generateCreateTableHql(TableDesc tableDesc) { StringBuilder ddl = new StringBuilder(); ddl.append("DROP TABLE IF EXISTS " + tableDesc.getName() + ";\n"); ddl.append("CREATE TABLE " + tableDesc.getName() + "\n"); ddl.append("(" + "\n"); for (int i = 0; i < tableDesc.getColumns().length; i++) { ColumnDesc col = tableDesc.getColumns()[i]; if (i > 0) { ddl.append(","); } ddl.append(col.getName() + " " + SqlHiveDataTypeMapping.getHiveDataType((col.getDatatype())) + "\n"); } ddl.append(")" + "\n"); ddl.append("ROW FORMAT DELIMITED FIELDS TERMINATED BY ','" + "\n"); ddl.append("STORED AS TEXTFILE;"); return ddl.toString(); } }
package mgks.os.swv; class SmartWebView { static boolean ASWP_JSCRIPT = true; // enable JavaScript for webview static boolean ASWP_FUPLOAD = true; // upload file from webview static boolean ASWP_CAMUPLOAD = true; // enable upload from camera for photos static boolean ASWP_ONLYCAM = false; // incase you want only camera files to upload static boolean ASWP_MULFILE = true; // upload multiple files in webview static boolean ASWP_LOCATION = true; // track GPS locations static boolean ASWP_CP = false; // enable copy/paste within webview static boolean ASWP_RATINGS = true; // show ratings dialog; auto configured ; edit method get_rating() for customizations static boolean ASWP_PULLFRESH = true; // pull refresh current url static boolean ASWP_PBAR = true; // show progress bar in app static boolean ASWP_ZOOM = false; // zoom control for webpages view static boolean ASWP_SFORM = false; // save form cache and auto-fill information static boolean ASWP_OFFLINE = false; // whether the loading webpages are offline or online static boolean ASWP_EXTURL = true; // open external url with default browser instead of app webview static boolean ASWP_TAB = true; // instead of default browser, open external URLs in chrome tab static boolean ASWP_ADMOB = true; // to load admob or not static boolean ASWP_EXITDIAL = true; // confirm to exit app on back press /* -- SECURITY VARIABLES -- */ static boolean ASWP_CERT_VERI = true; // verify whether HTTPS port needs certificate verification /* -- CONFIG VARIABLES -- */ // layout selection static int ASWV_LAYOUT = 0; // default=0; for clear fullscreen layout, and =1 for drawer layout // URL configs static String ASWV_URL = "https://apps.mgks.dev/swv/?android=true"; // complete URL of your website or offline webpage "file:///android_asset/offline.html"; static String ASWV_SEARCH = "https: static String ASWV_SHARE_URL = ASWV_URL + "?share="; // URL where you process external content shared with the app // domains allowed to be opened inside webview static String ASWV_EXC_LIST = "github.com"; //separate domains with a comma (,) // custom user agent defaults static boolean POSTFIX_USER_AGENT = true; // set to true to append USER_AGENT_POSTFIX to user agent static boolean OVERRIDE_USER_AGENT = false; // set to true to use USER_AGENT instead of default one static String USER_AGENT_POSTFIX = "SWVAndroid"; // useful for identifying traffic, e.g. in Google Analytics static String CUSTOM_USER_AGENT = "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Mobile Safari/537.36"; // custom user-agent // to upload any file type using "*/*"; check file type references for more static String ASWV_F_TYPE = "*/*"; // admob config static String ASWV_ADMOB = "pub-1566476371455791"; // your unique publishers ID /* -- RATING SYSTEM VARIABLES -- */ static int ASWR_DAYS = 3; // after how many days of usage would you like to show the dialog static int ASWR_TIMES = 10; // overall request launch times being ignored static int ASWR_INTERVAL = 2; // reminding users to rate after days interval }
package avrora.sim.platform; import avrora.sim.FiniteStateMachine; import avrora.sim.Simulator; import avrora.sim.output.SimPrinter; import avrora.sim.state.BooleanView; import avrora.sim.state.BooleanView.ValueSetListener; import avrora.sim.state.Register; import avrora.sim.state.RegisterUtil; import avrora.sim.clock.Clock; import avrora.sim.energy.Energy; import avrora.sim.mcu.Microcontroller; import cck.text.Terminal; /** * The <code>ExternalFlash</code> class implements the necessary functionality of the * Atmega Dataflash interface to use the Mica2 DataFlash * This device requires use of the following pins: * <p/> * PA3 - Flash Cable Seclect * <p/> * PD2 - USART1_RXD * PD3 - USART1_TXD * PD5 - USART1_CLK * * @author Thomas Gaertner */ public class ExternalFlash { protected final Simulator sim; protected final Clock clock; protected Microcontroller mcu; protected final SimPrinter printer; private boolean isSelected; // true if PA3 is 0 private boolean isReading; // mcu is reading from so of dataflash? private int dfOpcode; private int dfPageAddress; private int dfByteOffset; private int dfTempByte; private short dfStatus; // Dataflash Status Register private double delay; // delay while busy in ms private BooleanView so = RegisterUtil.booleanView(new Register(1), 0); // serial output private boolean si; // serial output, serial input private int icPage; // internal address counter private boolean tick; private short step; private byte i; // DataFlash Status Register // bits 5, 4, 3 public static final int DF_STATUS_REGISTER_DENSITY = 0x18; public static final int DF_STATUS_READY = 0x80; public static final int DF_STATUS_COMPARE = 0x40; // SC Characteristics // all below in ms public static final int DF_TEP = 20; public static final int DF_TP = 14; public static final int DF_TPE = 8; public static final int DF_TBE = 12; public static final double DF_TXFR = 0.0003; // names of the states of this device private static final String[] modeName = {"standby", "read", "write", "load"}; // power consumption of the device states private static final double[] modeAmpere = {0.000002, 0.004, 0.015, 0.000002}; // default mode of the device is standby private static final int startMode = 0; // the Dataflash Memory public Memory memory; protected final FiniteStateMachine stateMachine; /** * The <code>Memory</code> class simulates the Dataflash Memory */ private class Memory { private final int bytesPerPage; private final Page[] pages; Page buffer1; Page buffer2; protected Memory(int numPages, int numBytes) { pages = new Page[numPages]; bytesPerPage = numBytes; buffer1 = new Page(numBytes); buffer2 = new Page(numBytes); } Page getPage(int pageNum) { ExternalFlash.Page page = pages[pageNum]; if (page == null) { page = new Page(bytesPerPage); pages[pageNum] = page; } return page; } void setPage(int pageNum, Page page) { pages[pageNum] = page; } } private class Page { final short[] bytes; protected Page(int numBytes) { bytes = new short[numBytes]; java.util.Arrays.fill(bytes, (short)0xff); // empty flash is filled with 0xff, not 0! } void debug() { if (printer != null) { int i; for(i = 0; i < bytes.length; i++) { echo("Byte " + i + " = " + bytes[i]); } } } } public ExternalFlash(Microcontroller mcunit, int numPages, int pageBytes) { memory = new Memory(numPages, pageBytes); mcu = mcunit; sim = mcu.getSimulator(); printer = sim.getPrinter("mica2.flash"); clock = sim.getClock(); dfStatus = DF_STATUS_REGISTER_DENSITY | DF_STATUS_READY; tick = false; i = 0; step = 0; stateMachine = new FiniteStateMachine(clock, startMode, modeName, 0); // connect Pins // output mcu.getPin("PA3").connectOutput(new PA3Output()); mcu.getPin("PD3").connectOutput(new PD3Output()); mcu.getPin("PD5").connectOutput(new PD5Output()); // input mcu.getPin("PD2").connectInput(new PD2Input()); //setup energy recording new Energy("flash", modeAmpere, stateMachine, sim.getEnergyControl()); } private Page getMemoryPage(int num) { return memory.getPage(num); } private short getMemoryPageAt(int num, int offset) { return memory.getPage(num).bytes[offset]; } private void setMemoryPage(int num, Page val) { memory.setPage(num, val); val.debug(); } private Page getBuffer1() { return memory.buffer1; } private short getBuffer1(int offset) { return memory.buffer1.bytes[offset]; } private void setBuffer1(Page value) { memory.buffer1 = value; } private void setBuffer1(int offset, short value) { memory.buffer1.bytes[offset] = value; } private Page getBuffer2() { return memory.buffer2; } private short getBuffer2(int offset) { return memory.buffer2.bytes[offset]; } private void setBuffer2(Page value) { memory.buffer2 = value; } private void setBuffer2(int offset, short value) { memory.buffer2.bytes[offset] = value; } private void copyBuffer1toPage(int num) { setMemoryPage(num, getBuffer1()); } private void copyBuffer2toPage(int num) { setMemoryPage(num, getBuffer2()); } private void copyPageToBuffer1(int num) { setBuffer1(getMemoryPage(num)); } private void copyPageToBuffer2(int num) { setBuffer2(getMemoryPage(num)); } // Flash_CS as output pin protected class PA3Output implements Microcontroller.Pin.Output { // Flash_CS is connected inverted public void write(boolean level) { if (!level && !isSelected) { // falling edge, so instruction starts if (clock.getCount() > 1500) { echo("Instruction started"); } isSelected = true; } else if (level && isSelected) { // rising edge, so instruction terminates if (clock.getCount() < 1500) { echo("initialized"); } else { echo("Instruction finished"); } isSelected = false; switch (dfOpcode) { // Read Commands case 0x68: // Continous Array Read case 0xE8: // Continous Array Read case 0x52: // Main Memory Page Read case 0xD2: // Main Memory Page Read case 0x54: // Buffer1 Read case 0xD4: // Buffer1 Read case 0x56: // Buffer2 Read case 0xD6: // Buffer2 Read case 0x57: // Status Register Read case 0xD7: // Status Register Read break; // Program and Erase Commands case 0x83: // Buffer1 to Memory with Built-in Erase copyBuffer1toPage(dfPageAddress); echo("copy Buffer1 to Memory Page " + dfPageAddress); delay = DF_TEP; break; case 0x86: // Buffer2 to Memory with Built-in Erase copyBuffer2toPage(dfPageAddress); echo("copy Buffer2 to Memory Page " + dfPageAddress); delay = DF_TEP; break; case 0x88: // Buffer1 to Memory without Built-in Erase copyBuffer1toPage(dfPageAddress); echo("copy Buffer1 to Memory Page " + dfPageAddress); delay = DF_TP; break; case 0x89: // Buffer2 to Memory without Built-in Erase copyBuffer2toPage(dfPageAddress); echo("copy Buffer2 to Memory Page " + dfPageAddress); delay = DF_TP; break; case 0x81: // Page Erase delay = DF_TPE; break; case 0x50: // Block Erase delay = DF_TBE; break; case 0x82: // Memory Program through Buffer1 // read from SI into Buffer1, write to Memory when Flash_CS gets 1 copyBuffer1toPage(dfPageAddress); echo("copy Buffer1 to Memory Page " + dfPageAddress); delay = DF_TEP; break; case 0x85: // Memory Program through Buffer2 // read from SI into Buffer2, write to Memory when Flash_CS gets 1 copyBuffer2toPage(dfPageAddress); echo("copy Buffer2 to Memory Page " + dfPageAddress); delay = DF_TEP; break; // Additional Commands case 0x53: // Main Memory Page to Buffer1 Transfer copyPageToBuffer1(dfPageAddress); echo("copy Memory Page " + dfPageAddress + " to Buffer1"); delay = DF_TXFR; break; case 0x55: // Main Memory Page to Buffer2 Transfer copyPageToBuffer2(dfPageAddress); echo("copy Memory Page " + dfPageAddress + " to Buffer2"); delay = DF_TXFR; break; case 0x60: // Main Memory Page to Buffer1 Compare if (getBuffer1() == getMemoryPage(dfPageAddress)) { dfStatus &= ~DF_STATUS_COMPARE; echo("compare Memory Page " + dfPageAddress + " to Buffer1: identical"); } else { dfStatus |= DF_STATUS_COMPARE; echo("compare Memory Page " + dfPageAddress + " to Buffer1: different"); } delay = DF_TXFR; break; case 0x61: // Main Memory Page to Buffer2 Compare if (getBuffer2() == getMemoryPage(dfPageAddress)) { dfStatus &= ~DF_STATUS_COMPARE; echo("compare Memory Page " + dfPageAddress + " to Buffer2: identical"); } else { dfStatus |= DF_STATUS_COMPARE; echo("compare Memory Page " + dfPageAddress + " to Buffer2: different"); } delay = DF_TXFR; break; case 0x58: // Auto Page Rewrite case 0x59: // Auto Page Rewrite delay = DF_TEP; break; } // Dataflash is busy dfStatus &= ~DF_STATUS_READY; long dfDelay = clock.millisToCycles(delay / 1000); clock.insertEvent(new Delay(), dfDelay); // reset values dfOpcode = 0; dfByteOffset = 0; dfPageAddress = 0; step = 0; isReading = false; i = 0; } } } // USART1_TXD as output pin connected to SI protected class PD3Output implements Microcontroller.Pin.Output { public void write(boolean level) { si = level; } } // USART1_CLK as output pin connected to SCK protected class PD5Output implements Microcontroller.Pin.Output { private short temp; public void write(boolean level) { if (isSelected) { // toggling SCK if (tick != level) { if (tick) { // <<<<<<<< high-to-low <<<<<<<< if (isReading) { //echo("dfByteOffset = " + dfByteOffset); //set so bitwise setSO(); // Energy stateMachine.transition(1); // read mode i++; if (i > 7) { echo("1 Byte of serial data was output on the SO: " + temp); // internal address counter int icOffset = dfByteOffset + 1; if (icOffset > 263) { icOffset -= 264; icPage = dfPageAddress++; if (icPage > 2047) { icPage -= 2048; } } dfByteOffset = icOffset; dfPageAddress = icPage; i = 0; } } } else { // >>>>>>>> low-to-high >>>>>>>> // first starts here with step 1: get opcode if (!isReading) { // get SI bytewise dfTempByte |= (si ? 1 : 0) << (7 - i); // MSB first i++; if (i > 7) { i = 0; step++; doStep(); dfTempByte = 0; // energy if (step <= 4) { stateMachine.transition(3); // load } else { stateMachine.transition(2); // write } } } } // set clock state tick = level; } } } private void setSO() { switch (dfOpcode) { case 0x68: // Continous Array Read case 0xE8: // Continous Array Read case 0x52: // Main Memory Page Read case 0xD2: // Main Memory Page Read // Buffer 1 Read case 0x54: case 0xD4: temp = getBuffer1(dfByteOffset); break; // Buffer 2 Read case 0x56: case 0xD6: temp = getBuffer2(dfByteOffset); break; // Status Register Read case 0x57: case 0xD7: temp = dfStatus; break; default: temp = getMemoryPageAt(dfPageAddress, dfByteOffset); } // write relevant bit to so so.setValue((temp & 1 << 7 - i) > 0); // MSB first } private void doStep() { switch (step) { case 1: // get opcode dfOpcode = dfTempByte; echo("Received Opcode: " + dfOpcode); // Status Register Read? if (dfOpcode == 0x57 || dfOpcode == 0xD7) { isReading = true; } break; case 2: // get first part of adressing sequence dfPageAddress = dfTempByte << 7 & 0x0780; echo("Received Address byte 1: " + dfTempByte); break; case 3: // get second part of adressing sequence dfPageAddress |= dfTempByte >> 1; // and first part of byte offset dfByteOffset = dfTempByte & 0x0100; echo("Received Address byte 2: " + dfTempByte); break; case 4: // get second part of byte offset dfByteOffset |= dfTempByte; echo("Received Address byte 3: " + dfByteOffset); break; default: // adressing sequence complete if (step > 4) { doAction(); } } } private void doAction() { // ajust offset if (dfByteOffset > 263) { dfByteOffset -= 264; } switch (dfOpcode) { // Read Commands // Continous Array Read case 0x68: case 0xE8: // Additional Don't cares Required: 4 Bytes if (step == 4 + 4) { isReading = true; } break; // Main Memory Page Read case 0x52: case 0xD2: // Additional Don't cares Required: 4 Bytes if (step == 4 + 4) { isReading = true; } break; // Buffer 1 Read case 0x54: case 0xD4: // Additional Don't cares Required: 1 Byte if (step == 4 + 1) { isReading = true; } break; // Buffer 2 Read case 0x56: case 0xD6: if (step == 4 + 1) { isReading = true; } break; // Status Register Read case 0x57: case 0xD7: //Program and Erase Commands // Buffer 1 Write case 0x84: setBuffer1(dfByteOffset, (short) dfTempByte); echo("written Buffer 1 Byte: " + (short)dfByteOffset + ": " + dfTempByte); dfByteOffset += 1; break; // Buffer 2 Write case 0x87: setBuffer2(dfByteOffset, (short) dfTempByte); echo("written Buffer 2 Byte: " + (short)dfByteOffset + ": " + dfTempByte); dfByteOffset += 1; break; // Buffer 1 to Memory with Built-in Erase case 0x83: // write when Flash_CS gets 1 break; // Buffer 2 to Memory with Built-in Erase case 0x86: // write when Flash_CS gets 1 break; // Buffer 1 to Memory without Built-in Erase case 0x88: // write when Flash_CS gets 1 break; // Buffer 2 to Memory without Built-in Erase case 0x89: // write when Flash_CS gets 1 break; // Page Erase case 0x81: // erase when Flash_CS gets 1 break; case 0x50: // Block Erase // Block address in this case dfPageAddress >>= 3; break; // Memory Program through Buffer 1 case 0x82: // read from SI into buffer1, write to memory when Flash_CS gets 1 setBuffer1(dfByteOffset, (short) dfTempByte); echo("written Buffer 1 Byte: " + (short)dfByteOffset + ": " + dfTempByte); dfByteOffset += 1; break; // Memory Program through Buffer 2 case 0x85: // read from SI into buffer2, write to mem when Flash_CS gets 1 setBuffer2(dfByteOffset, (short) dfTempByte); echo("written Buffer 2 Byte: " + (short)dfByteOffset + ": " + dfTempByte); dfByteOffset += 1; break; } } } // Flash_RXD as input pin from SO protected class PD2Input extends Microcontroller.Pin.ListenableInput implements ValueSetListener { public PD2Input() { so.setValueSetListener(this); } // connected to serial output of dataflash public boolean read() { return so.getValue(); } @Override public void onValueSet(BooleanView view, boolean newValue) { notifyListeners(newValue); } } protected class Delay implements Simulator.Event { /** * delay while dataflash is busy * * @see Simulator.Event#fire() */ public void fire() { // operation finished dfStatus |= DF_STATUS_READY; } } private void echo(String str) { if (printer != null) { StringBuffer buf = printer.getBuffer(20); Terminal.append(Terminal.COLOR_BLUE, buf, "Dataflash"); buf.append(": "); buf.append(str); printer.printBuffer(buf); } } }
package org.jasig.portal; import org.jasig.portal.security.IPerson; import org.jasig.portal.jndi.JNDIManager; import java.sql.*; import org.w3c.dom.*; import org.apache.xalan.xpath.*; import org.apache.xalan.xslt.*; import org.apache.xml.serialize.*; import org.w3c.dom.*; import javax.servlet.*; import javax.servlet.jsp.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import java.text.*; import java.net.*; /** * UserLayoutManager participates in all operations associated with the * user layout and user preferences. * @author Peter Kharchenko * @version $Revision$ */ public class UserLayoutManager { private Document uLayoutXML; // this one will contain user Layout XML with attrubutes for the // first (structure) transformation private Document argumentedUserLayoutXML; private UserPreferences up; private UserPreferences complete_up; // caching of stylesheet descriptions is recommended // if they'll take up too much space, we can take them // out, but cache stylesheet URIs, mime type and serializer name. // Those are used in every rendering cycle. private ThemeStylesheetDescription tsd; private StructureStylesheetDescription ssd; private boolean unmapped_user_agent=false; private IPerson person; /** * Constructor does the following * 1. Read layout.properties * 2. read userLayout from the database * @param the servlet request object * @param person object */ public UserLayoutManager (HttpServletRequest req, IPerson person) { String fs = System.getProperty ("file.separator"); String propertiesDir = GenericPortalBean.getPortalBaseDir () + "properties" + fs; int guestId = 1; // belongs in a properties file uLayoutXML = null; try { this.person=person; // read uLayoutXML if (this.person == null) { // determine the default user this.person=new org.jasig.portal.security.provider.PersonImpl(); this.person.setID(guestId); } // load user preferences IUserPreferencesDB updb=new UserPreferencesDBImpl(); // determine user profile String userAgent=req.getHeader("user-Agent"); UserProfile upl=updb.getUserProfile(this.person.getID(),userAgent); if(upl!=null) { IUserLayoutDB uldb = new UserLayoutDBImpl(); uLayoutXML = uldb.getUserLayout(this.person.getID(),upl.getProfileId()); if(uLayoutXML==null) Logger.log(Logger.ERROR,"UserLayoutManager::UserLayoutManager() : unable to retreive userLayout for user=\""+this.person.getID()+"\", profile=\""+upl.getProfileName()+"\"."); this.setCurrentUserPreferences(updb.getUserPreferences(this.person.getID(),upl)); } else { // there is no user-defined mapping for this particular browser. // user should be redirected to a browser-registration page. unmapped_user_agent=true; Logger.log(Logger.DEBUG,"UserLayoutManager::UserLayoutManager() : unable to find a profile for user \""+this.person.getID()+"\" and userAgent=\""+userAgent+"\"."); }; // Initialize the JNDI context for this user JNDIManager.initializeUserContext(uLayoutXML, req.getSession().getId(), this.person); } catch (Exception e) { Logger.log(Logger.ERROR,e); } } /* This function processes request parameters related to * setting Structure/Theme stylesheet parameters and attributes. * (uP_sparam, uP_tparam, uP_sfattr, uP_scattr uP_tcattr) * It also processes layout root requests (uP_root) */ public void processUserPreferencesParameters(HttpServletRequest req) { // layout root setting String root; if((root=req.getParameter("uP_root"))!=null) { complete_up.getStructureStylesheetUserPreferences().putParameterValue("userLayoutRoot",root); } // other params String[] sparams=req.getParameterValues("uP_sparam"); if(sparams!=null) { for(int i=0;i<sparams.length;i++) { String pValue=req.getParameter(sparams[i]); complete_up.getStructureStylesheetUserPreferences().putParameterValue(sparams[i],pValue); Logger.log(Logger.DEBUG,"UserLayoutManager::processUserPreferencesParameters() : setting sparam \""+sparams[i]+"\"=\""+pValue+"\"."); } } String[] tparams=req.getParameterValues("uP_tparam"); if(tparams!=null) { for(int i=0;i<tparams.length;i++) { String pValue=req.getParameter(tparams[i]); complete_up.getThemeStylesheetUserPreferences().putParameterValue(tparams[i],pValue); Logger.log(Logger.DEBUG,"UserLayoutManager::processUserPreferencesParameters() : setting tparam \""+tparams[i]+"\"=\""+pValue+"\"."); } } // attribute processing // structure transformation String[] sfattrs=req.getParameterValues("uP_sfattr"); if(sfattrs!=null) { for(int i=0;i<sfattrs.length;i++) { String aName=sfattrs[i]; String[] aNode=req.getParameterValues(aName+"_folderId"); if(aNode!=null && aNode.length>0) { for(int j=0;j<aNode.length;j++) { String aValue=req.getParameter(aName+"_"+aNode[j]+"_value"); complete_up.getStructureStylesheetUserPreferences().setFolderAttributeValue(aNode[j],aName,aValue); Logger.log(Logger.DEBUG,"UserLayoutManager::processUserPreferencesParameters() : setting sfattr \""+aName+"\" of \""+aNode[j]+"\" to \""+aValue+"\"."); } } } } String[] scattrs=req.getParameterValues("uP_scattr"); if(scattrs!=null) { for(int i=0;i<scattrs.length;i++) { String aName=scattrs[i]; String[] aNode=req.getParameterValues(aName+"_channelId"); if(aNode!=null && aNode.length>0) { for(int j=0;j<aNode.length;j++) { String aValue=req.getParameter(aName+"_"+aNode[j]+"_value"); complete_up.getStructureStylesheetUserPreferences().setChannelAttributeValue(aNode[j],aName,aValue); Logger.log(Logger.DEBUG,"UserLayoutManager::processUserPreferencesParameters() : setting scattr \""+aName+"\" of \""+aNode[j]+"\" to \""+aValue+"\"."); } } } } // theme stylesheet attributes String[] tcattrs=req.getParameterValues("uP_tcattr"); if(tcattrs!=null) { for(int i=0;i<tcattrs.length;i++) { String aName=tcattrs[i]; String[] aNode=req.getParameterValues(aName+"_channelId"); if(aNode!=null && aNode.length>0) { for(int j=0;j<aNode.length;j++) { String aValue=req.getParameter(aName+"_"+aNode[j]+"_value"); complete_up.getThemeStylesheetUserPreferences().setChannelAttributeValue(aNode[j],aName,aValue); Logger.log(Logger.DEBUG,"UserLayoutManager::processUserPreferencesParameters() : setting tcattr \""+aName+"\" of \""+aNode[j]+"\" to \""+aValue+"\"."); } } } } } public IPerson getPerson() { return person; } public boolean userAgentUnmapped() { return unmapped_user_agent; } public void synchUserPreferencesWithLayout(UserPreferences someup) { StructureStylesheetUserPreferences fsup=someup.getStructureStylesheetUserPreferences(); ThemeStylesheetUserPreferences ssup=someup.getThemeStylesheetUserPreferences(); // make a list of channels in the XML Layout NodeList channelNodes=uLayoutXML.getElementsByTagName("channel"); HashSet channelSet=new HashSet(); for(int i=0;i<channelNodes.getLength();i++) { Element el=(Element) channelNodes.item(i); if(el!=null) { String chID=el.getAttribute("ID"); if(!fsup.hasChannel(chID)) { fsup.addChannel(chID); // Logger.log(Logger.DEBUG,"UserLayoutManager::synchUserPreferencesWithLayout() : StructureStylesheetUserPreferences were missing a channel="+chID); } if(!ssup.hasChannel(chID)) { ssup.addChannel(chID); // Logger.log(Logger.DEBUG,"UserLayoutManager::synchUserPreferencesWithLayout() : ThemeStylesheetUserPreferences were missing a channel="+chID); } channelSet.add(chID); } } // make a list of categories in the XML Layout NodeList folderNodes=uLayoutXML.getElementsByTagName("folder"); HashSet folderSet=new HashSet(); for(int i=0;i<folderNodes.getLength();i++) { Element el=(Element) folderNodes.item(i); if(el!=null) { String caID=el.getAttribute("ID"); if(!fsup.hasFolder(caID)) { fsup.addFolder(caID); // Logger.log(Logger.DEBUG,"UserLayoutManager::synchUserPreferencesWithLayout() : StructureStylesheetUserPreferences were missing a folder="+caID); } folderSet.add(caID); } } // cross check for(Enumeration e=fsup.getChannels();e.hasMoreElements();) { String chID=(String)e.nextElement(); if(!channelSet.contains(chID)) { fsup.removeChannel(chID); // Logger.log(Logger.DEBUG,"UserLayoutManager::synchUserPreferencesWithLayout() : StructureStylesheetUserPreferences had a non-existent channel="+chID); } } for(Enumeration e=fsup.getFolders();e.hasMoreElements();) { String caID=(String)e.nextElement(); if(!folderSet.contains(caID)) { fsup.removeFolder(caID); // Logger.log(Logger.DEBUG,"UserLayoutManager::synchUserPreferencesWithLayout() : StructureStylesheetUserPreferences had a non-existent folder="+caID); } } for(Enumeration e=ssup.getChannels();e.hasMoreElements();) { String chID=(String)e.nextElement(); if(!channelSet.contains(chID)) { ssup.removeChannel(chID); // Logger.log(Logger.DEBUG,"UserLayoutManager::synchUserPreferencesWithLayout() : ThemeStylesheetUserPreferences had a non-existent channel="+chID); } } someup.setStructureStylesheetUserPreferences(fsup); someup.setThemeStylesheetUserPreferences(ssup); } public UserPreferences getCompleteCurrentUserPreferences() { return complete_up; } public void setCurrentUserPreferences(UserPreferences current_up) { if(current_up!=null) up=current_up; // load stylesheet description files and fix user preferences ICoreStylesheetDescriptionDB csddb=new CoreStylesheetDescriptionDBImpl(); // clean up StructureStylesheetUserPreferences fsup=up.getStructureStylesheetUserPreferences(); StructureStylesheetDescription fssd=csddb.getStructureStylesheetDescription(fsup.getStylesheetName()); if(fssd==null) { // assign a default stylesheet instead } else { fsup.synchronizeWithDescription(fssd); } ThemeStylesheetUserPreferences ssup=up.getThemeStylesheetUserPreferences(); ThemeStylesheetDescription sssd=csddb.getThemeStylesheetDescription(ssup.getStylesheetName()); if(sssd==null) { // assign a default stylesheet instead } else { ssup.synchronizeWithDescription(sssd); } // in case something was reset to default up.setStructureStylesheetUserPreferences(fsup); up.setThemeStylesheetUserPreferences(ssup); // now generate "filled-out copies" complete_up=new UserPreferences(up); // syncronize up with layout synchUserPreferencesWithLayout(complete_up); StructureStylesheetUserPreferences complete_fsup=complete_up.getStructureStylesheetUserPreferences(); ThemeStylesheetUserPreferences complete_ssup=complete_up.getThemeStylesheetUserPreferences(); complete_fsup.completeWithDescriptionInformation(fssd); complete_ssup.completeWithDescriptionInformation(sssd); complete_up.setStructureStylesheetUserPreferences(complete_fsup); complete_up.setThemeStylesheetUserPreferences(complete_ssup); // complete user preferences are used to: // 1. fill out userLayoutXML with attributes required for the first transform // 2. contruct a filter that will fill out attributes required for the second transform // argumentedUserLayoutXML=(Document) uLayoutXML.cloneNode(true); argumentedUserLayoutXML= UtilitiesBean.cloneDocument((org.apache.xerces.dom.DocumentImpl) uLayoutXML); // deal with folder attributes first NodeList folderElements=argumentedUserLayoutXML.getElementsByTagName("folder"); if(folderElements==null) Logger.log(Logger.DEBUG,"UserLayoutManager::setCurrentUserPreferences() : empty list of folder elements obtained!"); for(Enumeration fe=complete_fsup.getFolderAttributeNames(); fe.hasMoreElements();) { String attributeName=(String) fe.nextElement(); for(int i=folderElements.getLength()-1;i>=0;i Element folderElement=(Element) folderElements.item(i); folderElement.setAttribute(attributeName,complete_fsup.getFolderAttributeValue(folderElement.getAttribute("ID"),attributeName)); // Logger.log(Logger.DEBUG,"UserLayoutManager::setCurrentUserPreferences() : added attribute "+(String) cl.get(j)+"="+complete_fsup.getFolderAttributeValue(folderElement.getAttribute("ID"),(String) cl.get(j))+" for a folder "+folderElement.getAttribute("ID")); } } // channel attributes NodeList channelElements=argumentedUserLayoutXML.getElementsByTagName("channel"); if(channelElements==null) Logger.log(Logger.DEBUG,"UserLayoutManager::setCurrentUserPreferences() : empty list of channel elements obtained!"); for(Enumeration ce=complete_fsup.getChannelAttributeNames(); ce.hasMoreElements();) { String attributeName=(String) ce.nextElement(); for(int i=channelElements.getLength()-1;i>=0;i Element channelElement=(Element) channelElements.item(i); channelElement.setAttribute(attributeName,complete_fsup.getChannelAttributeValue(channelElement.getAttribute("ID"),attributeName)); // Logger.log(Logger.DEBUG,"UserLayoutManager::setCurrentUserPreferences() : added attribute "+(String) chl.get(j)+"="+complete_fsup.getChannelAttributeValue(channelElement.getAttribute("ID"),(String) chl.get(j))+" for a channel "+channelElement.getAttribute("ID")); } } } /* * Resets both user layout and user preferences. * Note that if any of the two are "null", old values will be used. */ public void setNewUserLayoutAndUserPreferences(Document newLayout,UserPreferences newPreferences) { if(newLayout!=null) { uLayoutXML=newLayout; IUserLayoutDB uldb=new UserLayoutDBImpl(); uldb.setUserLayout(person.getID(),up.getProfile().getProfileId(),uLayoutXML); } if(newPreferences!=null) { this.setCurrentUserPreferences(newPreferences); IUserPreferencesDB updb=new UserPreferencesDBImpl(); updb.putUserPreferences(person.getID(),up); } } public Document getUserLayoutCopy() { return UtilitiesBean.cloneDocument((org.apache.xerces.dom.DocumentImpl) uLayoutXML); } public UserPreferences getUserPreferencesCopy() { return new UserPreferences(this.getUserPreferences()); } private UserPreferences getUserPreferences() { return up; } public UserProfile getCurrentProfile() { return this.getUserPreferences().getProfile(); } private ThemeStylesheetDescription getThemeStylesheetDescription() { if (this.tsd==null) { ICoreStylesheetDescriptionDB csddb=new CoreStylesheetDescriptionDBImpl(); tsd=csddb.getThemeStylesheetDescription(this.getCurrentProfile().getThemeStylesheetName()); } return tsd; } private StructureStylesheetDescription getStructureStylesheetDescription() { if (this.ssd==null) { ICoreStylesheetDescriptionDB csddb=new CoreStylesheetDescriptionDBImpl(); ssd=csddb.getStructureStylesheetDescription(this.getCurrentProfile().getStructureStylesheetName()); } return ssd; } /* * Returns structure stylesheet defined by the user profile */ public XSLTInputSource getStructureStylesheet() { return new XSLTInputSource(UtilitiesBean.fixURI(this.getStructureStylesheetDescription().getStylesheetURI())); } /* * Returns theme stylesheet defined by the user profile */ public XSLTInputSource getThemeStylesheet() { return new XSLTInputSource(UtilitiesBean.fixURI(this.getThemeStylesheetDescription().getStylesheetURI())); } /* * returns the mime type defined by the theme stylesheet * in the user profile */ public String getMimeType() { return this.getThemeStylesheetDescription().getMimeType(); } /* * returns a serializer defined by the theme stylesheet * in the user profile */ public String getSerializerName() { return this.getThemeStylesheetDescription().getSerializerName(); } public Node getNode (String elementID) { return argumentedUserLayoutXML.getElementById (elementID); } public Node getCleanNode (String elementID) { return uLayoutXML.getElementById (elementID); } public Node getRoot () { return argumentedUserLayoutXML; } // helper function that allows to determine the name of a channel or // folder in the current user layout given their ID. public String getNodeName(String nodeID) { Element node=argumentedUserLayoutXML.getElementById(nodeID); if(node!=null) { return node.getAttribute("name"); } else return null; } public void removeChannel (String str_ID) { // warning .. the channel should also be removed from uLayoutXML Element channel = argumentedUserLayoutXML.getElementById (str_ID); if (channel != null) { Node parent = channel.getParentNode (); if (parent != null) parent.removeChild (channel); else Logger.log (Logger.ERROR, "UserLayoutManager::removeChannel() : attempt to remove a root node !"); } else Logger.log (Logger.ERROR, "UserLayoutManager::removeChannel() : unable to find a channel with ID="+str_ID); } private Element getChildByTagName(Node node,String tagName) { if(node==null) return null; NodeList children=node.getChildNodes(); for(int i=children.getLength()-1;i>=0;i Node child=children.item(i); if(child.getNodeType()==Node.ELEMENT_NODE) { Element el=(Element) child; if((el.getTagName()).equals(tagName)) return el; } } return null; } }
package org.jfree.chart.plot; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Composite; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Polygon; import java.awt.Rectangle; import java.awt.Shape; import java.awt.Stroke; import java.awt.font.FontRenderContext; import java.awt.font.LineMetrics; import java.awt.geom.Arc2D; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Iterator; import java.util.List; import org.jfree.chart.LegendItem; import org.jfree.chart.LegendItemCollection; import org.jfree.chart.entity.CategoryItemEntity; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.PlotChangeEvent; import org.jfree.chart.labels.CategoryItemLabelGenerator; import org.jfree.chart.labels.CategoryToolTipGenerator; import org.jfree.chart.labels.StandardCategoryItemLabelGenerator; import org.jfree.chart.urls.CategoryURLGenerator; import org.jfree.data.category.CategoryDataset; import org.jfree.data.general.DatasetChangeEvent; import org.jfree.data.general.DatasetUtilities; import org.jfree.io.SerialUtilities; import org.jfree.ui.RectangleInsets; import org.jfree.util.ObjectUtilities; import org.jfree.util.PaintList; import org.jfree.util.PaintUtilities; import org.jfree.util.Rotation; import org.jfree.util.ShapeUtilities; import org.jfree.util.StrokeList; import org.jfree.util.TableOrder; /** * A plot that displays data from a {@link CategoryDataset} in the form of a * "spider web". Multiple series can be plotted on the same axis to allow * easy comparison. This plot doesn't support negative values at present. */ public class SpiderWebPlot extends Plot implements Cloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -5376340422031599463L; /** The default head radius percent (currently 1%). */ public static final double DEFAULT_HEAD = 0.01; /** The default axis label gap (currently 10%). */ public static final double DEFAULT_AXIS_LABEL_GAP = 0.10; /** The default interior gap. */ public static final double DEFAULT_INTERIOR_GAP = 0.25; /** The maximum interior gap (currently 40%). */ public static final double MAX_INTERIOR_GAP = 0.40; /** The default starting angle for the radar chart axes. */ public static final double DEFAULT_START_ANGLE = 90.0; /** The default series label font. */ public static final Font DEFAULT_LABEL_FONT = new Font("SansSerif", Font.PLAIN, 10); /** The default series label paint. */ public static final Paint DEFAULT_LABEL_PAINT = Color.black; /** The default series label background paint. */ public static final Paint DEFAULT_LABEL_BACKGROUND_PAINT = new Color(255, 255, 192); /** The default series label outline paint. */ public static final Paint DEFAULT_LABEL_OUTLINE_PAINT = Color.black; /** The default series label outline stroke. */ public static final Stroke DEFAULT_LABEL_OUTLINE_STROKE = new BasicStroke(0.5f); /** The default series label shadow paint. */ public static final Paint DEFAULT_LABEL_SHADOW_PAINT = Color.lightGray; /** * The default maximum value plotted - forces the plot to evaluate * the maximum from the data passed in */ public static final double DEFAULT_MAX_VALUE = -1.0; /** The head radius as a percentage of the available drawing area. */ protected double headPercent; /** The space left around the outside of the plot as a percentage. */ private double interiorGap; /** The gap between the labels and the axes as a %age of the radius. */ private double axisLabelGap; /** * The paint used to draw the axis lines. * * @since 1.0.4 */ private transient Paint axisLinePaint; /** * The stroke used to draw the axis lines. * * @since 1.0.4 */ private transient Stroke axisLineStroke; /** The dataset. */ private CategoryDataset dataset; /** The maximum value we are plotting against on each category axis */ private double maxValue; /** * The data extract order (BY_ROW or BY_COLUMN). This denotes whether * the data series are stored in rows (in which case the category names are * derived from the column keys) or in columns (in which case the category * names are derived from the row keys). */ private TableOrder dataExtractOrder; /** The starting angle. */ private double startAngle; /** The direction for drawing the radar axis & plots. */ private Rotation direction; /** The legend item shape. */ private transient Shape legendItemShape; /** The paint for ALL series (overrides list). */ private transient Paint seriesPaint; /** The series paint list. */ private PaintList seriesPaintList; /** The base series paint (fallback). */ private transient Paint baseSeriesPaint; /** The outline paint for ALL series (overrides list). */ private transient Paint seriesOutlinePaint; /** The series outline paint list. */ private PaintList seriesOutlinePaintList; /** The base series outline paint (fallback). */ private transient Paint baseSeriesOutlinePaint; /** The outline stroke for ALL series (overrides list). */ private transient Stroke seriesOutlineStroke; /** The series outline stroke list. */ private StrokeList seriesOutlineStrokeList; /** The base series outline stroke (fallback). */ private transient Stroke baseSeriesOutlineStroke; /** The font used to display the category labels. */ private Font labelFont; /** The color used to draw the category labels. */ private transient Paint labelPaint; /** The label generator. */ private CategoryItemLabelGenerator labelGenerator; /** controls if the web polygons are filled or not */ private boolean webFilled = true; /** A tooltip generator for the plot (<code>null</code> permitted). */ private CategoryToolTipGenerator toolTipGenerator; /** A URL generator for the plot (<code>null</code> permitted). */ private CategoryURLGenerator urlGenerator; /** * Creates a default plot with no dataset. */ public SpiderWebPlot() { this(null); } /** * Creates a new spider web plot with the given dataset, with each row * representing a series. * * @param dataset the dataset (<code>null</code> permitted). */ public SpiderWebPlot(CategoryDataset dataset) { this(dataset, TableOrder.BY_ROW); } /** * Creates a new spider web plot with the given dataset. * * @param dataset the dataset. * @param extract controls how data is extracted ({@link TableOrder#BY_ROW} * or {@link TableOrder#BY_COLUMN}). */ public SpiderWebPlot(CategoryDataset dataset, TableOrder extract) { super(); if (extract == null) { throw new IllegalArgumentException("Null 'extract' argument."); } this.dataset = dataset; if (dataset != null) { dataset.addChangeListener(this); } this.dataExtractOrder = extract; this.headPercent = DEFAULT_HEAD; this.axisLabelGap = DEFAULT_AXIS_LABEL_GAP; this.axisLinePaint = Color.black; this.axisLineStroke = new BasicStroke(1.0f); this.interiorGap = DEFAULT_INTERIOR_GAP; this.startAngle = DEFAULT_START_ANGLE; this.direction = Rotation.CLOCKWISE; this.maxValue = DEFAULT_MAX_VALUE; this.seriesPaint = null; this.seriesPaintList = new PaintList(); this.baseSeriesPaint = null; this.seriesOutlinePaint = null; this.seriesOutlinePaintList = new PaintList(); this.baseSeriesOutlinePaint = DEFAULT_OUTLINE_PAINT; this.seriesOutlineStroke = null; this.seriesOutlineStrokeList = new StrokeList(); this.baseSeriesOutlineStroke = DEFAULT_OUTLINE_STROKE; this.labelFont = DEFAULT_LABEL_FONT; this.labelPaint = DEFAULT_LABEL_PAINT; this.labelGenerator = new StandardCategoryItemLabelGenerator(); this.legendItemShape = DEFAULT_LEGEND_ITEM_CIRCLE; } /** * Returns a short string describing the type of plot. * * @return The plot type. */ public String getPlotType() { // return localizationResources.getString("Radar_Plot"); return ("Spider Web Plot"); } /** * Returns the dataset. * * @return The dataset (possibly <code>null</code>). * * @see #setDataset(CategoryDataset) */ public CategoryDataset getDataset() { return this.dataset; } /** * Sets the dataset used by the plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param dataset the dataset (<code>null</code> permitted). * * @see #getDataset() */ public void setDataset(CategoryDataset dataset) { // if there is an existing dataset, remove the plot from the list of // change listeners... if (this.dataset != null) { this.dataset.removeChangeListener(this); } // set the new dataset, and register the chart as a change listener... this.dataset = dataset; if (dataset != null) { setDatasetGroup(dataset.getGroup()); dataset.addChangeListener(this); } // send a dataset change event to self to trigger plot change event datasetChanged(new DatasetChangeEvent(this, dataset)); } /** * Method to determine if the web chart is to be filled. * * @return A boolean. * * @see #setWebFilled(boolean) */ public boolean isWebFilled() { return this.webFilled; } /** * Sets the webFilled flag and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param flag the flag. * * @see #isWebFilled() */ public void setWebFilled(boolean flag) { this.webFilled = flag; notifyListeners(new PlotChangeEvent(this)); } /** * Returns the data extract order (by row or by column). * * @return The data extract order (never <code>null</code>). * * @see #setDataExtractOrder(TableOrder) */ public TableOrder getDataExtractOrder() { return this.dataExtractOrder; } public void setDataExtractOrder(TableOrder order) { if (order == null) { throw new IllegalArgumentException("Null 'order' argument"); } this.dataExtractOrder = order; notifyListeners(new PlotChangeEvent(this)); } /** * Returns the head percent. * * @return The head percent. * * @see #setHeadPercent(double) */ public double getHeadPercent() { return this.headPercent; } /** * Sets the head percent and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param percent the percent. * * @see #getHeadPercent() */ public void setHeadPercent(double percent) { this.headPercent = percent; notifyListeners(new PlotChangeEvent(this)); } /** * Returns the start angle for the first radar axis. * <BR> * This is measured in degrees starting from 3 o'clock (Java Arc2D default) * and measuring anti-clockwise. * * @return The start angle. * * @see #setStartAngle(double) */ public double getStartAngle() { return this.startAngle; } /** * Sets the starting angle and sends a {@link PlotChangeEvent} to all * registered listeners. * <P> * The initial default value is 90 degrees, which corresponds to 12 o'clock. * A value of zero corresponds to 3 o'clock... this is the encoding used by * Java's Arc2D class. * * @param angle the angle (in degrees). * * @see #getStartAngle() */ public void setStartAngle(double angle) { this.startAngle = angle; notifyListeners(new PlotChangeEvent(this)); } /** * Returns the maximum value any category axis can take. * * @return The maximum value. * * @see #setMaxValue(double) */ public double getMaxValue() { return this.maxValue; } /** * Sets the maximum value any category axis can take and sends * a {@link PlotChangeEvent} to all registered listeners. * * @param value the maximum value. * * @see #getMaxValue() */ public void setMaxValue(double value) { this.maxValue = value; notifyListeners(new PlotChangeEvent(this)); } /** * Returns the direction in which the radar axes are drawn * (clockwise or anti-clockwise). * * @return The direction (never <code>null</code>). * * @see #setDirection(Rotation) */ public Rotation getDirection() { return this.direction; } /** * Sets the direction in which the radar axes are drawn and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param direction the direction (<code>null</code> not permitted). * * @see #getDirection() */ public void setDirection(Rotation direction) { if (direction == null) { throw new IllegalArgumentException("Null 'direction' argument."); } this.direction = direction; notifyListeners(new PlotChangeEvent(this)); } /** * Returns the interior gap, measured as a percentage of the available * drawing space. * * @return The gap (as a percentage of the available drawing space). * * @see #setInteriorGap(double) */ public double getInteriorGap() { return this.interiorGap; } /** * Sets the interior gap and sends a {@link PlotChangeEvent} to all * registered listeners. This controls the space between the edges of the * plot and the plot area itself (the region where the axis labels appear). * * @param percent the gap (as a percentage of the available drawing space). * * @see #getInteriorGap() */ public void setInteriorGap(double percent) { if ((percent < 0.0) || (percent > MAX_INTERIOR_GAP)) { throw new IllegalArgumentException( "Percentage outside valid range."); } if (this.interiorGap != percent) { this.interiorGap = percent; notifyListeners(new PlotChangeEvent(this)); } } /** * Returns the axis label gap. * * @return The axis label gap. * * @see #setAxisLabelGap(double) */ public double getAxisLabelGap() { return this.axisLabelGap; } /** * Sets the axis label gap and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param gap the gap. * * @see #getAxisLabelGap() */ public void setAxisLabelGap(double gap) { this.axisLabelGap = gap; notifyListeners(new PlotChangeEvent(this)); } /** * Returns the paint used to draw the axis lines. * * @return The paint used to draw the axis lines (never <code>null</code>). * * @see #setAxisLinePaint(Paint) * @see #getAxisLineStroke() * @since 1.0.4 */ public Paint getAxisLinePaint() { return this.axisLinePaint; } /** * Sets the paint used to draw the axis lines and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getAxisLinePaint() * @since 1.0.4 */ public void setAxisLinePaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.axisLinePaint = paint; notifyListeners(new PlotChangeEvent(this)); } /** * Returns the stroke used to draw the axis lines. * * @return The stroke used to draw the axis lines (never <code>null</code>). * * @see #setAxisLineStroke(Stroke) * @see #getAxisLinePaint() * @since 1.0.4 */ public Stroke getAxisLineStroke() { return this.axisLineStroke; } /** * Sets the stroke used to draw the axis lines and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param stroke the stroke (<code>null</code> not permitted). * * @see #getAxisLineStroke() * @since 1.0.4 */ public void setAxisLineStroke(Stroke stroke) { if (stroke == null) { throw new IllegalArgumentException("Null 'stroke' argument."); } this.axisLineStroke = stroke; notifyListeners(new PlotChangeEvent(this)); } //// SERIES PAINT ///////////////////////// /** * Returns the paint for ALL series in the plot. * * @return The paint (possibly <code>null</code>). * * @see #setSeriesPaint(Paint) */ public Paint getSeriesPaint() { return this.seriesPaint; } /** * Sets the paint for ALL series in the plot. If this is set to</code> null * </code>, then a list of paints is used instead (to allow different colors * to be used for each series of the radar group). * * @param paint the paint (<code>null</code> permitted). * * @see #getSeriesPaint() */ public void setSeriesPaint(Paint paint) { this.seriesPaint = paint; notifyListeners(new PlotChangeEvent(this)); } /** * Returns the paint for the specified series. * * @param series the series index (zero-based). * * @return The paint (never <code>null</code>). * * @see #setSeriesPaint(int, Paint) */ public Paint getSeriesPaint(int series) { // return the override, if there is one... if (this.seriesPaint != null) { return this.seriesPaint; } // otherwise look up the paint list Paint result = this.seriesPaintList.getPaint(series); if (result == null) { DrawingSupplier supplier = getDrawingSupplier(); if (supplier != null) { Paint p = supplier.getNextPaint(); this.seriesPaintList.setPaint(series, p); result = p; } else { result = this.baseSeriesPaint; } } return result; } /** * Sets the paint used to fill a series of the radar and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param paint the paint (<code>null</code> permitted). * * @see #getSeriesPaint(int) */ public void setSeriesPaint(int series, Paint paint) { this.seriesPaintList.setPaint(series, paint); notifyListeners(new PlotChangeEvent(this)); } /** * Returns the base series paint. This is used when no other paint is * available. * * @return The paint (never <code>null</code>). * * @see #setBaseSeriesPaint(Paint) */ public Paint getBaseSeriesPaint() { return this.baseSeriesPaint; } /** * Sets the base series paint. * * @param paint the paint (<code>null</code> not permitted). * * @see #getBaseSeriesPaint() */ public void setBaseSeriesPaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.baseSeriesPaint = paint; notifyListeners(new PlotChangeEvent(this)); } //// SERIES OUTLINE PAINT //////////////////////////// /** * Returns the outline paint for ALL series in the plot. * * @return The paint (possibly <code>null</code>). */ public Paint getSeriesOutlinePaint() { return this.seriesOutlinePaint; } /** * Sets the outline paint for ALL series in the plot. If this is set to * </code> null</code>, then a list of paints is used instead (to allow * different colors to be used for each series). * * @param paint the paint (<code>null</code> permitted). */ public void setSeriesOutlinePaint(Paint paint) { this.seriesOutlinePaint = paint; notifyListeners(new PlotChangeEvent(this)); } /** * Returns the paint for the specified series. * * @param series the series index (zero-based). * * @return The paint (never <code>null</code>). */ public Paint getSeriesOutlinePaint(int series) { // return the override, if there is one... if (this.seriesOutlinePaint != null) { return this.seriesOutlinePaint; } // otherwise look up the paint list Paint result = this.seriesOutlinePaintList.getPaint(series); if (result == null) { result = this.baseSeriesOutlinePaint; } return result; } /** * Sets the paint used to fill a series of the radar and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param paint the paint (<code>null</code> permitted). */ public void setSeriesOutlinePaint(int series, Paint paint) { this.seriesOutlinePaintList.setPaint(series, paint); notifyListeners(new PlotChangeEvent(this)); } /** * Returns the base series paint. This is used when no other paint is * available. * * @return The paint (never <code>null</code>). */ public Paint getBaseSeriesOutlinePaint() { return this.baseSeriesOutlinePaint; } /** * Sets the base series paint. * * @param paint the paint (<code>null</code> not permitted). */ public void setBaseSeriesOutlinePaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.baseSeriesOutlinePaint = paint; notifyListeners(new PlotChangeEvent(this)); } //// SERIES OUTLINE STROKE ///////////////////// /** * Returns the outline stroke for ALL series in the plot. * * @return The stroke (possibly <code>null</code>). */ public Stroke getSeriesOutlineStroke() { return this.seriesOutlineStroke; } /** * Sets the outline stroke for ALL series in the plot. If this is set to * </code> null</code>, then a list of paints is used instead (to allow * different colors to be used for each series). * * @param stroke the stroke (<code>null</code> permitted). */ public void setSeriesOutlineStroke(Stroke stroke) { this.seriesOutlineStroke = stroke; notifyListeners(new PlotChangeEvent(this)); } /** * Returns the stroke for the specified series. * * @param series the series index (zero-based). * * @return The stroke (never <code>null</code>). */ public Stroke getSeriesOutlineStroke(int series) { // return the override, if there is one... if (this.seriesOutlineStroke != null) { return this.seriesOutlineStroke; } // otherwise look up the paint list Stroke result = this.seriesOutlineStrokeList.getStroke(series); if (result == null) { result = this.baseSeriesOutlineStroke; } return result; } /** * Sets the stroke used to fill a series of the radar and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param stroke the stroke (<code>null</code> permitted). */ public void setSeriesOutlineStroke(int series, Stroke stroke) { this.seriesOutlineStrokeList.setStroke(series, stroke); notifyListeners(new PlotChangeEvent(this)); } /** * Returns the base series stroke. This is used when no other stroke is * available. * * @return The stroke (never <code>null</code>). */ public Stroke getBaseSeriesOutlineStroke() { return this.baseSeriesOutlineStroke; } /** * Sets the base series stroke. * * @param stroke the stroke (<code>null</code> not permitted). */ public void setBaseSeriesOutlineStroke(Stroke stroke) { if (stroke == null) { throw new IllegalArgumentException("Null 'stroke' argument."); } this.baseSeriesOutlineStroke = stroke; notifyListeners(new PlotChangeEvent(this)); } /** * Returns the shape used for legend items. * * @return The shape (never <code>null</code>). * * @see #setLegendItemShape(Shape) */ public Shape getLegendItemShape() { return this.legendItemShape; } /** * Sets the shape used for legend items and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param shape the shape (<code>null</code> not permitted). * * @see #getLegendItemShape() */ public void setLegendItemShape(Shape shape) { if (shape == null) { throw new IllegalArgumentException("Null 'shape' argument."); } this.legendItemShape = shape; notifyListeners(new PlotChangeEvent(this)); } /** * Returns the series label font. * * @return The font (never <code>null</code>). * * @see #setLabelFont(Font) */ public Font getLabelFont() { return this.labelFont; } /** * Sets the series label font and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param font the font (<code>null</code> not permitted). * * @see #getLabelFont() */ public void setLabelFont(Font font) { if (font == null) { throw new IllegalArgumentException("Null 'font' argument."); } this.labelFont = font; notifyListeners(new PlotChangeEvent(this)); } /** * Returns the series label paint. * * @return The paint (never <code>null</code>). * * @see #setLabelPaint(Paint) */ public Paint getLabelPaint() { return this.labelPaint; } /** * Sets the series label paint and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getLabelPaint() */ public void setLabelPaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.labelPaint = paint; notifyListeners(new PlotChangeEvent(this)); } /** * Returns the label generator. * * @return The label generator (never <code>null</code>). * * @see #setLabelGenerator(CategoryItemLabelGenerator) */ public CategoryItemLabelGenerator getLabelGenerator() { return this.labelGenerator; } /** * Sets the label generator and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param generator the generator (<code>null</code> not permitted). * * @see #getLabelGenerator() */ public void setLabelGenerator(CategoryItemLabelGenerator generator) { if (generator == null) { throw new IllegalArgumentException("Null 'generator' argument."); } this.labelGenerator = generator; } /** * Returns the tool tip generator for the plot. * * @return The tool tip generator (possibly <code>null</code>). * * @see #setToolTipGenerator(CategoryToolTipGenerator) * * @since 1.0.2 */ public CategoryToolTipGenerator getToolTipGenerator() { return this.toolTipGenerator; } /** * Sets the tool tip generator for the plot and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param generator the generator (<code>null</code> permitted). * * @see #getToolTipGenerator() * * @since 1.0.2 */ public void setToolTipGenerator(CategoryToolTipGenerator generator) { this.toolTipGenerator = generator; this.notifyListeners(new PlotChangeEvent(this)); } /** * Returns the URL generator for the plot. * * @return The URL generator (possibly <code>null</code>). * * @see #setURLGenerator(CategoryURLGenerator) * * @since 1.0.2 */ public CategoryURLGenerator getURLGenerator() { return this.urlGenerator; } /** * Sets the URL generator for the plot and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param generator the generator (<code>null</code> permitted). * * @see #getURLGenerator() * * @since 1.0.2 */ public void setURLGenerator(CategoryURLGenerator generator) { this.urlGenerator = generator; this.notifyListeners(new PlotChangeEvent(this)); } /** * Returns a collection of legend items for the radar chart. * * @return The legend items. */ public LegendItemCollection getLegendItems() { LegendItemCollection result = new LegendItemCollection(); List keys = null; if (this.dataExtractOrder == TableOrder.BY_ROW) { keys = this.dataset.getRowKeys(); } else if (this.dataExtractOrder == TableOrder.BY_COLUMN) { keys = this.dataset.getColumnKeys(); } if (keys != null) { int series = 0; Iterator iterator = keys.iterator(); Shape shape = getLegendItemShape(); while (iterator.hasNext()) { String label = iterator.next().toString(); String description = label; Paint paint = getSeriesPaint(series); Paint outlinePaint = getSeriesOutlinePaint(series); Stroke stroke = getSeriesOutlineStroke(series); LegendItem item = new LegendItem(label, description, null, null, shape, paint, stroke, outlinePaint); item.setDataset(getDataset()); result.add(item); series++; } } return result; } /** * Returns a cartesian point from a polar angle, length and bounding box * * @param bounds the area inside which the point needs to be. * @param angle the polar angle, in degrees. * @param length the relative length. Given in percent of maximum extend. * * @return The cartesian point. */ protected Point2D getWebPoint(Rectangle2D bounds, double angle, double length) { double angrad = Math.toRadians(angle); double x = Math.cos(angrad) * length * bounds.getWidth() / 2; double y = -Math.sin(angrad) * length * bounds.getHeight() / 2; return new Point2D.Double(bounds.getX() + x + bounds.getWidth() / 2, bounds.getY() + y + bounds.getHeight() / 2); } /** * Draws the plot on a Java 2D graphics device (such as the screen or a * printer). * * @param g2 the graphics device. * @param area the area within which the plot should be drawn. * @param anchor the anchor point (<code>null</code> permitted). * @param parentState the state from the parent plot, if there is one. * @param info collects info about the drawing. */ public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState, PlotRenderingInfo info) { // adjust for insets... RectangleInsets insets = getInsets(); insets.trim(area); if (info != null) { info.setPlotArea(area); info.setDataArea(area); } drawBackground(g2, area); drawOutline(g2, area); Shape savedClip = g2.getClip(); g2.clip(area); Composite originalComposite = g2.getComposite(); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getForegroundAlpha())); if (!DatasetUtilities.isEmptyOrNull(this.dataset)) { int seriesCount = 0, catCount = 0; if (this.dataExtractOrder == TableOrder.BY_ROW) { seriesCount = this.dataset.getRowCount(); catCount = this.dataset.getColumnCount(); } else { seriesCount = this.dataset.getColumnCount(); catCount = this.dataset.getRowCount(); } // ensure we have a maximum value to use on the axes if (this.maxValue == DEFAULT_MAX_VALUE) calculateMaxValue(seriesCount, catCount); // Next, setup the plot area // adjust the plot area by the interior spacing value double gapHorizontal = area.getWidth() * getInteriorGap(); double gapVertical = area.getHeight() * getInteriorGap(); double X = area.getX() + gapHorizontal / 2; double Y = area.getY() + gapVertical / 2; double W = area.getWidth() - gapHorizontal; double H = area.getHeight() - gapVertical; double headW = area.getWidth() * this.headPercent; double headH = area.getHeight() * this.headPercent; // make the chart area a square double min = Math.min(W, H) / 2; X = (X + X + W) / 2 - min; Y = (Y + Y + H) / 2 - min; W = 2 * min; H = 2 * min; Point2D centre = new Point2D.Double(X + W / 2, Y + H / 2); Rectangle2D radarArea = new Rectangle2D.Double(X, Y, W, H); // draw the axis and category label for (int cat = 0; cat < catCount; cat++) { double angle = getStartAngle() + (getDirection().getFactor() * cat * 360 / catCount); Point2D endPoint = getWebPoint(radarArea, angle, 1); // 1 = end of axis Line2D line = new Line2D.Double(centre, endPoint); g2.setPaint(this.axisLinePaint); g2.setStroke(this.axisLineStroke); g2.draw(line); drawLabel(g2, radarArea, 0.0, cat, angle, 360.0 / catCount); } // Now actually plot each of the series polygons.. for (int series = 0; series < seriesCount; series++) { drawRadarPoly(g2, radarArea, centre, info, series, catCount, headH, headW); } } else { drawNoDataMessage(g2, area); } g2.setClip(savedClip); g2.setComposite(originalComposite); drawOutline(g2, area); } /** * loop through each of the series to get the maximum value * on each category axis * * @param seriesCount the number of series * @param catCount the number of categories */ private void calculateMaxValue(int seriesCount, int catCount) { double v = 0; Number nV = null; for (int seriesIndex = 0; seriesIndex < seriesCount; seriesIndex++) { for (int catIndex = 0; catIndex < catCount; catIndex++) { nV = getPlotValue(seriesIndex, catIndex); if (nV != null) { v = nV.doubleValue(); if (v > this.maxValue) { this.maxValue = v; } } } } } /** * Draws a radar plot polygon. * * @param g2 the graphics device. * @param plotArea the area we are plotting in (already adjusted). * @param centre the centre point of the radar axes * @param info chart rendering info. * @param series the series within the dataset we are plotting * @param catCount the number of categories per radar plot * @param headH the data point height * @param headW the data point width */ protected void drawRadarPoly(Graphics2D g2, Rectangle2D plotArea, Point2D centre, PlotRenderingInfo info, int series, int catCount, double headH, double headW) { Polygon polygon = new Polygon(); EntityCollection entities = null; if (info != null) { entities = info.getOwner().getEntityCollection(); } // plot the data... for (int cat = 0; cat < catCount; cat++) { Number dataValue = getPlotValue(series, cat); if (dataValue != null) { double value = dataValue.doubleValue(); if (value >= 0) { // draw the polygon series... // Finds our starting angle from the centre for this axis double angle = getStartAngle() + (getDirection().getFactor() * cat * 360 / catCount); // The following angle calc will ensure there isn't a top // vertical axis - this may be useful if you don't want any // given criteria to 'appear' move important than the // others.. // + (getDirection().getFactor() // * (cat + 0.5) * 360 / catCount); // find the point at the appropriate distance end point // along the axis/angle identified above and add it to the // polygon Point2D point = getWebPoint(plotArea, angle, value / this.maxValue); polygon.addPoint((int) point.getX(), (int) point.getY()); // put an elipse at the point being plotted.. Paint paint = getSeriesPaint(series); Paint outlinePaint = getSeriesOutlinePaint(series); Stroke outlineStroke = getSeriesOutlineStroke(series); Ellipse2D head = new Ellipse2D.Double(point.getX() - headW / 2, point.getY() - headH / 2, headW, headH); g2.setPaint(paint); g2.fill(head); g2.setStroke(outlineStroke); g2.setPaint(outlinePaint); g2.draw(head); if (entities != null) { String tip = null; if (this.toolTipGenerator != null) { tip = this.toolTipGenerator.generateToolTip( this.dataset, series, cat); } String url = null; if (this.urlGenerator != null) { url = this.urlGenerator.generateURL(this.dataset, series, cat); } Shape area = new Rectangle( (int) (point.getX() - headW), (int) (point.getY() - headH), (int) (headW * 2), (int) (headH * 2)); CategoryItemEntity entity = new CategoryItemEntity( area, tip, url, this.dataset, this.dataset.getRowKey(series), this.dataset.getColumnKey(cat)); entities.add(entity); } } } } // Plot the polygon Paint paint = getSeriesPaint(series); g2.setPaint(paint); g2.setStroke(getSeriesOutlineStroke(series)); g2.draw(polygon); // Lastly, fill the web polygon if this is required if (this.webFilled) { g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.1f)); g2.fill(polygon); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getForegroundAlpha())); } } /** * Returns the value to be plotted at the interseries of the * series and the category. This allows us to plot * <code>BY_ROW</code> or <code>BY_COLUMN</code> which basically is just * reversing the definition of the categories and data series being * plotted. * * @param series the series to be plotted. * @param cat the category within the series to be plotted. * * @return The value to be plotted (possibly <code>null</code>). * * @see #getDataExtractOrder() */ protected Number getPlotValue(int series, int cat) { Number value = null; if (this.dataExtractOrder == TableOrder.BY_ROW) { value = this.dataset.getValue(series, cat); } else if (this.dataExtractOrder == TableOrder.BY_COLUMN) { value = this.dataset.getValue(cat, series); } return value; } /** * Draws the label for one axis. * * @param g2 the graphics device. * @param plotArea the plot area * @param value the value of the label (ignored). * @param cat the category (zero-based index). * @param startAngle the starting angle. * @param extent the extent of the arc. */ protected void drawLabel(Graphics2D g2, Rectangle2D plotArea, double value, int cat, double startAngle, double extent) { FontRenderContext frc = g2.getFontRenderContext(); String label = null; if (this.dataExtractOrder == TableOrder.BY_ROW) { // if series are in rows, then the categories are the column keys label = this.labelGenerator.generateColumnLabel(this.dataset, cat); } else { // if series are in columns, then the categories are the row keys label = this.labelGenerator.generateRowLabel(this.dataset, cat); } Rectangle2D labelBounds = getLabelFont().getStringBounds(label, frc); LineMetrics lm = getLabelFont().getLineMetrics(label, frc); double ascent = lm.getAscent(); Point2D labelLocation = calculateLabelLocation(labelBounds, ascent, plotArea, startAngle); Composite saveComposite = g2.getComposite(); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f)); g2.setPaint(getLabelPaint()); g2.setFont(getLabelFont()); g2.drawString(label, (float) labelLocation.getX(), (float) labelLocation.getY()); g2.setComposite(saveComposite); } /** * Returns the location for a label * * @param labelBounds the label bounds. * @param ascent the ascent (height of font). * @param plotArea the plot area * @param startAngle the start angle for the pie series. * * @return The location for a label. */ protected Point2D calculateLabelLocation(Rectangle2D labelBounds, double ascent, Rectangle2D plotArea, double startAngle) { Arc2D arc1 = new Arc2D.Double(plotArea, startAngle, 0, Arc2D.OPEN); Point2D point1 = arc1.getEndPoint(); double deltaX = -(point1.getX() - plotArea.getCenterX()) * this.axisLabelGap; double deltaY = -(point1.getY() - plotArea.getCenterY()) * this.axisLabelGap; double labelX = point1.getX() - deltaX; double labelY = point1.getY() - deltaY; if (labelX < plotArea.getCenterX()) { labelX -= labelBounds.getWidth(); } if (labelX == plotArea.getCenterX()) { labelX -= labelBounds.getWidth() / 2; } if (labelY > plotArea.getCenterY()) { labelY += ascent; } return new Point2D.Double(labelX, labelY); } /** * Tests this plot for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof SpiderWebPlot)) { return false; } if (!super.equals(obj)) { return false; } SpiderWebPlot that = (SpiderWebPlot) obj; if (!this.dataExtractOrder.equals(that.dataExtractOrder)) { return false; } if (this.headPercent != that.headPercent) { return false; } if (this.interiorGap != that.interiorGap) { return false; } if (this.startAngle != that.startAngle) { return false; } if (!this.direction.equals(that.direction)) { return false; } if (this.maxValue != that.maxValue) { return false; } if (this.webFilled != that.webFilled) { return false; } if (this.axisLabelGap != that.axisLabelGap) { return false; } if (!PaintUtilities.equal(this.axisLinePaint, that.axisLinePaint)) { return false; } if (!this.axisLineStroke.equals(that.axisLineStroke)) { return false; } if (!ShapeUtilities.equal(this.legendItemShape, that.legendItemShape)) { return false; } if (!PaintUtilities.equal(this.seriesPaint, that.seriesPaint)) { return false; } if (!this.seriesPaintList.equals(that.seriesPaintList)) { return false; } if (!PaintUtilities.equal(this.baseSeriesPaint, that.baseSeriesPaint)) { return false; } if (!PaintUtilities.equal(this.seriesOutlinePaint, that.seriesOutlinePaint)) { return false; } if (!this.seriesOutlinePaintList.equals(that.seriesOutlinePaintList)) { return false; } if (!PaintUtilities.equal(this.baseSeriesOutlinePaint, that.baseSeriesOutlinePaint)) { return false; } if (!ObjectUtilities.equal(this.seriesOutlineStroke, that.seriesOutlineStroke)) { return false; } if (!this.seriesOutlineStrokeList.equals( that.seriesOutlineStrokeList)) { return false; } if (!this.baseSeriesOutlineStroke.equals( that.baseSeriesOutlineStroke)) { return false; } if (!this.labelFont.equals(that.labelFont)) { return false; } if (!PaintUtilities.equal(this.labelPaint, that.labelPaint)) { return false; } if (!this.labelGenerator.equals(that.labelGenerator)) { return false; } if (!ObjectUtilities.equal(this.toolTipGenerator, that.toolTipGenerator)) { return false; } if (!ObjectUtilities.equal(this.urlGenerator, that.urlGenerator)) { return false; } return true; } /** * Returns a clone of this plot. * * @return A clone of this plot. * * @throws CloneNotSupportedException if the plot cannot be cloned for * any reason. */ public Object clone() throws CloneNotSupportedException { SpiderWebPlot clone = (SpiderWebPlot) super.clone(); clone.legendItemShape = ShapeUtilities.clone(this.legendItemShape); clone.seriesPaintList = (PaintList) this.seriesPaintList.clone(); clone.seriesOutlinePaintList = (PaintList) this.seriesOutlinePaintList.clone(); clone.seriesOutlineStrokeList = (StrokeList) this.seriesOutlineStrokeList.clone(); return clone; } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writeShape(this.legendItemShape, stream); SerialUtilities.writePaint(this.seriesPaint, stream); SerialUtilities.writePaint(this.baseSeriesPaint, stream); SerialUtilities.writePaint(this.seriesOutlinePaint, stream); SerialUtilities.writePaint(this.baseSeriesOutlinePaint, stream); SerialUtilities.writeStroke(this.seriesOutlineStroke, stream); SerialUtilities.writeStroke(this.baseSeriesOutlineStroke, stream); SerialUtilities.writePaint(this.labelPaint, stream); SerialUtilities.writePaint(this.axisLinePaint, stream); SerialUtilities.writeStroke(this.axisLineStroke, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.legendItemShape = SerialUtilities.readShape(stream); this.seriesPaint = SerialUtilities.readPaint(stream); this.baseSeriesPaint = SerialUtilities.readPaint(stream); this.seriesOutlinePaint = SerialUtilities.readPaint(stream); this.baseSeriesOutlinePaint = SerialUtilities.readPaint(stream); this.seriesOutlineStroke = SerialUtilities.readStroke(stream); this.baseSeriesOutlineStroke = SerialUtilities.readStroke(stream); this.labelPaint = SerialUtilities.readPaint(stream); this.axisLinePaint = SerialUtilities.readPaint(stream); this.axisLineStroke = SerialUtilities.readStroke(stream); if (this.dataset != null) { this.dataset.addChangeListener(this); } } }
package org.jfree.data.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.sql.Types; import org.jfree.data.general.DefaultPieDataset; import org.jfree.data.general.PieDataset; /** * A {@link PieDataset} that reads data from a database via JDBC. * <P> * A query should be supplied that returns data in two columns, the first * containing VARCHAR data, and the second containing numerical data. The * data is cached in-memory and can be refreshed at any time. */ public class JDBCPieDataset extends DefaultPieDataset { /** For serialization. */ static final long serialVersionUID = -8753216855496746108L; /** The database connection. */ private transient Connection connection; /** * Creates a new JDBCPieDataset and establishes a new database connection. * * @param url the URL of the database connection. * @param driverName the database driver class name. * @param user the database user. * @param password the database users password. * * @throws ClassNotFoundException if the driver cannot be found. * @throws SQLException if there is a problem obtaining a database * connection. */ public JDBCPieDataset(String url, String driverName, String user, String password) throws SQLException, ClassNotFoundException { Class.forName(driverName); this.connection = DriverManager.getConnection(url, user, password); } /** * Creates a new JDBCPieDataset using a pre-existing database connection. * <P> * The dataset is initially empty, since no query has been supplied yet. * * @param con the database connection. */ public JDBCPieDataset(Connection con) { if (con == null) { throw new NullPointerException("A connection must be supplied."); } this.connection = con; } /** * Creates a new JDBCPieDataset using a pre-existing database connection. * <P> * The dataset is initialised with the supplied query. * * @param con the database connection. * @param query the database connection. * * @throws SQLException if there is a problem executing the query. */ public JDBCPieDataset(Connection con, String query) throws SQLException { this(con); executeQuery(query); } /** * ExecuteQuery will attempt execute the query passed to it against the * existing database connection. If no connection exists then no action * is taken. * The results from the query are extracted and cached locally, thus * applying an upper limit on how many rows can be retrieved successfully. * * @param query the query to be executed. * * @throws SQLException if there is a problem executing the query. */ public void executeQuery(String query) throws SQLException { executeQuery(this.connection, query); } /** * ExecuteQuery will attempt execute the query passed to it against the * existing database connection. If no connection exists then no action * is taken. * The results from the query are extracted and cached locally, thus * applying an upper limit on how many rows can be retrieved successfully. * * @param query the query to be executed * @param con the connection the query is to be executed against * * @throws SQLException if there is a problem executing the query. */ public void executeQuery(Connection con, String query) throws SQLException { Statement statement = null; ResultSet resultSet = null; try { statement = con.createStatement(); resultSet = statement.executeQuery(query); ResultSetMetaData metaData = resultSet.getMetaData(); int columnCount = metaData.getColumnCount(); if (columnCount != 2) { throw new SQLException( "Invalid sql generated. PieDataSet requires 2 columns only" ); } int columnType = metaData.getColumnType(2); double value; while (resultSet.next()) { Comparable key = resultSet.getString(1); switch (columnType) { case Types.NUMERIC: case Types.REAL: case Types.INTEGER: case Types.DOUBLE: case Types.FLOAT: case Types.DECIMAL: case Types.BIGINT: value = resultSet.getDouble(2); setValue(key, value); break; case Types.DATE: case Types.TIME: case Types.TIMESTAMP: Timestamp date = resultSet.getTimestamp(2); value = date.getTime(); setValue(key, value); break; default: System.err.println( "JDBCPieDataset - unknown data type"); break; } } fireDatasetChanged(); } finally { if (resultSet != null) { try { resultSet.close(); } catch (Exception e) { System.err.println("JDBCPieDataset: swallowing exception."); } } if (statement != null) { try { statement.close(); } catch (Exception e) { System.err.println("JDBCPieDataset: swallowing exception."); } } } } /** * Close the database connection */ public void close() { try { this.connection.close(); } catch (Exception e) { System.err.println("JdbcXYDataset: swallowing exception."); } } }
package be.ibridge.kettle.trans; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.Date; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.MessageDialogWithToggle; import org.eclipse.swt.widgets.Shell; import org.w3c.dom.Document; import org.w3c.dom.Node; import be.ibridge.kettle.cluster.ClusterSchema; import be.ibridge.kettle.cluster.SlaveServer; import be.ibridge.kettle.core.CheckResult; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.DBCache; import be.ibridge.kettle.core.KettleVariables; import be.ibridge.kettle.core.LogWriter; import be.ibridge.kettle.core.NotePadMeta; import be.ibridge.kettle.core.Point; import be.ibridge.kettle.core.Props; import be.ibridge.kettle.core.Rectangle; import be.ibridge.kettle.core.Result; import be.ibridge.kettle.core.Row; import be.ibridge.kettle.core.SQLStatement; import be.ibridge.kettle.core.SharedObjectInterface; import be.ibridge.kettle.core.SharedObjects; import be.ibridge.kettle.core.TransAction; import be.ibridge.kettle.core.XMLHandler; import be.ibridge.kettle.core.XMLInterface; import be.ibridge.kettle.core.database.Database; import be.ibridge.kettle.core.database.DatabaseMeta; import be.ibridge.kettle.core.exception.KettleDatabaseException; import be.ibridge.kettle.core.exception.KettleException; import be.ibridge.kettle.core.exception.KettleStepException; import be.ibridge.kettle.core.exception.KettleXMLException; import be.ibridge.kettle.core.reflection.StringSearchResult; import be.ibridge.kettle.core.reflection.StringSearcher; import be.ibridge.kettle.core.util.StringUtil; import be.ibridge.kettle.core.value.Value; import be.ibridge.kettle.partition.PartitionSchema; import be.ibridge.kettle.repository.Repository; import be.ibridge.kettle.repository.RepositoryDirectory; import be.ibridge.kettle.spoon.Spoon; import be.ibridge.kettle.trans.step.StepMeta; import be.ibridge.kettle.trans.step.StepMetaInterface; import be.ibridge.kettle.trans.step.StepPartitioningMeta; /** * This class defines a transformation and offers methods to save and load it from XML or a Kettle database repository. * * @since 20-jun-2003 * @author Matt * */ public class TransMeta implements XMLInterface, Comparator { public static final String XML_TAG = "transformation"; private static LogWriter log = LogWriter.getInstance(); private List inputFiles; private ArrayList databases; private ArrayList steps; private ArrayList hops; private ArrayList notes; private ArrayList dependencies; private ArrayList slaveServers; private ArrayList clusterSchemas; private RepositoryDirectory directory; private RepositoryDirectory directoryTree; private String name; private String filename; private StepMeta readStep; private StepMeta writeStep; private StepMeta inputStep; private StepMeta outputStep; private StepMeta updateStep; private String logTable; private DatabaseMeta logConnection; private int sizeRowset; private DatabaseMeta maxDateConnection; private String maxDateTable; private String maxDateField; private double maxDateOffset; private double maxDateDifference; private String arguments[]; private Hashtable counters; private ArrayList sourceRows; private boolean changed, changed_steps, changed_databases, changed_hops, changed_notes; private ArrayList undo; private int max_undo; private int undo_position; private DBCache dbCache; private long id; private boolean useBatchId; private boolean logfieldUsed; private String createdUser, modifiedUser; private Value createdDate, modifiedDate; private int sleepTimeEmpty; private int sleepTimeFull; private Result previousResult; private ArrayList resultRows; private ArrayList resultFiles; private List partitionSchemas; private boolean usingUniqueConnections; private boolean feedbackShown; private int feedbackSize; private boolean usingThreadPriorityManagment; /** If this is null, we load from the default shared objects file : $KETTLE_HOME/.kettle/shared.xml */ private String sharedObjectsFile; public static final int TYPE_UNDO_CHANGE = 1; public static final int TYPE_UNDO_NEW = 2; public static final int TYPE_UNDO_DELETE = 3; public static final int TYPE_UNDO_POSITION = 4; public static final String desc_type_undo[] = { "", Messages.getString("TransMeta.UndoTypeDesc.UndoChange"), Messages.getString("TransMeta.UndoTypeDesc.UndoNew"), Messages.getString("TransMeta.UndoTypeDesc.UndoDelete"), Messages.getString("TransMeta.UndoTypeDesc.UndoPosition") }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ private static final String STRING_MODIFIED_DATE = "modified_date"; /** * Builds a new empty transformation. */ public TransMeta() { clear(); } /** * Constructs a new transformation specifying the filename, name and arguments. * * @param filename The filename of the transformation * @param name The name of the transformation * @param arguments The arguments as Strings */ public TransMeta(String filename, String name, String arguments[]) { clear(); this.filename = filename; this.name = name; this.arguments = arguments; } /** * Compares two transformation on name, filename */ public int compare(Object o1, Object o2) { TransMeta t1 = (TransMeta) o1; TransMeta t2 = (TransMeta) o2; if (Const.isEmpty(t1.getName()) && !Const.isEmpty(t2.getName())) return -1; if (!Const.isEmpty(t1.getName()) && Const.isEmpty(t2.getName())) return 1; if (Const.isEmpty(t1.getName()) && Const.isEmpty(t2.getName())) { if (Const.isEmpty(t1.getFilename()) && !Const.isEmpty(t2.getFilename())) return -1; if (Const.isEmpty(t1.getFilename()) && Const.isEmpty(t2.getFilename())) return 1; if (Const.isEmpty(t1.getFilename()) && Const.isEmpty(t2.getFilename())) { return 0; } return t1.getFilename().compareTo(t2.getFilename()); } return t1.getName().compareTo(t2.getName()); } public boolean equals(Object obj) { return compare(this, obj)==0; } /** * Get the database ID in the repository for this object. * * @return the database ID in the repository for this object. */ public long getID() { return id; } /** * Set the database ID for this object in the repository. * * @param id the database ID for this object in the repository. */ public void setID(long id) { this.id = id; } /** * Clears the transformation. */ public void clear() { setID(-1L); databases = new ArrayList(); steps = new ArrayList(); hops = new ArrayList(); notes = new ArrayList(); dependencies = new ArrayList(); partitionSchemas = new ArrayList(); slaveServers = new ArrayList(); clusterSchemas = new ArrayList(); name = null; filename = null; readStep = null; writeStep = null; inputStep = null; outputStep = null; updateStep = null; logTable = null; logConnection = null; sizeRowset = Const.ROWS_IN_ROWSET; sleepTimeEmpty = Const.SLEEP_EMPTY_NANOS; sleepTimeFull = Const.SLEEP_FULL_NANOS; maxDateConnection = null; maxDateTable = null; maxDateField = null; maxDateOffset = 0.0; maxDateDifference = 0.0; undo = new ArrayList(); max_undo = Const.MAX_UNDO; undo_position = -1; counters = new Hashtable(); resultRows = null; clearUndo(); clearChanged(); useBatchId = true; // Make this one the default from now on... logfieldUsed = false; // Don't use the log-field by default... modifiedUser = "-"; //$NON-NLS-1$ modifiedDate = new Value("modified_date", new Date()); //$NON-NLS-1$ // LOAD THE DATABASE CACHE! dbCache = DBCache.getInstance(); directoryTree = new RepositoryDirectory(); // Default directory: root directory = directoryTree; resultRows = new ArrayList(); resultFiles = new ArrayList(); feedbackShown = true; feedbackSize = Const.ROWS_UPDATE; usingThreadPriorityManagment = true; // For testing purposes only, we add a single cluster schema. // T O D O: remove this test-code later on. /* ClusterSchema clusterSchema = new ClusterSchema(); clusterSchema.setName("Local cluster"); SlaveServer localSlave = new SlaveServer("127.0.0.1", "80", null, null, null, null, null); clusterSchema.getSlaveServers().add(localSlave); clusterSchemas.add(clusterSchema); */ } public void clearUndo() { undo = new ArrayList(); undo_position = -1; } /** * Get an ArrayList of defined DatabaseInfo objects. * * @return an ArrayList of defined DatabaseInfo objects. */ public ArrayList getDatabases() { return databases; } /** * @param databases The databases to set. */ public void setDatabases(ArrayList databases) { this.databases = databases; } /** * Add a database connection to the transformation. * * @param databaseMeta The database connection information. */ public void addDatabase(DatabaseMeta databaseMeta) { databases.add(databaseMeta); } /** * Add a database connection to the transformation if that connection didn't exists yet. * Otherwise, replace the connection in the transformation * * @param databaseMeta The database connection information. */ public void addOrReplaceDatabase(DatabaseMeta databaseMeta) { int index = databases.indexOf(databaseMeta); if (index<0) { databases.add(databaseMeta); } else { DatabaseMeta previous = getDatabase(index); previous.replaceMeta(databaseMeta); } changed_databases = true; } /** * Add a new step to the transformation * * @param stepMeta The step to be added. */ public void addStep(StepMeta stepMeta) { steps.add(stepMeta); changed_steps = true; } /** * Add a new step to the transformation if that step didn't exist yet. * Otherwise, replace the step. * * @param stepMeta The step to be added. */ public void addOrReplaceStep(StepMeta stepMeta) { int index = steps.indexOf(stepMeta); if (index<0) { steps.add(stepMeta); } else { StepMeta previous = getStep(index); previous.replaceMeta(stepMeta); } changed_steps = true; } /** * Add a new hop to the transformation. * * @param hi The hop to be added. */ public void addTransHop(TransHopMeta hi) { hops.add(hi); changed_hops = true; } /** * Add a new note to the transformation. * * @param ni The note to be added. */ public void addNote(NotePadMeta ni) { notes.add(ni); changed_notes = true; } /** * Add a new dependency to the transformation. * * @param td The transformation dependency to be added. */ public void addDependency(TransDependency td) { dependencies.add(td); } /** * Add a database connection to the transformation on a certain location. * * @param p The location * @param ci The database connection information. */ public void addDatabase(int p, DatabaseMeta ci) { databases.add(p, ci); } /** * Add a new step to the transformation * * @param p The location * @param stepMeta The step to be added. */ public void addStep(int p, StepMeta stepMeta) { steps.add(p, stepMeta); changed_steps = true; } /** * Add a new hop to the transformation on a certain location. * * @param p the location * @param hi The hop to be added. */ public void addTransHop(int p, TransHopMeta hi) { hops.add(p, hi); changed_hops = true; } /** * Add a new note to the transformation on a certain location. * * @param p The location * @param ni The note to be added. */ public void addNote(int p, NotePadMeta ni) { notes.add(p, ni); changed_notes = true; } /** * Add a new dependency to the transformation on a certain location * * @param p The location. * @param td The transformation dependency to be added. */ public void addDependency(int p, TransDependency td) { dependencies.add(p, td); } /** * Retrieves a database connection information a a certain location. * * @param i The database number. * @return The database connection information. */ public DatabaseMeta getDatabase(int i) { return (DatabaseMeta) databases.get(i); } /** * Get an ArrayList of defined steps. * * @return an ArrayList of defined steps. */ public ArrayList getSteps() { return steps; } /** * Retrieves a step on a certain location. * * @param i The location. * @return The step information. */ public StepMeta getStep(int i) { return (StepMeta) steps.get(i); } /** * Retrieves a hop on a certain location. * * @param i The location. * @return The hop information. */ public TransHopMeta getTransHop(int i) { return (TransHopMeta) hops.get(i); } /** * Retrieves notepad information on a certain location. * * @param i The location * @return The notepad information. */ public NotePadMeta getNote(int i) { return (NotePadMeta) notes.get(i); } /** * Retrieves a dependency on a certain location. * * @param i The location. * @return The dependency. */ public TransDependency getDependency(int i) { return (TransDependency) dependencies.get(i); } /** * Removes a database from the transformation on a certain location. * * @param i The location */ public void removeDatabase(int i) { if (i < 0 || i >= databases.size()) return; databases.remove(i); } /** * Removes a step from the transformation on a certain location. * * @param i The location */ public void removeStep(int i) { if (i < 0 || i >= steps.size()) return; steps.remove(i); changed_steps = true; } /** * Removes a hop from the transformation on a certain location. * * @param i The location */ public void removeTransHop(int i) { if (i < 0 || i >= hops.size()) return; hops.remove(i); changed_hops = true; } /** * Removes a note from the transformation on a certain location. * * @param i The location */ public void removeNote(int i) { if (i < 0 || i >= notes.size()) return; notes.remove(i); changed_notes = true; } /** * Removes a dependency from the transformation on a certain location. * * @param i The location */ public void removeDependency(int i) { if (i < 0 || i >= dependencies.size()) return; dependencies.remove(i); } /** * Clears all the dependencies from the transformation. */ public void removeAllDependencies() { dependencies.clear(); } /** * Count the nr of databases in the transformation. * * @return The nr of databases */ public int nrDatabases() { return databases.size(); } /** * Count the nr of steps in the transformation. * * @return The nr of steps */ public int nrSteps() { return steps.size(); } /** * Count the nr of hops in the transformation. * * @return The nr of hops */ public int nrTransHops() { return hops.size(); } /** * Count the nr of notes in the transformation. * * @return The nr of notes */ public int nrNotes() { return notes.size(); } /** * Count the nr of dependencies in the transformation. * * @return The nr of dependencies */ public int nrDependencies() { return dependencies.size(); } /** * Changes the content of a step on a certain position * * @param i The position * @param stepMeta The Step */ public void setStep(int i, StepMeta stepMeta) { steps.set(i, stepMeta); } /** * Changes the content of a hop on a certain position * * @param i The position * @param hi The hop */ public void setTransHop(int i, TransHopMeta hi) { hops.set(i, hi); } /** * Counts the number of steps that are actually used in the transformation. * * @return the number of used steps. */ public int nrUsedSteps() { int nr = 0; for (int i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); if (isStepUsedInTransHops(stepMeta)) nr++; } return nr; } /** * Gets a used step on a certain location * * @param lu The location * @return The used step. */ public StepMeta getUsedStep(int lu) { int nr = 0; for (int i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); if (isStepUsedInTransHops(stepMeta)) { if (lu == nr) return stepMeta; nr++; } } return null; } /** * Searches the list of databases for a database with a certain name * * @param name The name of the database connection * @return The database connection information or null if nothing was found. */ public DatabaseMeta findDatabase(String name) { int i; for (i = 0; i < nrDatabases(); i++) { DatabaseMeta ci = getDatabase(i); if (ci.getName().equalsIgnoreCase(name)) { return ci; } } return null; } /** * Searches the list of steps for a step with a certain name * * @param name The name of the step to look for * @return The step information or null if no nothing was found. */ public StepMeta findStep(String name) { return findStep(name, null); } /** * Searches the list of steps for a step with a certain name while excluding one step. * * @param name The name of the step to look for * @param exclude The step information to exclude. * @return The step information or null if nothing was found. */ public StepMeta findStep(String name, StepMeta exclude) { if (name==null) return null; int excl = -1; if (exclude != null) excl = indexOfStep(exclude); for (int i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); if (i != excl && stepMeta.getName().equalsIgnoreCase(name)) { return stepMeta; } } return null; } /** * Searches the list of hops for a hop with a certain name * * @param name The name of the hop to look for * @return The hop information or null if nothing was found. */ public TransHopMeta findTransHop(String name) { int i; for (i = 0; i < nrTransHops(); i++) { TransHopMeta hi = getTransHop(i); if (hi.toString().equalsIgnoreCase(name)) { return hi; } } return null; } /** * Search all hops for a hop where a certain step is at the start. * * @param fromstep The step at the start of the hop. * @return The hop or null if no hop was found. */ public TransHopMeta findTransHopFrom(StepMeta fromstep) { int i; for (i = 0; i < nrTransHops(); i++) { TransHopMeta hi = getTransHop(i); if (hi.getFromStep() != null && hi.getFromStep().equals(fromstep)) // return the first { return hi; } } return null; } /** * Find a certain hop in the transformation.. * * @param hi The hop information to look for. * @return The hop or null if no hop was found. */ public TransHopMeta findTransHop(TransHopMeta hi) { return findTransHop(hi.getFromStep(), hi.getToStep()); } /** * Search all hops for a hop where a certain step is at the start and another is at the end. * * @param from The step at the start of the hop. * @param to The step at the end of the hop. * @return The hop or null if no hop was found. */ public TransHopMeta findTransHop(StepMeta from, StepMeta to) { int i; for (i = 0; i < nrTransHops(); i++) { TransHopMeta hi = getTransHop(i); if (hi.isEnabled()) { if (hi.getFromStep() != null && hi.getToStep() != null && hi.getFromStep().equals(from) && hi.getToStep().equals(to)) { return hi; } } } return null; } /** * Search all hops for a hop where a certain step is at the end. * * @param tostep The step at the end of the hop. * @return The hop or null if no hop was found. */ public TransHopMeta findTransHopTo(StepMeta tostep) { int i; for (i = 0; i < nrTransHops(); i++) { TransHopMeta hi = getTransHop(i); if (hi.getToStep() != null && hi.getToStep().equals(tostep)) // Return the first! { return hi; } } return null; } /** * Determines whether or not a certain step is informative. This means that the previous step is sending information * to this step, but only informative. This means that this step is using the information to process the actual * stream of data. We use this in StreamLookup, TableInput and other types of steps. * * @param this_step The step that is receiving information. * @param prev_step The step that is sending information * @return true if prev_step if informative for this_step. */ public boolean isStepInformative(StepMeta this_step, StepMeta prev_step) { String[] infoSteps = this_step.getStepMetaInterface().getInfoSteps(); if (infoSteps == null) return false; for (int i = 0; i < infoSteps.length; i++) { if (prev_step.getName().equalsIgnoreCase(infoSteps[i])) return true; } return false; } /** * Counts the number of previous steps for a step name. * * @param stepname The name of the step to start from * @return The number of preceding steps. */ public int findNrPrevSteps(String stepname) { return findNrPrevSteps(findStep(stepname), false); } /** * Counts the number of previous steps for a step name taking into account whether or not they are informational. * * @param stepname The name of the step to start from * @return The number of preceding steps. */ public int findNrPrevSteps(String stepname, boolean info) { return findNrPrevSteps(findStep(stepname), info); } /** * Find the number of steps that precede the indicated step. * * @param stepMeta The source step * * @return The number of preceding steps found. */ public int findNrPrevSteps(StepMeta stepMeta) { return findNrPrevSteps(stepMeta, false); } /** * Find the previous step on a certain location. * * @param stepname The source step name * @param nr the location * * @return The preceding step found. */ public StepMeta findPrevStep(String stepname, int nr) { return findPrevStep(findStep(stepname), nr); } /** * Find the previous step on a certain location taking into account the steps being informational or not. * * @param stepname The name of the step * @param nr The location * @param info true if we only want the informational steps. * @return The step information */ public StepMeta findPrevStep(String stepname, int nr, boolean info) { return findPrevStep(findStep(stepname), nr, info); } /** * Find the previous step on a certain location. * * @param stepMeta The source step information * @param nr the location * * @return The preceding step found. */ public StepMeta findPrevStep(StepMeta stepMeta, int nr) { return findPrevStep(stepMeta, nr, false); } /** * Count the number of previous steps on a certain location taking into account the steps being informational or * not. * * @param stepMeta The name of the step * @param info true if we only want the informational steps. * @return The number of preceding steps */ public int findNrPrevSteps(StepMeta stepMeta, boolean info) { int count = 0; int i; for (i = 0; i < nrTransHops(); i++) // Look at all the hops; { TransHopMeta hi = getTransHop(i); if (hi.getToStep() != null && hi.isEnabled() && hi.getToStep().equals(stepMeta)) { // Check if this previous step isn't informative (StreamValueLookup) // We don't want fields from this stream to show up! if (info || !isStepInformative(stepMeta, hi.getFromStep())) { count++; } } } return count; } /** * Find the previous step on a certain location taking into account the steps being informational or not. * * @param stepMeta The step * @param nr The location * @param info true if we only want the informational steps. * @return The preceding step information */ public StepMeta findPrevStep(StepMeta stepMeta, int nr, boolean info) { int count = 0; int i; for (i = 0; i < nrTransHops(); i++) // Look at all the hops; { TransHopMeta hi = getTransHop(i); if (hi.getToStep() != null && hi.isEnabled() && hi.getToStep().equals(stepMeta)) { if (info || !isStepInformative(stepMeta, hi.getFromStep())) { if (count == nr) { return hi.getFromStep(); } count++; } } } return null; } /** * Get the informational steps for a certain step. An informational step is a step that provides information for * lookups etc. * * @param stepMeta The name of the step * @return The informational steps found */ public StepMeta[] getInfoStep(StepMeta stepMeta) { String[] infoStepName = stepMeta.getStepMetaInterface().getInfoSteps(); if (infoStepName == null) return null; StepMeta[] infoStep = new StepMeta[infoStepName.length]; for (int i = 0; i < infoStep.length; i++) { infoStep[i] = findStep(infoStepName[i]); } return infoStep; } /** * Find the the number of informational steps for a certains step. * * @param stepMeta The step * @return The number of informational steps found. */ public int findNrInfoSteps(StepMeta stepMeta) { if (stepMeta == null) return 0; int count = 0; for (int i = 0; i < nrTransHops(); i++) // Look at all the hops; { TransHopMeta hi = getTransHop(i); if (hi == null || hi.getToStep() == null) { log.logError(toString(), Messages.getString("TransMeta.Log.DestinationOfHopCannotBeNull")); //$NON-NLS-1$ } if (hi != null && hi.getToStep() != null && hi.isEnabled() && hi.getToStep().equals(stepMeta)) { // Check if this previous step isn't informative (StreamValueLookup) // We don't want fields from this stream to show up! if (isStepInformative(stepMeta, hi.getFromStep())) { count++; } } } return count; } /** * Find the informational fields coming from an informational step into the step specified. * * @param stepname The name of the step * @return A row containing fields with origin. */ public Row getPrevInfoFields(String stepname) throws KettleStepException { return getPrevInfoFields(findStep(stepname)); } /** * Find the informational fields coming from an informational step into the step specified. * * @param stepMeta The receiving step * @return A row containing fields with origin. */ public Row getPrevInfoFields(StepMeta stepMeta) throws KettleStepException { Row row = new Row(); for (int i = 0; i < nrTransHops(); i++) // Look at all the hops; { TransHopMeta hi = getTransHop(i); if (hi.isEnabled() && hi.getToStep().equals(stepMeta)) { if (isStepInformative(stepMeta, hi.getFromStep())) { getThisStepFields(stepMeta, row); return row; } } } return row; } /** * Find the number of succeeding steps for a certain originating step. * * @param stepMeta The originating step * @return The number of succeeding steps. */ public int findNrNextSteps(StepMeta stepMeta) { int count = 0; int i; for (i = 0; i < nrTransHops(); i++) // Look at all the hops; { TransHopMeta hi = getTransHop(i); if (hi.isEnabled() && hi.getFromStep().equals(stepMeta)) count++; } return count; } /** * Find the succeeding step at a location for an originating step. * * @param stepMeta The originating step * @param nr The location * @return The step found. */ public StepMeta findNextStep(StepMeta stepMeta, int nr) { int count = 0; int i; for (i = 0; i < nrTransHops(); i++) // Look at all the hops; { TransHopMeta hi = getTransHop(i); if (hi.isEnabled() && hi.getFromStep().equals(stepMeta)) { if (count == nr) { return hi.getToStep(); } count++; } } return null; } /** * Retrieve an array of preceding steps for a certain destination step. * * @param stepMeta The destination step * @return An array containing the preceding steps. */ public StepMeta[] getPrevSteps(StepMeta stepMeta) { int nr = findNrPrevSteps(stepMeta, true); StepMeta retval[] = new StepMeta[nr]; for (int i = 0; i < nr; i++) { retval[i] = findPrevStep(stepMeta, i, true); } return retval; } /** * Retrieve an array of succeeding step names for a certain originating step name. * * @param stepname The originating step name * @return An array of succeeding step names */ public String[] getPrevStepNames(String stepname) { return getPrevStepNames(findStep(stepname)); } /** * Retrieve an array of preceding steps for a certain destination step. * * @param stepMeta The destination step * @return an array of preceding step names. */ public String[] getPrevStepNames(StepMeta stepMeta) { StepMeta prevStepMetas[] = getPrevSteps(stepMeta); String retval[] = new String[prevStepMetas.length]; for (int x = 0; x < prevStepMetas.length; x++) retval[x] = prevStepMetas[x].getName(); return retval; } /** * Retrieve an array of succeeding steps for a certain originating step. * * @param stepMeta The originating step * @return an array of succeeding steps. */ public StepMeta[] getNextSteps(StepMeta stepMeta) { int nr = findNrNextSteps(stepMeta); StepMeta retval[] = new StepMeta[nr]; for (int i = 0; i < nr; i++) { retval[i] = findNextStep(stepMeta, i); } return retval; } /** * Retrieve an array of succeeding step names for a certain originating step. * * @param stepMeta The originating step * @return an array of succeeding step names. */ public String[] getNextStepNames(StepMeta stepMeta) { StepMeta nextStepMeta[] = getNextSteps(stepMeta); String retval[] = new String[nextStepMeta.length]; for (int x = 0; x < nextStepMeta.length; x++) retval[x] = nextStepMeta[x].getName(); return retval; } /** * Find the step that is located on a certain point on the canvas, taking into account the icon size. * * @param x the x-coordinate of the point queried * @param y the y-coordinate of the point queried * @return The step information if a step is located at the point. Otherwise, if no step was found: null. */ public StepMeta getStep(int x, int y, int iconsize) { int i, s; s = steps.size(); for (i = s - 1; i >= 0; i--) // Back to front because drawing goes from start to end { StepMeta stepMeta = (StepMeta) steps.get(i); if (partOfTransHop(stepMeta) || stepMeta.isDrawn()) // Only consider steps from active or inactive hops! { Point p = stepMeta.getLocation(); if (p != null) { if (x >= p.x && x <= p.x + iconsize && y >= p.y && y <= p.y + iconsize + 20) { return stepMeta; } } } } return null; } /** * Find the note that is located on a certain point on the canvas. * * @param x the x-coordinate of the point queried * @param y the y-coordinate of the point queried * @return The note information if a note is located at the point. Otherwise, if nothing was found: null. */ public NotePadMeta getNote(int x, int y) { int i, s; s = notes.size(); for (i = s - 1; i >= 0; i--) // Back to front because drawing goes from start to end { NotePadMeta ni = (NotePadMeta) notes.get(i); Point loc = ni.getLocation(); Point p = new Point(loc.x, loc.y); if (x >= p.x && x <= p.x + ni.width + 2 * Const.NOTE_MARGIN && y >= p.y && y <= p.y + ni.height + 2 * Const.NOTE_MARGIN) { return ni; } } return null; } /** * Determines whether or not a certain step is part of a hop. * * @param stepMeta The step queried * @return true if the step is part of a hop. */ public boolean partOfTransHop(StepMeta stepMeta) { int i; for (i = 0; i < nrTransHops(); i++) { TransHopMeta hi = getTransHop(i); if (hi.getFromStep() == null || hi.getToStep() == null) return false; if (hi.getFromStep().equals(stepMeta) || hi.getToStep().equals(stepMeta)) return true; } return false; } /** * Returns the fields that are emitted by a certain step name * * @param stepname The stepname of the step to be queried. * @return A row containing the fields emitted. */ public Row getStepFields(String stepname) throws KettleStepException { StepMeta stepMeta = findStep(stepname); if (stepMeta != null) return getStepFields(stepMeta); else return null; } /** * Returns the fields that are emitted by a certain step * * @param stepMeta The step to be queried. * @return A row containing the fields emitted. */ public Row getStepFields(StepMeta stepMeta) throws KettleStepException { return getStepFields(stepMeta, null); } public Row getStepFields(StepMeta[] stepMeta) throws KettleStepException { Row fields = new Row(); for (int i = 0; i < stepMeta.length; i++) { Row flds = getStepFields(stepMeta[i]); if (flds != null) fields.mergeRow(flds); } return fields; } /** * Returns the fields that are emitted by a certain step * * @param stepMeta The step to be queried. * @param monitor The progress monitor for progress dialog. (null if not used!) * @return A row containing the fields emitted. */ public Row getStepFields(StepMeta stepMeta, IProgressMonitor monitor) throws KettleStepException { Row row = new Row(); if (stepMeta == null) return row; log.logDebug(toString(), Messages.getString("TransMeta.Log.FromStepALookingAtPreviousStep", stepMeta.getName(), String.valueOf(findNrPrevSteps(stepMeta)) )); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ for (int i = 0; i < findNrPrevSteps(stepMeta); i++) { StepMeta prevStepMeta = findPrevStep(stepMeta, i); if (monitor != null) { monitor.subTask(Messages.getString("TransMeta.Monitor.CheckingStepTask.Title", prevStepMeta.getName() )); //$NON-NLS-1$ //$NON-NLS-2$ } Row add = getStepFields(prevStepMeta, monitor); if (add == null) add = new Row(); log.logDebug(toString(), Messages.getString("TransMeta.Log.FoundFieldsToAdd") + add.toString()); //$NON-NLS-1$ if (i == 0) { row.addRow(add); } else { // See if the add fields are not already in the row for (int x = 0; x < add.size(); x++) { Value v = add.getValue(x); Value s = row.searchValue(v.getName()); if (s == null) { row.addValue(v); } } } } // Finally, see if we need to add/modify/delete fields with this step "name" return getThisStepFields(stepMeta, row, monitor); } /** * Find the fields that are entering a step with a certain name. * * @param stepname The name of the step queried * @return A row containing the fields (w/ origin) entering the step */ public Row getPrevStepFields(String stepname) throws KettleStepException { return getPrevStepFields(findStep(stepname)); } /** * Find the fields that are entering a certain step. * * @param stepMeta The step queried * @return A row containing the fields (w/ origin) entering the step */ public Row getPrevStepFields(StepMeta stepMeta) throws KettleStepException { return getPrevStepFields(stepMeta, null); } /** * Find the fields that are entering a certain step. * * @param stepMeta The step queried * @param monitor The progress monitor for progress dialog. (null if not used!) * @return A row containing the fields (w/ origin) entering the step */ public Row getPrevStepFields(StepMeta stepMeta, IProgressMonitor monitor) throws KettleStepException { Row row = new Row(); if (stepMeta == null) { return null; } log.logDebug(toString(), Messages.getString("TransMeta.Log.FromStepALookingAtPreviousStep", stepMeta.getName(), String.valueOf(findNrPrevSteps(stepMeta)) )); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ for (int i = 0; i < findNrPrevSteps(stepMeta); i++) { StepMeta prevStepMeta = findPrevStep(stepMeta, i); if (monitor != null) { monitor.subTask(Messages.getString("TransMeta.Monitor.CheckingStepTask.Title", prevStepMeta.getName() )); //$NON-NLS-1$ //$NON-NLS-2$ } Row add = getStepFields(prevStepMeta, monitor); log.logDebug(toString(), Messages.getString("TransMeta.Log.FoundFieldsToAdd2") + add.toString()); //$NON-NLS-1$ if (i == 0) // we expect all input streams to be of the same layout! { row.addRow(add); // recursive! } else { // See if the add fields are not already in the row for (int x = 0; x < add.size(); x++) { Value v = add.getValue(x); Value s = row.searchValue(v.getName()); if (s == null) { row.addValue(v); } } } } return row; } /** * Return the fields that are emitted by a step with a certain name * * @param stepname The name of the step that's being queried. * @param row A row containing the input fields or an empty row if no input is required. * @return A Row containing the output fields. */ public Row getThisStepFields(String stepname, Row row) throws KettleStepException { return getThisStepFields(findStep(stepname), row); } /** * Returns the fields that are emitted by a step * * @param stepMeta : The StepMeta object that's being queried * @param row : A row containing the input fields or an empty row if no input is required. * * @return A Row containing the output fields. */ public Row getThisStepFields(StepMeta stepMeta, Row row) throws KettleStepException { return getThisStepFields(stepMeta, row, null); } /** * Returns the fields that are emitted by a step * * @param stepMeta : The StepMeta object that's being queried * @param row : A row containing the input fields or an empty row if no input is required. * * @return A Row containing the output fields. */ public Row getThisStepFields(StepMeta stepMeta, Row row, IProgressMonitor monitor) throws KettleStepException { // Then this one. log.logDebug(toString(), Messages.getString("TransMeta.Log.GettingFieldsFromStep",stepMeta.getName(), stepMeta.getStepID())); //$NON-NLS-1$ //$NON-NLS-2$ String name = stepMeta.getName(); if (monitor != null) { monitor.subTask(Messages.getString("TransMeta.Monitor.GettingFieldsFromStepTask.Title", name )); //$NON-NLS-1$ //$NON-NLS-2$ } StepMetaInterface stepint = stepMeta.getStepMetaInterface(); Row inform = null; StepMeta[] lu = getInfoStep(stepMeta); if (lu != null) { inform = getStepFields(lu); } else { inform = stepint.getTableFields(); } stepint.getFields(row, name, inform); return row; } /** * Determine if we should put a replace warning or not for the transformation in a certain repository. * * @param rep The repository. * @return True if we should show a replace warning, false if not. */ public boolean showReplaceWarning(Repository rep) { if (getID() < 0) { try { if (rep.getTransformationID(getName(), directory.getID()) > 0) return true; } catch (KettleDatabaseException dbe) { log.logError(toString(), Messages.getString("TransMeta.Log.DatabaseError") + dbe.getMessage()); //$NON-NLS-1$ return true; } } return false; } /** * Saves the transformation to a repository. * * @param rep The repository. * @throws KettleException if an error occurrs. */ public void saveRep(Repository rep) throws KettleException { saveRep(rep, null); } /** * Saves the transformation to a repository. * * @param rep The repository. * @throws KettleException if an error occurrs. */ public void saveRep(Repository rep, IProgressMonitor monitor) throws KettleException { try { if (monitor!=null) monitor.subTask(Messages.getString("TransMeta.Monitor.LockingRepository")); //$NON-NLS-1$ rep.lockRepository(); // make sure we're they only one using the repository at the moment // Clear attribute id cache rep.clearNextIDCounters(); // force repository lookup. // Do we have a valid directory? if (directory.getID() < 0) { throw new KettleException(Messages.getString("TransMeta.Exception.PlsSelectAValidDirectoryBeforeSavingTheTransformation")); } //$NON-NLS-1$ int nrWorks = 2 + nrDatabases() + nrNotes() + nrSteps() + nrTransHops(); if (monitor != null) monitor.beginTask(Messages.getString("TransMeta.Monitor.SavingTransformationTask.Title") + getPathAndName(), nrWorks); //$NON-NLS-1$ log.logDebug(toString(), Messages.getString("TransMeta.Log.SavingOfTransformationStarted")); //$NON-NLS-1$ if (monitor!=null && monitor.isCanceled()) throw new KettleDatabaseException(); // Before we start, make sure we have a valid transformation ID! // Two possibilities: // 1) We have a ID: keep it // 2) We don't have an ID: look it up. // If we find a transformation with the same name: ask! if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.HandlingOldVersionTransformationTask.Title")); //$NON-NLS-1$ setID(rep.getTransformationID(getName(), directory.getID())); // If no valid id is available in the database, assign one... if (getID() <= 0) { setID(rep.getNextTransformationID()); } else { // If we have a valid ID, we need to make sure everything is cleared out // of the database for this id_transformation, before we put it back in... if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.DeletingOldVersionTransformationTask.Title")); //$NON-NLS-1$ log.logDebug(toString(), Messages.getString("TransMeta.Log.DeletingOldVersionTransformation")); //$NON-NLS-1$ rep.delAllFromTrans(getID()); log.logDebug(toString(), Messages.getString("TransMeta.Log.OldVersionOfTransformationRemoved")); //$NON-NLS-1$ } if (monitor != null) monitor.worked(1); log.logDebug(toString(), Messages.getString("TransMeta.Log.SavingNotes")); //$NON-NLS-1$ for (int i = 0; i < nrNotes(); i++) { if (monitor!=null && monitor.isCanceled()) throw new KettleDatabaseException(Messages.getString("TransMeta.Log.UserCancelledTransSave")); if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.SavingNoteTask.Title") + (i + 1) + "/" + nrNotes()); //$NON-NLS-1$ //$NON-NLS-2$ NotePadMeta ni = getNote(i); ni.saveRep(rep, getID()); if (ni.getID() > 0) rep.insertTransNote(getID(), ni.getID()); if (monitor != null) monitor.worked(1); } log.logDebug(toString(), Messages.getString("TransMeta.Log.SavingDatabaseConnections")); //$NON-NLS-1$ for (int i = 0; i < nrDatabases(); i++) { if (monitor!=null && monitor.isCanceled()) throw new KettleDatabaseException(Messages.getString("TransMeta.Log.UserCancelledTransSave")); if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.SavingDatabaseTask.Title") + (i + 1) + "/" + nrDatabases()); //$NON-NLS-1$ //$NON-NLS-2$ DatabaseMeta ci = getDatabase(i); // ONLY save the database connection if it has changed and nothing was saved in the repository if(ci.hasChanged() || ci.getID()<=0) { ci.saveRep(rep); } if (monitor != null) monitor.worked(1); } // Before saving the steps, make sure we have all the step-types. // It is possible that we received another step through a plugin. log.logDebug(toString(), Messages.getString("TransMeta.Log.CheckingStepTypes")); //$NON-NLS-1$ rep.updateStepTypes(); log.logDebug(toString(), Messages.getString("TransMeta.Log.SavingSteps")); //$NON-NLS-1$ for (int i = 0; i < nrSteps(); i++) { if (monitor!=null && monitor.isCanceled()) throw new KettleDatabaseException(Messages.getString("TransMeta.Log.UserCancelledTransSave")); if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.SavingStepTask.Title") + (i + 1) + "/" + nrSteps()); //$NON-NLS-1$ //$NON-NLS-2$ StepMeta stepMeta = getStep(i); stepMeta.saveRep(rep, getID()); if (monitor != null) monitor.worked(1); } rep.closeStepAttributeInsertPreparedStatement(); log.logDebug(toString(), Messages.getString("TransMeta.Log.SavingHops")); //$NON-NLS-1$ for (int i = 0; i < nrTransHops(); i++) { if (monitor!=null && monitor.isCanceled()) throw new KettleDatabaseException(Messages.getString("TransMeta.Log.UserCancelledTransSave")); if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.SavingHopTask.Title") + (i + 1) + "/" + nrTransHops()); //$NON-NLS-1$ //$NON-NLS-2$ TransHopMeta hi = getTransHop(i); hi.saveRep(rep, getID()); if (monitor != null) monitor.worked(1); } if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.FinishingTask.Title")); //$NON-NLS-1$ log.logDebug(toString(), Messages.getString("TransMeta.Log.SavingTransformationInfo")); //$NON-NLS-1$ rep.insertTransformation(this); // save the top level information for the transformation rep.closeTransAttributeInsertPreparedStatement(); // Save the partition schemas for (int i=0;i<partitionSchemas.size();i++) { PartitionSchema schema = (PartitionSchema) partitionSchemas.get(i); schema.saveRep(rep, getID()); } // Save the slaves for (int i=0;i<slaveServers.size();i++) { SlaveServer slaveServer = (SlaveServer) slaveServers.get(i); slaveServer.saveRep(rep, getID()); } // Save the clustering schemas for (int i=0;i<clusterSchemas.size();i++) { ClusterSchema schema = (ClusterSchema) clusterSchemas.get(i); schema.saveRep(rep, getID()); } log.logDebug(toString(), Messages.getString("TransMeta.Log.SavingDependencies")); //$NON-NLS-1$ for (int i = 0; i < nrDependencies(); i++) { if (monitor!=null && monitor.isCanceled()) throw new KettleDatabaseException(Messages.getString("TransMeta.Log.UserCancelledTransSave")); TransDependency td = getDependency(i); td.saveRep(rep, getID()); } log.logDebug(toString(), Messages.getString("TransMeta.Log.SavingFinished")); //$NON-NLS-1$ if (monitor!=null) monitor.subTask(Messages.getString("TransMeta.Monitor.UnlockingRepository")); //$NON-NLS-1$ rep.unlockRepository(); // Perform a commit! rep.commit(); clearChanged(); if (monitor != null) monitor.worked(1); if (monitor != null) monitor.done(); } catch (KettleDatabaseException dbe) { // Oops, rollback! rep.rollback(); log.logError(toString(), Messages.getString("TransMeta.Log.ErrorSavingTransformationToRepository") + Const.CR + dbe.getMessage()); //$NON-NLS-1$ throw new KettleException(Messages.getString("TransMeta.Log.ErrorSavingTransformationToRepository"), dbe); //$NON-NLS-1$ } finally { // don't forget to unlock the repository. // Normally this is done by the commit / rollback statement, but hey there are some freaky database out // there... rep.unlockRepository(); } } /** * Read the database connections in the repository and add them to this transformation if they are not yet present. * * @param rep The repository to load the database connections from. * @param overWriteShared if an object with the same name exists, overwrite */ public void readDatabases(Repository rep, boolean overWriteShared) throws KettleException { try { long dbids[] = rep.getDatabaseIDs(); for (int i = 0; i < dbids.length; i++) { DatabaseMeta databaseMeta = new DatabaseMeta(rep, dbids[i]); DatabaseMeta check = findDatabase(databaseMeta.getName()); // Check if there already is one in the transformation if (check==null || overWriteShared) // We only add, never overwrite database connections. { if (databaseMeta.getName() != null) { addOrReplaceDatabase(databaseMeta); if (!overWriteShared) databaseMeta.setChanged(false); } } } changed_databases = false; } catch (KettleDatabaseException dbe) { throw new KettleException(Messages.getString("TransMeta.Log.UnableToReadDatabaseIDSFromRepository"), dbe); //$NON-NLS-1$ } catch (KettleException ke) { throw new KettleException(Messages.getString("TransMeta.Log.UnableToReadDatabasesFromRepository"), ke); //$NON-NLS-1$ } } /** * Read the database partitions in the repository and add them to this transformation if they are not yet present. * @param rep The repository to load from. * @param overWriteShared if an object with the same name exists, overwrite * @throws KettleException */ public void readPartitionSchemas(Repository rep, boolean overWriteShared) throws KettleException { try { long dbids[] = rep.getPartitionSchemaIDs(); for (int i = 0; i < dbids.length; i++) { PartitionSchema partitionSchema = new PartitionSchema(rep, dbids[i]); PartitionSchema check = findPartitionSchema(partitionSchema.getName()); // Check if there already is one in the transformation if (check==null || overWriteShared) { if (!Const.isEmpty(partitionSchema.getName())) { addOrReplacePartitionSchema(partitionSchema); if (!overWriteShared) partitionSchema.setChanged(false); } } } } catch (KettleException dbe) { throw new KettleException(Messages.getString("TransMeta.Log.UnableToReadPartitionSchemaFromRepository"), dbe); //$NON-NLS-1$ } } /** * Read the slave servers in the repository and add them to this transformation if they are not yet present. * @param rep The repository to load from. * @param overWriteShared if an object with the same name exists, overwrite * @throws KettleException */ public void readSlaves(Repository rep, boolean overWriteShared) throws KettleException { try { long dbids[] = rep.getSlaveIDs(); for (int i = 0; i < dbids.length; i++) { SlaveServer slaveServer = new SlaveServer(rep, dbids[i]); SlaveServer check = findSlaveServer(slaveServer.getName()); // Check if there already is one in the transformation if (check==null || overWriteShared) { if (!Const.isEmpty(slaveServer.getName())) { addOrReplaceSlaveServer(slaveServer); if (!overWriteShared) slaveServer.setChanged(false); } } } } catch (KettleDatabaseException dbe) { throw new KettleException(Messages.getString("TransMeta.Log.UnableToReadSlaveServersFromRepository"), dbe); //$NON-NLS-1$ } } /** * Read the clusters in the repository and add them to this transformation if they are not yet present. * @param rep The repository to load from. * @param overWriteShared if an object with the same name exists, overwrite * @throws KettleException */ public void readClusters(Repository rep, boolean overWriteShared) throws KettleException { try { long dbids[] = rep.getClusterIDs(); for (int i = 0; i < dbids.length; i++) { ClusterSchema cluster = new ClusterSchema(rep, dbids[i], slaveServers); ClusterSchema check = findClusterSchema(cluster.getName()); // Check if there already is one in the transformation if (check==null || overWriteShared) { if (!Const.isEmpty(cluster.getName())) { addOrReplaceClusterSchema(cluster); if (!overWriteShared) cluster.setChanged(false); } } } } catch (KettleDatabaseException dbe) { throw new KettleException(Messages.getString("TransMeta.Log.UnableToReadClustersFromRepository"), dbe); //$NON-NLS-1$ } } /** * Load the transformation name & other details from a repository. * * @param rep The repository to load the details from. */ public void loadRepTrans(Repository rep) throws KettleException { try { Row r = rep.getTransformation(getID()); if (r != null) { name = r.searchValue("NAME").getString(); //$NON-NLS-1$ readStep = findStep(steps, r.getInteger("ID_STEP_READ", -1L)); //$NON-NLS-1$ writeStep = findStep(steps, r.getInteger("ID_STEP_WRITE", -1L)); //$NON-NLS-1$ inputStep = findStep(steps, r.getInteger("ID_STEP_INPUT", -1L)); //$NON-NLS-1$ outputStep = findStep(steps, r.getInteger("ID_STEP_OUTPUT", -1L)); //$NON-NLS-1$ updateStep = findStep(steps, r.getInteger("ID_STEP_UPDATE", -1L)); //$NON-NLS-1$ logConnection = Const.findDatabase(databases, r.getInteger("ID_DATABASE_LOG", -1L)); //$NON-NLS-1$ logTable = r.getString("TABLE_NAME_LOG", null); //$NON-NLS-1$ useBatchId = r.getBoolean("USE_BATCHID", false); //$NON-NLS-1$ logfieldUsed = r.getBoolean("USE_LOGFIELD", false); //$NON-NLS-1$ maxDateConnection = Const.findDatabase(databases, r.getInteger("ID_DATABASE_MAXDATE", -1L)); //$NON-NLS-1$ maxDateTable = r.getString("TABLE_NAME_MAXDATE", null); //$NON-NLS-1$ maxDateField = r.getString("FIELD_NAME_MAXDATE", null); //$NON-NLS-1$ maxDateOffset = r.getNumber("OFFSET_MAXDATE", 0.0); //$NON-NLS-1$ maxDateDifference = r.getNumber("DIFF_MAXDATE", 0.0); //$NON-NLS-1$ modifiedUser = r.getString("MODIFIED_USER", null); //$NON-NLS-1$ modifiedDate = r.searchValue("MODIFIED_DATE"); //$NON-NLS-1$ // Optional: sizeRowset = Const.ROWS_IN_ROWSET; Value val_size_rowset = r.searchValue("SIZE_ROWSET"); //$NON-NLS-1$ if (val_size_rowset != null && !val_size_rowset.isNull()) { sizeRowset = (int) val_size_rowset.getInteger(); } long id_directory = r.getInteger("ID_DIRECTORY", -1L); //$NON-NLS-1$ if (id_directory >= 0) { log.logDetailed(toString(), "ID_DIRECTORY=" + id_directory); //$NON-NLS-1$ // Set right directory... directory = directoryTree.findDirectory(id_directory); } usingUniqueConnections = rep.getTransAttributeBoolean(getID(), 0, "UNIQUE_CONNECTIONS"); feedbackShown = !"N".equalsIgnoreCase( rep.getTransAttributeString(getID(), 0, "FEEDBACK_SHOWN") ); feedbackSize = (int) rep.getTransAttributeInteger(getID(), 0, "FEEDBACK_SIZE"); usingThreadPriorityManagment = !"N".equalsIgnoreCase( rep.getTransAttributeString(getID(), 0, "USING_THREAD_PRIORITIES") ); } } catch (KettleDatabaseException dbe) { throw new KettleException(Messages.getString("TransMeta.Exception.UnableToLoadTransformationInfoFromRepository"), dbe); //$NON-NLS-1$ } finally { setInternalKettleVariables(); } } /** * Read a transformation with a certain name from a repository * * @param rep The repository to read from. * @param transname The name of the transformation. * @param repdir the path to the repository directory */ public TransMeta(Repository rep, String transname, RepositoryDirectory repdir) throws KettleException { this(rep, transname, repdir, null, true); } /** * Read a transformation with a certain name from a repository * * @param rep The repository to read from. * @param transname The name of the transformation. * @param repdir the path to the repository directory * @param setInternalVariables true if you want to set the internal variables based on this transformation information */ public TransMeta(Repository rep, String transname, RepositoryDirectory repdir, boolean setInternalVariables) throws KettleException { this(rep, transname, repdir, null, setInternalVariables); } /** * Read a transformation with a certain name from a repository * * @param rep The repository to read from. * @param transname The name of the transformation. * @param repdir the path to the repository directory * @param monitor The progress monitor to display the progress of the file-open operation in a dialog */ public TransMeta(Repository rep, String transname, RepositoryDirectory repdir, IProgressMonitor monitor) throws KettleException { this(rep, transname, repdir, monitor, true); } /** * Read a transformation with a certain name from a repository * * @param rep The repository to read from. * @param transname The name of the transformation. * @param repdir the path to the repository directory * @param monitor The progress monitor to display the progress of the file-open operation in a dialog * @param setInternalVariables true if you want to set the internal variables based on this transformation information */ public TransMeta(Repository rep, String transname, RepositoryDirectory repdir, IProgressMonitor monitor, boolean setInternalVariables) throws KettleException { try { String pathAndName = repdir.isRoot() ? repdir + transname : repdir + RepositoryDirectory.DIRECTORY_SEPARATOR + transname; // Clear everything... clear(); // Also read objects from the shared XML file readSharedObjects(rep); setName(transname); directory = repdir; directoryTree = directory.findRoot(); // Get the transformation id log.logDetailed(toString(), Messages.getString("TransMeta.Log.LookingForTransformation", transname ,directory.getPath() )); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.ReadingTransformationInfoTask.Title")); //$NON-NLS-1$ setID(rep.getTransformationID(transname, directory.getID())); if (monitor != null) monitor.worked(1); // If no valid id is available in the database, then give error... if (getID() > 0) { long noteids[] = rep.getTransNoteIDs(getID()); long stepids[] = rep.getStepIDs(getID()); long hopids[] = rep.getTransHopIDs(getID()); int nrWork = 3 + noteids.length + stepids.length + hopids.length; if (monitor != null) monitor.beginTask(Messages.getString("TransMeta.Monitor.LoadingTransformationTask.Title") + pathAndName, nrWork); //$NON-NLS-1$ log.logDetailed(toString(), Messages.getString("TransMeta.Log.LoadingTransformation", getName() )); //$NON-NLS-1$ //$NON-NLS-2$ // Load the common database connections if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.ReadingTheAvailableSharedObjectsTask.Title")); //$NON-NLS-1$ readSharedObjects(rep); if (monitor != null) monitor.worked(1); // Load the notes... if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.ReadingNoteTask.Title")); //$NON-NLS-1$ for (int i = 0; i < noteids.length; i++) { NotePadMeta ni = new NotePadMeta(log, rep, noteids[i]); if (indexOfNote(ni) < 0) addNote(ni); if (monitor != null) monitor.worked(1); } if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.ReadingStepsTask.Title")); //$NON-NLS-1$ rep.fillStepAttributesBuffer(getID()); // read all the attributes on one go! for (int i = 0; i < stepids.length; i++) { log.logDetailed(toString(), Messages.getString("TransMeta.Log.LoadingStepWithID") + stepids[i]); //$NON-NLS-1$ if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.ReadingStepTask.Title") + (i + 1) + "/" + (stepids.length)); //$NON-NLS-1$ //$NON-NLS-2$ StepMeta stepMeta = new StepMeta(rep, stepids[i], databases, counters, partitionSchemas); // In this case, we just add or replace the shared steps. // The repository is considered "more central" addOrReplaceStep(stepMeta); if (monitor != null) monitor.worked(1); } if (monitor != null) monitor.worked(1); rep.setStepAttributesBuffer(null); // clear the buffer (should be empty anyway) // Have all StreamValueLookups, etc. reference the correct source steps... for (int i = 0; i < nrSteps(); i++) { StepMetaInterface sii = getStep(i).getStepMetaInterface(); sii.searchInfoAndTargetSteps(steps); } if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.ReadingHopTask.Title")); //$NON-NLS-1$ for (int i = 0; i < hopids.length; i++) { TransHopMeta hi = new TransHopMeta(rep, hopids[i], steps); addTransHop(hi); if (monitor != null) monitor.worked(1); } // Have all step partitioning meta-data reference the correct schemas that we just loaded for (int i = 0; i < nrSteps(); i++) { StepPartitioningMeta stepPartitioningMeta = getStep(i).getStepPartitioningMeta(); if (stepPartitioningMeta!=null) { stepPartitioningMeta.setPartitionSchemaAfterLoading(partitionSchemas); } } // Have all step clustering schema meta-data reference the correct cluster schemas that we just loaded for (int i = 0; i < nrSteps(); i++) { getStep(i).setClusterSchemaAfterLoading(clusterSchemas); } if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.LoadingTransformationDetailsTask.Title")); //$NON-NLS-1$ loadRepTrans(rep); if (monitor != null) monitor.worked(1); // Have all partitioned step reference the correct partitioning schema for (int i = 0; i < nrSteps(); i++) { getStep(i).getStepPartitioningMeta().setPartitionSchemaAfterLoading(partitionSchemas); } if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.ReadingTheDependenciesTask.Title")); //$NON-NLS-1$ long depids[] = rep.getTransDependencyIDs(getID()); for (int i = 0; i < depids.length; i++) { TransDependency td = new TransDependency(rep, depids[i], databases); addDependency(td); } if (monitor != null) monitor.worked(1); if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.SortingStepsTask.Title")); //$NON-NLS-1$ sortSteps(); if (monitor != null) monitor.worked(1); if (monitor != null) monitor.done(); } else { throw new KettleException(Messages.getString("TransMeta.Exception.TransformationDoesNotExist") + name); //$NON-NLS-1$ } log.logDetailed(toString(), Messages.getString("TransMeta.Log.LoadedTransformation2", transname , String.valueOf(directory == null))); //$NON-NLS-1$ //$NON-NLS-2$ log.logDetailed(toString(), Messages.getString("TransMeta.Log.LoadedTransformation", transname , directory.getPath() )); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } catch (KettleDatabaseException e) { log.logError(toString(), Messages.getString("TransMeta.Log.DatabaseErrorOccuredReadingTransformation") + Const.CR + e); //$NON-NLS-1$ throw new KettleException(Messages.getString("TransMeta.Exception.DatabaseErrorOccuredReadingTransformation"), e); //$NON-NLS-1$ } catch (Exception e) { log.logError(toString(), Messages.getString("TransMeta.Log.DatabaseErrorOccuredReadingTransformation") + Const.CR + e); //$NON-NLS-1$ throw new KettleException(Messages.getString("TransMeta.Exception.DatabaseErrorOccuredReadingTransformation2"), e); //$NON-NLS-1$ } finally { if (setInternalVariables) setInternalKettleVariables(); } } /** * Find the location of hop * * @param hi The hop queried * @return The location of the hop, -1 if nothing was found. */ public int indexOfTransHop(TransHopMeta hi) { return hops.indexOf(hi); } /** * Find the location of step * * @param stepMeta The step queried * @return The location of the step, -1 if nothing was found. */ public int indexOfStep(StepMeta stepMeta) { return steps.indexOf(stepMeta); } /** * Find the location of database * * @param ci The database queried * @return The location of the database, -1 if nothing was found. */ public int indexOfDatabase(DatabaseMeta ci) { return databases.indexOf(ci); } /** * Find the location of a note * * @param ni The note queried * @return The location of the note, -1 if nothing was found. */ public int indexOfNote(NotePadMeta ni) { return notes.indexOf(ni); } public String getXML() { Props props = null; if (Props.isInitialized()) props=Props.getInstance(); StringBuffer retval = new StringBuffer(); retval.append("<"+XML_TAG+">" + Const.CR); //$NON-NLS-1$ retval.append(" <info>" + Const.CR); //$NON-NLS-1$ retval.append(" " + XMLHandler.addTagValue("name", name)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" " + XMLHandler.addTagValue("directory", directory != null ? directory.getPath() : RepositoryDirectory.DIRECTORY_SEPARATOR)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" <log>" + Const.CR); //$NON-NLS-1$ retval.append(" " + XMLHandler.addTagValue("read", readStep == null ? "" : readStep.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ retval.append(" " + XMLHandler.addTagValue("write", writeStep == null ? "" : writeStep.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ retval.append(" " + XMLHandler.addTagValue("input", inputStep == null ? "" : inputStep.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ retval.append(" " + XMLHandler.addTagValue("output", outputStep == null ? "" : outputStep.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ retval.append(" " + XMLHandler.addTagValue("update", updateStep == null ? "" : updateStep.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ retval.append(" " + XMLHandler.addTagValue("connection", logConnection == null ? "" : logConnection.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ retval.append(" " + XMLHandler.addTagValue("table", logTable)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" " + XMLHandler.addTagValue("use_batchid", useBatchId)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" " + XMLHandler.addTagValue("use_logfield", logfieldUsed)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" </log>" + Const.CR); //$NON-NLS-1$ retval.append(" <maxdate>" + Const.CR); //$NON-NLS-1$ retval.append(" " + XMLHandler.addTagValue("connection", maxDateConnection == null ? "" : maxDateConnection.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ retval.append(" " + XMLHandler.addTagValue("table", maxDateTable)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" " + XMLHandler.addTagValue("field", maxDateField)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" " + XMLHandler.addTagValue("offset", maxDateOffset)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" " + XMLHandler.addTagValue("maxdiff", maxDateDifference)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" </maxdate>" + Const.CR); //$NON-NLS-1$ retval.append(" " + XMLHandler.addTagValue("size_rowset", sizeRowset)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" " + XMLHandler.addTagValue("sleep_time_empty", sleepTimeEmpty)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" " + XMLHandler.addTagValue("sleep_time_full", sleepTimeFull)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" " + XMLHandler.addTagValue("unique_connections", usingUniqueConnections)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" " + XMLHandler.addTagValue("feedback_shown", feedbackShown)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" " + XMLHandler.addTagValue("feedback_size", feedbackSize)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" " + XMLHandler.addTagValue("using_thread_priorities", usingThreadPriorityManagment)); // $NON-NLS-1$ retval.append(" <dependencies>" + Const.CR); //$NON-NLS-1$ for (int i = 0; i < nrDependencies(); i++) { TransDependency td = getDependency(i); retval.append(td.getXML()); } retval.append(" </dependencies>" + Const.CR); //$NON-NLS-1$ // The database partitioning schemas... retval.append(" <partitionschemas>" + Const.CR); //$NON-NLS-1$ for (int i = 0; i < partitionSchemas.size(); i++) { PartitionSchema partitionSchema = (PartitionSchema) partitionSchemas.get(i); retval.append(partitionSchema.getXML()); } retval.append(" </partitionschemas>" + Const.CR); //$NON-NLS-1$ // The slave servers... retval.append(" <slaveservers>" + Const.CR); //$NON-NLS-1$ for (int i = 0; i < slaveServers.size(); i++) { SlaveServer slaveServer = (SlaveServer) slaveServers.get(i); retval.append(" ").append(slaveServer.getXML()).append(Const.CR); } retval.append(" </slaveservers>" + Const.CR); //$NON-NLS-1$ // The cluster schemas... retval.append(" <clusterschemas>" + Const.CR); //$NON-NLS-1$ for (int i = 0; i < clusterSchemas.size(); i++) { ClusterSchema clusterSchema = (ClusterSchema) clusterSchemas.get(i); retval.append(clusterSchema.getXML()); } retval.append(" </clusterschemas>" + Const.CR); //$NON-NLS-1$ retval.append(" "+XMLHandler.addTagValue("modified_user", modifiedUser)); retval.append(" "+XMLHandler.addTagValue("modified_date", modifiedDate!=null?modifiedDate.getString():"")); retval.append(" </info>" + Const.CR); //$NON-NLS-1$ retval.append(" <notepads>" + Const.CR); //$NON-NLS-1$ if (notes != null) for (int i = 0; i < nrNotes(); i++) { NotePadMeta ni = getNote(i); retval.append(ni.getXML()); } retval.append(" </notepads>" + Const.CR); //$NON-NLS-1$ // The database connections... for (int i = 0; i < nrDatabases(); i++) { DatabaseMeta dbMeta = getDatabase(i); if (props!=null && props.areOnlyUsedConnectionsSavedToXML()) { if (isDatabaseConnectionUsed(dbMeta)) retval.append(dbMeta.getXML()); } else { retval.append(dbMeta.getXML()); } } retval.append(" <order>" + Const.CR); //$NON-NLS-1$ for (int i = 0; i < nrTransHops(); i++) { TransHopMeta transHopMeta = getTransHop(i); retval.append(transHopMeta.getXML()); } retval.append(" </order>" + Const.CR + Const.CR); //$NON-NLS-1$ for (int i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); retval.append(stepMeta.getXML()); } retval.append("</"+XML_TAG+">" + Const.CR); //$NON-NLS-1$ return retval.toString(); } /** * Parse a file containing the XML that describes the transformation. * No default connections are loaded since no repository is available at this time. * Since the filename is set, internal variables are being set that relate to this. * * @param fname The filename */ public TransMeta(String fname) throws KettleXMLException { this(fname, true); } /** * Parse a file containing the XML that describes the transformation. * No default connections are loaded since no repository is available at this time. * * @param fname The filename * @param setInternalVariables true if you want to set the internal variables based on this transformation information */ public TransMeta(String fname, boolean setInternalVariables) throws KettleXMLException { this(fname, null, setInternalVariables); } /** * Parse a file containing the XML that describes the transformation. * * @param fname The filename * @param rep The repository to load the default set of connections from, null if no repository is avaailable */ public TransMeta(String fname, Repository rep) throws KettleXMLException { this(fname, rep, true); } /** * Parse a file containing the XML that describes the transformation. * * @param fname The filename * @param rep The repository to load the default set of connections from, null if no repository is avaailable * @param setInternalVariables true if you want to set the internal variables based on this transformation information */ public TransMeta(String fname, Repository rep, boolean setInternalVariables ) throws KettleXMLException { Document doc = XMLHandler.loadXMLFile(fname); if (doc != null) { // Clear the transformation clearUndo(); clear(); // Root node: Node transnode = XMLHandler.getSubNode(doc, "transformation"); //$NON-NLS-1$ // Load from this node... loadXML(transnode, rep, setInternalVariables); setFilename(fname); } else { throw new KettleXMLException(Messages.getString("TransMeta.Exception.ErrorOpeningOrValidatingTheXMLFile", fname)); //$NON-NLS-1$ } } /** * Load the transformation from an XML node * * @param transnode The XML node to parse * @throws KettleXMLException */ public TransMeta(Node transnode) throws KettleXMLException { loadXML(transnode); } /** * Parse a file containing the XML that describes the transformation. * (no repository is available to load default list of database connections from) * * @param transnode The XML node to load from * @throws KettleXMLException */ private void loadXML(Node transnode) throws KettleXMLException { loadXML(transnode, null, false); } /** * Parse a file containing the XML that describes the transformation. * * @param transnode The XML node to load from * @param rep The repository to load the default list of database connections from (null if no repository is available) * @param setInternalVariables true if you want to set the internal variables based on this transformation information * @throws KettleXMLException */ private void loadXML(Node transnode, Repository rep, boolean setInternalVariables ) throws KettleXMLException { Props props = null; if (Props.isInitialized()) { props=Props.getInstance(); } try { // Clear the transformation clearUndo(); clear(); // Read all the database connections from the repository to make sure that we don't overwrite any there by loading from XML. try { readSharedObjects(rep); clearChanged(); } catch(KettleException e) { throw new KettleXMLException(Messages.getString("TransMeta.Exception.UnableToReadSharedObjectsFromRepository.Message"), e); } // Handle connections int n = XMLHandler.countNodes(transnode, "connection"); //$NON-NLS-1$ log.logDebug(toString(), Messages.getString("TransMeta.Log.WeHaveConnections", String.valueOf(n) )); //$NON-NLS-1$ //$NON-NLS-2$ for (int i = 0; i < n; i++) { log.logDebug(toString(), Messages.getString("TransMeta.Log.LookingAtConnection") + i); //$NON-NLS-1$ Node nodecon = XMLHandler.getSubNodeByNr(transnode, "connection", i); //$NON-NLS-1$ DatabaseMeta dbcon = new DatabaseMeta(nodecon); DatabaseMeta exist = findDatabase(dbcon.getName()); if (exist == null) { addDatabase(dbcon); } else { if (!exist.isShared()) // otherwise, we just keep the shared connection. { boolean askOverwrite = Props.isInitialized() ? props.askAboutReplacingDatabaseConnections() : false; boolean overwrite = Props.isInitialized() ? props.replaceExistingDatabaseConnections() : true; if (askOverwrite) { // That means that we have a Display variable set in Props... if (props.getDisplay()!=null) { Shell shell = props.getDisplay().getActiveShell(); MessageDialogWithToggle md = new MessageDialogWithToggle(shell, "Warning", null, "Connection ["+dbcon.getName()+"] already exists, do you want to overwrite this database connection?", MessageDialog.WARNING, new String[] { "Yes", "No" },//"Yes", "No" 1, "Please, don't show this warning anymore.", !props.askAboutReplacingDatabaseConnections() ); int idx = md.open(); props.setAskAboutReplacingDatabaseConnections(!md.getToggleState()); overwrite = ((idx&0xFF)==0); // Yes means: overwrite } } if (overwrite) { int idx = indexOfDatabase(exist); removeDatabase(idx); addDatabase(idx, dbcon); } } } } // Read the notes... Node notepadsnode = XMLHandler.getSubNode(transnode, "notepads"); //$NON-NLS-1$ int nrnotes = XMLHandler.countNodes(notepadsnode, "notepad"); //$NON-NLS-1$ for (int i = 0; i < nrnotes; i++) { Node notepadnode = XMLHandler.getSubNodeByNr(notepadsnode, "notepad", i); //$NON-NLS-1$ NotePadMeta ni = new NotePadMeta(notepadnode); notes.add(ni); } // Handle Steps int s = XMLHandler.countNodes(transnode, "step"); //$NON-NLS-1$ log.logDebug(toString(), Messages.getString("TransMeta.Log.ReadingSteps") + s + " steps..."); //$NON-NLS-1$ //$NON-NLS-2$ for (int i = 0; i < s; i++) { Node stepnode = XMLHandler.getSubNodeByNr(transnode, "step", i); //$NON-NLS-1$ log.logDebug(toString(), Messages.getString("TransMeta.Log.LookingAtStep") + i); //$NON-NLS-1$ StepMeta stepMeta = new StepMeta(stepnode, databases, counters); // Check if the step exists and if it's a shared step. // If so, then we will keep the shared version, not this one. // The stored XML is only for backup purposes. StepMeta check = findStep(stepMeta.getName()); if (check!=null) { if (!check.isShared()) // Don't overwrite shared objects { addOrReplaceStep(stepMeta); } else { check.setDraw(stepMeta.isDrawn()); // Just keep the drawn flag and location check.setLocation(stepMeta.getLocation()); } } else { addStep(stepMeta); // simply add it. } } // Have all StreamValueLookups, etc. reference the correct source steps... for (int i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); StepMetaInterface sii = stepMeta.getStepMetaInterface(); if (sii != null) sii.searchInfoAndTargetSteps(steps); } // Handle Hops Node ordernode = XMLHandler.getSubNode(transnode, "order"); //$NON-NLS-1$ n = XMLHandler.countNodes(ordernode, "hop"); //$NON-NLS-1$ log.logDebug(toString(), Messages.getString("TransMeta.Log.WeHaveHops") + n + " hops..."); //$NON-NLS-1$ //$NON-NLS-2$ for (int i = 0; i < n; i++) { log.logDebug(toString(), Messages.getString("TransMeta.Log.LookingAtHop") + i); //$NON-NLS-1$ Node hopnode = XMLHandler.getSubNodeByNr(ordernode, "hop", i); //$NON-NLS-1$ TransHopMeta hopinf = new TransHopMeta(hopnode, steps); addTransHop(hopinf); } // get transformation info: Node infonode = XMLHandler.getSubNode(transnode, "info"); //$NON-NLS-1$ // Name name = XMLHandler.getTagValue(infonode, "name"); //$NON-NLS-1$ /* * Directory String directoryPath = XMLHandler.getTagValue(infonode, "directory"); */ // Logging method... readStep = findStep(XMLHandler.getTagValue(infonode, "log", "read")); //$NON-NLS-1$ //$NON-NLS-2$ writeStep = findStep(XMLHandler.getTagValue(infonode, "log", "write")); //$NON-NLS-1$ //$NON-NLS-2$ inputStep = findStep(XMLHandler.getTagValue(infonode, "log", "input")); //$NON-NLS-1$ //$NON-NLS-2$ outputStep = findStep(XMLHandler.getTagValue(infonode, "log", "output")); //$NON-NLS-1$ //$NON-NLS-2$ updateStep = findStep(XMLHandler.getTagValue(infonode, "log", "update")); //$NON-NLS-1$ //$NON-NLS-2$ String logcon = XMLHandler.getTagValue(infonode, "log", "connection"); //$NON-NLS-1$ //$NON-NLS-2$ logConnection = findDatabase(logcon); logTable = XMLHandler.getTagValue(infonode, "log", "table"); //$NON-NLS-1$ //$NON-NLS-2$ useBatchId = "Y".equalsIgnoreCase(XMLHandler.getTagValue(infonode, "log", "use_batchid")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ logfieldUsed= "Y".equalsIgnoreCase(XMLHandler.getTagValue(infonode, "log", "USE_LOGFIELD")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // Maxdate range options... String maxdatcon = XMLHandler.getTagValue(infonode, "maxdate", "connection"); //$NON-NLS-1$ //$NON-NLS-2$ maxDateConnection = findDatabase(maxdatcon); maxDateTable = XMLHandler.getTagValue(infonode, "maxdate", "table"); //$NON-NLS-1$ //$NON-NLS-2$ maxDateField = XMLHandler.getTagValue(infonode, "maxdate", "field"); //$NON-NLS-1$ //$NON-NLS-2$ String offset = XMLHandler.getTagValue(infonode, "maxdate", "offset"); //$NON-NLS-1$ //$NON-NLS-2$ maxDateOffset = Const.toDouble(offset, 0.0); String mdiff = XMLHandler.getTagValue(infonode, "maxdate", "maxdiff"); //$NON-NLS-1$ //$NON-NLS-2$ maxDateDifference = Const.toDouble(mdiff, 0.0); // Check the dependencies as far as dates are concerned... // We calculate BEFORE we run the MAX of these dates // If the date is larger then enddate, startdate is set to MIN_DATE Node depsNode = XMLHandler.getSubNode(infonode, "dependencies"); //$NON-NLS-1$ int nrDeps = XMLHandler.countNodes(depsNode, "dependency"); //$NON-NLS-1$ for (int i = 0; i < nrDeps; i++) { Node depNode = XMLHandler.getSubNodeByNr(depsNode, "dependency", i); //$NON-NLS-1$ TransDependency transDependency = new TransDependency(depNode, databases); if (transDependency.getDatabase() != null && transDependency.getFieldname() != null) { addDependency(transDependency); } } // Read the partitioning schemas Node partSchemasNode = XMLHandler.getSubNode(infonode, "partitionschemas"); //$NON-NLS-1$ int nrPartSchemas = XMLHandler.countNodes(partSchemasNode, PartitionSchema.XML_TAG); //$NON-NLS-1$ for (int i = 0 ; i < nrPartSchemas ; i++) { Node partSchemaNode = XMLHandler.getSubNodeByNr(partSchemasNode, PartitionSchema.XML_TAG, i); PartitionSchema partitionSchema = new PartitionSchema(partSchemaNode); // Check if the step exists and if it's a shared step. // If so, then we will keep the shared version, not this one. // The stored XML is only for backup purposes. PartitionSchema check = findPartitionSchema(partitionSchema.getName()); if (check!=null) { if (!check.isShared()) // we don't overwrite shared objects. { addOrReplacePartitionSchema(partitionSchema); } } else { partitionSchemas.add(partitionSchema); } } // Have all step partitioning meta-data reference the correct schemas that we just loaded for (int i = 0; i < nrSteps(); i++) { StepPartitioningMeta stepPartitioningMeta = getStep(i).getStepPartitioningMeta(); if (stepPartitioningMeta!=null) { stepPartitioningMeta.setPartitionSchemaAfterLoading(partitionSchemas); } } // Read the slave servers... Node slaveServersNode = XMLHandler.getSubNode(infonode, "slaveservers"); //$NON-NLS-1$ int nrSlaveServers = XMLHandler.countNodes(slaveServersNode, SlaveServer.XML_TAG); //$NON-NLS-1$ for (int i = 0 ; i < nrSlaveServers ; i++) { Node slaveServerNode = XMLHandler.getSubNodeByNr(slaveServersNode, SlaveServer.XML_TAG, i); SlaveServer slaveServer = new SlaveServer(slaveServerNode); // Check if the object exists and if it's a shared object. // If so, then we will keep the shared version, not this one. // The stored XML is only for backup purposes. SlaveServer check = findSlaveServer(slaveServer.getName()); if (check!=null) { if (!check.isShared()) // we don't overwrite shared objects. { addOrReplaceSlaveServer(slaveServer); } } else { slaveServers.add(slaveServer); } } // Read the cluster schemas Node clusterSchemasNode = XMLHandler.getSubNode(infonode, "clusterschemas"); //$NON-NLS-1$ int nrClusterSchemas = XMLHandler.countNodes(clusterSchemasNode, ClusterSchema.XML_TAG); //$NON-NLS-1$ for (int i = 0 ; i < nrClusterSchemas ; i++) { Node clusterSchemaNode = XMLHandler.getSubNodeByNr(clusterSchemasNode, ClusterSchema.XML_TAG, i); ClusterSchema clusterSchema = new ClusterSchema(clusterSchemaNode, slaveServers); System.out.println("Loaded "+clusterSchema.getSlaveServers().size()+" servers in cluster "+clusterSchema.getName()); // Check if the object exists and if it's a shared object. // If so, then we will keep the shared version, not this one. // The stored XML is only for backup purposes. ClusterSchema check = findClusterSchema(clusterSchema.getName()); if (check!=null) { if (!check.isShared()) // we don't overwrite shared objects. { addOrReplaceClusterSchema(clusterSchema); } } else { clusterSchemas.add(clusterSchema); } } // Have all step clustering schema meta-data reference the correct cluster schemas that we just loaded for (int i = 0; i < nrSteps(); i++) { getStep(i).setClusterSchemaAfterLoading(clusterSchemas); } String srowset = XMLHandler.getTagValue(infonode, "size_rowset"); //$NON-NLS-1$ sizeRowset = Const.toInt(srowset, Const.ROWS_IN_ROWSET); sleepTimeEmpty = Const.toInt(XMLHandler.getTagValue(infonode, "sleep_time_empty"), Const.SLEEP_EMPTY_NANOS); //$NON-NLS-1$ sleepTimeFull = Const.toInt(XMLHandler.getTagValue(infonode, "sleep_time_full"), Const.SLEEP_FULL_NANOS); //$NON-NLS-1$ usingUniqueConnections = "Y".equalsIgnoreCase( XMLHandler.getTagValue(infonode, "unique_connections") ); //$NON-NLS-1$ feedbackShown = !"N".equalsIgnoreCase( XMLHandler.getTagValue(infonode, "feedback_shown") ); //$NON-NLS-1$ feedbackSize = Const.toInt(XMLHandler.getTagValue(infonode, "feedback_size"), Const.ROWS_UPDATE); //$NON-NLS-1$ usingThreadPriorityManagment = !"N".equalsIgnoreCase( XMLHandler.getTagValue(infonode, "using_thread_priorities") ); //$NON-NLS-1$ // Changed user/date modifiedUser = XMLHandler.getTagValue(infonode, "modified_user"); String modDate = XMLHandler.getTagValue(infonode, "modified_date"); if (modDate!=null) { modifiedDate = new Value(STRING_MODIFIED_DATE, modDate); modifiedDate.setType(Value.VALUE_TYPE_DATE); } log.logDebug(toString(), Messages.getString("TransMeta.Log.NumberOfStepsReaded") + nrSteps()); //$NON-NLS-1$ log.logDebug(toString(), Messages.getString("TransMeta.Log.NumberOfHopsReaded") + nrTransHops()); //$NON-NLS-1$ sortSteps(); } catch (KettleXMLException xe) { throw new KettleXMLException(Messages.getString("TransMeta.Exception.ErrorReadingTransformation"), xe); //$NON-NLS-1$ } finally { if (setInternalVariables) setInternalKettleVariables(); } } public void readSharedObjects(Repository rep) throws KettleException { // Extract the shared steps, connections, etc. using the SharedObjects class String soFile = StringUtil.environmentSubstitute(sharedObjectsFile); SharedObjects sharedObjects = new SharedObjects(soFile); Map objectsMap = sharedObjects.getObjectsMap(); Collection objects = objectsMap.values(); // First read the databases... // We read databases & slaves first because there might be dependencies that need to be resolved. for (Iterator iter = objects.iterator(); iter.hasNext();) { Object object = iter.next(); if (object instanceof DatabaseMeta) { DatabaseMeta databaseMeta = (DatabaseMeta) object; addOrReplaceDatabase(databaseMeta); } else if (object instanceof SlaveServer) { SlaveServer slaveServer = (SlaveServer) object; addOrReplaceSlaveServer(slaveServer); } else if (object instanceof StepMeta) { StepMeta stepMeta = (StepMeta) object; addOrReplaceStep(stepMeta); } else if (object instanceof PartitionSchema) { PartitionSchema partitionSchema = (PartitionSchema) object; addOrReplacePartitionSchema(partitionSchema); } else if (object instanceof ClusterSchema) { ClusterSchema clusterSchema = (ClusterSchema) object; addOrReplaceClusterSchema(clusterSchema); } } if (rep!=null) { readDatabases(rep, true); readPartitionSchemas(rep, true); readSlaves(rep, true); readClusters(rep, true); } } /** * Gives you an ArrayList of all the steps that are at least used in one active hop. These steps will be used to * execute the transformation. The others will not be executed. * * @param all Set to true if you want to get ALL the steps from the transformation. * @return A ArrayList of steps */ public ArrayList getTransHopSteps(boolean all) { ArrayList st = new ArrayList(); int idx; for (int x = 0; x < nrTransHops(); x++) { TransHopMeta hi = getTransHop(x); if (hi.isEnabled() || all) { idx = st.indexOf(hi.getFromStep()); // FROM if (idx < 0) st.add(hi.getFromStep()); idx = st.indexOf(hi.getToStep()); if (idx < 0) st.add(hi.getToStep()); } } // Also, add the steps that need to be painted, but are not part of a hop for (int x = 0; x < nrSteps(); x++) { StepMeta stepMeta = getStep(x); if (stepMeta.isDrawn() && !isStepUsedInTransHops(stepMeta)) { st.add(stepMeta); } } return st; } /** * Get the name of the transformation * * @return The name of the transformation */ public String getName() { return name; } /** * Set the name of the transformation. * * @param n The new name of the transformation */ public void setName(String n) { name = n; setInternalKettleVariables(); } /** * Get the filename (if any) of the transformation * * @return The filename of the transformation. */ public String getFilename() { return filename; } /** * Set the filename of the transformation * * @param fname The new filename of the transformation. */ public void setFilename(String fname) { filename = fname; setInternalKettleVariables(); } /** * Determines if a step has been used in a hop or not. * * @param stepMeta The step queried. * @return True if a step is used in a hop (active or not), false if this is not the case. */ public boolean isStepUsedInTransHops(StepMeta stepMeta) { TransHopMeta fr = findTransHopFrom(stepMeta); TransHopMeta to = findTransHopTo(stepMeta); if (fr != null || to != null) return true; return false; } /** * Mark the transformation as being changed. * */ public void setChanged() { setChanged(true); } /** * Sets the changed parameter of the transformation. * * @param ch True if you want to mark the transformation as changed, false if not. */ public void setChanged(boolean ch) { changed = ch; } /** * Clears the different changed flags of the transformation. * */ public void clearChanged() { changed = false; changed_steps = false; changed_databases = false; changed_hops = false; changed_notes = false; for (int i = 0; i < nrSteps(); i++) { getStep(i).setChanged(false); } for (int i = 0; i < nrDatabases(); i++) { getDatabase(i).setChanged(false); } for (int i = 0; i < nrTransHops(); i++) { getTransHop(i).setChanged(false); } for (int i = 0; i < nrNotes(); i++) { getNote(i).setChanged(false); } for (int i = 0; i < partitionSchemas.size(); i++) { ((PartitionSchema)partitionSchemas.get(i)).setChanged(false); } for (int i = 0; i < clusterSchemas.size(); i++) { ((ClusterSchema)clusterSchemas.get(i)).setChanged(false); } } /** * Checks whether or not the connections have changed. * * @return True if the connections have been changed. */ public boolean haveConnectionsChanged() { if (changed_databases) return true; for (int i = 0; i < nrDatabases(); i++) { DatabaseMeta ci = getDatabase(i); if (ci.hasChanged()) return true; } return false; } /** * Checks whether or not the steps have changed. * * @return True if the connections have been changed. */ public boolean haveStepsChanged() { if (changed_steps) return true; for (int i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); if (stepMeta.hasChanged()) return true; } return false; } /** * Checks whether or not any of the hops have been changed. * * @return True if a hop has been changed. */ public boolean haveHopsChanged() { if (changed_hops) return true; for (int i = 0; i < nrTransHops(); i++) { TransHopMeta hi = getTransHop(i); if (hi.hasChanged()) return true; } return false; } /** * Checks whether or not any of the notes have been changed. * * @return True if the notes have been changed. */ public boolean haveNotesChanged() { if (changed_notes) return true; for (int i = 0; i < nrNotes(); i++) { NotePadMeta ni = getNote(i); if (ni.hasChanged()) return true; } return false; } /** * Checks whether or not any of the database partitioning schemas have been changed. * * @return True if the partitioning schemas have been changed. */ public boolean havePartitionSchemasChanged() { for (int i = 0; i < partitionSchemas.size(); i++) { PartitionSchema ps = (PartitionSchema) partitionSchemas.get(i); if (ps.hasChanged()) return true; } return false; } /** * Checks whether or not any of the clustering schemas have been changed. * * @return True if the clustering schemas have been changed. */ public boolean haveClusterSchemasChanged() { for (int i = 0; i < clusterSchemas.size(); i++) { ClusterSchema cs = (ClusterSchema) clusterSchemas.get(i); if (cs.hasChanged()) return true; } return false; } /** * Checks whether or not the transformation has changed. * * @return True if the transformation has changed. */ public boolean hasChanged() { if (changed) return true; if (haveConnectionsChanged()) return true; if (haveStepsChanged()) return true; if (haveHopsChanged()) return true; if (haveNotesChanged()) return true; if (havePartitionSchemasChanged()) return true; if (haveClusterSchemasChanged()) return true; return false; } /** * See if there are any loops in the transformation, starting at the indicated step. This works by looking at all * the previous steps. If you keep going backward and find the step, there is a loop. Both the informational and the * normal steps need to be checked for loops! * * @param stepMeta The step position to start looking * * @return True if a loop has been found, false if no loop is found. */ public boolean hasLoop(StepMeta stepMeta) { return hasLoop(stepMeta, null, true) || hasLoop(stepMeta, null, false); } /** * See if there are any loops in the transformation, starting at the indicated step. This works by looking at all * the previous steps. If you keep going backward and find the orginal step again, there is a loop. * * @param stepMeta The step position to start looking * @param lookup The original step when wandering around the transformation. * @param info Check the informational steps or not. * * @return True if a loop has been found, false if no loop is found. */ public boolean hasLoop(StepMeta stepMeta, StepMeta lookup, boolean info) { int nr = findNrPrevSteps(stepMeta, info); for (int i = 0; i < nr; i++) { StepMeta prevStepMeta = findPrevStep(stepMeta, i, info); if (prevStepMeta != null) { if (prevStepMeta.equals(stepMeta)) return true; if (prevStepMeta.equals(lookup)) return true; if (hasLoop(prevStepMeta, lookup == null ? stepMeta : lookup, info)) return true; } } return false; } /** * Mark all steps in the transformation as selected. * */ public void selectAll() { int i; for (i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); stepMeta.setSelected(true); } for (i = 0; i < nrNotes(); i++) { NotePadMeta ni = getNote(i); ni.setSelected(true); } } /** * Clear the selection of all steps. * */ public void unselectAll() { int i; for (i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); stepMeta.setSelected(false); } for (i = 0; i < nrNotes(); i++) { NotePadMeta ni = getNote(i); ni.setSelected(false); } } /** * Count the number of selected steps in this transformation * * @return The number of selected steps. */ public int nrSelectedSteps() { int i, count; count = 0; for (i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); if (stepMeta.isSelected() && stepMeta.isDrawn()) count++; } return count; } /** * Get the selected step at a certain location * * @param nr The location * @return The selected step */ public StepMeta getSelectedStep(int nr) { int i, count; count = 0; for (i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); if (stepMeta.isSelected() && stepMeta.isDrawn()) { if (nr == count) return stepMeta; count++; } } return null; } /** * Count the number of selected notes in this transformation * * @return The number of selected notes. */ public int nrSelectedNotes() { int i, count; count = 0; for (i = 0; i < nrNotes(); i++) { NotePadMeta ni = getNote(i); if (ni.isSelected()) count++; } return count; } /** * Get the selected note at a certain index * * @param nr The index * @return The selected note */ public NotePadMeta getSelectedNote(int nr) { int i, count; count = 0; for (i = 0; i < nrNotes(); i++) { NotePadMeta ni = getNote(i); if (ni.isSelected()) { if (nr == count) return ni; count++; } } return null; } /** * Select all the steps in a certain (screen) rectangle * * @param rect The selection area as a rectangle */ public void selectInRect(Rectangle rect) { for (int i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); Point a = stepMeta.getLocation(); if (rect.contains(a)) stepMeta.setSelected(true); } for (int i = 0; i < nrNotes(); i++) { NotePadMeta ni = getNote(i); Point a = ni.getLocation(); Point b = new Point(a.x + ni.width, a.y + ni.height); if (rect.contains(a) && rect.contains(b)) ni.setSelected(true); } } /** * Get an array of all the selected step and note locations * * @return The selected step and notes locations. */ public Point[] getSelectedStepLocations() { ArrayList points = new ArrayList(); for (int i = 0; i < nrSelectedSteps(); i++) { StepMeta stepMeta = getSelectedStep(i); Point p = stepMeta.getLocation(); points.add(new Point(p.x, p.y)); // explicit copy of location } return (Point[]) points.toArray(new Point[points.size()]); } /** * Get an array of all the selected step and note locations * * @return The selected step and notes locations. */ public Point[] getSelectedNoteLocations() { ArrayList points = new ArrayList(); for (int i = 0; i < nrSelectedNotes(); i++) { NotePadMeta ni = getSelectedNote(i); Point p = ni.getLocation(); points.add(new Point(p.x, p.y)); // explicit copy of location } return (Point[]) points.toArray(new Point[points.size()]); } /** * Get an array of all the selected steps * * @return An array of all the selected steps. */ public StepMeta[] getSelectedSteps() { int sels = nrSelectedSteps(); if (sels == 0) return null; StepMeta retval[] = new StepMeta[sels]; for (int i = 0; i < sels; i++) { StepMeta stepMeta = getSelectedStep(i); retval[i] = stepMeta; } return retval; } /** * Get an array of all the selected steps * * @return A list containing all the selected & drawn steps. */ public List getSelectedDrawnStepsList() { List list = new ArrayList(); for (int i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); if (stepMeta.isDrawn() && stepMeta.isSelected()) list.add(stepMeta); } return list; } /** * Get an array of all the selected notes * * @return An array of all the selected notes. */ public NotePadMeta[] getSelectedNotes() { int sels = nrSelectedNotes(); if (sels == 0) return null; NotePadMeta retval[] = new NotePadMeta[sels]; for (int i = 0; i < sels; i++) { NotePadMeta si = getSelectedNote(i); retval[i] = si; } return retval; } /** * Get an array of all the selected step names * * @return An array of all the selected step names. */ public String[] getSelectedStepNames() { int sels = nrSelectedSteps(); if (sels == 0) return null; String retval[] = new String[sels]; for (int i = 0; i < sels; i++) { StepMeta stepMeta = getSelectedStep(i); retval[i] = stepMeta.getName(); } return retval; } /** * Get an array of the locations of an array of steps * * @param steps An array of steps * @return an array of the locations of an array of steps */ public int[] getStepIndexes(StepMeta steps[]) { int retval[] = new int[steps.length]; for (int i = 0; i < steps.length; i++) { retval[i] = indexOfStep(steps[i]); } return retval; } /** * Get an array of the locations of an array of notes * * @param notes An array of notes * @return an array of the locations of an array of notes */ public int[] getNoteIndexes(NotePadMeta notes[]) { int retval[] = new int[notes.length]; for (int i = 0; i < notes.length; i++) retval[i] = indexOfNote(notes[i]); return retval; } /** * Get the maximum number of undo operations possible * * @return The maximum number of undo operations that are allowed. */ public int getMaxUndo() { return max_undo; } /** * Sets the maximum number of undo operations that are allowed. * * @param mu The maximum number of undo operations that are allowed. */ public void setMaxUndo(int mu) { max_undo = mu; while (undo.size() > mu && undo.size() > 0) undo.remove(0); } /** * Add an undo operation to the undo list * * @param from array of objects representing the old state * @param to array of objectes representing the new state * @param pos An array of object locations * @param prev An array of points representing the old positions * @param curr An array of points representing the new positions * @param type_of_change The type of change that's being done to the transformation. * @param nextAlso indicates that the next undo operation needs to follow this one. */ public void addUndo(Object from[], Object to[], int pos[], Point prev[], Point curr[], int type_of_change, boolean nextAlso) { // First clean up after the current position. // Example: position at 3, size=5 // 012345 // remove 34 // Add 4 // 01234 while (undo.size() > undo_position + 1 && undo.size() > 0) { int last = undo.size() - 1; undo.remove(last); } TransAction ta = new TransAction(); switch (type_of_change) { case TYPE_UNDO_CHANGE: ta.setChanged(from, to, pos); break; case TYPE_UNDO_DELETE: ta.setDelete(from, pos); break; case TYPE_UNDO_NEW: ta.setNew(from, pos); break; case TYPE_UNDO_POSITION: ta.setPosition(from, pos, prev, curr); break; } ta.setNextAlso(nextAlso); undo.add(ta); undo_position++; if (undo.size() > max_undo) { undo.remove(0); undo_position } } /** * Get the previous undo operation and change the undo pointer * * @return The undo transaction to be performed. */ public TransAction previousUndo() { if (undo.size() == 0 || undo_position < 0) return null; // No undo left! TransAction retval = (TransAction) undo.get(undo_position); undo_position return retval; } /** * View current undo, don't change undo position * * @return The current undo transaction */ public TransAction viewThisUndo() { if (undo.size() == 0 || undo_position < 0) return null; // No undo left! TransAction retval = (TransAction) undo.get(undo_position); return retval; } /** * View previous undo, don't change undo position * * @return The previous undo transaction */ public TransAction viewPreviousUndo() { if (undo.size() == 0 || undo_position - 1 < 0) return null; // No undo left! TransAction retval = (TransAction) undo.get(undo_position - 1); return retval; } /** * Get the next undo transaction on the list. Change the undo pointer. * * @return The next undo transaction (for redo) */ public TransAction nextUndo() { int size = undo.size(); if (size == 0 || undo_position >= size - 1) return null; // no redo left... undo_position++; TransAction retval = (TransAction) undo.get(undo_position); return retval; } /** * Get the next undo transaction on the list. * * @return The next undo transaction (for redo) */ public TransAction viewNextUndo() { int size = undo.size(); if (size == 0 || undo_position >= size - 1) return null; // no redo left... TransAction retval = (TransAction) undo.get(undo_position + 1); return retval; } /** * Get the maximum size of the canvas by calculating the maximum location of a step * * @return Maximum coordinate of a step in the transformation + (100,100) for safety. */ public Point getMaximum() { int maxx = 0, maxy = 0; for (int i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); Point loc = stepMeta.getLocation(); if (loc.x > maxx) maxx = loc.x; if (loc.y > maxy) maxy = loc.y; } for (int i = 0; i < nrNotes(); i++) { NotePadMeta notePadMeta = getNote(i); Point loc = notePadMeta.getLocation(); if (loc.x + notePadMeta.width > maxx) maxx = loc.x + notePadMeta.width; if (loc.y + notePadMeta.height > maxy) maxy = loc.y + notePadMeta.height; } return new Point(maxx + 100, maxy + 100); } /** * Get the names of all the steps. * * @return An array of step names. */ public String[] getStepNames() { String retval[] = new String[nrSteps()]; for (int i = 0; i < nrSteps(); i++) retval[i] = getStep(i).getName(); return retval; } /** * Get all the steps in an array. * * @return An array of all the steps in the transformation. */ public StepMeta[] getStepsArray() { StepMeta retval[] = new StepMeta[nrSteps()]; for (int i = 0; i < nrSteps(); i++) retval[i] = getStep(i); return retval; } /** * Find a step with the ID in a given ArrayList of steps * * @param steps The ArrayList of steps * @param id The ID of the step * @return The step if it was found, null if nothing was found */ public static final StepMeta findStep(ArrayList steps, long id) { if (steps == null) return null; for (int i = 0; i < steps.size(); i++) { StepMeta stepMeta = (StepMeta) steps.get(i); if (stepMeta.getID() == id) return stepMeta; } return null; } /** * Find a step with its name in a given ArrayList of steps * * @param steps The ArrayList of steps * @param stepname The name of the step * @return The step if it was found, null if nothing was found */ public static final StepMeta findStep(ArrayList steps, String stepname) { if (steps == null) return null; for (int i = 0; i < steps.size(); i++) { StepMeta stepMeta = (StepMeta) steps.get(i); if (stepMeta.getName().equalsIgnoreCase(stepname)) return stepMeta; } return null; } /** * Look in the transformation and see if we can find a step in a previous location starting somewhere. * * @param startStep The starting step * @param stepToFind The step to look for backward in the transformation * @return true if we can find the step in an earlier location in the transformation. */ public boolean findPrevious(StepMeta startStep, StepMeta stepToFind) { // Normal steps int nrPrevious = findNrPrevSteps(startStep, false); for (int i = 0; i < nrPrevious; i++) { StepMeta stepMeta = findPrevStep(startStep, i, false); if (stepMeta.equals(stepToFind)) return true; boolean found = findPrevious(stepMeta, stepToFind); // Look further back in the tree. if (found) return true; } // Info steps nrPrevious = findNrPrevSteps(startStep, true); for (int i = 0; i < nrPrevious; i++) { StepMeta stepMeta = findPrevStep(startStep, i, true); if (stepMeta.equals(stepToFind)) return true; boolean found = findPrevious(stepMeta, stepToFind); // Look further back in the tree. if (found) return true; } return false; } /** * Put the steps in alfabetical order. */ public void sortSteps() { try { Const.quickSort(steps); } catch (Exception e) { System.out.println(Messages.getString("TransMeta.Exception.ErrorOfSortingSteps") + e); //$NON-NLS-1$ e.printStackTrace(); } } public void sortHops() { Const.quickSort(hops); } /** * Put the steps in a more natural order: from start to finish. For the moment, we ignore splits and joins. Splits * and joins can't be listed sequentially in any case! * */ public void sortStepsNatural() { // Loop over the steps... for (int j = 0; j < nrSteps(); j++) { // Buble sort: we need to do this several times... for (int i = 0; i < nrSteps() - 1; i++) { StepMeta one = getStep(i); StepMeta two = getStep(i + 1); if (!findPrevious(two, one)) { setStep(i + 1, one); setStep(i, two); } } } } /** * Sort the hops in a natural way: from beginning to end */ public void sortHopsNatural() { // Loop over the hops... for (int j = 0; j < nrTransHops(); j++) { // Buble sort: we need to do this several times... for (int i = 0; i < nrTransHops() - 1; i++) { TransHopMeta one = getTransHop(i); TransHopMeta two = getTransHop(i + 1); StepMeta a = two.getFromStep(); StepMeta b = one.getToStep(); if (!findPrevious(a, b) && !a.equals(b)) { setTransHop(i + 1, one); setTransHop(i, two); } } } } /** * This procedure determines the impact of the different steps in a transformation on databases, tables and field. * * @param impact An ArrayList of DatabaseImpact objects. * */ public void analyseImpact(ArrayList impact, IProgressMonitor monitor) throws KettleStepException { if (monitor != null) { monitor.beginTask(Messages.getString("TransMeta.Monitor.DeterminingImpactTask.Title"), nrSteps()); //$NON-NLS-1$ } boolean stop = false; for (int i = 0; i < nrSteps() && !stop; i++) { if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.LookingAtStepTask.Title") + (i + 1) + "/" + nrSteps()); //$NON-NLS-1$ //$NON-NLS-2$ StepMeta stepMeta = getStep(i); Row prev = getPrevStepFields(stepMeta); StepMetaInterface stepint = stepMeta.getStepMetaInterface(); Row inform = null; StepMeta[] lu = getInfoStep(stepMeta); if (lu != null) { inform = getStepFields(lu); } else { inform = stepint.getTableFields(); } stepint.analyseImpact(impact, this, stepMeta, prev, null, null, inform); if (monitor != null) { monitor.worked(1); stop = monitor.isCanceled(); } } if (monitor != null) monitor.done(); } /** * Proposes an alternative stepname when the original already exists... * * @param stepname The stepname to find an alternative for.. * @return The alternative stepname. */ public String getAlternativeStepname(String stepname) { String newname = stepname; StepMeta stepMeta = findStep(newname); int nr = 1; while (stepMeta != null) { nr++; newname = stepname + " " + nr; //$NON-NLS-1$ stepMeta = findStep(newname); } return newname; } /** * Builds a list of all the SQL statements that this transformation needs in order to work properly. * * @return An ArrayList of SQLStatement objects. */ public ArrayList getSQLStatements() throws KettleStepException { return getSQLStatements(null); } /** * Builds a list of all the SQL statements that this transformation needs in order to work properly. * * @return An ArrayList of SQLStatement objects. */ public ArrayList getSQLStatements(IProgressMonitor monitor) throws KettleStepException { if (monitor != null) monitor.beginTask(Messages.getString("TransMeta.Monitor.GettingTheSQLForTransformationTask.Title"), nrSteps() + 1); //$NON-NLS-1$ ArrayList stats = new ArrayList(); for (int i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.GettingTheSQLForStepTask.Title",""+stepMeta )); //$NON-NLS-1$ //$NON-NLS-2$ Row prev = getPrevStepFields(stepMeta); SQLStatement sql = stepMeta.getStepMetaInterface().getSQLStatements(this, stepMeta, prev); if (sql.getSQL() != null || sql.hasError()) { stats.add(sql); } if (monitor != null) monitor.worked(1); } // Also check the sql for the logtable... if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.GettingTheSQLForTransformationTask.Title2")); //$NON-NLS-1$ if (logConnection != null && logTable != null && logTable.length() > 0) { Database db = new Database(logConnection); try { db.connect(); Row fields = Database.getTransLogrecordFields(useBatchId, logfieldUsed); String sql = db.getDDL(logTable, fields); if (sql != null && sql.length() > 0) { SQLStatement stat = new SQLStatement("<this transformation>", logConnection, sql); //$NON-NLS-1$ stats.add(stat); } } catch (KettleDatabaseException dbe) { SQLStatement stat = new SQLStatement("<this transformation>", logConnection, null); //$NON-NLS-1$ stat.setError(Messages.getString("TransMeta.SQLStatement.ErrorDesc.ErrorObtainingTransformationLogTableInfo") + dbe.getMessage()); //$NON-NLS-1$ stats.add(stat); } finally { db.disconnect(); } } if (monitor != null) monitor.worked(1); if (monitor != null) monitor.done(); return stats; } /** * Get the SQL statements, needed to run this transformation, as one String. * * @return the SQL statements needed to run this transformation. */ public String getSQLStatementsString() throws KettleStepException { String sql = ""; //$NON-NLS-1$ ArrayList stats = getSQLStatements(); for (int i = 0; i < stats.size(); i++) { SQLStatement stat = (SQLStatement) stats.get(i); if (!stat.hasError() && stat.hasSQL()) { sql += stat.getSQL(); } } return sql; } /** * Checks all the steps and fills a List of (CheckResult) remarks. * * @param remarks The remarks list to add to. * @param only_selected Check only the selected steps. * @param monitor The progress monitor to use, null if not used */ public void checkSteps(ArrayList remarks, boolean only_selected, IProgressMonitor monitor) { try { remarks.clear(); // Start with a clean slate... Hashtable values = new Hashtable(); String stepnames[]; StepMeta steps[]; if (!only_selected || nrSelectedSteps() == 0) { stepnames = getStepNames(); steps = getStepsArray(); } else { stepnames = getSelectedStepNames(); steps = getSelectedSteps(); } boolean stop_checking = false; if (monitor != null) monitor.beginTask(Messages.getString("TransMeta.Monitor.VerifyingThisTransformationTask.Title"), steps.length + 2); //$NON-NLS-1$ for (int i = 0; i < steps.length && !stop_checking; i++) { if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.VerifyingStepTask.Title",stepnames[i])); //$NON-NLS-1$ //$NON-NLS-2$ StepMeta stepMeta = steps[i]; int nrinfo = findNrInfoSteps(stepMeta); StepMeta[] infostep = null; if (nrinfo > 0) { infostep = getInfoStep(stepMeta); } Row info = null; if (infostep != null) { try { info = getStepFields(infostep); } catch (KettleStepException kse) { info = null; CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, Messages.getString("TransMeta.CheckResult.TypeResultError.ErrorOccurredGettingStepInfoFields.Description",""+stepMeta , Const.CR + kse.getMessage()), stepMeta); //$NON-NLS-1$ remarks.add(cr); } } // The previous fields from non-informative steps: Row prev = null; try { prev = getPrevStepFields(stepMeta); } catch (KettleStepException kse) { CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, Messages.getString("TransMeta.CheckResult.TypeResultError.ErrorOccurredGettingInputFields.Description", ""+stepMeta , Const.CR + kse.getMessage()), stepMeta); //$NON-NLS-1$ remarks.add(cr); // This is a severe error: stop checking... // Otherwise we wind up checking time & time again because nothing gets put in the database // cache, the timeout of certain databases is very long... (Oracle) stop_checking = true; } if (isStepUsedInTransHops(stepMeta)) { // Get the input & output steps! // Copy to arrays: String input[] = getPrevStepNames(stepMeta); String output[] = getPrevStepNames(stepMeta); // Check step specific info... stepMeta.check(remarks, prev, input, output, info); if (prev != null) { for (int x = 0; x < prev.size(); x++) { Value v = prev.getValue(x); String name = v.getName(); if (name == null) values.put(v, Messages.getString("TransMeta.Value.CheckingFieldName.FieldNameIsEmpty.Description")); //$NON-NLS-1$ else if (name.indexOf(' ') >= 0) values.put(v, Messages.getString("TransMeta.Value.CheckingFieldName.FieldNameContainsSpaces.Description")); //$NON-NLS-1$ else { char list[] = new char[] { '.', ',', '-', '/', '+', '*', '\'', '\t', '"', '|', '@', '(', ')', '{', '}', '!', '^' }; for (int c = 0; c < list.length; c++) { if (name.indexOf(list[c]) >= 0) values.put(v, Messages.getString("TransMeta.Value.CheckingFieldName.FieldNameContainsUnfriendlyCodes.Description",String.valueOf(list[c]) )); //$NON-NLS-1$ //$NON-NLS-2$ } } } // Check if 2 steps with the same name are entering the step... if (prev.size() > 1) { String fieldNames[] = prev.getFieldNames(); String sortedNames[] = Const.sortStrings(fieldNames); String prevName = sortedNames[0]; for (int x = 1; x < sortedNames.length; x++) { // Checking for doubles if (prevName.equalsIgnoreCase(sortedNames[x])) { // Give a warning!! CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_WARNING, Messages.getString("TransMeta.CheckResult.TypeResultWarning.HaveTheSameNameField.Description", prevName ), stepMeta); //$NON-NLS-1$ //$NON-NLS-2$ remarks.add(cr); } else { prevName = sortedNames[x]; } } } } else { CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, Messages.getString("TransMeta.CheckResult.TypeResultError.CannotFindPreviousFields.Description") + stepMeta.getName(), //$NON-NLS-1$ stepMeta); remarks.add(cr); } } else { CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_WARNING, Messages.getString("TransMeta.CheckResult.TypeResultWarning.StepIsNotUsed.Description"), stepMeta); //$NON-NLS-1$ remarks.add(cr); } if (monitor != null) { monitor.worked(1); // progress bar... if (monitor.isCanceled()) stop_checking = true; } } // Also, check the logging table of the transformation... if (monitor == null || !monitor.isCanceled()) { if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.CheckingTheLoggingTableTask.Title")); //$NON-NLS-1$ if (getLogConnection() != null) { Database logdb = new Database(getLogConnection()); try { logdb.connect(); CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_OK, Messages.getString("TransMeta.CheckResult.TypeResultOK.ConnectingWorks.Description"), //$NON-NLS-1$ null); remarks.add(cr); if (getLogTable() != null) { if (logdb.checkTableExists(getLogTable())) { cr = new CheckResult(CheckResult.TYPE_RESULT_OK, Messages.getString("TransMeta.CheckResult.TypeResultOK.LoggingTableExists.Description", getLogTable() ), null); //$NON-NLS-1$ //$NON-NLS-2$ remarks.add(cr); Row fields = Database.getTransLogrecordFields(isBatchIdUsed(), isLogfieldUsed()); String sql = logdb.getDDL(getLogTable(), fields); if (sql == null || sql.length() == 0) { cr = new CheckResult(CheckResult.TYPE_RESULT_OK, Messages.getString("TransMeta.CheckResult.TypeResultOK.CorrectLayout.Description"), null); //$NON-NLS-1$ remarks.add(cr); } else { cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, Messages.getString("TransMeta.CheckResult.TypeResultError.LoggingTableNeedsAdjustments.Description") + Const.CR + sql, //$NON-NLS-1$ null); remarks.add(cr); } } else { cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, Messages.getString("TransMeta.CheckResult.TypeResultError.LoggingTableDoesNotExist.Description"), null); //$NON-NLS-1$ remarks.add(cr); } } else { cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, Messages.getString("TransMeta.CheckResult.TypeResultError.LogTableNotSpecified.Description"), null); //$NON-NLS-1$ remarks.add(cr); } } catch (KettleDatabaseException dbe) { } finally { logdb.disconnect(); } } if (monitor != null) monitor.worked(1); } if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.CheckingForDatabaseUnfriendlyCharactersInFieldNamesTask.Title")); //$NON-NLS-1$ if (values.size() > 0) { Enumeration keys = values.keys(); while (keys.hasMoreElements()) { Value v = (Value) keys.nextElement(); String message = (String) values.get(v); CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_WARNING, Messages.getString("TransMeta.CheckResult.TypeResultWarning.Description",v.getName() , message ,v.getOrigin() ), findStep(v.getOrigin())); //$NON-NLS-1$ remarks.add(cr); } } else { CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_OK, Messages.getString("TransMeta.CheckResult.TypeResultOK.Description"), null); //$NON-NLS-1$ remarks.add(cr); } if (monitor != null) monitor.worked(1); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } /** * @return Returns the resultRows. */ public ArrayList getResultRows() { return resultRows; } /** * @param resultRows The resultRows to set. */ public void setResultRows(ArrayList resultRows) { this.resultRows = resultRows; } /** * @return Returns the sourceRows. * @deprecated : use getPreviousResult().getRows() */ public ArrayList getSourceRows() { return sourceRows; } /** * @param sourceRows The sourceRows to set. * @deprecated : use getPreviousResult().getRows().addAll(sourceRows) */ public void setSourceRows(ArrayList sourceRows) { this.sourceRows = sourceRows; } /** * @return Returns the directory. */ public RepositoryDirectory getDirectory() { return directory; } /** * @param directory The directory to set. */ public void setDirectory(RepositoryDirectory directory) { this.directory = directory; setInternalKettleVariables(); } /** * @return Returns the directoryTree. * @deprecated */ public RepositoryDirectory getDirectoryTree() { return directoryTree; } /** * @param directoryTree The directoryTree to set. * @deprecated */ public void setDirectoryTree(RepositoryDirectory directoryTree) { this.directoryTree = directoryTree; } /** * @return The directory path plus the name of the transformation */ public String getPathAndName() { if (getDirectory().isRoot()) return getDirectory().getPath() + getName(); else return getDirectory().getPath() + RepositoryDirectory.DIRECTORY_SEPARATOR + getName(); } /** * @return Returns the arguments. */ public String[] getArguments() { return arguments; } /** * @param arguments The arguments to set. */ public void setArguments(String[] arguments) { this.arguments = arguments; } /** * @return Returns the counters. */ public Hashtable getCounters() { return counters; } /** * @param counters The counters to set. */ public void setCounters(Hashtable counters) { this.counters = counters; } /** * @return Returns the dependencies. */ public ArrayList getDependencies() { return dependencies; } /** * @param dependencies The dependencies to set. */ public void setDependencies(ArrayList dependencies) { this.dependencies = dependencies; } /** * @return Returns the id. */ public long getId() { return id; } /** * @param id The id to set. */ public void setId(long id) { this.id = id; } /** * @return Returns the inputStep. */ public StepMeta getInputStep() { return inputStep; } /** * @param inputStep The inputStep to set. */ public void setInputStep(StepMeta inputStep) { this.inputStep = inputStep; } /** * @return Returns the logConnection. */ public DatabaseMeta getLogConnection() { return logConnection; } /** * @param logConnection The logConnection to set. */ public void setLogConnection(DatabaseMeta logConnection) { this.logConnection = logConnection; } /** * @return Returns the logTable. */ public String getLogTable() { return logTable; } /** * @param logTable The logTable to set. */ public void setLogTable(String logTable) { this.logTable = logTable; } /** * @return Returns the maxDateConnection. */ public DatabaseMeta getMaxDateConnection() { return maxDateConnection; } /** * @param maxDateConnection The maxDateConnection to set. */ public void setMaxDateConnection(DatabaseMeta maxDateConnection) { this.maxDateConnection = maxDateConnection; } /** * @return Returns the maxDateDifference. */ public double getMaxDateDifference() { return maxDateDifference; } /** * @param maxDateDifference The maxDateDifference to set. */ public void setMaxDateDifference(double maxDateDifference) { this.maxDateDifference = maxDateDifference; } /** * @return Returns the maxDateField. */ public String getMaxDateField() { return maxDateField; } /** * @param maxDateField The maxDateField to set. */ public void setMaxDateField(String maxDateField) { this.maxDateField = maxDateField; } /** * @return Returns the maxDateOffset. */ public double getMaxDateOffset() { return maxDateOffset; } /** * @param maxDateOffset The maxDateOffset to set. */ public void setMaxDateOffset(double maxDateOffset) { this.maxDateOffset = maxDateOffset; } /** * @return Returns the maxDateTable. */ public String getMaxDateTable() { return maxDateTable; } /** * @param maxDateTable The maxDateTable to set. */ public void setMaxDateTable(String maxDateTable) { this.maxDateTable = maxDateTable; } /** * @return Returns the outputStep. */ public StepMeta getOutputStep() { return outputStep; } /** * @param outputStep The outputStep to set. */ public void setOutputStep(StepMeta outputStep) { this.outputStep = outputStep; } /** * @return Returns the readStep. */ public StepMeta getReadStep() { return readStep; } /** * @param readStep The readStep to set. */ public void setReadStep(StepMeta readStep) { this.readStep = readStep; } /** * @return Returns the updateStep. */ public StepMeta getUpdateStep() { return updateStep; } /** * @param updateStep The updateStep to set. */ public void setUpdateStep(StepMeta updateStep) { this.updateStep = updateStep; } /** * @return Returns the writeStep. */ public StepMeta getWriteStep() { return writeStep; } /** * @param writeStep The writeStep to set. */ public void setWriteStep(StepMeta writeStep) { this.writeStep = writeStep; } /** * @return Returns the sizeRowset. */ public int getSizeRowset() { return sizeRowset; } /** * @param sizeRowset The sizeRowset to set. */ public void setSizeRowset(int sizeRowset) { this.sizeRowset = sizeRowset; } /** * @return Returns the dbCache. */ public DBCache getDbCache() { return dbCache; } /** * @param dbCache The dbCache to set. */ public void setDbCache(DBCache dbCache) { this.dbCache = dbCache; } /** * @return Returns the useBatchId. */ public boolean isBatchIdUsed() { return useBatchId; } /** * @param useBatchId The useBatchId to set. */ public void setBatchIdUsed(boolean useBatchId) { this.useBatchId = useBatchId; } /** * @return Returns the logfieldUsed. */ public boolean isLogfieldUsed() { return logfieldUsed; } /** * @param logfieldUsed The logfieldUsed to set. */ public void setLogfieldUsed(boolean logfieldUsed) { this.logfieldUsed = logfieldUsed; } /** * @return Returns the createdDate. */ public Value getCreatedDate() { return createdDate; } /** * @param createdDate The createdDate to set. */ public void setCreatedDate(Value createdDate) { this.createdDate = createdDate; } /** * @param createdUser The createdUser to set. */ public void setCreatedUser(String createdUser) { this.createdUser = createdUser; } /** * @return Returns the createdUser. */ public String getCreatedUser() { return createdUser; } /** * @param modifiedDate The modifiedDate to set. */ public void setModifiedDate(Value modifiedDate) { this.modifiedDate = modifiedDate; } /** * @return Returns the modifiedDate. */ public Value getModifiedDate() { return modifiedDate; } /** * @param modifiedUser The modifiedUser to set. */ public void setModifiedUser(String modifiedUser) { this.modifiedUser = modifiedUser; } /** * @return Returns the modifiedUser. */ public String getModifiedUser() { return modifiedUser; } /** * @return the textual representation of the transformation: it's name. If the name has not been set, the classname * is returned. */ public String toString() { if (name != null) return name; if (filename != null) return filename; return TransMeta.class.getName(); } /** * Cancel queries opened for checking & fieldprediction */ public void cancelQueries() throws KettleDatabaseException { for (int i = 0; i < nrSteps(); i++) { getStep(i).getStepMetaInterface().cancelQueries(); } } /** * Get the arguments used by this transformation. * * @param arguments * @return A row with the used arguments in it. */ public Row getUsedArguments(String[] arguments) { Row args = new Row(); // Always at least return an empty row, not null! for (int i = 0; i < nrSteps(); i++) { StepMetaInterface smi = getStep(i).getStepMetaInterface(); Row row = smi.getUsedArguments(); // Get the command line arguments that this step uses. if (row != null) { for (int x = 0; x < row.size(); x++) { Value value = row.getValue(x); String argname = value.getName(); if (args.searchValueIndex(argname) < 0) args.addValue(value); } } } // OK, so perhaps, we can use the arguments from a previous execution? String[] saved = Props.isInitialized() ? Props.getInstance().getLastArguments() : null; // Set the default values on it... // Also change the name to "Argument 1" .. "Argument 10" for (int i = 0; i < args.size(); i++) { Value arg = args.getValue(i); int argNr = Const.toInt(arg.getName(), -1); if (arguments!=null && argNr >= 0 && argNr < arguments.length) { arg.setValue(arguments[argNr]); } if (arg.isNull() || arg.getString() == null) // try the saved option... { if (argNr >= 0 && argNr < saved.length && saved[argNr] != null) { arg.setValue(saved[argNr]); } } arg.setName("Argument " + arg.getName()); //$NON-NLS-1$ } return args; } public StepMeta getMappingInputStep() { for (int i = 0; i < nrSteps(); i++) { if (getStep(i).getStepID().equalsIgnoreCase("MappingInput")) { return getStep(i); } //$NON-NLS-1$ } return null; } public StepMeta getMappingOutputStep() { for (int i = 0; i < nrSteps(); i++) { if (getStep(i).getStepID().equalsIgnoreCase("MappingOutput")) { return getStep(i); } //$NON-NLS-1$ } return null; } /** * @return Sleep time waiting when buffer is empty, in nano-seconds */ public int getSleepTimeEmpty() { return Const.SLEEP_EMPTY_NANOS; } /** * @return Sleep time waiting when buffer is full, in nano-seconds */ public int getSleepTimeFull() { return Const.SLEEP_FULL_NANOS; } /** * @param sleepTimeEmpty The sleepTimeEmpty to set. */ public void setSleepTimeEmpty(int sleepTimeEmpty) { this.sleepTimeEmpty = sleepTimeEmpty; } /** * @param sleepTimeFull The sleepTimeFull to set. */ public void setSleepTimeFull(int sleepTimeFull) { this.sleepTimeFull = sleepTimeFull; } /** * This method asks all steps in the transformation whether or not the specified database connection is used. * The connection is used in the transformation if any of the steps uses it or if it is being used to log to. * @param databaseMeta The connection to check * @return true if the connection is used in this transformation. */ public boolean isDatabaseConnectionUsed(DatabaseMeta databaseMeta) { for (int i=0;i<nrSteps();i++) { StepMeta stepMeta = getStep(i); DatabaseMeta dbs[] = stepMeta.getStepMetaInterface().getUsedDatabaseConnections(); for (int d=0;d<dbs.length;d++) { if (dbs[d].equals(databaseMeta)) return true; } } if (logConnection!=null && logConnection.equals(databaseMeta)) return true; return false; } public List getInputFiles() { return inputFiles; } public void setInputFiles(List inputFiles) { this.inputFiles = inputFiles; } /** * Get a list of all the strings used in this transformation. * * @return A list of StringSearchResult with strings used in the */ public List getStringList(boolean searchSteps, boolean searchDatabases, boolean searchNotes) { ArrayList stringList = new ArrayList(); if (searchSteps) { // Loop over all steps in the transformation and see what the used vars are... for (int i=0;i<nrSteps();i++) { StepMeta stepMeta = getStep(i); stringList.add(new StringSearchResult(stepMeta.getName(), stepMeta, this, "Step name")); if (stepMeta.getDescription()!=null) stringList.add(new StringSearchResult(stepMeta.getDescription(), stepMeta, this, "Step description")); StepMetaInterface metaInterface = stepMeta.getStepMetaInterface(); StringSearcher.findMetaData(metaInterface, 1, stringList, stepMeta, this); } } // Loop over all steps in the transformation and see what the used vars are... if (searchDatabases) { for (int i=0;i<nrDatabases();i++) { DatabaseMeta meta = getDatabase(i); stringList.add(new StringSearchResult(meta.getName(), meta, this, "Database connection name")); if (meta.getDatabaseName()!=null) stringList.add(new StringSearchResult(meta.getDatabaseName(), meta, this, "Database name")); if (meta.getUsername()!=null) stringList.add(new StringSearchResult(meta.getUsername(), meta, this, "Database Username")); if (meta.getDatabaseTypeDesc()!=null) stringList.add(new StringSearchResult(meta.getDatabaseTypeDesc(), meta, this, "Database type description")); if (meta.getDatabasePortNumberString()!=null) stringList.add(new StringSearchResult(meta.getDatabasePortNumberString(), meta, this, "Database port")); } } // Loop over all steps in the transformation and see what the used vars are... if (searchNotes) { for (int i=0;i<nrNotes();i++) { NotePadMeta meta = getNote(i); if (meta.getNote()!=null) stringList.add(new StringSearchResult(meta.getNote(), meta, this, "Notepad text")); } } return stringList; } public List getUsedVariables() { // Get the list of Strings. List stringList = getStringList(true, true, false); List varList = new ArrayList(); // Look around in the strings, see what we find... for (int i=0;i<stringList.size();i++) { StringSearchResult result = (StringSearchResult) stringList.get(i); StringUtil.getUsedVariables(result.getString(), varList, false); } return varList; } /** * @return Returns the previousResult. */ public Result getPreviousResult() { return previousResult; } /** * @param previousResult The previousResult to set. */ public void setPreviousResult(Result previousResult) { this.previousResult = previousResult; } /** * @return Returns the resultFiles. */ public synchronized ArrayList getResultFiles() { return resultFiles; } /** * @param resultFiles The resultFiles to set. */ public void setResultFiles(ArrayList resultFiles) { this.resultFiles = resultFiles; } /** * This method sets various internal kettle variables that can be used by the transformation. */ public void setInternalKettleVariables() { KettleVariables variables = KettleVariables.getInstance(); if (filename!=null) // we have a finename that's defined. { File file = new File(filename); try { file = file.getCanonicalFile(); } catch(IOException e) { file = file.getAbsoluteFile(); } // The directory of the transformation variables.setVariable(Const.INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_DIRECTORY, file.getParent()); // The filename of the transformation variables.setVariable(Const.INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_NAME, file.getName()); } else { variables.setVariable(Const.INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_DIRECTORY, ""); variables.setVariable(Const.INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_NAME, ""); } // The name of the transformation variables.setVariable(Const.INTERNAL_VARIABLE_TRANSFORMATION_NAME, Const.NVL(name, "")); // The name of the directory in the repository variables.setVariable(Const.INTERNAL_VARIABLE_TRANSFORMATION_REPOSITORY_DIRECTORY, directory!=null?directory.getPath():""); } /** * @return the partitionSchemas */ public List getPartitionSchemas() { return partitionSchemas; } /** * @param partitionSchemas the partitionSchemas to set */ public void setPartitionSchemas(List partitionSchemas) { this.partitionSchemas = partitionSchemas; } /** * Get the available partition schema names. * @return */ public String[] getPartitionSchemasNames() { String names[] = new String[partitionSchemas.size()]; for (int i=0;i<names.length;i++) { names[i] = ((PartitionSchema)partitionSchemas.get(i)).getName(); } return names; } /** * @return the feedbackShown */ public boolean isFeedbackShown() { return feedbackShown; } /** * @param feedbackShown the feedbackShown to set */ public void setFeedbackShown(boolean feedbackShown) { this.feedbackShown = feedbackShown; } /** * @return the feedbackSize */ public int getFeedbackSize() { return feedbackSize; } /** * @param feedbackSize the feedbackSize to set */ public void setFeedbackSize(int feedbackSize) { this.feedbackSize = feedbackSize; } /** * @return the usingUniqueConnections */ public boolean isUsingUniqueConnections() { return usingUniqueConnections; } /** * @param usingUniqueConnections the usingUniqueConnections to set */ public void setUsingUniqueConnections(boolean usingUniqueConnections) { this.usingUniqueConnections = usingUniqueConnections; } public ArrayList getClusterSchemas() { return clusterSchemas; } public void setClusterSchemas(ArrayList clusterSchemas) { this.clusterSchemas = clusterSchemas; } /** * @return The slave server strings from this cluster schema */ public String[] getClusterSchemaNames() { String[] names = new String[clusterSchemas.size()]; for (int i=0;i<names.length;i++) { names[i] = ((ClusterSchema)clusterSchemas.get(i)).getName(); } return names; } /** * Find a partition schema using its name. * @param name The name of the partition schema to look for. * @return the partition with the specified name of null if nothing was found */ public PartitionSchema findPartitionSchema(String name) { for (int i=0;i<partitionSchemas.size();i++) { PartitionSchema schema = (PartitionSchema)partitionSchemas.get(i); if (schema.getName().equalsIgnoreCase(name)) return schema; } return null; } /** * Find a clustering schema using its name * @param name The name of the clustering schema to look for. * @return the cluster schema with the specified name of null if nothing was found */ public ClusterSchema findClusterSchema(String name) { for (int i=0;i<clusterSchemas.size();i++) { ClusterSchema schema = (ClusterSchema)clusterSchemas.get(i); if (schema.getName().equalsIgnoreCase(name)) return schema; } return null; } /** * Add a new partition schema to the transformation if that didn't exist yet. * Otherwise, replace it. * * @param partitionSchema The partition schema to be added. */ public void addOrReplacePartitionSchema(PartitionSchema partitionSchema) { int index = partitionSchemas.indexOf(partitionSchema); if (index<0) { partitionSchemas.add(partitionSchema); } else { PartitionSchema previous = (PartitionSchema) partitionSchemas.get(index); previous.replaceMeta(partitionSchema); } setChanged(); } /** * Add a new slave server to the transformation if that didn't exist yet. * Otherwise, replace it. * * @param slaveServer The slave server to be added. */ public void addOrReplaceSlaveServer(SlaveServer slaveServer) { int index = slaveServers.indexOf(slaveServer); if (index<0) { slaveServers.add(slaveServer); } else { SlaveServer previous = (SlaveServer) slaveServers.get(index); previous.replaceMeta(slaveServer); } setChanged(); } /** * Add a new cluster schema to the transformation if that didn't exist yet. * Otherwise, replace it. * * @param clusterSchema The cluster schema to be added. */ public void addOrReplaceClusterSchema(ClusterSchema clusterSchema) { int index = clusterSchemas.indexOf(clusterSchema); if (index<0) { clusterSchemas.add(clusterSchema); } else { ClusterSchema previous = (ClusterSchema) clusterSchemas.get(index); previous.replaceMeta(clusterSchema); } setChanged(); } public String getSharedObjectsFile() { return sharedObjectsFile; } public void setSharedObjectsFile(String sharedObjectsFile) { this.sharedObjectsFile = sharedObjectsFile; } public void saveSharedObjects() throws KettleException { try { // First load all the shared objects... String soFile = StringUtil.environmentSubstitute(sharedObjectsFile); SharedObjects sharedObjects = new SharedObjects(soFile); // Now overwrite the objects in there List shared = new ArrayList(); shared.addAll(databases); shared.addAll(steps); shared.addAll(partitionSchemas); shared.addAll(slaveServers); shared.addAll(clusterSchemas); // The databases connections... for (int i=0;i<shared.size();i++) { SharedObjectInterface sharedObject = (SharedObjectInterface) shared.get(i); if (sharedObject.isShared()) { sharedObjects.storeObject(sharedObject); } } // Save the objects sharedObjects.saveToFile(); } catch(IOException e) { } } /** * @return the usingThreadPriorityManagment */ public boolean isUsingThreadPriorityManagment() { return usingThreadPriorityManagment; } /** * @param usingThreadPriorityManagment the usingThreadPriorityManagment to set */ public void setUsingThreadPriorityManagment(boolean usingThreadPriorityManagment) { this.usingThreadPriorityManagment = usingThreadPriorityManagment; } public SlaveServer findSlaveServer(String serverString) { return SlaveServer.findSlaveServer(slaveServers, serverString); } public String[] getSlaveServerNames() { return SlaveServer.getSlaveServerNames(slaveServers); } /** * @return the slaveServers */ public ArrayList getSlaveServers() { return slaveServers; } /** * @param slaveServers the slaveServers to set */ public void setSlaveServers(ArrayList slaveServers) { this.slaveServers = slaveServers; } }
package polytheque.model.DAO; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import polytheque.model.pojos.Jeu; public class JeuDAO extends DAO { /** * Mthode de cration * @param Jeu * @return boolean */ public boolean create(Jeu jeu, int idCategorie, int idEditeur) { try { super.connect(); PreparedStatement psInsert = connection.prepareStatement("INSERT INTO " + "JEU(nom, description, annee_parution, status, nombre_exemplaires, nombre_reserves," + "age_mini, nombre_joueurs, id_categorie, id_editeur) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); psInsert.setString(1, jeu.getNom()); psInsert.setString(2, jeu.getDescription()); psInsert.setInt(3, jeu.getAnneeParution()); psInsert.setString(4, jeu.getStatut()); psInsert.setInt(5, jeu.getNbExemplaires()); psInsert.setInt(6, jeu.getNbReserves()); psInsert.setInt(7, jeu.getAgeMini()); psInsert.setInt(8, jeu.getNbJoueurs()); psInsert.setInt(9, idCategorie); psInsert.setInt(10, idEditeur); psInsert.executeUpdate(); ResultSet idResult = psInsert.getGeneratedKeys(); if (idResult != null && idResult.next()) { jeu.setIdJeu(idResult.getInt(1));; } else { throw new SQLException(); } super.disconnect(); return true; } catch (SQLException e) { e.printStackTrace(); return false; } } /** * Mthode pour effacer * @param Jeu * @return boolean */ public boolean delete(Jeu jeu) { try { super.connect(); PreparedStatement psDelete = connection.prepareStatement("DELETE * FROM JEU WHERE id_jeu " + jeu.getIdJeu()); psDelete.executeUpdate(); ResultSet idResult = psDelete.getGeneratedKeys(); if (idResult != null && idResult.next()) { jeu.setIdJeu(idResult.getInt(1));; } else { throw new SQLException(); } super.disconnect(); return true; } catch (SQLException e) { e.printStackTrace(); return false; } } /** * Mthode de mise jour * @param obj * @return boolean */ public boolean update(Jeu jeu) { try { super.connect(); PreparedStatement psUpdate = connection.prepareStatement("UPDATE JEU SET nom_jeu = '" + jeu.getNom() + "',"+ " jeu_description = '" + jeu.getDescription() + "',"+ " jeu_anneeparution = '" + jeu.getAnneeParution() + "',"+ " jeu_status = '" + jeu.getStatut() + "',"+ " jeu_nbExemplaire = '" + jeu.getNbExemplaires() + "',"+ " jeu_reserve = '" + jeu.getNbReserves() + "',"+ " jeu_ageMini = '" + jeu.getAgeMini() + "',"+ " jeu_joueurs = '" + jeu.getNbJoueurs() + "',"+ " jeu_categorie = '" + jeu.getCategorie() + "',"+ " jeu_editeur = '" + jeu.getEditeur() + "'"+ " WHERE jeu_id = " + jeu.getIdJeu()); psUpdate.executeUpdate(); jeu = this.retreive(jeu.getIdJeu()); super.disconnect(); return true; } catch (SQLException e) { e.printStackTrace(); return false; } } /** * Mthode de recherche des informations * @param id * @return T */ public Jeu retreive(int id) { try { super.connect(); PreparedStatement psSelect = connection.prepareStatement("SELECT * FROM JEU WHERE id_jeu = ?"); psSelect.setInt(1, id); psSelect.execute(); psSelect.closeOnCompletion(); ResultSet resSet = psSelect.getResultSet(); Jeu jeu = null; if (resSet.next()) { jeu = new Jeu(id, resSet.getString(1), resSet.getString(2), resSet.getInt(3), resSet.getString(4), resSet.getInt(5), resSet.getInt(6), resSet.getInt(7), resSet.getInt(8), resSet.getString(9), resSet.getString(10)); } super.disconnect(); return jeu; } catch(SQLException e) { e.printStackTrace(); return null; } } }
package net.finkn.inputspec.tools; import net.finkn.inputspec.tools.types.Point; import se.miun.itm.input.model.InPUTException; import se.miun.itm.input.model.design.IDesign; /** * Helper for writing more concise tests. * Exports common configurations and small functions that are common to * multiple tests. * * @author Christoffer Fink */ public class Helper { private static final String defaultDesignId = "Design"; private static final GenTestCase genTest = GenTestCase.getInstance(); private static final SinkTestCase sinkTest = SinkTestCase.getInstance(); public static final ParamCfg pointParam = ParamCfg.builder() .id("X").inclMin("10").inclMax("20").add() .id("Y").inclMin("15").inclMax("25").add() .structured() .id("Point") .build(); public static final MappingCfg pointMapping = MappingCfg.builder() .infer(pointParam, Point.class) .build(); public static ParamCfg.Builder pb() { return ParamCfg.builder(); } public static SinkTestCase sinkTest(ParamCfg.Builder builder) throws InPUTException { return sinkTest.sink(Sink.fromParam(builder.build())); } public static SinkTestCase sinkTest(IDesign design, String id) throws InPUTException { return sinkTest.sink(Sink.fromDesign(design, id)); } public static SinkTestCase sinkTest(String id, ParamCfg ... cfgs) throws InPUTException { return sinkTest(design(cfgs), id); } public static GenTestCase genTest(ParamCfg.Builder builder) throws InPUTException { return genTest.gen(Generator.fromParam(builder.build())); } public static GenTestCase genTest(String id, ParamCfg ... cfgs) throws InPUTException { DesignSpaceCfg space = DesignSpaceCfg.builder().param(cfgs).build(); return genTest.gen(Generator.fromDesignSpace(space.getDesignSpace(), id)); } public static IDesign design(ParamCfg ... params) throws InPUTException { return design(null, params); } public static IDesign design(CodeMappingCfg mapping, ParamCfg ... params) throws InPUTException { return DesignSpaceCfg.builder() .param(params) .mapping(mapping) .build() .getDesignSpace() .nextDesign(defaultDesignId); } }
package cellsociety_team01.modelview; import java.util.ArrayList; import java.util.HashMap; import javafx.animation.Animation; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.util.Duration; import cellsociety_team01.CellState.Cell; import cellsociety_team01.simulations.Simulation; public class Grid { Simulation simulation; private ArrayList<Cell> cells; private GUI myView; private boolean simRunning; private double updateRate; private String author; private Timeline myLoop; public Grid() { } public void setView(GUI viewIn) { myView = viewIn; } public boolean isSimRunning() { return simRunning; } public void setAnimationLoop(Timeline anIn) { myLoop = anIn; } public void play() { simRunning = true; } public void pause() { simRunning = false; } public void step() { updateGrid(); myView.update(true); } public void changeUpdateRate(double newRate) { myLoop.stop(); KeyFrame frame = start(newRate); myLoop.setCycleCount(Animation.INDEFINITE); myLoop.getKeyFrames().add(frame); myLoop.play(); } public void setConfigs(HashMap<String, String> configs) { } public void setSimulation(Simulation simulationIn) { simulation = simulationIn; } public void updateGrid(ArrayList<Cell> cellsIn) { cells = cellsIn; } public void setTitle(String titleIn) { myView.getStage().setTitle(titleIn); } public void setAuthor(String authorIn) { author = authorIn; } /** * Create the game's frame */ public KeyFrame start(double frameRate) { updateRate = frameRate; return new KeyFrame(Duration.millis(1000 / updateRate * 1000), e -> update()); } public ArrayList<Cell> getCells() { return cells; } private void update() { if (simRunning) { updateGrid(); } myView.update(false); } private void setNotUpdated(){ for (Cell c : cells) { c.setUpdated(false); } } private void updateGrid() { cells = simulation.updateGrid(cells); setNotUpdated(); } }
package server.logic.data; import commons.interfaces.data.IContinent; import commons.interfaces.data.ICountry; import commons.interfaces.data.IMap; import commons.interfaces.data.IPlayer; import java.rmi.RemoteException; import java.awt.*; import java.rmi.server.UnicastRemoteObject; import java.util.*; import java.util.List; public class Map extends UnicastRemoteObject implements IMap{ public static final String DEFAULT_MAP_UUID = "03c64c20-fc74-11e3-a3ac-0800200c9a66"; private final ArrayList<Country> countries = new ArrayList<Country>(); private final ArrayList<Continent> continents = new ArrayList<Continent>(); /** * ID der Karte */ private final UUID id = UUID.fromString(Map.DEFAULT_MAP_UUID); /** * Erstellt eine neue Standard-Karte */ public Map() throws RemoteException{ //Kontinente erzeugen Continent northAmerica = new Continent("Nord Amerika", 5); Continent southAmerica = new Continent("Süd Amerika", 2); Continent europe = new Continent("Europa", 5); Continent asia = new Continent("Asien", 7); Continent afrika = new Continent("Afrika", 3); Continent australia = new Continent("Australien", 2); this.continents.add(northAmerica); this.continents.add(southAmerica); this.continents.add(asia); this.continents.add(afrika); this.continents.add(australia); this.countries.add(new Country("Alaska", northAmerica, new Color(222,55,0))); this.countries.add(new Country("Nordwest-Territorium", northAmerica, new Color(255,222,111))); this.countries.add(new Country("Alberta", northAmerica, new Color(150,0,222))); this.countries.add(new Country("Ontario", northAmerica, new Color(0,222,150))); this.countries.add(new Country("Quebec", northAmerica, new Color(222,111,150))); this.countries.add(new Country("Weststaaten", northAmerica, new Color(222,0,222))); this.countries.add(new Country("Oststaaten", northAmerica, new Color(222,111,222))); this.countries.add(new Country("Mittelamerika", northAmerica, new Color(222,111,111))); this.countries.add(new Country("Hawaii", northAmerica, new Color(255,222,22))); this.countries.add(new Country("Nunavut", northAmerica, new Color(222,40,111))); this.countries.add(new Country("Venezuela", southAmerica, new Color(111,111,222))); this.countries.add(new Country("Brasilien", southAmerica, new Color(50,150,50))); this.countries.add(new Country("Peru", southAmerica, new Color(222,0,111))); this.countries.add(new Country("Falkland-Inseln", southAmerica, new Color(50,150,150))); this.countries.add(new Country("Argentinien", southAmerica, new Color(50,150,100))); this.countries.add(new Country("Grönland", europe, new Color(0,255,0))); this.countries.add(new Country("Island", europe, new Color(22,255,123))); this.countries.add(new Country("Großbritannien", europe, new Color(22,111,222))); this.countries.add(new Country("Skandinavien", europe, new Color(50,120,120))); this.countries.add(new Country("Mitteleuropa", europe, new Color(255,111,137))); this.countries.add(new Country("Westeuropa", europe, new Color(0,255,199))); this.countries.add(new Country("Südeuropa", europe, new Color(30,99,255))); this.countries.add(new Country("Ukraine", europe, new Color(255,255,0))); this.countries.add(new Country("Svalbard", europe, new Color(50,60,120))); this.countries.add(new Country("Afghanistan", asia, new Color(255,200,0))); this.countries.add(new Country("Ural", asia, new Color(105,8,90))); this.countries.add(new Country("Sibirien", asia, new Color(100,0,0))); this.countries.add(new Country("Irrutsk", asia, new Color(0,0,100))); this.countries.add(new Country("Jakutsk", asia, new Color(0,100,0))); this.countries.add(new Country("Kamtschatka", asia, new Color(0,158,225))); this.countries.add(new Country("Mongolei", asia, new Color(234,105,160))); this.countries.add(new Country("Japan", asia, new Color(227,0,122))); this.countries.add(new Country("China", asia, new Color(255,0,0))); this.countries.add(new Country("Indien", asia, new Color(171,140,188))); this.countries.add(new Country("Siam", asia, new Color(151,191,13))); this.countries.add(new Country("Mittlerer-Osten", asia, new Color(0,255,255))); this.countries.add(new Country("Ägypten", afrika, new Color(200,100,100))); this.countries.add(new Country("Ostafrika", afrika, new Color(100,200,100))); this.countries.add(new Country("Nordwestafrika", afrika, new Color(50,150,200))); this.countries.add(new Country("Südafrika", afrika, new Color(0,200,200))); this.countries.add(new Country("Madagaskar", afrika, new Color(0,200,0))); this.countries.add(new Country("Kongo", afrika, new Color(50,100,200))); this.countries.add(new Country("Indonesien", australia, new Color(122,0,122))); this.countries.add(new Country("Neu-Guinea", australia, new Color(100,0,200))); this.countries.add(new Country("Ostaustralien", australia, new Color(200,100,0))); this.countries.add(new Country("Westaustralien", australia, new Color(255,255,100))); this.countries.add(new Country("Neuseeland", australia, new Color(200,0,100))); this.countries.add(new Country("Philippinen", australia, new Color(255,147,0))); //Australien Country ostaustralien = this.getCountry("Ostaustralien"); ostaustralien.connectTo(this.getCountry("Westaustralien")); ostaustralien.connectTo(this.getCountry("Neu-Guinea")); Country indonesien = this.getCountry("Indonesien"); indonesien.connectTo(this.getCountry("Siam")); indonesien.connectTo(this.getCountry("Westaustralien")); indonesien.connectTo(this.getCountry("Philippinen")); Country Neuguinea = this.getCountry("Neu-Guinea"); Neuguinea.connectTo(this.getCountry("Westaustralien")); Country neuseeland = this.getCountry("Neuseeland"); neuseeland.connectTo(this.getCountry("Ostaustralien")); //Asien Country China = this.getCountry("China"); China.connectTo(this.getCountry("Siam")); China.connectTo(this.getCountry("Indien")); China.connectTo(this.getCountry("Mongolei")); China.connectTo(this.getCountry("Afghanistan")); China.connectTo(this.getCountry("Sibirien")); China.connectTo(this.getCountry("Ural")); Country mongolei = this.getCountry("Mongolei"); mongolei.connectTo(this.getCountry("Japan")); mongolei.connectTo(this.getCountry("Irrutsk")); mongolei.connectTo(this.getCountry("Sibirien")); Country jakutsk = this.getCountry("Jakutsk"); jakutsk.connectTo(this.getCountry("Kamtschatka")); jakutsk.connectTo(this.getCountry("Sibirien")); jakutsk.connectTo(this.getCountry("Irrutsk")); Country japan = this.getCountry("Japan"); japan.connectTo(this.getCountry("Hawaii")); japan.connectTo(this.getCountry("Philippinen")); japan.connectTo(this.getCountry("Kamtschatka")); Country irrutsk = this.getCountry("Irrutsk"); irrutsk.connectTo(this.getCountry("Kamtschatka")); irrutsk.connectTo(this.getCountry("Sibirien")); Country Indien = this.getCountry("Indien"); Indien.connectTo(this.getCountry("Siam")); Indien.connectTo(this.getCountry("Mittlerer-Osten")); Indien.connectTo(this.getCountry("Afghanistan")); Country ural = this.getCountry("Ural"); ural.connectTo(this.getCountry("Sibirien")); ural.connectTo(this.getCountry("Afghanistan")); ural.connectTo(this.getCountry("Ukraine")); Country mittlererOsten = this.getCountry("Mittlerer-Osten"); mittlererOsten.connectTo(this.getCountry("Afghanistan")); mittlererOsten.connectTo(this.getCountry("Ukraine")); mittlererOsten.connectTo(this.getCountry("Ägypten")); mittlererOsten.connectTo(this.getCountry("Südeuropa")); //Europa Country ukraine = this.getCountry("Ukraine"); ukraine.connectTo(this.getCountry("Afghanistan")); ukraine.connectTo(this.getCountry("Südeuropa")); ukraine.connectTo(this.getCountry("Skandinavien")); ukraine.connectTo(this.getCountry("Mitteleuropa")); Country Skandinavien = this.getCountry("Skandinavien"); Skandinavien.connectTo(this.getCountry("Svalbard")); Skandinavien.connectTo(this.getCountry("Island")); Skandinavien.connectTo(this.getCountry("Großbritannien")); Skandinavien.connectTo(this.getCountry("Mitteleuropa")); Country gb = this.getCountry("Großbritannien"); gb.connectTo(this.getCountry("Island")); gb.connectTo(this.getCountry("Mitteleuropa")); gb.connectTo(this.getCountry("Westeuropa")); Country westEu = this.getCountry("Westeuropa"); westEu.connectTo(this.getCountry("Nordwestafrika")); westEu.connectTo(this.getCountry("Südeuropa")); westEu.connectTo(this.getCountry("Mitteleuropa")); Country southEu = this.getCountry("Südeuropa"); southEu.connectTo(this.getCountry("Ägypten")); southEu.connectTo(this.getCountry("Nordwestafrika")); //Afrika Country noWeAfrika = this.getCountry("Nordwestafrika"); noWeAfrika.connectTo(this.getCountry("Ägypten")); noWeAfrika.connectTo(this.getCountry("Ostafrika")); noWeAfrika.connectTo(this.getCountry("Kongo")); Country ostAfrika = this.getCountry("Ostafrika"); ostAfrika.connectTo(this.getCountry("Ägypten")); ostAfrika.connectTo(this.getCountry("Kongo")); ostAfrika.connectTo(this.getCountry("Südafrika")); ostAfrika.connectTo(this.getCountry("Madagaskar")); Country southAfrika = this.getCountry("Südafrika"); southAfrika.connectTo(this.getCountry("Madagaskar")); southAfrika.connectTo(this.getCountry("Kongo")); southAfrika.connectTo(this.getCountry("Falkland-Inseln")); Country brasil = this.getCountry("Brasilien"); brasil.connectTo(this.getCountry("Nordwestafrika")); brasil.connectTo(this.getCountry("Venezuela")); brasil.connectTo(this.getCountry("Peru")); brasil.connectTo(this.getCountry("Argentinien")); Country venezuela = this.getCountry("Venezuela"); venezuela.connectTo(this.getCountry("Peru")); venezuela.connectTo(this.getCountry("Mittelamerika")); Country Argentinien = this.getCountry("Argentinien"); Argentinien.connectTo(this.getCountry("Peru")); Argentinien.connectTo(this.getCountry("Falkland-Inseln")); Argentinien.connectTo(this.getCountry("Neuseeland")); //Nord-Amerika Country mittelamerika = this.getCountry("Mittelamerika"); mittelamerika.connectTo(this.getCountry("Oststaaten")); mittelamerika.connectTo(this.getCountry("Weststaaten")); Country Weststaaten = this.getCountry("Weststaaten"); Weststaaten.connectTo(this.getCountry("Oststaaten")); Weststaaten.connectTo(this.getCountry("Hawaii")); Weststaaten.connectTo(this.getCountry("Alberta")); Weststaaten.connectTo(this.getCountry("Ontario")); Country Ontario = this.getCountry("Ontario"); Ontario.connectTo(this.getCountry("Quebec")); Weststaaten.connectTo(this.getCountry("Oststaaten")); Weststaaten.connectTo(this.getCountry("Nunavut")); Weststaaten.connectTo(this.getCountry("Nordwest-Territorium")); Weststaaten.connectTo(this.getCountry("Alberta")); Country alaska = this.getCountry("Alaska"); alaska.connectTo(this.getCountry("Kamtschatka")); alaska.connectTo(this.getCountry("Nordwest-Territorium")); alaska.connectTo(this.getCountry("Alberta")); Country Nordwest = this.getCountry("Nordwest-Territorium"); Nordwest.connectTo(this.getCountry("Alberta")); Nordwest.connectTo(this.getCountry("Nunavut")); Country Nunavut = this.getCountry("Nunavut"); Nunavut.connectTo(this.getCountry("Quebec")); Nunavut.connectTo(this.getCountry("Grönland")); Country groenland = this.getCountry("Grönland"); groenland.connectTo(this.getCountry("Quebec")); groenland.connectTo(this.getCountry("Svalbard")); groenland.connectTo(this.getCountry("Island")); } public List<? extends ICountry> getCountries() throws RemoteException { return this.countries; } public ArrayList<Country> getCountriesReal() { return this.countries; } /** * Berechnet den Benous, den ein Spieler an Einheiten bekommt fr die komplette Einnahme des jeweilligen Kontinents * @param p der aktuelle Spieler * @return die Anzahl der Bonus Einheiten */ public int getBonus(Player p) throws RemoteException{ int bonus = 0; for (IContinent c : this.continents){ if(c.getCurrentOwner() != null){ if(c.getCurrentOwner().equals(p)){ bonus += c.getBonus(); } } } return bonus; } /** * Vergleicht die Namen der Lnder mit bergebenem String * @param n String (name des zu suchenden Landes) * @return das zu suchende Land */ public Country getCountry(String n) throws RemoteException{ for (Country c : countries){ if(c.getName().equals(n)){ return c; } } return null; } public Country getCountry(Color col) throws RemoteException{ for (Country c : countries){ if(c.getColor().equals(col)){ return c; } } return null; } public Country getCountry(ICountry otherCountry) throws RemoteException{ for (Country c : countries){ if(c.equals(otherCountry)){ return c; } } return null; } /** * * @return Alle Kontinente dieser Karte */ public List<? extends IContinent> getContinents() throws RemoteException { return this.continents; } /** * * @return Alle Kontinente dieser Karte */ public List<Continent> getContinentsReal() { return this.continents; } public UUID getId() throws RemoteException{ return id; } @Override public String toStringRemote() throws RemoteException { return this.toString(); } }
package nju.software.jxjs.service; import java.util.Date; import java.util.List; import nju.software.jxjs.dao.JxjsDao; import nju.software.jxjs.dao.SpxxDao; import nju.software.jxjs.dao.XtglDmbDao; import nju.software.jxjs.dao.XtglYhbDao; import nju.software.jxjs.model.PubDmb; import nju.software.jxjs.model.PubXtglYhb; import nju.software.jxjs.model.TJxjs; import nju.software.jxjs.model.TSpxx; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class JxjsService { @Autowired private JxjsDao jd; @Autowired private XtglDmbDao dmbDao; @Autowired private XtglYhbDao yhbDao; @Autowired private SpxxDao spxxDao; public TJxjs getJxjsBybh(int jxjsbh){ return jd.getJxjsByBh(jxjsbh); } public List<TJxjs> getDsplb(){ PubDmb dmb = dmbDao.getDmbByLbbhAndDmms("JXJS-AJZT", ""); String ajztbh = dmb.getDmbh(); return jd.getJxjsByAjztbh(ajztbh); } public List<TJxjs> getYlalb(){ PubDmb dmb = dmbDao.getDmbByLbbhAndDmms("JXJS-AJZT", ""); String ajztbh = dmb.getDmbh(); return jd.getJxjsByAjztbh(ajztbh); } public List<TJxjs> getYsplb(){ PubDmb dmb = dmbDao.getDmbByLbbhAndDmms("JXJS-AJZT", ""); String ajztbh = dmb.getDmbh(); return jd.getJxjsByAjztbh(ajztbh); } public List<TJxjs> getJxjsByDateAndType(Date begin,Date end,String type){ PubDmb dmb = dmbDao.getDmbByLbbhAndDmms("JXJS-AJZT", type); String ajztbh = dmb.getDmbh(); return jd.getJxjsByDateAndAjztbh(begin, end, ajztbh); } // public int getSumByDateAndType(Date kssj,Date jssj,String type){ // int sz = 0; // switch(type){ // case "1": // sz = jd.get // return jd.getSumByDateAndType(kssj, jssj, type); public void approval(String jxjsbhList,String spr,String spyj,Date spsj){ String[] bhList = jxjsbhList.split(","); int jxjsbh; int spxxbh; PubDmb dmb = dmbDao.getDmbByLbbhAndDmms("JXJS-AJZT", ""); PubXtglYhb yhb = new PubXtglYhb(); List<PubXtglYhb> yhbs = yhbDao.findByYhdm(spr); if(yhbs != null && yhbs.size()>0) yhb = yhbs.get(0); for(String bh:bhList){ jxjsbh = Integer.valueOf(bh); TJxjs jxjs = jd.getJxjsByBh(jxjsbh); jxjs.setAjztbh(dmb.getDmbh()); jd.updateJxjs(jxjs); TSpxx spxx = new TSpxx(); spxx.setJxjsbh(jxjsbh); spxx.setSplx("1"); spxx.setSpr(yhb); spxx.setSpsj(new Date()); spxx.setSpyj(spyj); spxxbh = spxxDao.getMaxBh(); spxxbh ++; spxx.setSpxxbh(spxxbh); spxxDao.save(spxx); } } public TJxjs add(TJxjs jxjs){ int jxjsbh = jd.getMaxBh(); jxjsbh ++; jxjs.setJxjsbh(jxjsbh); jd.save(jxjs); return jxjs; } public void update(TJxjs jxjs){ jd.updateJxjs(jxjs); } public void delete(TJxjs jxjs){ jd.delete(jxjs); } }
package ca.stephenjust.todolist; import java.util.List; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.TextView; public class TodoAdapter extends ArrayAdapter<TodoItem> { final Context m_context; final List<TodoItem> m_items; public TodoAdapter(Context context, List<TodoItem> objects) { super(context, R.layout.list_todo, objects); m_context = context; m_items = objects; } @Override public View getView(int position, View convertView, ViewGroup parent) { View rowView; LayoutInflater inflater = (LayoutInflater) m_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); if (convertView != null) { rowView = convertView; } else { rowView = inflater.inflate(R.layout.list_todo, parent, false); } CheckBox check = (CheckBox) rowView.findViewById(R.id.check_todo); TextView text = (TextView) rowView.findViewById(R.id.text_todo); TodoItem item = m_items.get(position); check.setOnCheckedChangeListener(null); // Clear listener before setting value check.setChecked(item.getCompleted()); check.setOnCheckedChangeListener(new TodoCheckboxListener(position)); check.setText(item.getText()); text.setText(item.getText()); text.setVisibility(View.GONE); return rowView; } private class TodoCheckboxListener implements OnCheckedChangeListener { int m_position; public TodoCheckboxListener(int position) { m_position = position; } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { m_items.get(m_position).setCompleted(isChecked); } } }
package net.sourceforge.cilib.pso.guideprovider; import net.sourceforge.cilib.algorithm.AbstractAlgorithm; import net.sourceforge.cilib.pso.PSO; import net.sourceforge.cilib.pso.particle.Particle; import net.sourceforge.cilib.type.types.container.StructuredType; import net.sourceforge.cilib.type.types.container.Vector; import net.sourceforge.cilib.util.selection.recipes.Selector; import net.sourceforge.cilib.util.selection.recipes.TournamentSelector; public class SelectionGuideProvider implements GuideProvider { private Selector<Particle> selector; private boolean perDimension; private GuideProvider component; public SelectionGuideProvider() { this.selector = new TournamentSelector(); this.perDimension = true; this.component = new CurrentPositionGuideProvider(); } private SelectionGuideProvider(SelectionGuideProvider other) { this.selector = other.selector; this.perDimension = other.perDimension; this.component = other.component.getClone(); } @Override public SelectionGuideProvider getClone() { return new SelectionGuideProvider(this); } @Override public StructuredType get(Particle particle) { fj.data.List<Particle> topology = ((PSO) AbstractAlgorithm.get()).getTopology(); if (perDimension) { Vector.Builder builder = Vector.newBuilder(); for (int i = 0; i < particle.getDimension(); i++) { Vector v = (Vector) component.get(selector.on(topology).select()); builder.add(v.get(i)); } return builder.build(); } return component.get(selector.on(topology).select()); } public void setSelector(Selector<Particle> selector) { this.selector = selector; } public void setPerDimension(boolean perDimension) { this.perDimension = perDimension; } public void setComponent(GuideProvider component) { this.component = component; } }
package io.apiman.manager.api.rest.impl; import io.apiman.common.logging.ApimanLoggerFactory; import io.apiman.common.logging.IApimanLogger; import io.apiman.common.util.Preconditions; import io.apiman.manager.api.beans.download.BlobDto; import io.apiman.manager.api.beans.download.BlobRef; import io.apiman.manager.api.core.IBlobStore; import io.apiman.manager.api.rest.IBlobResource; import io.apiman.manager.api.rest.impl.util.MultipartHelper; import io.apiman.manager.api.rest.impl.util.MultipartHelper.MultipartUploadHolder; import io.apiman.manager.api.security.ISecurityContext; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.net.URI; import java.util.regex.Pattern; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriBuilder; import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput; import static java.util.regex.Pattern.CASE_INSENSITIVE; /** * Implementation of the Blob REST API. * * @author Marc Savy {@literal <marc@blackparrotlabs.io>} */ @ApplicationScoped public class BlobResourceImpl implements IBlobResource { private static final IApimanLogger LOGGER = ApimanLoggerFactory.getLogger(BlobResourceImpl.class); private static final Pattern IMAGE_SUBTYPES_ALLOWED = Pattern.compile("^(apng|png|jpg|jpeg|jfif|pjpeg|pjp|svg|webp|gif|avif)$", CASE_INSENSITIVE); private IBlobStore blobStore; private ISecurityContext securityContext; @Inject public BlobResourceImpl(IBlobStore blobStore, ISecurityContext securityContext) { this.blobStore = blobStore; this.securityContext = securityContext; } public BlobResourceImpl() {} /** * {@inheritDoc} * * <p>Serves the blob as a stream * * @param uid file's unique ID. * @return the file in response. */ @Override public Response getBlob(String uid) { BlobDto blob = blobStore.getBlob(uid); if (blob == null) { LOGGER.trace("Blob requested but not found: {0}", uid); return Response.status(Status.NOT_FOUND).build(); } else { try { LOGGER.trace("Blob requested: {0}", blob); InputStream bis = blob.getBlob().asByteSource().openBufferedStream(); return Response.ok() .header("Content-Type", blob.getMimeType()) .entity(bis) .build(); } catch (IOException ioe) { throw new UncheckedIOException(ioe); } } } @Override public Response uploadBlob(MultipartFormDataInput multipartInput) throws IOException { Preconditions.checkState(securityContext.getCurrentUser() != null, "Must be logged in!"); // Try to do image first as it is probably more likely to fail. MultipartUploadHolder image = MultipartHelper.getRequiredImage(multipartInput, "image", 1_048_576); /* We'll ignore the filename and generate our own to make security a bit easier. Preconditions.checkArgument(image.getFilename().length() > 254, "Filename too long"); Preconditions.checkArgument(checkExtension(image.getFilename()), "Must have a recognised image extension"); */ Preconditions.checkArgument(checkExtension(image.getMediaType().getSubtype()), "Must have a recognised image content type (" + IMAGE_SUBTYPES_ALLOWED + ")"); String filename = System.currentTimeMillis() + "." + image.getMediaType().getSubtype(); // Blob is unreferenced and will be deleted if nobody attaches to it. BlobRef blobRef = blobStore.storeBlob(filename, image.getMediaType().toString(), image.getFileBackedOutputStream(), 0); // Where the blob can be resolved URI location = UriBuilder.fromResource(IBlobResource.class).path(blobRef.getId()).build(); return Response .created(location) .entity(blobRef) .build(); } private boolean checkExtension(String ext) { return IMAGE_SUBTYPES_ALLOWED.matcher(ext).matches(); } }
import ucar.nc2.NetcdfFile; import ucar.nc2.Variable; import ucar.ma2.*; import java.io.IOException; public class Simple_xy_rd { public static void main(String args[]) throws Exception, java.lang.NullPointerException { final int NX = 6; final int NY = 12; // This is the array we will read. int[][] dataIn = new int[NX][NY]; // Open the file. The ReadOnly parameter tells netCDF we want // read-only access to the file. NetcdfFile dataFile = null; String filename = "simple_xy.nc"; // Open the file. try { dataFile = NetcdfFile.open(filename, null); // Retrieve the variable named "data" Variable dataVar = dataFile.findVariable("data"); if (dataVar == null) { System.out.println("Cant find Variable data"); return; } // Read all the values from the "data" variable into memory. int [] shape = dataVar.getShape(); int[] origin = new int[2]; ArrayInt.D2 dataArray; dataArray = (ArrayInt.D2) dataVar.read(origin, shape); // Check the values. assert shape[0] == NX; assert shape[1] == NY; for (int j=0; j<shape[0]; j++) { for (int i=0; i<shape[1]; i++) { dataIn[j][i] = dataArray.get(j,i); } } // The file is closed no matter what by putting inside a try/catch block. } catch (java.io.IOException e) { e.printStackTrace(); return; } catch (InvalidRangeException e) { e.printStackTrace(); } finally { if (dataFile != null) try { dataFile.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } System.out.println( "*** SUCCESS reading example file simple_xy.nc!"); } }
package org.echovantage.metafactory; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Generated; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.lang.model.SourceVersion; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.PackageElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.MirroredTypeException; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.tools.Diagnostic.Kind; import javax.tools.FileObject; import javax.tools.JavaFileManager; import javax.tools.JavaFileManager.Location; import javax.tools.JavaFileObject; import javax.tools.StandardLocation; /** * @author Fuwjax */ @SupportedAnnotationTypes("*") public class MetafactoryAnnotationProcessor extends AbstractProcessor { private final DateFormat ISO8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); private final Map<CharSequence, MetaFactory> metas = new HashMap<>(); @Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.latestSupported(); } @Override public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv) { for(final TypeElement annotation : annotations) { if(annotation.getAnnotation(Meta.class) == null) { continue; } try { MetaFactory factory = metas.get(annotation.getQualifiedName()); if(factory == null) { factory = new MetaFactory(annotation); metas.put(annotation.getQualifiedName(), factory); } for(final Element service : roundEnv.getElementsAnnotatedWith(annotation)) { factory.process((TypeElement) service); } } catch(final IOException e) { error(annotation, "IO error while processing annotation: %s", e.getLocalizedMessage()); } catch(final RuntimeException e) { error(annotation, "Unexpected exception: %s: %s", e.getClass(), e.getLocalizedMessage()); e.printStackTrace(); } } if(roundEnv.processingOver()) { for(final MetaFactory factory : metas.values()) { factory.writeMetaInfServices(); } } return false; } private class MetaFactory { final Set<String> factories = new HashSet<>(); final Set<Element> services = new HashSet<>(); private final TypeElement contract; private final ExecutableElement method; private final TypeElement annotation; public MetaFactory(final TypeElement annotation) throws IOException { this.annotation = annotation; contract = typeOf(annotation.getAnnotation(Meta.class)); method = serviceMethod(); loadExisting(); } private void loadExisting() throws IOException { try { final FileObject f = getResource(StandardLocation.SOURCE_PATH, "", metaInfServices()); try(InputStream input = f.openInputStream(); Reader reader = new InputStreamReader(input, "UTF-8"); final BufferedReader r = new BufferedReader(reader)) { String line; while((line = r.readLine()) != null) { final TypeElement type = typeOf(line); if(isService(type) && isAssignable(contract, type)) { factories.add(line); } else { error("Existing service factory %s is not a public concrete class with a default constructor implementing %s, removing it from meta-inf/services", type, contract); } } } } catch(final FileNotFoundException x) { // doesn't exist } } private String metaInfServices() { return "META-INF/services/" + binaryNameOf(contract); } private ExecutableElement serviceMethod() { if(!isInterface(contract) && !hasPublicDefaultConstructor(contract)) { error("Service contract %s must be an interface or abstract class with a default constructor", contract); return null; } ExecutableElement m = null; for(final Element e : contract.getEnclosedElements()) { if(e.getKind() == ElementKind.METHOD) { if(e.getModifiers().contains(Modifier.ABSTRACT)) { if(m != null) { error("Service contract %s must contain exactly one abstract method", contract); return null; } m = (ExecutableElement) e; } } } return m; } public void process(final TypeElement service) throws IOException { if(method == null) { return; } final Generated generated = service.getAnnotation(Generated.class); if(generated != null && Arrays.asList(generated.value()).contains(MetafactoryAnnotationProcessor.class.getCanonicalName())) { return; } if(!isAssignable(typeOf(method.getReturnType()), service)) { error("%s is not a %s, service does not satisfy factory method signature", service, method.getReturnType()); } else if(!hasConstructor(service, method)) { error("%s does not have a constructor that matches the signature of %s", service, method); } else if(services.add(service)) { factories.add(createFactory(contract, method, service)); } } public void writeMetaInfServices() { log("Writing " + metaInfServices()); try { final FileObject metainfServices = createResource(StandardLocation.CLASS_OUTPUT, "", metaInfServices(), services.toArray(new Element[services.size()])); try(Writer writer = metainfServices.openWriter(); PrintWriter pw = new PrintWriter(writer)) { for(final String value : factories) { pw.println(value); } } } catch(final IOException e) { error("IO error while writing to meta-inf/services: %s", e.getLocalizedMessage()); } catch(final RuntimeException e) { error("Unexpected exception: %s: %s", e.getClass(), e.getLocalizedMessage()); e.printStackTrace(); } } private void error(final String pattern, final Object... args) { MetafactoryAnnotationProcessor.this.error(annotation, pattern, args); } } static boolean isInterface(final TypeElement contract) { return contract.getKind() == ElementKind.INTERFACE; } String createFactory(final TypeElement contract, final ExecutableElement method, final TypeElement service) throws IOException { final String name = service.getQualifiedName() + "CgFactory"; final JavaFileObject f = processingEnv.getFiler().createSourceFile(name, contract, service); try(final PrintWriter pw = new PrintWriter(f.openWriter())) { pw.printf("package %s;", packageOf(service)).println(); for(final AnnotationMirror annotation : service.getAnnotationMirrors()) { pw.println(annotation); } pw.printf("@javax.annotation.Generated(value=\"%s\", date=\"%s\")", MetafactoryAnnotationProcessor.class.getCanonicalName(), ISO8601.format(new Date())).println(); pw.printf("public final class %sCgFactory %s %s {", service.getSimpleName(), isInterface(contract) ? "implements" : "extends", contract.getQualifiedName()).println(); pw.printf(" public %s %s(", service.getSimpleName(), method.getSimpleName()); String delim = ""; for(final VariableElement param : method.getParameters()) { pw.print(delim); pw.printf("%s %s", typeOf(param.asType()).getQualifiedName(), param.getSimpleName()); delim = ", "; } pw.print(")"); delim = " throws "; for(final TypeMirror ex : method.getThrownTypes()) { pw.print(delim); pw.print(typeOf(ex).getQualifiedName()); delim = ", "; } pw.println(" {"); pw.printf(" return new %s(", service.getSimpleName()); delim = ""; for(final VariableElement param : method.getParameters()) { pw.print(delim); pw.print(param.getSimpleName()); delim = ", "; } pw.println(");"); pw.println(" }"); pw.println("}"); } return name; } static boolean hasConstructor(final TypeElement type, final ExecutableElement signature) { for(final Element e : type.getEnclosedElements()) { if(e.getKind().equals(ElementKind.CONSTRUCTOR)) { final ExecutableElement constructor = (ExecutableElement) e; if(isCallable(constructor.getParameters(), signature.getParameters())) { return true; } } } return false; } static boolean isCallable(final List<? extends VariableElement> cParams, final List<? extends VariableElement> mParams) { if(cParams.size() != mParams.size()) { return false; } for(int i = 0; i < cParams.size(); i++) { if(!isAssignable(typeOf(cParams.get(i).asType()), typeOf(mParams.get(i).asType()))) { return false; } } return true; } PackageElement packageOf(final Element service) { final Element e = service.getEnclosingElement(); if(e == null) { return null; } return e.getKind() == ElementKind.PACKAGE ? (PackageElement) e : packageOf(e); } FileObject createResource(final JavaFileManager.Location location, final CharSequence pkg, final CharSequence relativeName, final Element... originatingElements) throws IOException { return processingEnv.getFiler().createResource(location, pkg, relativeName, originatingElements); } FileObject getResource(final Location location, final CharSequence pkg, final CharSequence relativeName) throws IOException { return processingEnv.getFiler().getResource(location, pkg, relativeName); } String binaryNameOf(final TypeElement elm) { return processingEnv.getElementUtils().getBinaryName(elm).toString(); } TypeElement typeOf(final String name) { return processingEnv.getElementUtils().getTypeElement(name); } TypeElement typeOf(final Meta meta) { try { final Class<?> cls = meta.value(); return typeOf(cls.getName()); } catch(final MirroredTypeException e) { return typeOf(e.getTypeMirror()); } } static boolean isAssignable(final TypeElement variable, final TypeElement expression) { if(expression == null) { return false; } if(variable.equals(expression)) { return true; } if(isAssignable(variable, typeOf(expression.getSuperclass()))) { return true; } for(final TypeMirror i : expression.getInterfaces()) { if(isAssignable(variable, typeOf(i))) { return true; } } return false; } static TypeElement typeOf(final TypeMirror superclass) { return superclass.getKind() == TypeKind.NONE ? null : (TypeElement) ((DeclaredType) superclass).asElement(); } static boolean isService(final TypeElement type) { if(!type.getKind().isClass()) { return false; } if(isAbstract(type)) { return false; } if(isNested(type) && !isStatic(type)) { return false; } return hasPublicDefaultConstructor(type); } static boolean isStatic(final TypeElement type) { return type.getModifiers().contains(Modifier.STATIC); } static boolean isNested(final TypeElement type) { return !ElementKind.PACKAGE.equals(type.getEnclosingElement().getKind()); } static boolean isAbstract(final TypeElement type) { return type.getModifiers().contains(Modifier.ABSTRACT); } static boolean hasPublicDefaultConstructor(final TypeElement type) { for(final Element e : type.getEnclosedElements()) { if(e.getKind().equals(ElementKind.CONSTRUCTOR) && ((ExecutableElement) e).getParameters().isEmpty()) { return isPublic(type); } } return false; } static boolean isPublic(final TypeElement type) { return type.getModifiers().contains(Modifier.PUBLIC); } void log(final String pattern, final Object... args) { processingEnv.getMessager().printMessage(Kind.NOTE, String.format(pattern, args)); } void error(final Element source, final String pattern, final Object... args) { processingEnv.getMessager().printMessage(Kind.ERROR, String.format(pattern, args), source); } }
package io.spine.model.assemble; import io.spine.annotation.SPI; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Messager; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import java.lang.annotation.Annotation; import java.util.Map; import java.util.Optional; import java.util.Set; import static java.util.Collections.singleton; import static javax.tools.Diagnostic.Kind.ERROR; import static javax.tools.Diagnostic.Kind.WARNING; /** * An abstract base for the Spine * {@linkplain javax.annotation.processing.Processor annotation processors}. * * <p>This class provides the handy lifecycle for the processors basing on their round-oriented * nature. * * <p>Be sure to add the fully qualified name of your implementation of this class to * {@code resources/META_INF/services/javax.annotation.processing.Processor} to make it visible * to the compiler. * * <p>Warning: do not use standard Java {@linkplain Throwable throwables} in the methods of this * class to intentionally break the compilation. It may cause unreadable error messages. Use * {@link #error(String) error()} method instead with the error message. Use throwables only * to state the programming mistakes in the processor itself. * * @author Dmytro Dashenkov */ @SPI public abstract class SpineAnnotationProcessor extends AbstractProcessor { @SuppressWarnings("FieldAccessedSynchronizedAndUnsynchronized") // Initialized in the synchronized `init` method. private Messager messager; @SuppressWarnings("FieldAccessedSynchronizedAndUnsynchronized") // Initialized in the synchronized `init` method. private Map<String, String> options; /** * Retrieves the supported by this processor annotation type. * * <p>Basic implementation example is: * <pre> * {@code @Override * protected Class getAnnotationType() { * return Assign.class; * }} * </pre> * * <p>Note: it's required that this method returns the same value on any invocation. * * @return the {@link Class} of the target annotation */ protected abstract Class<? extends Annotation> getAnnotationType(); /** * Performs the processing of the given annotated {@linkplain Element code element}. * * <p>It's guaranteed that the argument is annotated with * the {@linkplain #getAnnotationType() processor target annotation}. * * <p>The processing may include validation, code generation, etc. */ protected abstract void processElement(Element element); /** * States if the processing of the annotation is finished or not. * * @return {@code true} if the processing of the annotation is finished, {@code false} otherwise * @see javax.annotation.processing.Processor#process return section for the usage */ protected abstract boolean isFinished(); /** * A lifecycle method called when a processing round is started. * * <p>Does nothing by default. Override this method to change the processing flow. */ @SuppressWarnings("NoopMethodInAbstractClass") protected void onRoundStarted() { // NoOp } /** * A lifecycle method called when a processing round is finished. * * <p>Does nothing by default. Override this method to change the processing flow. */ @SuppressWarnings("NoopMethodInAbstractClass") protected void onRoundFinished() { // NoOp } @Override public final synchronized void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); this.messager = processingEnv.getMessager(); this.options = processingEnv.getOptions(); } @Override public final Set<String> getSupportedAnnotationTypes() { Set<String> names = singleton(getAnnotationType().getName()); return names; } @Override public final SourceVersion getSupportedSourceVersion() { return SourceVersion.latestSupported(); } @Override public final boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { if (roundEnv.errorRaised() || roundEnv.processingOver()) { return true; } onRoundStarted(); processAnnotation(getAnnotationType(), roundEnv); onRoundFinished(); boolean result = isFinished(); return result; } private void processAnnotation(Class<? extends Annotation> annotation, RoundEnvironment roundEnv) { Set<? extends Element> annotated = roundEnv.getElementsAnnotatedWith(annotation); for (Element element : annotated) { processElement(element); } } /** * Prints an error message. * * <p>A call to this method causes eventual compilation failure. * * @param message the error message to print * @see Messager#printMessage for more details */ protected final void error(String message) { messager.printMessage(ERROR, message); } /** * Prints a compiler warning. * * @param message the error message to print * @see Messager#printMessage for more details */ protected final void warn(String message) { messager.printMessage(WARNING, message); } /** * Retrieves the value of the given annotation processor option. * * <p>The options are passed to the compiler as follows: {@code javac -Akey=value [...]}. * * @param optName the name of the desired option * @return the value of the desired option or {@link Optional#empty() Optional.empty()} if * the option is not present in the processor or has no value (i.e. is a flag option) */ protected final Optional<String> getOption(String optName) { String optValue = options.get(optName); return Optional.ofNullable(optValue); } }
package org.mrgeo.resources.wcs; import org.mrgeo.rasterops.OpImageRegistrar; import org.mrgeo.services.SecurityUtils; import org.mrgeo.services.Version; import org.mrgeo.services.mrspyramid.rendering.ImageHandlerFactory; import org.mrgeo.services.mrspyramid.rendering.ImageRenderer; import org.mrgeo.services.mrspyramid.rendering.ImageResponseWriter; import org.mrgeo.services.utils.DocumentUtils; import org.mrgeo.services.utils.RequestUtils; import org.mrgeo.utils.Bounds; import org.mrgeo.utils.XmlUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.CDATASection; import org.w3c.dom.Document; import org.w3c.dom.Element; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.awt.image.Raster; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.util.List; import java.util.Properties; @Path("/wcs") public class WcsGenerator { private static final Logger log = LoggerFactory.getLogger(WcsGenerator.class); public static final String WCS_VERSION = "2.0.1"; private Version version = null; @GET public Response doGet(@Context UriInfo uriInfo) { return handleRequest(uriInfo); } @POST public Response doPost(@Context UriInfo uriInfo) { return handleRequest(uriInfo); } private Response handleRequest(UriInfo uriInfo) { long start = System.currentTimeMillis(); MultivaluedMap<String, String> allParams = uriInfo.getQueryParameters(); String request = getQueryParam(allParams, "request", "GetCapabilities"); Properties providerProperties = SecurityUtils.getProviderProperties(); try { String serviceName = getQueryParam(allParams, "service"); if (serviceName == null) { return writeError(Response.Status.BAD_REQUEST, "Missing required SERVICE parameter. Should be set to \"WMS\""); } if (!serviceName.equalsIgnoreCase("wms")) { return writeError(Response.Status.BAD_REQUEST, "Invalid SERVICE parameter. Should be set to \"WMS\""); } if (request.equalsIgnoreCase("getcapabilities")) { return getCapabilities(uriInfo, allParams, providerProperties); } else if (request.equalsIgnoreCase("describecoverage")) { return describeCoverage(uriInfo, allParams, providerProperties); } else if (request.equalsIgnoreCase("getcoverage")) { return getCoverage(allParams, providerProperties); } return writeError(Response.Status.BAD_REQUEST, "Invalid request"); } finally { if (log.isDebugEnabled()) { log.debug("WCS request time: {}ms", (System.currentTimeMillis() - start)); // this can be resource intensive. System.gc(); final Runtime rt = Runtime.getRuntime(); log.debug(String.format("WMS request memory: %.1fMB / %.1fMB\n", (rt.totalMemory() - rt .freeMemory()) / 1e6, rt.maxMemory() / 1e6)); } } } /** * Returns the value for the specified paramName case-insensitively. If the * parameter does not exist, it returns null. * * @param allParams * @param paramName * @return */ private String getQueryParam(MultivaluedMap<String, String> allParams, String paramName) { for (String key: allParams.keySet()) { if (key.equalsIgnoreCase(paramName)) { List<String> value = allParams.get(key); if (value.size() == 1) { return value.get(0); } } } return null; } private Response describeCoverage(UriInfo uriInfo, MultivaluedMap<String,String> allParams, final Properties providerProperties) { // String versionStr = getQueryParam(allParams, "version", "1.4.0"); // version = new Version(versionStr); // if (version.isLess("1.4.0")) // return writeError(Response.Status.BAD_REQUEST, "Describe tiles is only supported with version >= 1.4.0"); // try // final DescribeTilesDocumentGenerator docGen = new DescribeTilesDocumentGenerator(); // final Document doc = docGen.generateDoc(version, uriInfo.getRequestUri().toString(), // getPyramidFilesList(providerProperties)); // ByteArrayOutputStream xmlStream = new ByteArrayOutputStream(); // final PrintWriter out = new PrintWriter(xmlStream); // // DocumentUtils.checkForErrors(doc); // DocumentUtils.writeDocument(doc, version, out); // out.close(); // return Response.ok(xmlStream.toString()).type(MediaType.APPLICATION_XML).build(); // catch (Exception e) // return writeError(Response.Status.BAD_REQUEST, e); return writeError(Response.Status.BAD_REQUEST, "Not Implemented"); } private Response getCapabilities(UriInfo uriInfo, MultivaluedMap<String, String> allParams, Properties providerProperties) { // The versionParamName will be null if the request did not include the // version parameter. String versionParamName = getActualQueryParamName(allParams, "version"); String versionStr = getQueryParam(allParams, "version", "1.1.1"); Version version = new Version(versionStr); // final GetCapabilitiesDocumentGenerator docGen = new GetCapabilitiesDocumentGenerator(); // try // // The following code re-builds the request URI to include in the GetCapabilities // // output. It sorts the parameters so that they are included in the URI in a // // predictable order. The reason for this is so that test cases can compare XML // // golden files against the XML generated here without worrying about parameters // // shifting locations in the URI. // Set<String> keys = uriInfo.getQueryParameters().keySet(); // String[] sortedKeys = new String[keys.size()]; // keys.toArray(sortedKeys); // Arrays.sort(sortedKeys); // UriBuilder builder = uriInfo.getBaseUriBuilder().path(uriInfo.getPath()); // for (String key : sortedKeys) // // Only include the VERSION parameter in the URI used in GetCapabilities // // if it was included in the original URI request. // if (key.equalsIgnoreCase("version")) // if (versionParamName != null) // builder = builder.queryParam(versionParamName, versionStr); // else // builder = builder.queryParam(key, getQueryParam(allParams, key)); // final Document doc = docGen.generateDoc(version, builder.build().toString(), // getPyramidFilesList(providerProperties)); // ByteArrayOutputStream xmlStream = new ByteArrayOutputStream(); // final PrintWriter out = new PrintWriter(xmlStream); // // DocumentUtils.checkForErrors(doc); // DocumentUtils.writeDocument(doc, version, out); // out.close(); // return Response.ok(xmlStream.toString()).type(MediaType.APPLICATION_XML).build(); // catch (Exception e) // return writeError(Response.Status.BAD_REQUEST, e); return writeError(Response.Status.BAD_REQUEST, "Not Implemented"); } private Response getCoverage(MultivaluedMap<String, String> allParams, Properties providerProperties) { OpImageRegistrar.registerMrGeoOps(); // Get all of the query parameter values needed and validate them String layers = getQueryParam(allParams, "coverage"); String[] layerNames = null; if (layers != null && !layers.isEmpty()) { layerNames = layers.split(","); } if (layerNames == null || layerNames.length == 0) { return writeError(Response.Status.BAD_REQUEST, "Missing required COVERAGE parameter"); } if (layerNames.length > 1) { return writeError(Response.Status.BAD_REQUEST, "Only one COVERAGE is supported"); } String srs = null; try { srs = getCrsParam(allParams); } catch (Exception e) { return writeError(Response.Status.BAD_REQUEST, e); } Bounds bounds = null; try { bounds = getBoundsParam(allParams, "bbox"); } catch (Exception e) { return writeError(Response.Status.BAD_REQUEST, e.getMessage()); } String format = getQueryParam(allParams, "format"); if (format == null) { return writeError(Response.Status.BAD_REQUEST, "Missing required FORMAT parameter"); } int width = getQueryParamAsInt(allParams, "width", -1); if (width < 0) { return writeError(Response.Status.BAD_REQUEST, "Missing required WIDTH parameter"); } else if (width == 0) { return writeError(Response.Status.BAD_REQUEST, "WIDTH parameter must be greater than 0"); } int height = getQueryParamAsInt(allParams, "height", -1); if (height < 0) { return writeError(Response.Status.BAD_REQUEST, "Missing required HEIGHT parameter"); } else if (height == 0) { return writeError(Response.Status.BAD_REQUEST, "HEIGHT parameter must be greater than 0"); } ImageRenderer renderer = null; try { renderer = (ImageRenderer) ImageHandlerFactory.getHandler(format, ImageRenderer.class); } catch (Exception e) { return writeError(Response.Status.BAD_REQUEST, e.getMessage()); } // Reproject bounds to EPSG:4326 if necessary try { bounds = RequestUtils.reprojectBounds(bounds, srs); } catch (org.opengis.referencing.NoSuchAuthorityCodeException e) { return writeError(Response.Status.BAD_REQUEST, "InvalidCRS", e.getMessage()); } catch (Exception e) { return writeError(Response.Status.BAD_REQUEST, e); } // Return the resulting image try { Raster result = renderer.renderImage(layerNames[0], bounds, width, height, providerProperties, srs); Response.ResponseBuilder builder = ((ImageResponseWriter) ImageHandlerFactory .getHandler(format, ImageResponseWriter.class)) .write(result, layerNames[0], bounds); return builder.build(); } catch (Exception e) { log.error("Unable to render the image in getCoverage", e); return writeError(Response.Status.BAD_REQUEST, e); } } /** * Returns the value for the specified paramName case-insensitively. If the * parameter does not exist, it returns defaultValue. * * @param allParams * @param paramName * @param defaultValue * @return */ private String getQueryParam(MultivaluedMap<String, String> allParams, String paramName, String defaultValue) { String value = getQueryParam(allParams, paramName); if (value != null) { return value; } return defaultValue; } private String getActualQueryParamName(MultivaluedMap<String, String> allParams, String paramName) { for (String key: allParams.keySet()) { if (key.equalsIgnoreCase(paramName)) { return key; } } return null; } /** * Returns the int value for the specified paramName case-insensitively. If * the parameter value exists, but is not an int, it throws a NumberFormatException. * If it does not exist, it returns defaultValue. * * @param allParams * @param paramName * @return */ private int getQueryParamAsInt(MultivaluedMap<String, String> allParams, String paramName, int defaultValue) throws NumberFormatException { for (String key: allParams.keySet()) { if (key.equalsIgnoreCase(paramName)) { List<String> value = allParams.get(key); if (value.size() == 1) { return Integer.parseInt(value.get(0)); } } } return defaultValue; } /** * Returns the int value for the specified paramName case-insensitively. If * the parameter value exists, but is not an int, it throws a NumberFormatException. * If it does not exist, it returns defaultValue. * * @param allParams * @param paramName * @return */ private double getQueryParamAsDouble(MultivaluedMap<String, String> allParams, String paramName, double defaultValue) throws NumberFormatException { for (String key: allParams.keySet()) { if (key.equalsIgnoreCase(paramName)) { List<String> value = allParams.get(key); if (value.size() == 1) { return Double.parseDouble(value.get(0)); } } } return defaultValue; } private Bounds getBoundsParam(MultivaluedMap<String, String> allParams, String paramName) throws Exception { String bbox = getQueryParam(allParams, paramName); if (bbox == null) { throw new Exception("Missing required BBOX parameter"); } String[] bboxComponents = bbox.split(","); if (bboxComponents.length != 4) { throw new Exception("Invalid BBOX parameter. Should contain minX, minY, maxX, maxY"); } double[] bboxValues = new double[4]; for (int index=0; index < bboxComponents.length; index++) { try { bboxValues[index] = Double.parseDouble(bboxComponents[index]); } catch (NumberFormatException nfe) { throw new Exception("Invalid BBOX value: " + bboxComponents[index]); } } return new Bounds(bboxValues[0], bboxValues[1], bboxValues[2], bboxValues[3]); } private String getCrsParam(MultivaluedMap<String, String> allParams) throws Exception { String crs = getQueryParam(allParams, "crs"); if (crs == null || crs.isEmpty()) { return null; } else { return crs; } } /* * Writes OGC spec error messages to the response */ private Response writeError(Response.Status httpStatus, final Exception e) { try { Document doc; final DocumentBuilderFactory dBF = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder; builder = dBF.newDocumentBuilder(); doc = builder.newDocument(); final Element ser = doc.createElement("ServiceExceptionReport"); doc.appendChild(ser); ser.setAttribute("version", WCS_VERSION); final Element se = XmlUtils.createElement(ser, "ServiceException"); String msg = e.getLocalizedMessage(); if (msg == null || msg.isEmpty()) { msg = e.getClass().getName(); } final ByteArrayOutputStream strm = new ByteArrayOutputStream(); e.printStackTrace(new PrintStream(strm)); CDATASection msgNode = doc.createCDATASection(strm.toString()); se.appendChild(msgNode); final ByteArrayOutputStream xmlStream = new ByteArrayOutputStream(); final PrintWriter out = new PrintWriter(xmlStream); DocumentUtils.writeDocument(doc, version, out); out.close(); return Response .status(httpStatus) .header("Content-Type", MediaType.TEXT_XML) .entity(xmlStream.toString()) .build(); } catch (ParserConfigurationException e1) { } catch (TransformerException e1) { } // Fallback in case there is an XML exception above return Response.status(httpStatus).entity(e.getLocalizedMessage()).build(); } /* * Writes OGC spec error messages to the response */ private Response writeError(Response.Status httpStatus, final String msg) { try { Document doc; final DocumentBuilderFactory dBF = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = dBF.newDocumentBuilder(); doc = builder.newDocument(); final Element ser = doc.createElement("ServiceExceptionReport"); doc.appendChild(ser); ser.setAttribute("version", WCS_VERSION); final Element se = XmlUtils.createElement(ser, "ServiceException"); CDATASection msgNode = doc.createCDATASection(msg); se.appendChild(msgNode); final ByteArrayOutputStream xmlStream = new ByteArrayOutputStream(); final PrintWriter out = new PrintWriter(xmlStream); DocumentUtils.writeDocument(doc, version, out); out.close(); return Response .status(httpStatus) .header("Content-Type", MediaType.TEXT_XML) .entity(xmlStream.toString()) .build(); } catch (ParserConfigurationException e1) { } catch (TransformerException e1) { } // Fallback in case there is an XML exception above return Response.status(httpStatus).entity(msg).build(); } /* * Writes OGC spec error messages to the response */ private Response writeError(Response.Status httpStatus, final String code, final String msg) { try { Document doc; final DocumentBuilderFactory dBF = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = dBF.newDocumentBuilder(); doc = builder.newDocument(); final Element ser = doc.createElement("ServiceExceptionReport"); doc.appendChild(ser); ser.setAttribute("version", WCS_VERSION); final Element se = XmlUtils.createElement(ser, "ServiceException"); se.setAttribute("code", code); CDATASection msgNode = doc.createCDATASection(msg); se.appendChild(msgNode); final ByteArrayOutputStream xmlStream = new ByteArrayOutputStream(); final PrintWriter out = new PrintWriter(xmlStream); DocumentUtils.writeDocument(doc, version, out); out.close(); return Response .status(httpStatus) .header("Content-Type", MediaType.TEXT_XML) .entity(xmlStream.toString()) .build(); } catch (ParserConfigurationException e1) { } catch (TransformerException e1) { } // Fallback in case there is an XML exception above return Response.status(httpStatus).entity(msg).build(); } }
package org.navalplanner.business.util.deepcopy; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import org.apache.commons.lang.Validate; import org.hibernate.proxy.HibernateProxy; import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.navalplanner.business.workingday.EffortDuration; public class DeepCopy { private static Set<Class<?>> inmmutableTypes = new HashSet<Class<?>>(Arrays .<Class<?>> asList(Boolean.class, String.class, BigDecimal.class, Double.class, Float.class, Integer.class, Short.class, Byte.class, Character.class, LocalDate.class, DateTime.class, EffortDuration.class)); public static boolean isImmutableType(Class<?> klass) { return klass.isPrimitive() || isEnum(klass) || inmmutableTypes.contains(klass); } private static boolean isEnum(Class<?> klass) { Class<?> currentClass = klass; do { if (currentClass.isEnum()) { return true; } currentClass = currentClass.getSuperclass(); } while (currentClass != null); return false; } public interface ICustomCopy { public boolean canHandle(Object object); public Object instantiateCopy(Strategy strategy, Object originValue); public void copyDataToResult(DeepCopy deepCopy, Object origin, Strategy strategy, Object result); } private static class DateCopy implements ICustomCopy { @Override public boolean canHandle(Object object) { return object instanceof Date; } @Override public void copyDataToResult(DeepCopy deepCopy, Object origin, Strategy strategy, Object result) { // already completed } @Override public Object instantiateCopy(Strategy strategy, Object originValue) { Date date = (Date) originValue; return new Date(date.getTime()); } } private static abstract class CollectionCopy implements ICustomCopy { @Override public Object instantiateCopy(Strategy strategy, Object originValue) { return getResultData(originValue); } protected abstract Collection<Object> getResultData(Object originValue); @Override public void copyDataToResult(DeepCopy deepCopy, Object origin, Strategy strategy, Object result) { copy(deepCopy, origin, strategy, (Collection<Object>) result); } private void copy(DeepCopy deepCopy, Object origin, Strategy strategy, Collection<Object> destination) { Strategy childrenStrategy = getChildrenStrategy(strategy); for (Object each : originDataAsIterable(origin)) { destination.add(deepCopy.copy(each, childrenStrategy)); } } private Strategy getChildrenStrategy(Strategy strategy) { if (strategy == Strategy.SHARE_COLLECTION_ELEMENTS) { return Strategy.SHARE; } return strategy; } private Iterable<Object> originDataAsIterable(Object originValue) { return (Iterable<Object>) originValue; } } private static class SetCopy extends CollectionCopy { @Override public boolean canHandle(Object object) { return object instanceof Set; } @Override protected Collection<Object> getResultData(Object object) { return instantiate(object.getClass()); } private Set<Object> instantiate(final Class<? extends Object> klass) { return new ImplementationInstantiation() { @Override protected Set<?> createDefault() { if (SortedSet.class.isAssignableFrom(klass)) { return new TreeSet<Object>(); } return new HashSet<Object>(); } }.instantiate(klass); } } private static class MapCopy implements ICustomCopy { @Override public boolean canHandle(Object object) { return object instanceof Map; } @Override public Object instantiateCopy(Strategy strategy, Object originValue) { return instantiate(originValue.getClass()); } private Map<Object, Object> instantiate(Class<? extends Object> klass) { return new ImplementationInstantiation() { @Override protected Object createDefault() { return new HashMap<Object, Object>(); } }.instantiate(klass); } @Override public void copyDataToResult(DeepCopy deepCopy, Object origin, Strategy strategy, Object result) { doCopy(deepCopy, (Map<?, ?>) ((Map<?, ?>) origin), strategy, ((Map<Object, Object>) result)); } private void doCopy(DeepCopy deepCopy, Map<?, ?> origin, Strategy strategy, Map<Object, Object> resultMap) { Strategy keyStrategy = getKeysStrategy(strategy); Strategy valueStrategy = getValuesStrategy(strategy); for (Entry<?, ?> entry : origin.entrySet()) { Object key = deepCopy.copy(entry.getKey(), keyStrategy); Object value = deepCopy.copy(entry.getValue(), valueStrategy); resultMap.put(key, value); } } private Strategy getKeysStrategy(Strategy strategy) { if (Strategy.ONLY_SHARE_KEYS == strategy || Strategy.SHARE_COLLECTION_ELEMENTS == strategy) { return Strategy.SHARE; } return strategy; } private Strategy getValuesStrategy(Strategy strategy) { if (Strategy.ONLY_SHARE_VALUES == strategy || Strategy.SHARE_COLLECTION_ELEMENTS == strategy) { return Strategy.SHARE; } return strategy; } } private static class ListCopy extends CollectionCopy { @Override public boolean canHandle(Object object) { return object instanceof List; } @Override protected Collection<Object> getResultData(Object originValue) { return instantiate(originValue.getClass()); } private List<Object> instantiate(Class<? extends Object> klass) { return new ImplementationInstantiation() { @Override protected Object createDefault() { return new ArrayList<Object>(); } }.instantiate(klass); } } private static abstract class ImplementationInstantiation { private static final String[] VETOED_IMPLEMENTATIONS = { "PersistentSet", "PersistentList", "PersistentMap", "PersistentSortedSet" }; ImplementationInstantiation() { } <T> T instantiate(Class<?> type) { if (!isVetoed(type)) { try { Constructor<? extends Object> constructor = type .getConstructor(); return (T) type.cast(constructor.newInstance()); } catch (Exception e) { } } return (T) createDefault(); } private static boolean isVetoed(Class<?> type) { final String simpleName = type.getSimpleName(); for (String each : VETOED_IMPLEMENTATIONS) { if (each.equalsIgnoreCase(simpleName)) { return true; } } return false; } protected abstract Object createDefault(); } private static List<ICustomCopy> DEFAULT_CUSTOM_COPIERS = Arrays .<ICustomCopy> asList(new DateCopy(), new SetCopy(), new MapCopy(), new ListCopy()); private Map<ByIdentity, Object> alreadyCopiedObjects = new HashMap<ByIdentity, Object>(); private class ByIdentity { private final Object wrapped; ByIdentity(Object wrapped) { Validate.notNull(wrapped); this.wrapped = wrapped; } @Override public int hashCode() { return wrapped.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof ByIdentity) { ByIdentity other = (ByIdentity) obj; return this.wrapped == other.wrapped; } return false; } } private ByIdentity byIdentity(Object value) { return new ByIdentity(value); } public <T> T copy(T entity) { return copy(entity, null); } private <T> T copy(T couldBeProxyValue, Strategy strategy) { if (couldBeProxyValue == null) { return null; } T value = desproxify(couldBeProxyValue); if (alreadyCopiedObjects.containsKey(byIdentity(value))) { return (T) alreadyCopiedObjects.get(byIdentity(value)); } if (Strategy.SHARE == strategy || isImmutable(value)) { return value; } ICustomCopy copier = findCopier(value); if (copier != null) { Object resultData = copier.instantiateCopy(strategy, value); alreadyCopiedObjects.put(byIdentity(value), resultData); copier.copyDataToResult(this, value, strategy, resultData); return (T) resultData; } T result = instantiateUsingDefaultConstructor(getTypedClassFrom(value)); alreadyCopiedObjects.put(byIdentity(value), result); copyProperties(value, result); callAferCopyHooks(result); return result; } private <T> T desproxify(T value) { if (value instanceof HibernateProxy) { HibernateProxy proxy = (HibernateProxy) value; return (T) proxy.getHibernateLazyInitializer() .getImplementation(); } return value; } private boolean isImmutable(Object value) { return isImmutableType(value.getClass()); } @SuppressWarnings("unchecked") private <T> Class<T> getTypedClassFrom(T entity) { return (Class<T>) entity.getClass(); } private <T> T instantiateUsingDefaultConstructor(Class<T> klass) { Constructor<T> constructor; try { constructor = klass.getConstructor(); } catch (SecurityException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new IllegalArgumentException( "could not invoke default no-args constructor", e); } try { return constructor.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } private void copyProperties(Object source, Object target) { List<Field> fields = getAllFieldsFor(source); for (Field each : fields) { each.setAccessible(true); if (!isIgnored(each)) { Object sourceValue = readFieldValue(source, each); if (sourceValue != null) { Strategy strategy = getStrategy(each, sourceValue); try { writeFieldValue(target, each, copy(sourceValue, strategy)); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } } } } private List<Field> getAllFieldsFor(Object source) { List<Field> result = new ArrayList<Field>(); Class<? extends Object> currentClass = source.getClass(); while (currentClass != null) { result.addAll(Arrays.asList(currentClass.getDeclaredFields())); currentClass = currentClass.getSuperclass(); } return result; } private boolean isIgnored(Field field) { return isStatic(field) || isMarkedWithIgnore(field); } private boolean isStatic(Field field) { return Modifier.isStatic(field.getModifiers()); } private boolean isMarkedWithIgnore(Field each) { OnCopy onCopy = each.getAnnotation(OnCopy.class); return onCopy != null && onCopy.value() == Strategy.IGNORE; } private void writeFieldValue(Object target, Field field, Object value) { try { field.set(target, value); } catch (Exception e) { throw new RuntimeException(e); } } private Object readFieldValue(Object source, Field field) { try { return field.get(source); } catch (Exception e) { throw new RuntimeException(e); } } private Strategy getStrategy(Field field, Object sourceValue) { OnCopy onCopy = field.getAnnotation(OnCopy.class); return onCopy != null ? onCopy.value() : null; } private ICustomCopy findCopier(Object sourceValue) { for (ICustomCopy each : DEFAULT_CUSTOM_COPIERS) { if (each.canHandle(sourceValue)) { return each; } } return null; } private void callAferCopyHooks(Object value) { assert value != null; for (Method each : getAfterCopyHooks(value.getClass())) { each.setAccessible(true); try { each.invoke(value); } catch (Exception e) { throw new RuntimeException(e); } } } private List<Method> getAfterCopyHooks(Class<?> klass) { Class<?> current = klass; List<Method> result = new ArrayList<Method>(); while (current != null) { result.addAll(getAfterCopyDeclaredAt(current)); current = current.getSuperclass(); } return result; } private List<Method> getAfterCopyDeclaredAt(Class<?> klass) { List<Method> result = new ArrayList<Method>(); for (Method each : klass.getDeclaredMethods()) { if (isAfterCopyHook(each)) { result.add(each); } } return result; } private boolean isAfterCopyHook(Method each) { AfterCopy annotation = each.getAnnotation(AfterCopy.class); return annotation != null; } public <T> DeepCopy replace(T toBeReplaced, T substitution) { alreadyCopiedObjects.put(byIdentity(toBeReplaced), substitution); return this; } }
package org.navalplanner.web.common.entrypoints; import static org.navalplanner.web.I18nHelper._; import java.lang.reflect.Method; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.Validate; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.navalplanner.web.common.converters.IConverter; import org.navalplanner.web.common.converters.IConverterFactory; import org.zkoss.zk.ui.Execution; import org.zkoss.zk.ui.Page; import org.zkoss.zk.ui.event.BookmarkEvent; import org.zkoss.zk.ui.event.Event; import org.zkoss.zk.ui.event.EventListener; public class URLHandler<T> { private static final String FLAG_ATTRIBUTE = URLHandler.class.getName() + "_"; private static final Log LOG = LogFactory.getLog(URLHandler.class); private static class EntryPointMetadata { private final Method method; private final EntryPoint annotation; private EntryPointMetadata(Method method, EntryPoint annotation) { this.method = method; this.annotation = annotation; } } private final IExecutorRetriever executorRetriever; private Map<String, EntryPointMetadata> metadata = new HashMap<String, EntryPointMetadata>(); private final String page; private final IConverterFactory converterFactory; public URLHandler(IConverterFactory converterFactory, IExecutorRetriever executorRetriever, Class<T> interfaceDefiningEntryPoints) { Validate.isTrue(interfaceDefiningEntryPoints.isInterface()); this.converterFactory = converterFactory; this.executorRetriever = executorRetriever; EntryPoints entryPoints = interfaceDefiningEntryPoints .getAnnotation(EntryPoints.class); Validate.notNull(entryPoints, _("{0} annotation required on {1}", EntryPoints.class.getName(), interfaceDefiningEntryPoints.getName())); this.page = entryPoints.page(); for (Method method : interfaceDefiningEntryPoints.getMethods()) { EntryPoint entryPoint = method.getAnnotation(EntryPoint.class); if (entryPoint != null) { metadata.put(method.getName(), new EntryPointMetadata(method, entryPoint)); } } } public void doTransition(String methodName, Object... values) { if (isFlagedInThisRequest()) { return; } flagAlreadyExecutedInThisRequest(); if (!metadata.containsKey(methodName)) { LOG.error("Method " + methodName + "doesn't represent a state(It doesn't have a " + EntryPoint.class.getSimpleName() + " annotation). Nothing will be done"); return; } EntryPointMetadata linkableMetadata = metadata.get(methodName); Class<?>[] types = linkableMetadata.method.getParameterTypes(); String[] parameterNames = linkableMetadata.annotation.value(); String[] stringRepresentations = new String[parameterNames.length]; for (int i = 0; i < types.length; i++) { Class<?> type = types[i]; IConverter<?> converterFor = converterFactory.getConverterFor(type); stringRepresentations[i] = converterFor .asStringUngeneric(values[i]); } String fragment = getFragment(parameterNames, stringRepresentations); String requestPath = executorRetriever.getCurrent().getDesktop() .getRequestPath(); if (requestPath.contains(page)) { doBookmark(fragment); } else { sendRedirect(fragment); } } private boolean isFlagedInThisRequest() { return getRequest().getAttribute(FLAG_ATTRIBUTE) == this; } private void flagAlreadyExecutedInThisRequest() { getRequest().setAttribute(FLAG_ATTRIBUTE, this); } private void doBookmark(String fragment) { executorRetriever.getCurrent().getDesktop().setBookmark( stripHash(fragment)); } private String stripHash(String fragment) { if (fragment.startsWith(" return fragment.substring(1); } return fragment; } private void sendRedirect(String fragment) { StringBuilder linkValue = new StringBuilder(page).append(fragment); executorRetriever.getCurrent().sendRedirect(linkValue.toString()); } private String getFragment(String[] parameterNames, String[] stringRepresentations) { StringBuilder result = new StringBuilder(); if (parameterNames.length > 0) { result.append(" } for (int i = 0; i < parameterNames.length; i++) { result.append(parameterNames[i]); if (stringRepresentations[i] != null) { result.append("=").append(stringRepresentations[i]); } if (i < parameterNames.length - 1) { result.append(";"); } } return result.toString(); } private static void callMethod(Object target, Method superclassMethod, Object[] params) { try { Method method = target.getClass().getMethod( superclassMethod.getName(), superclassMethod.getParameterTypes()); method.invoke(target, params); } catch (Exception e) { throw new RuntimeException(e); } } public <S extends T> boolean applyIfMatches(S controller) { String uri = getRequest().getRequestURI(); return applyIfMatches(controller, uri); } private HttpServletRequest getRequest() { Execution current = executorRetriever.getCurrent(); HttpServletRequest request = (HttpServletRequest) current .getNativeRequest(); return request; } public <S extends T> boolean applyIfMatches(S controller, String fragment) { if (isFlagedInThisRequest()) { return false; } flagAlreadyExecutedInThisRequest(); String string = insertSemicolonIfNeeded(fragment); Map<String, String> matrixParams = MatrixParameters.extract(string); Set<String> matrixParamsNames = matrixParams.keySet(); for (Entry<String, EntryPointMetadata> entry : metadata.entrySet()) { EntryPointMetadata entryPointMetadata = entry.getValue(); EntryPoint entryPointAnnotation = entryPointMetadata.annotation; HashSet<String> requiredParams = new HashSet<String>(Arrays .asList(entryPointAnnotation.value())); if (matrixParamsNames.equals(requiredParams)) { Object[] arguments = retrieveArguments(matrixParams, entryPointAnnotation, entryPointMetadata.method .getParameterTypes()); callMethod(controller, entryPointMetadata.method, arguments); return true; } } return false; } public <S extends T> void registerListener(final S controller, Page page) { page.addEventListener("onBookmarkChange", new EventListener() { @Override public void onEvent(Event event) throws Exception { BookmarkEvent bookmarkEvent = (BookmarkEvent) event; String bookmark = bookmarkEvent.getBookmark(); applyIfMatches(controller, bookmark); } }); } private String insertSemicolonIfNeeded(String uri) { if (!uri.startsWith(";")) { return ";" + uri; } return uri; } private Object[] retrieveArguments(Map<String, String> matrixParams, EntryPoint linkToStateAnnotation, Class<?>[] parameterTypes) { Object[] result = new Object[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { Object argumentName = linkToStateAnnotation.value()[i]; String parameterValue = matrixParams.get(argumentName); IConverter<?> converter = converterFactory .getConverterFor(parameterTypes[i]); result[i] = converter.asObject(parameterValue); } return result; } }
package com.t2; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; /** * A static class that provides a global abstraction of an app's shared * preferences. * @author robbiev * */ public class SharedPref { private static SharedPreferences sSharedPref; private static void init(Context c) { if(sSharedPref == null) { sSharedPref = PreferenceManager.getDefaultSharedPreferences(c.getApplicationContext()); } } public SharedPreferences getSharedPreferences(Context c) { init(c); return sSharedPref; } public static String[] getValues(SharedPreferences sharedPref, String key, String separator, String[] defaultValue) { String dataStr = sharedPref.getString(key, "!<[NULLFOUND]>["); if(dataStr.equals("!<[NULLFOUND]>[")) { return defaultValue; } return dataStr.split(separator); } public static void setValues(SharedPreferences sharedPref, String key, String separator, String[] values) { StringBuffer sb = new StringBuffer(); for(int i = 0; i < values.length; ++i) { sb.append(values[i]); sb.append(separator); } sharedPref.edit().putString(key, sb.toString()).commit(); } public static void setIntValues(SharedPreferences sharedPref, String key, String separator, int[] values) { StringBuffer sb = new StringBuffer(); for(int i = 0; i < values.length; ++i) { sb.append(Integer.toString(values[i])); sb.append(separator); } sharedPref.edit().putString(key, sb.toString()).commit(); } public static int[] getIntValues(SharedPreferences sharedPref, String key, String separator) { String dataStr = sharedPref.getString(key, "!<[NULLFOUND]>["); if(dataStr.equals("!<[NULLFOUND]>[")) { return null; } String strResults[] = dataStr.split(separator); int numItems = strResults.length; int results[] = new int[numItems]; for (int i = 0; i < numItems; i++ ) { results[i] = Integer.parseInt(strResults[i]); } return results; } /** * @see SharedPreferences.getBoolean * @param c * @param key * @param defValue * @return */ public static boolean getBoolean(Context c, String key, boolean defValue) { init(c); return sSharedPref.getBoolean(key, defValue); } /** * @see SharedPreferences.getFloat * @param c * @param key * @param defValue * @return */ public static float getFloat(Context c, String key, float defValue) { init(c); return sSharedPref.getFloat(key, defValue); } /** * @see SharedPreferences.getInt * @param c * @param key * @param defValue * @return */ public static int getInt(Context c, String key, int defValue) { init(c); return sSharedPref.getInt(key, defValue); } /** * @see SharedPreferences.getLong * @param c * @param key * @param defValue * @return */ public static long getLong(Context c, String key, long defValue) { init(c); return sSharedPref.getLong(key, defValue); } /** * @see SharedPreferences.getString * @param c * @param key * @param defValue * @return */ public static String getString(Context c, String key, String defValue) { init(c); return sSharedPref.getString(key, defValue); } /** * @see SharedPreferences.putBoolean * @param c * @param key * @param value */ public static void putBoolean(Context c, String key, boolean value) { init(c); sSharedPref.edit().putBoolean(key, value).commit(); } /** * @see SharedPreferences.putFloat * @param c * @param key * @param value */ public static void putFloat(Context c, String key, float value) { init(c); sSharedPref.edit().putFloat(key, value).commit(); } /** * @see SharedPreferences.putInt * @param c * @param key * @param value */ public static void putInt(Context c, String key, int value) { init(c); sSharedPref.edit().putInt(key, value).commit(); } /** * @see SharedPreferences.putLong * @param c * @param key * @param value */ public static void putLong(Context c, String key, long value) { init(c); sSharedPref.edit().putLong(key, value).commit(); } /** * @see SharedPreferences.putString * @param c * @param key * @param value */ public static void putString(Context c, String key, String value) { init(c); sSharedPref.edit().putString(key, value).commit(); } public static class Analytics { public static boolean isEnabled(Context c) { return getBoolean(c, "analytics_enabled", false); } public static void setIsEnabled(Context c, boolean b) { putBoolean(c, "analytics_enabled", b); } } public static class RemoteStackTrace { public static boolean isEnabled(Context c) { return getBoolean(c, "remote_stack_trace_enabled", true); } public static void setIsEnabled(Context c, boolean b) { putBoolean(c, "remote_stack_trace_enabled", b); } } public static class Security { public static boolean isEnabled(Context c) { return getBoolean(c, "security_enabled", false); } public static boolean doesPasswordMatch(Context c, String inputPassword) { return getString(c, "security_password", "").equals(md5(inputPassword)); } public static boolean isPasswordSet(Context c) { return getString(c, "security_password", "").length() > 0; } public static String getQuestion1(Context c) { return getQuestion(c, 1, sSharedPref); } public static String getQuestion2(Context c) { return getQuestion(c, 2, sSharedPref); } public static boolean doesAnswer1Match(Context c, String answer) { return doesAnswerMatch(c, 1, answer); } public static boolean isAnswer1Set(Context c) { return isAnswerSet(c, 1); } public static boolean doesAnswer2Match(Context c, String answer) { return doesAnswerMatch(c, 2, answer); } public static boolean isAnswer2Set(Context c) { return isAnswerSet(c, 2); } private static String getQuestion(Context c, int index, SharedPreferences sharedPref) { return getString(c, "security_question"+index, ""); } private static boolean doesAnswerMatch(Context c, int index, String answer) { return getString(c, "security_answer"+index, "").equals(md5(cleanString(answer))); } private static boolean isAnswerSet(Context c, int index) { return getString(c, "security_answer"+index, "").length() > 0; } public static void setEnabled(Context c, boolean b) { putBoolean(c, "security_enabled", b); } public static void setPassword(Context c, String password) { if(password != null && password.length() > 0) { putString(c, "security_password", md5(password.trim())); } } public static void setChallenge1(Context c, String question, String answer) { setChallenge(c, 1, question, answer); } public static void setChallenge2(Context c, String question, String answer) { setChallenge(c, 2, question, answer); } private static void setChallenge(Context c, int index, String question, String answer) { putString(c, "security_question"+ index, question); if(answer != null && answer.length() > 0) { putString(c, "security_answer"+ index, md5(cleanString(answer))); } } private static String cleanString(String str) { return str.trim().toLowerCase().replaceAll("[^a-z0-9]", ""); } } private static String md5(String s) { MessageDigest m = null; try { m = java.security.MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { // ignore } if (m != null) m.update(s.getBytes(), 0, s.length()); String hash = new BigInteger(1, m.digest()).toString(); return hash; } }
package com.perm.kate.api; import java.io.Serializable; import org.json.JSONException; import org.json.JSONObject; public class Photo implements Serializable { private static final long serialVersionUID = 1L; public long pid; public long aid; public String owner_id; public String src; public String src_small;//not used for now because in newsfeed it's empty public String src_big; public String src_xbig; public String src_xxbig; public String src_xxxbig; public String phototext; public long created; public Integer like_count; public Boolean user_likes; public static Photo parse(JSONObject o) throws NumberFormatException, JSONException{ Photo p = new Photo(); p.pid = o.getLong("pid"); p.aid = o.optLong("aid"); p.owner_id = o.getString("owner_id"); p.src = o.getString("src"); p.src_small = o.optString("src_small"); p.src_big = o.getString("src_big"); p.src_xbig = o.optString("src_xbig"); p.src_xxbig = o.optString("src_xxbig"); p.src_xxxbig = o.optString("src_xxxbig"); p.phototext = Api.unescape(o.optString("text")); p.created = o.optLong("created"); if (o.has("likes")){ JSONObject jlikes = o.getJSONObject("likes"); p.like_count = jlikes.getInt("count"); p.user_likes = jlikes.getInt("user_likes")==1; } return p; } public Photo(){ } public Photo(Long id, String owner_id, String src, String src_big){ this.pid=id; this.owner_id=owner_id; this.src=src; this.src_big=src_big; } }
package uk.ac.ebi.quickgo.ontology.common; import org.apache.solr.client.solrj.SolrServerException; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.solr.core.SolrTemplate; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import uk.ac.ebi.quickgo.common.QueryUtils; import uk.ac.ebi.quickgo.common.store.TemporarySolrDataStore; import uk.ac.ebi.quickgo.ontology.common.document.OntologyDocMocker; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNull.notNullValue; /** * Test that the ontology repository can be accessed as expected. * <p> * Created 11/11/15 * * @author Edd */ @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = OntologyRepoConfig.class) public class OntologyRepositoryIT { private static final String COLLECTION = "ontology"; // temporary data store for solr's data, which is automatically cleaned on exit @ClassRule public static final TemporarySolrDataStore solrDataStore = new TemporarySolrDataStore(); @Autowired private OntologyRepository ontologyRepository; @Autowired private SolrTemplate ontologyTemplate; @Before public void before() { ontologyRepository.deleteAll(); } @Test public void add1DocumentThenFind1Documents() throws IOException, SolrServerException { ontologyRepository.save(OntologyDocMocker.createGODoc("A", "Alice Cooper")); assertThat(ontologyRepository.findAll(new PageRequest(0, 10)).getTotalElements(), is(1L)); } @Test public void add3DocumentsThenFind3Documents() { ontologyRepository.save(OntologyDocMocker.createGODoc("A", "Alice Cooper")); ontologyRepository.save(OntologyDocMocker.createGODoc("B", "Bob The Builder")); ontologyRepository.save(OntologyDocMocker.createGODoc("C", "Clint Eastwood")); assertThat(ontologyRepository.findAll(new PageRequest(0, 10)).getTotalElements(), is(3L)); } @Test public void retrieves1DocCoreFieldsOnly() { String id = "GO:0000001"; ontologyRepository.save(OntologyDocMocker.createGODoc(id, "GO name 1")); List<OntologyDocument> results = ontologyRepository.findCoreAttrByTermId(OntologyType.GO.name(), buildIdList(id)); assertThat(results.size(), is(1)); OntologyDocument ontologyDocument = results.get(0); assertThat(copyAsCoreDoc(ontologyDocument), is(equalTo(ontologyDocument))); } @Test public void retrieves2DocsCoreFieldsOnly() { String id1 = "GO:0000001"; String id2 = "GO:0000002"; ontologyRepository.save(OntologyDocMocker.createGODoc(id1, "GO name 1")); ontologyRepository.save(OntologyDocMocker.createGODoc(id2, "GO name 2")); ontologyRepository.save(OntologyDocMocker.createGODoc("GO:0000003", "GO name 3")); ontologyRepository.findAll().forEach(System.out::println); List<OntologyDocument> results = ontologyRepository.findCoreAttrByTermId(OntologyType.GO.name(), buildIdList(id1,id2)); assertThat(results.size(), is(2)); results.forEach(doc -> assertThat(copyAsCoreDoc(doc), is(equalTo(doc)))); } @Test public void retrievesReplacesField() { String id = "GO:0000001"; OntologyDocument doc = OntologyDocMocker.createGODoc(id, "GO name 1"); ontologyRepository.save(doc); List<OntologyDocument> resultList = ontologyRepository.findCompleteByTermId(OntologyType.GO.name(), buildIdList(id)); assertThat(resultList, is(notNullValue())); assertThat(resultList.size(), is(1)); OntologyDocument ontologyDocument = resultList.get(0); assertThat(ontologyDocument.replaces, hasSize(doc.replaces.size())); } @Test public void retrievesReplacementField() { String id = "GO:0000001"; OntologyDocument doc = OntologyDocMocker.createGODoc(id, "GO name 1"); ontologyRepository.save(doc); List<OntologyDocument> resultList = ontologyRepository.findCompleteByTermId(OntologyType.GO.name(), buildIdList(id)); assertThat(resultList, is(notNullValue())); assertThat(resultList.size(), is(1)); OntologyDocument ontologyDocument = resultList.get(0); assertThat(ontologyDocument.replacements, hasSize(doc.replacements.size())); } @Test public void retrievesHistoryField() { String id = "GO:0000001"; ontologyRepository.save(OntologyDocMocker.createGODoc(id, "GO name 1")); List<OntologyDocument> resultList = ontologyRepository.findHistoryByTermId(OntologyType.GO.name(), buildIdList(id)); assertThat(resultList, is(notNullValue())); assertThat(resultList.size(), is(1)); OntologyDocument doc = resultList.get(0); OntologyDocument docToMatch = copyAsBasicDoc(doc); docToMatch.history = doc.history; assertThat(doc, is(equalTo(docToMatch))); } @Test public void retrievesXrefsField() { String id = "GO:0000001"; ontologyRepository.save(OntologyDocMocker.createGODoc(id, "GO name 1")); List<OntologyDocument> resultList = ontologyRepository.findXRefsByTermId(OntologyType.GO.name(), buildIdList(id)); assertThat(resultList, is(notNullValue())); assertThat(resultList.size(), is(1)); OntologyDocument doc = resultList.get(0); OntologyDocument docToMatch = copyAsBasicDoc(doc); docToMatch.xrefs = doc.xrefs; assertThat(doc, is(equalTo(docToMatch))); } @Test public void retrievesAnnotationGuidelinesField() { String id = "GO:0000001"; ontologyRepository.save(OntologyDocMocker.createGODoc(id, "GO name 1")); List<OntologyDocument> resultList = ontologyRepository .findAnnotationGuidelinesByTermId(OntologyType.GO.name(), buildIdList(id)); assertThat(resultList, is(notNullValue())); assertThat(resultList.size(), is(1)); OntologyDocument doc = resultList.get(0); OntologyDocument docToMatch = copyAsBasicDoc(doc); docToMatch.annotationGuidelines = doc.annotationGuidelines; assertThat(doc, is(equalTo(docToMatch))); } @Test public void retrievesTaxonConstraintsField() { String id = "GO:0000001"; ontologyRepository.save(OntologyDocMocker.createGODoc(id, "GO name 1")); List<OntologyDocument> resultList = ontologyRepository .findTaxonConstraintsByTermId(OntologyType.GO.name(), buildIdList(id)); assertThat(resultList, is(notNullValue())); assertThat(resultList.size(), is(1)); OntologyDocument doc = resultList.get(0); OntologyDocument docToMatch = copyAsBasicDoc(doc); docToMatch.taxonConstraints = doc.taxonConstraints; docToMatch.blacklist = doc.blacklist; assertThat(doc, is(equalTo(docToMatch))); } @Test public void retrievesXOntologyRelationsField() { String id = "GO:0000001"; ontologyRepository.save(OntologyDocMocker.createGODoc(id, "GO name 1")); List<OntologyDocument> resultList = ontologyRepository .findXOntologyRelationsByTermId(OntologyType.GO.name(), buildIdList(id)); assertThat(resultList, is(notNullValue())); assertThat(resultList.size(), is(1)); OntologyDocument doc = resultList.get(0); OntologyDocument docToMatch = copyAsBasicDoc(doc); docToMatch.xRelations = doc.xRelations; assertThat(doc, is(equalTo(docToMatch))); } @Test public void add1DocumentAndFailToFindForWrongId() { ontologyRepository.save(OntologyDocMocker.createGODoc("A", "Alice Cooper")); assertThat(ontologyRepository.findCoreAttrByTermId(OntologyType.GO.name(), buildIdList("B")).size(), is(0)); assertThat(ontologyRepository.findCompleteByTermId(OntologyType.GO.name(), buildIdList("B")).size(), is(0)); } @Test public void add1GoDocumentAndFindItById() { ontologyRepository.save(OntologyDocMocker.createGODoc("A", "Alice Cooper")); assertThat(ontologyRepository.findCoreAttrByTermId(OntologyType.GO.name(), buildIdList("A")).size(), is(1)); assertThat(ontologyRepository.findCompleteByTermId(OntologyType.GO.name(), buildIdList("A")).size(), is(1)); assertThat(ontologyRepository.findHistoryByTermId(OntologyType.GO.name(), buildIdList("A")).size(), is(1)); } @Test public void add1GoAnd1EcoDocumentsAndFindAllOfTypeGO() { OntologyDocument goDoc = OntologyDocMocker.createGODoc("A", "Alice Cooper"); OntologyDocument ecoDoc = OntologyDocMocker.createECODoc("B", "Bob The Builder"); ontologyRepository.save(goDoc); ontologyRepository.save(ecoDoc); Page<OntologyDocument> pagedDocs = ontologyRepository.findAllByOntologyType(OntologyType.GO.name(), new PageRequest(0, 2)); assertThat(pagedDocs.getTotalElements(), is(1L)); assertThat(pagedDocs.getContent().get(0).getUniqueName(), is(goDoc.getUniqueName())); } @Test public void add3GoDocumentsAndFindAllOfTypeGOWith1DocPerPage() { List<OntologyDocument> ontologyDocuments = Arrays.asList( OntologyDocMocker.createGODoc("A", "Alice Cooper"), OntologyDocMocker.createGODoc("B", "Bob The Builder"), OntologyDocMocker.createGODoc("C", "Clint Eastwood") ); ontologyRepository.saveAll(ontologyDocuments); int count = 0; for (OntologyDocument ontologyDocument : ontologyDocuments) { Page<OntologyDocument> pagedDocs = ontologyRepository.findAllByOntologyType(OntologyType.GO.name(), new PageRequest(count++, 1)); assertThat(pagedDocs.getContent(), hasSize(1)); assertThat(pagedDocs.getContent().get(0).getUniqueName(), is(ontologyDocument.getUniqueName())); } } /** * Shows how to save directly to a solr server, bypassing transactional * operations that are managed by Spring. * * @throws IOException * @throws SolrServerException */ @Test public void saveDirectlyToSolrServer() throws IOException, SolrServerException { ontologyTemplate.getSolrClient().addBean(COLLECTION,OntologyDocMocker.createGODoc("A", "Alice Cooper")); ontologyTemplate.getSolrClient().addBean(COLLECTION,OntologyDocMocker.createGODoc("B", "Alice Cooper")); ontologyTemplate.getSolrClient().addBean(COLLECTION,OntologyDocMocker.createGODoc("C", "Alice Cooper")); ontologyTemplate.getSolrClient().addBeans(COLLECTION, Arrays.asList( OntologyDocMocker.createGODoc("D", "Alice Cooper"), OntologyDocMocker.createGODoc("E", "Alice Cooper"))); assertThat(ontologyRepository.findAll(new PageRequest(0, 10)).getTotalElements(), is(0L)); ontologyTemplate.getSolrClient().commit(COLLECTION); assertThat(ontologyRepository.findAll(new PageRequest(0, 10)).getTotalElements(), is(5L)); } private OntologyDocument copyAsBasicDoc(OntologyDocument document) { OntologyDocument basicDoc = new OntologyDocument(); basicDoc.id = document.id; basicDoc.isObsolete = document.isObsolete; basicDoc.name = document.name; basicDoc.comment = document.comment; basicDoc.definition = document.definition; return basicDoc; } private OntologyDocument copyAsCoreDoc(OntologyDocument document) { OntologyDocument coreDoc = copyAsBasicDoc(document); coreDoc.usage = document.usage; coreDoc.synonyms = document.synonyms; coreDoc.aspect = document.aspect; return coreDoc; } private List<String> buildIdList(String... ids) { return Arrays.stream(ids) .map(QueryUtils::solrEscape) .collect(Collectors.toList()); } }
package org.openregistry.core.web.resources; import org.springframework.stereotype.Component; import org.springframework.context.annotation.Scope; import org.springframework.beans.factory.annotation.Autowired; import org.openregistry.core.domain.sor.PersonSearch; import org.openregistry.core.domain.jpa.sor.JpaSorPersonSearchImpl; import org.openregistry.core.domain.Name; import org.openregistry.core.domain.Person; import org.openregistry.core.domain.Identifier; import org.openregistry.core.service.PersonService; import org.openregistry.core.service.ServiceExecutionResult; import org.openregistry.core.service.reconciliation.ReconciliationResult; import org.openregistry.core.service.reconciliation.PersonMatch; import javax.ws.rs.*; import javax.ws.rs.core.*; import javax.xml.bind.annotation.XmlElement; import javax.annotation.Resource; import java.net.URI; import java.util.*; import java.text.SimpleDateFormat; import java.text.ParseException; /** * Root RESTful resource representing people in Open Registry. * This component is managed and autowired by Spring by means of context-component-scan, * and served by Jersey when URI is matched against the @Path definition. This bean is a singleton, * and therefore is thread-safe. * * @author Dmitriy Kopylenko * @since 1.0 */ @Path("/people") @Component @Scope("singleton") public class PeopleResource { //Jersey specific injection @Context UriInfo uriInfo; @Autowired private PersonService personService; //JSR-250 injection which is more appropriate here for 'autowiring by name' in the case of multiple types //are defined in the app ctx (Strings). The looked up bean name defaults to the property name which //needs an injection. @Resource private String preferredPersonIdentifierType; @GET @Path("{personIdType}/{personId}") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) //auto content negotiation! public PersonResponseRepresentation showPerson(@PathParam("personId") String personId, @PathParam("personIdType") String personIdType) { //Build activation generator URI URI activationGeneratorUri = this.uriInfo.getAbsolutePathBuilder().path("activation").build(); //Build activation proccess URI URI activationProcessorUri = this.uriInfo.getAbsolutePathBuilder().path("activation").path("proccess") .queryParam("activation-token", "activation-token-skjfskjfhskjdfh").build(); return new PersonResponseRepresentation( activationGeneratorUri.toString(), activationProcessorUri.toString(), "AT-153254325", Arrays.asList(new PersonResponseRepresentation.PersonIdentifierRepresentation(personIdType, personId), new PersonResponseRepresentation.PersonIdentifierRepresentation("rcpId", "12345"))); } @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) //resp-type query param is here temporarily, for testing public Response processIncomingPerson(@DefaultValue("201") @QueryParam("resp-type") int respType, MultivaluedMap<String, String> formParams) { Response response = null; URI uri = null; PersonSearch personSearch = null; try { personSearch = personRequestToPersonSearch(new PersonRequestRepresentation(formParams)); } catch (IllegalArgumentException ex) { //HTTP 400 return Response.status(Response.Status.BAD_REQUEST).entity(ex.getMessage()).build(); } ServiceExecutionResult result = this.personService.addPerson(personSearch, null); //Now do the branching logic based on the result if (result.succeeded()) { if (personCreated(result.getReconciliationResult().getReconciliationType())) { uri = buildPersonResourceUri((Person) result.getTargetObject()); response = Response.created(uri).build(); } else if (personAlreadyExists(result.getReconciliationResult().getReconciliationType())) { uri = buildPersonResourceUri((Person) result.getTargetObject()); response = Response.temporaryRedirect(uri).build(); } } else { if (result.getValidationErrors().size() > 0) { //TODO: add more informative message to the entity body return Response.status(Response.Status.BAD_REQUEST).entity("The incoming request is malformed.").build(); } else if (multiplePeopleFound(result.getReconciliationResult().getReconciliationType())) { List<PersonMatch> conflictingPeopleFound = result.getReconciliationResult().getMatches(); response = Response.status(409).entity(buildLinksToConflictingPeopleFound(conflictingPeopleFound)) .type(MediaType.APPLICATION_XHTML_XML).build(); } } /*switch (respType) { case 201: response = Response.created(uri).build(); break; case 409: LinkRepresentation entityBody = new LinkRepresentation(Arrays.asList(new LinkRepresentation.Link("person", uri.toString()), new LinkRepresentation.Link("person", uri.toString()))); response = Response.status(409).entity(entityBody).type(MediaType.APPLICATION_XHTML_XML).build(); break; case 307: response = Response.temporaryRedirect(uri).build(); default: break; }*/ System.out.println("GOT HTTP form POSTed: " + formParams); return response; } private PersonSearch personRequestToPersonSearch(PersonRequestRepresentation request) { JpaSorPersonSearchImpl ps = new JpaSorPersonSearchImpl(); ps.getPerson().setSourceSorIdentifier(String.valueOf(request.getSystemOfRecordId())); ps.getPerson().setSorId(String.valueOf(request.getSystemOfRecordPersonId())); Name name = ps.getPerson().addName(); name.setGiven(request.getFirstName()); name.setFamily(request.getLastName()); ps.setEmailAddress(request.getEmail()); ps.setPhoneNumber(request.getPhoneNumber()); try { ps.getPerson().setDateOfBirth(new SimpleDateFormat("mmddyyyy").parse(request.getDateOfBirth())); } catch (Exception ex) { //Let the validation in JpaSorPersonSearchImpl catch the null property. Carry on... } ps.getPerson().setSsn(request.getSsn()); ps.getPerson().setGender(request.getGender()); ps.setAddressLine1(request.getAddressLine1()); ps.setAddressLine2(request.getAddressLine2()); ps.setCity(request.getCity()); ps.setRegion(request.getRegion()); ps.setPostalCode(request.getPostalCode()); return ps; } private URI buildPersonResourceUri(Person person) { for (Identifier id : person.getIdentifiers()) { if (this.preferredPersonIdentifierType.equals(id.getType().getName())) { return this.uriInfo.getAbsolutePathBuilder().path(this.preferredPersonIdentifierType) .path(id.getValue()).build(); } } //Person MUST have at least one id of the preferred configured type. Results in HTTP 500 throw new IllegalStateException("The person must have at least one id of the preferred configured type " + "which is <" + this.preferredPersonIdentifierType + ">"); } private LinkRepresentation buildLinksToConflictingPeopleFound(List<PersonMatch> matches) { //A little defensive stuff. Will result in HTTP 500 if (matches.size() == 0) { throw new IllegalStateException("Person matches cannot be empty if reconciliation result is <MAYBE>"); } List<LinkRepresentation.Link> links = new ArrayList<LinkRepresentation.Link>(); for (PersonMatch match : matches) { links.add(new LinkRepresentation.Link("person", buildPersonResourceUri(match.getPerson()).toString())); } return new LinkRepresentation(links); } //TODO: possibly refactor these methods into a helper type or encapsulate them in ReconciliationResult itself? private boolean personCreated(ReconciliationResult.ReconciliationType reconciliationType) { return (reconciliationType == ReconciliationResult.ReconciliationType.NONE); } private boolean personAlreadyExists(ReconciliationResult.ReconciliationType reconciliationType) { return (reconciliationType == ReconciliationResult.ReconciliationType.EXACT); } private boolean multiplePeopleFound(ReconciliationResult.ReconciliationType reconciliationType) { return (reconciliationType == ReconciliationResult.ReconciliationType.MAYBE); } }
package org.python.pydev.editor.codecompletion.revisited.visitors; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.Stack; import org.python.pydev.core.IModule; import org.python.pydev.core.IToken; import org.python.pydev.editor.codecompletion.PyCodeCompletion; import org.python.pydev.editor.codecompletion.revisited.modules.SourceModule; import org.python.pydev.editor.codecompletion.revisited.modules.SourceToken; import org.python.pydev.parser.jython.SimpleNode; import org.python.pydev.parser.jython.ast.Attribute; import org.python.pydev.parser.jython.ast.ClassDef; import org.python.pydev.parser.jython.ast.FunctionDef; import org.python.pydev.parser.jython.ast.Name; import org.python.pydev.parser.jython.ast.NameTok; import org.python.pydev.parser.visitors.NodeUtils; import org.python.pydev.parser.visitors.scope.ASTEntry; import org.python.pydev.parser.visitors.scope.SequencialASTIteratorVisitor; /** * @author Fabio Zadrozny */ public class Scope { public Stack<SimpleNode> scope = new Stack<SimpleNode>(); public int scopeEndLine = -1; public int ifMainLine = -1; public Scope(Stack<SimpleNode> scope){ this.scope.addAll(scope); } /** * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if (!(obj instanceof Scope)) { return false; } Scope s = (Scope) obj; if(this.scope.size() != s.scope.size()){ return false; } return checkIfScopesMatch(s); } /** * Checks if this scope is an outer scope of the scope passed as a param (s). * Or if it is the same scope. * * @param s * @return */ public boolean isOuterOrSameScope(Scope s){ if(this.scope.size() > s.scope.size()){ return false; } return checkIfScopesMatch(s); } /** * @param s * @return */ private boolean checkIfScopesMatch(Scope s) { Iterator otIt = s.scope.iterator(); for (Iterator iter = this.scope.iterator(); iter.hasNext();) { SimpleNode element = (SimpleNode) iter.next(); SimpleNode otElement = (SimpleNode) otIt.next(); if(element.beginColumn != otElement.beginColumn) return false; if(element.beginLine != otElement.beginLine) return false; if(! element.getClass().equals(otElement.getClass())) return false; if(! NodeUtils.getFullRepresentationString(element).equals( NodeUtils.getFullRepresentationString(otElement))) return false; } return true; } public IToken[] getAllLocalTokens(){ return getLocalTokens(Integer.MAX_VALUE, Integer.MAX_VALUE); } public List<ASTEntry> getOcurrences(String occurencesFor, IModule module) { SimpleNode simpleNode=null; if(this.scope.size() > 0){ simpleNode = this.scope.get(this.scope.size()-1); }else if (module instanceof SourceModule){ SourceModule m = (SourceModule) module; simpleNode = m.getAst(); } if (simpleNode == null){ return new ArrayList<ASTEntry>(); } return getOcurrences(occurencesFor, simpleNode); } public static List<ASTEntry> getOcurrences(String occurencesFor, SimpleNode simpleNode) { return getOcurrences(occurencesFor, simpleNode, true); } /** * @return a list of occurrences with the matches we're looking for. Does only return the first name in attributes. */ public static List<ASTEntry> getOcurrences(String occurencesFor, SimpleNode simpleNode, final boolean onlyFirstAttribPart) { List<ASTEntry> ret = new ArrayList<ASTEntry>(); SequencialASTIteratorVisitor visitor = new SequencialASTIteratorVisitor(){ @Override public Object visitAttribute(Attribute node) throws Exception { if(onlyFirstAttribPart){ List<SimpleNode> attributeParts = NodeUtils.getAttributeParts(node); atomic(attributeParts.get(0)); //an attribute should always have many parts return null; }else{ return super.visitAttribute(node); } } }; try { simpleNode.accept(visitor); } catch (Exception e) { throw new RuntimeException(e); } Iterator<ASTEntry> iterator = visitor.getIterator(new Class[]{Name.class, NameTok.class}); while(iterator.hasNext()){ ASTEntry entry = iterator.next(); if (occurencesFor.equals(entry.getName())){ ret.add(entry); } } return ret; } /** * Search for the attributes that start with the passed parameter. * * @param occurencesFor if 'foo', will look for all attributes that start with foo or foo. */ public static List<ASTEntry> getAttributeOcurrences(String occurencesFor, SimpleNode simpleNode){ List<ASTEntry> ret = new ArrayList<ASTEntry>(); SequencialASTIteratorVisitor visitor = SequencialASTIteratorVisitor.create(simpleNode); Iterator<ASTEntry> iterator = visitor.getIterator(new Class[]{Attribute.class}); while(iterator.hasNext()){ ASTEntry entry = iterator.next(); String rep = NodeUtils.getFullRepresentationString(entry.node); if (rep.equals(occurencesFor)){ ret.add(entry); } } return ret; } /** * @param endLine tokens will only be recognized if its beginLine is higher than this parameter. */ public IToken[] getLocalTokens(int endLine, int col){ Set<SourceToken> comps = new HashSet<SourceToken>(); for (Iterator iter = this.scope.iterator(); iter.hasNext();) { SimpleNode element = (SimpleNode) iter.next(); if (element instanceof FunctionDef) { FunctionDef f = (FunctionDef) element; for (int i = 0; i < f.args.args.length; i++) { String s = NodeUtils.getRepresentationString(f.args.args[i]); comps.add(new SourceToken(f.args.args[i], s, "", "", "", PyCodeCompletion.TYPE_PARAM)); } try { for (int i = 0; i < f.body.length; i++) { GlobalModelVisitor visitor = new GlobalModelVisitor(GlobalModelVisitor.GLOBAL_TOKENS, ""); f.body[i].accept(visitor); List t = visitor.tokens; for (Iterator iterator = t.iterator(); iterator.hasNext();) { SourceToken tok = (SourceToken) iterator.next(); //if it is found here, it is a local type tok.type = PyCodeCompletion.TYPE_PARAM; if(tok.getAst().beginLine <= endLine){ comps.add(tok); } } } } catch (Exception e) { e.printStackTrace(); } } } return (SourceToken[]) comps.toArray(new SourceToken[0]); } public List<IToken> getLocalImportedModules(int line, int col, String moduleName) { ArrayList<IToken> importedModules = new ArrayList<IToken>(); for (Iterator iter = this.scope.iterator(); iter.hasNext();) { SimpleNode element = (SimpleNode) iter.next(); if (element instanceof FunctionDef) { FunctionDef f = (FunctionDef) element; for (int i = 0; i < f.body.length; i++) { IToken[] tokens = GlobalModelVisitor.getTokens(f.body[i], GlobalModelVisitor.ALIAS_MODULES, moduleName); for (IToken token : tokens) { importedModules.add(token); } } } } return importedModules; } public ClassDef getClassDef() { for(SimpleNode node : this.scope){ if(node instanceof ClassDef){ return (ClassDef) node; } } return null; } }
package com.maxtimv.termfreq; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Comparator; /** * @author Maxim Timofeev * */ public class TermFreq { /** * @param args * the command line arguments */ public static void main(String[] args) throws IOException { // Set defaults ITermExtractor extractor = new TermExtractor(); Comparator<Term> comparator = null; String fileName = null; // Process arguments for (String arg : args) { if ("-acronym".equalsIgnoreCase(arg) || "-acr".equalsIgnoreCase(arg)) { extractor = new TermExtractorAcronym(); } else if ("-sorta".equalsIgnoreCase(arg) || "-sa".equalsIgnoreCase(arg)) { comparator = new TermComparatorA(); } else if ("-sortb".equalsIgnoreCase(arg) || "-sb".equalsIgnoreCase(arg)) { comparator = new TermComparatorB(); } else { fileName = arg; } } // No input file? if (fileName == null) { usage(); return; } // Load the file and extract terms String text = loadFile(fileName); Term[] terms = extractor.extract(text); // Sort the terms if asked if (comparator != null) { Arrays.sort(terms, comparator); } // Print results System.out.println("Total terms: " + terms.length); for (Term t : terms) { System.out.println(t); } } /** * Loads the content of the file into a String. */ private static String loadFile(String fileName) throws IOException { StringBuilder sb = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader( new FileInputStream(fileName))); for (String line = reader.readLine(); line != null; line = reader .readLine()) { sb.append(line).append(' '); } reader.close(); return sb.toString(); } /** * Prints usage instructions */ public static void usage() { System.out.println("Usage: TermFreq [-options] inputFile"); System.out .println(" (lists all terms found in <inputFile> with their frequency)"); System.out.println(); System.out.println("where options include:"); System.out.println(" -acronym | -acr preserves acronyms"); System.out.println(" -sorta | -sa uses sort method A"); System.out.println(" -sortb | -sb uses sort method B"); } }
package org.pac4j.cas.credentials.authenticator; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import org.pac4j.cas.config.CasConfiguration; import org.pac4j.cas.profile.CasRestProfile; import org.pac4j.core.context.HttpConstants; import org.pac4j.core.context.Pac4jConstants; import org.pac4j.core.context.WebContext; import org.pac4j.core.credentials.UsernamePasswordCredentials; import org.pac4j.core.credentials.authenticator.Authenticator; import org.pac4j.core.exception.HttpAction; import org.pac4j.core.exception.TechnicalException; import org.pac4j.core.util.CommonHelper; import org.pac4j.core.util.HttpUtils; import org.pac4j.core.util.InitializableWebObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This is a specific Authenticator to deal with the CAS REST API. * * @author Misagh Moayyed * @since 1.8.0 */ public class CasRestAuthenticator extends InitializableWebObject implements Authenticator<UsernamePasswordCredentials> { private final static Logger logger = LoggerFactory.getLogger(CasRestAuthenticator.class); private CasConfiguration configuration; public CasRestAuthenticator() {} public CasRestAuthenticator(final CasConfiguration configuration) { this.configuration = configuration; } @Override protected void internalInit(final WebContext context) { CommonHelper.assertNotNull("configuration", this.configuration); configuration.init(context); } @Override public void validate(final UsernamePasswordCredentials credentials, final WebContext context) throws HttpAction { init(context); if (credentials == null || credentials.getPassword() == null || credentials.getUsername() == null) { throw new TechnicalException("Credentials are required"); } final String ticketGrantingTicketId = requestTicketGrantingTicket(credentials.getUsername(), credentials.getPassword(), context); if (CommonHelper.isNotBlank(ticketGrantingTicketId)) { credentials.setUserProfile(new CasRestProfile(ticketGrantingTicketId, credentials.getUsername())); } } private String requestTicketGrantingTicket(final String username, final String password, final WebContext context) { HttpURLConnection connection = null; try { connection = HttpUtils.openPostConnection(new URL(this.configuration.computeFinalRestUrl(context))); final String payload = HttpUtils.encodeQueryParam(Pac4jConstants.USERNAME, username) + "&" + HttpUtils.encodeQueryParam(Pac4jConstants.PASSWORD, password); final BufferedWriter out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), HttpConstants.UTF8_ENCODING)); out.write(payload); out.close(); final String locationHeader = connection.getHeaderField("location"); final int responseCode = connection.getResponseCode(); if (locationHeader != null && responseCode == HttpConstants.CREATED) { return locationHeader.substring(locationHeader.lastIndexOf("/") + 1); } logger.debug("Ticket granting ticket request failed: " + locationHeader + " " + responseCode + HttpUtils.buildHttpErrorMessage(connection)); return null; } catch (final IOException e) { throw new TechnicalException(e); } finally { HttpUtils.closeConnection(connection); } } public CasConfiguration getConfiguration() { return configuration; } public void setConfiguration(final CasConfiguration configuration) { this.configuration = configuration; } }
package sk.henrichg.phoneprofilesplus; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.List; import java.util.Map; import java.util.Map.Entry; import sk.henrichg.phoneprofilesplus.EditorEventListFragment.OnFinishEventPreferencesActionMode; import sk.henrichg.phoneprofilesplus.EditorEventListFragment.OnStartEventPreferences; import sk.henrichg.phoneprofilesplus.EditorProfileListFragment.OnFinishProfilePreferencesActionMode; import sk.henrichg.phoneprofilesplus.EditorProfileListFragment.OnStartProfilePreferences; import sk.henrichg.phoneprofilesplus.EventPreferencesFragment.OnHideActionModeInEventPreferences; import sk.henrichg.phoneprofilesplus.EventPreferencesFragment.OnRedrawEventListFragment; import sk.henrichg.phoneprofilesplus.EventPreferencesFragment.OnRestartEventPreferences; import sk.henrichg.phoneprofilesplus.EventPreferencesFragment.OnShowActionModeInEventPreferences; import sk.henrichg.phoneprofilesplus.ProfilePreferencesFragment.OnHideActionModeInProfilePreferences; import sk.henrichg.phoneprofilesplus.ProfilePreferencesFragment.OnRedrawProfileListFragment; import sk.henrichg.phoneprofilesplus.ProfilePreferencesFragment.OnRestartProfilePreferences; import sk.henrichg.phoneprofilesplus.ProfilePreferencesFragment.OnShowActionModeInProfilePreferences; import android.content.Context; import android.content.pm.ActivityInfo; import android.graphics.Color; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceScreen; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.Fragment; import android.app.FragmentManager; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Configuration; import com.readystatesoftware.systembartint.SystemBarTintManager; public class EditorProfilesActivity extends ActionBarActivity implements OnStartProfilePreferences, OnRestartProfilePreferences, OnRedrawProfileListFragment, OnFinishProfilePreferencesActionMode, OnStartEventPreferences, OnRestartEventPreferences, OnRedrawEventListFragment, OnFinishEventPreferencesActionMode, OnShowActionModeInProfilePreferences, OnShowActionModeInEventPreferences, OnHideActionModeInProfilePreferences, OnHideActionModeInEventPreferences { private static EditorProfilesActivity instance; private ImageView eventsRunStopIndicator; private static boolean savedInstanceStateChanged; private static ApplicationsCache applicationsCache; private static ContactsCache contactsCache; private static ContactGroupsCache contactGroupsCache; private int editModeProfile; private int editModeEvent; private static final String SP_RESET_PREFERENCES_FRAGMENT = "editor_restet_preferences_fragment"; private static final String SP_RESET_PREFERENCES_FRAGMENT_DATA_ID = "editor_restet_preferences_fragment_data_id"; private static final String SP_RESET_PREFERENCES_FRAGMENT_EDIT_MODE = "editor_restet_preferences_fragment_edit_mode"; private static final int RESET_PREFERENCE_FRAGMENT_RESET_PROFILE = 1; private static final int RESET_PREFERENCE_FRAGMENT_RESET_EVENT = 2; private static final int RESET_PREFERENCE_FRAGMENT_REMOVE = 3; private static final String SP_EDITOR_DRAWER_SELECTED_ITEM = "editor_drawer_selected_item"; private static final String SP_EDITOR_ORDER_SELECTED_ITEM = "editor_order_selected_item"; /** * Whether or not the activity is in two-pane mode, i.e. running on a tablet * device. */ public static boolean mTwoPane; DrawerLayout drawerLayout; ScrimInsetsFrameLayout drawerRoot; ListView drawerListView; ActionBarDrawerToggle drawerToggle; TextView filterStatusbarTitle; TextView orderLabel; Spinner orderSpinner; ImageView drawerHeaderFilterImage; TextView drawerHeaderFilterTitle; TextView drawerHeaderFilterSubtitle; String[] drawerItemsTitle; String[] drawerItemsSubtitle; Integer[] drawerItemsIcon; EditorDrawerListAdapter drawerAdapter; private int drawerSelectedItem = 2; private int orderSelectedItem = 2; // priority private int profilesFilterType = EditorProfileListFragment.FILTER_TYPE_SHOW_IN_ACTIVATOR; private int eventsFilterType = EditorEventListFragment.FILTER_TYPE_ALL; private int eventsOrderType = EditorEventListFragment.ORDER_TYPE_EVENT_NAME; private static final int COUNT_DRAWER_PROFILE_ITEMS = 3; @SuppressLint("NewApi") @Override protected void onCreate(Bundle savedInstanceState) { GUIData.setTheme(this, false, true); GUIData.setLanguage(getBaseContext()); super.onCreate(savedInstanceState); instance = this; savedInstanceStateChanged = (savedInstanceState != null); createApplicationsCache(); createContactsCache(); createContactGroupsCache(); setContentView(R.layout.activity_editor_list_onepane); if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) && (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)) { Window w = getWindow(); // in Activity's onCreate() for instance //w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); // create our manager instance after the content view is set SystemBarTintManager tintManager = new SystemBarTintManager(this); // enable status bar tint tintManager.setStatusBarTintEnabled(true); // set a custom tint color for status bar if (GlobalData.applicationTheme.equals("material")) tintManager.setStatusBarTintColor(Color.parseColor("#ff237e9f")); else tintManager.setStatusBarTintColor(Color.parseColor("#ff202020")); } //if (android.os.Build.VERSION.SDK_INT >= 21) // getWindow().setNavigationBarColor(R.attr.colorPrimary); //setWindowContentOverlayCompat(); /* // add profile list into list container EditorProfileListFragment fragment = new EditorProfileListFragment(); getSupportFragmentManager().beginTransaction() .replace(R.id.editor_list_container, fragment, "EditorProfileListFragment").commit(); */ if (findViewById(R.id.editor_detail_container) != null) { // The detail container view will be present only in the // large-screen layouts (res/values-large and // res/values-sw600dp). If this view is present, then the // activity should be in two-pane mode. mTwoPane = true; if (savedInstanceState == null) onStartProfilePreferences(null, EditorProfileListFragment.EDIT_MODE_EDIT, profilesFilterType); else { // for 7 inch tablets lauout changed: // - portrait - one pane // - landscape - two pane // onRestartProfilePreferences is called, when user save/not save profile // preference changes (Back button, or Cancel in ActionMode) // In this method, editmode and profile_id is saved into shared preferences // And when orientaion changed into lanscape mode, profile preferences fragment // must by recreated due profile preference changes SharedPreferences preferences = getSharedPreferences(GlobalData.APPLICATION_PREFS_NAME, Activity.MODE_PRIVATE); int resetMode = preferences.getInt(SP_RESET_PREFERENCES_FRAGMENT, 0); if (resetMode == RESET_PREFERENCE_FRAGMENT_RESET_PROFILE) { // restart profile preferences fragmentu long profile_id = preferences.getLong(SP_RESET_PREFERENCES_FRAGMENT_DATA_ID, 0); int editMode = preferences.getInt(SP_RESET_PREFERENCES_FRAGMENT_EDIT_MODE, EditorProfileListFragment.EDIT_MODE_UNDEFINED); Bundle arguments = new Bundle(); arguments.putLong(GlobalData.EXTRA_PROFILE_ID, profile_id); arguments.putInt(GlobalData.EXTRA_NEW_PROFILE_MODE, editMode); arguments.putInt(GlobalData.EXTRA_PREFERENCES_STARTUP_SOURCE, GlobalData.PREFERENCES_STARTUP_SOURCE_FRAGMENT); ProfilePreferencesFragment fragment = new ProfilePreferencesFragment(); fragment.setArguments(arguments); getFragmentManager().beginTransaction() .replace(R.id.editor_detail_container, fragment, "ProfilePreferencesFragment").commit(); } if (resetMode == RESET_PREFERENCE_FRAGMENT_RESET_EVENT) { // restart event preferences fragmentu long event_id = preferences.getLong(SP_RESET_PREFERENCES_FRAGMENT_DATA_ID, 0); int editMode = preferences.getInt(SP_RESET_PREFERENCES_FRAGMENT_EDIT_MODE, EditorProfileListFragment.EDIT_MODE_UNDEFINED); Bundle arguments = new Bundle(); arguments.putLong(GlobalData.EXTRA_EVENT_ID, event_id); arguments.putInt(GlobalData.EXTRA_NEW_EVENT_MODE, editMode); arguments.putInt(GlobalData.EXTRA_PREFERENCES_STARTUP_SOURCE, GlobalData.PREFERENCES_STARTUP_SOURCE_FRAGMENT); EventPreferencesFragment fragment = new EventPreferencesFragment(); fragment.setArguments(arguments); getFragmentManager().beginTransaction() .replace(R.id.editor_detail_container, fragment, "EventPreferencesFragment").commit(); } else if (resetMode == RESET_PREFERENCE_FRAGMENT_REMOVE) { Fragment fragment = getFragmentManager().findFragmentById(R.id.editor_detail_container); if (fragment != null) { getFragmentManager().beginTransaction() .remove(fragment).commit(); } } // remove preferences Editor editor = preferences.edit(); editor.remove(SP_RESET_PREFERENCES_FRAGMENT); editor.remove(SP_RESET_PREFERENCES_FRAGMENT_DATA_ID); editor.remove(SP_RESET_PREFERENCES_FRAGMENT_EDIT_MODE); editor.commit(); } } else { mTwoPane = false; FragmentManager fragmentManager = getFragmentManager(); Fragment fragment = fragmentManager.findFragmentByTag("ProfilePreferencesFragment"); if (fragment != null) fragmentManager.beginTransaction() .remove(fragment).commit(); fragment = fragmentManager.findFragmentByTag("EventPreferencesFragment"); if (fragment != null) fragmentManager.beginTransaction() .remove(fragment).commit(); fragmentManager.executePendingTransactions(); } drawerLayout = (DrawerLayout) findViewById(R.id.editor_list_drawer_layout); drawerRoot = (ScrimInsetsFrameLayout) findViewById(R.id.editor_drawer_root); // set status bar background for Activity body layout if (GlobalData.applicationTheme.equals("material")) drawerLayout.setStatusBarBackground(R.color.profile_all_primaryDark); else if (GlobalData.applicationTheme.equals("dark")) drawerLayout.setStatusBarBackground(R.color.profile_all_primaryDark_dark); else if (GlobalData.applicationTheme.equals("dlight")) drawerLayout.setStatusBarBackground(R.color.profile_all_primaryDark_dark); drawerListView = (ListView) findViewById(R.id.editor_drawer_list); View headerView = ((LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.editor_drawer_list_header, null, false); drawerListView.addHeaderView(headerView, null, false); drawerHeaderFilterImage = (ImageView) findViewById(R.id.editor_drawer_list_header_icon); drawerHeaderFilterTitle = (TextView) findViewById(R.id.editor_drawer_list_header_title); drawerHeaderFilterSubtitle = (TextView) findViewById(R.id.editor_drawer_list_header_subtitle); int drawerShadowId; if (GlobalData.applicationTheme.equals("dark")) drawerShadowId = R.drawable.drawer_shadow_dark; else drawerShadowId = R.drawable.drawer_shadow; drawerLayout.setDrawerShadow(drawerShadowId, GravityCompat.START); // actionbar titles drawerItemsTitle = new String[] { getResources().getString(R.string.editor_drawer_title_profiles), getResources().getString(R.string.editor_drawer_title_profiles), getResources().getString(R.string.editor_drawer_title_profiles), getResources().getString(R.string.editor_drawer_title_events), getResources().getString(R.string.editor_drawer_title_events), getResources().getString(R.string.editor_drawer_title_events), getResources().getString(R.string.editor_drawer_title_events) }; // drawer item titles drawerItemsSubtitle = new String[] { getResources().getString(R.string.editor_drawer_list_item_profiles_all), getResources().getString(R.string.editor_drawer_list_item_profiles_show_in_activator), getResources().getString(R.string.editor_drawer_list_item_profiles_no_show_in_activator), getResources().getString(R.string.editor_drawer_list_item_events_all), getResources().getString(R.string.editor_drawer_list_item_events_running), getResources().getString(R.string.editor_drawer_list_item_events_paused), getResources().getString(R.string.editor_drawer_list_item_events_stopped) }; drawerItemsIcon = new Integer[] { R.drawable.ic_events_drawer_profile_filter_2, R.drawable.ic_events_drawer_profile_filter_0, R.drawable.ic_events_drawer_profile_filter_1, R.drawable.ic_events_drawer_event_filter_2, R.drawable.ic_events_drawer_event_filter_0, R.drawable.ic_events_drawer_event_filter_1, R.drawable.ic_events_drawer_event_filter_3, }; // Pass string arrays to EditorDrawerListAdapter // use action bar themed context //drawerAdapter = new EditorDrawerListAdapter(drawerListView, getSupportActionBar().getThemedContext(), drawerItemsTitle, drawerItemsSubtitle, drawerItemsIcon); drawerAdapter = new EditorDrawerListAdapter(drawerListView, getBaseContext(), drawerItemsTitle, drawerItemsSubtitle, drawerItemsIcon); // Set the MenuListAdapter to the ListView drawerListView.setAdapter(drawerAdapter); // Capture listview menu item click drawerListView.setOnItemClickListener(new DrawerItemClickListener()); Toolbar toolbar = (Toolbar)findViewById(R.id.editor_tollbar); setSupportActionBar(toolbar); // Enable ActionBar app icon to behave as action to toggle nav drawer getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); // ActionBarDrawerToggle ties together the the proper interactions // between the sliding drawer and the action bar app icon /*int drawerIconId; if (GlobalData.applicationTheme.equals("light")) drawerIconId = R.drawable.ic_drawer; else drawerIconId = R.drawable.ic_drawer_dark;*/ drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.editor_drawer_open, R.string.editor_drawer_open) { public void onDrawerClosed(View view) { super.onDrawerClosed(view); } public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); } // this disable animation @Override public void onDrawerSlide(View drawerView, float slideOffset) { if(drawerView!=null && drawerView == drawerRoot){ super.onDrawerSlide(drawerView, 0); }else{ super.onDrawerSlide(drawerView, slideOffset); } } }; drawerLayout.setDrawerListener(drawerToggle); filterStatusbarTitle = (TextView) findViewById(R.id.editor_filter_title); orderLabel = (TextView) findViewById(R.id.editor_drawer_order_title); orderSpinner = (Spinner) findViewById(R.id.editor_drawer_order); ArrayAdapter<CharSequence> orderSpinneAadapter = ArrayAdapter.createFromResource( //getSupportActionBar().getThemedContext(), getBaseContext(), R.array.drawerOrderEvents, //android.R.layout.simple_spinner_item); R.layout.editor_drawer_spinner); orderSpinneAadapter.setDropDownViewResource(android.support.v7.appcompat.R.layout.support_simple_spinner_dropdown_item); orderSpinneAadapter.setDropDownViewResource(R.layout.editor_drawer_spinner_dropdown); orderSpinner.setAdapter(orderSpinneAadapter); orderSpinner.setOnItemSelectedListener(new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (position != orderSelectedItem) changeEventOrder(position, false); } public void onNothingSelected(AdapterView<?> parent) { } }); //getSupportActionBar().setDisplayShowTitleEnabled(false); //getSupportActionBar().setTitle(R.string.title_activity_phone_profiles); /* // Create an array adapter to populate dropdownlist ArrayAdapter<CharSequence> navigationAdapter = ArrayAdapter.createFromResource(getSupportActionBar().getThemedContext(), R.array.phoneProfilesNavigator, R.layout.sherlock_spinner_item); // Enabling dropdown list navigation for the action bar getSupportActionBar().setNavigationMode(com.actionbarsherlock.app.ActionBar.NAVIGATION_MODE_LIST); // Defining Navigation listener ActionBar.OnNavigationListener navigationListener = new ActionBar.OnNavigationListener() { public boolean onNavigationItemSelected(int itemPosition, long itemId) { switch(itemPosition) { case 0: EditorProfileListFragment profileFragment = new EditorProfileListFragment(); getSupportFragmentManager().beginTransaction() .replace(R.id.editor_list_container, profileFragment, "EditorProfileListFragment").commit(); onStartProfilePreferences(-1, false); break; case 1: EditorEventListFragment eventFragment = new EditorEventListFragment(); getSupportFragmentManager().beginTransaction() .replace(R.id.editor_list_container, eventFragment, "EditorEventListFragment").commit(); onStartEventPreferences(-1, false); break; } return false; } }; // Setting dropdown items and item navigation listener for the actionbar getSupportActionBar().setListNavigationCallbacks(navigationAdapter, navigationListener); navigationAdapter.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item); */ eventsRunStopIndicator = (ImageView)findViewById(R.id.editor_list_run_stop_indicator); // set drawer item and order //Log.e("EditorProfilesActivity.onCreate","applicationEditorSaveEditorState="+GlobalData.applicationEditorSaveEditorState); if ((savedInstanceState != null) || (GlobalData.applicationEditorSaveEditorState)) { SharedPreferences preferences = getSharedPreferences(GlobalData.APPLICATION_PREFS_NAME, Activity.MODE_PRIVATE); drawerSelectedItem = preferences.getInt(SP_EDITOR_DRAWER_SELECTED_ITEM, 2); orderSelectedItem = preferences.getInt(SP_EDITOR_ORDER_SELECTED_ITEM, 2); // priority } //Log.e("EditorProfilesActivity.onCreate","orderSelectedItem="+orderSelectedItem); // first must be set eventsOrderType changeEventOrder(orderSelectedItem, savedInstanceState != null); selectDrawerItem(drawerSelectedItem, false, savedInstanceState != null); refreshGUI(); //Log.e("EditorProfilesActivity.onCreate", "drawerSelectedItem="+drawerSelectedItem); } public static EditorProfilesActivity getInstance() { return instance; } @Override protected void onStart() { super.onStart(); //Log.d("EditorProfilesActivity.onStart", "xxxx"); } @Override protected void onStop() { super.onStop(); instance = null; } @Override protected void onResume() { //Debug.stopMethodTracing(); super.onResume(); if (instance == null) { instance = this; refreshGUI(); } } @Override protected void onDestroy() { if (!savedInstanceStateChanged) { // no destroy caches on orientation change if (applicationsCache != null) applicationsCache.clearCache(true); applicationsCache = null; if (contactsCache != null) contactsCache.clearCache(true); contactsCache = null; } super.onDestroy(); //Log.e("EditorProfilesActivity.onDestroy","xxx"); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.activity_editor_profiles, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { // change global events run/stop menu item title MenuItem menuItem = menu.findItem(R.id.menu_run_stop_events); if (menuItem != null) { if (GlobalData.getGlobalEventsRuning(getBaseContext())) { menuItem.setTitle(R.string.menu_stop_events); } else { menuItem.setTitle(R.string.menu_run_events); } } boolean isPPHInstalled = PhoneProfilesHelper.isPPHelperInstalled(getBaseContext(), PhoneProfilesHelper.PPHELPER_CURRENT_VERSION); menuItem = menu.findItem(R.id.menu_pphelper_install); if (menuItem != null) { //menuItem.setVisible(GlobalData.isRooted(true) && (!isPPHInstalled)); menuItem.setVisible(!isPPHInstalled); if (PhoneProfilesHelper.PPHelperVersion != -1) { menuItem.setTitle(R.string.menu_phoneprofilehepler_upgrade); } else { menuItem.setTitle(R.string.menu_phoneprofilehepler_install); } } menuItem = menu.findItem(R.id.menu_pphelper_uninstall); if (menuItem != null) { //menuItem.setVisible(GlobalData.isRooted(true) && (PhoneProfilesHelper.PPHelperVersion != -1)); menuItem.setVisible(PhoneProfilesHelper.PPHelperVersion != -1); } menuItem = menu.findItem(R.id.menu_restart_events); if (menuItem != null) { menuItem.setVisible(GlobalData.getGlobalEventsRuning(getBaseContext())); } return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent intent; switch (item.getItemId()) { case android.R.id.home: if (drawerLayout.isDrawerOpen(drawerRoot)) { drawerLayout.closeDrawer(drawerRoot); } else { drawerLayout.openDrawer(drawerRoot); } return super.onOptionsItemSelected(item); case R.id.menu_restart_events: // ignoruj manualnu aktivaciu profilu // a odblokuj forceRun eventy getDataWrapper().restartEventsWithAlert(this); return true; case R.id.menu_run_stop_events: DataWrapper dataWrapper = getDataWrapper(); if (GlobalData.getGlobalEventsRuning(getBaseContext())) { // no setup for next start dataWrapper.removeAllEventDelays(); dataWrapper.pauseAllEvents(true, false, false); GlobalData.setGlobalEventsRuning(getBaseContext(), false); // stop Wifi scanner WifiScanAlarmBroadcastReceiver.initialize(getBaseContext()); WifiScanAlarmBroadcastReceiver.removeAlarm(getBaseContext(), false); // stop bluetooth scanner BluetoothScanAlarmBroadcastReceiver.initialize(getBaseContext()); BluetoothScanAlarmBroadcastReceiver.removeAlarm(getBaseContext(), false); } else { GlobalData.setGlobalEventsRuning(getBaseContext(), true); // setup for next start dataWrapper.firstStartEvents(false, true); } invalidateOptionsMenu(); refreshGUI(); return true; case R.id.menu_default_profile: // start preferences activity for default profile intent = new Intent(getBaseContext(), ProfilePreferencesFragmentActivity.class); intent.putExtra(GlobalData.EXTRA_PROFILE_ID, GlobalData.DEFAULT_PROFILE_ID); intent.putExtra(GlobalData.EXTRA_NEW_PROFILE_MODE, EditorProfileListFragment.EDIT_MODE_EDIT); startActivityForResult(intent, GlobalData.REQUEST_CODE_PROFILE_PREFERENCES); return true; case R.id.menu_settings: //Log.d("EditorProfilesActivity.onOptionsItemSelected", "menu_settings"); intent = new Intent(getBaseContext(), PhoneProfilesPreferencesActivity.class); startActivityForResult(intent, GlobalData.REQUEST_CODE_APPLICATION_PREFERENCES); return true; case R.id.menu_pphelper_install: PhoneProfilesHelper.installPPHelper(this, false); return true; case R.id.menu_pphelper_uninstall: PhoneProfilesHelper.uninstallPPHelper(this); return true; case R.id.menu_export: //Log.d("EditorProfilesActivity.onOptionsItemSelected", "menu_export"); exportData(); return true; case R.id.menu_import: //Log.d("EditorProfilesActivity.onOptionsItemSelected", "menu_import"); importData(); return true; case R.id.menu_exit: //Log.d("EditorProfilesActivity.onOptionsItemSelected", "menu_exit"); GlobalData.setApplicationStarted(getBaseContext(), false); // stop all events getDataWrapper().stopAllEvents(false, false); // zrusenie notifikacie getDataWrapper().getActivateProfileHelper().removeNotification(); SearchCalendarEventsBroadcastReceiver.removeAlarm(getApplicationContext()); WifiScanAlarmBroadcastReceiver.removeAlarm(getApplicationContext(), false); stopService(new Intent(getApplicationContext(), ReceiversService.class)); if (Keyguard.keyguardService != null) stopService(Keyguard.keyguardService); Keyguard.reenable(); finish(); return true; default: return super.onOptionsItemSelected(item); } } // fix for bug in LG stock ROM Android <= 4.1 @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_MENU) && (Build.VERSION.SDK_INT <= 16) && (Build.MANUFACTURER.compareTo("LGE") == 0)) { return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_MENU) && (Build.VERSION.SDK_INT <= 16) && (Build.MANUFACTURER.compareTo("LGE") == 0)) { openOptionsMenu(); return true; } return super.onKeyUp(keyCode, event); } // ListView click listener in the navigation drawer private class DrawerItemClickListener implements ListView.OnItemClickListener { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // header is position=0 if (position > 0) selectDrawerItem(position, true, false); } } private void selectDrawerItem(int position, boolean removePreferences, boolean orientationChange) { Log.e("EditorProfilesActivity.selectDrawerItem","position="+position); Log.e("EditorProfilesActivity.selectDrawerItem","orientationChange="+orientationChange); Fragment fragment = getFragmentManager().findFragmentById(R.id.editor_list_container); if (position == 0) position = 2; if ((position != drawerSelectedItem) || (fragment == null)) { drawerSelectedItem = position; // save into shared preferences SharedPreferences preferences = getSharedPreferences(GlobalData.APPLICATION_PREFS_NAME, Activity.MODE_PRIVATE); Editor editor = preferences.edit(); editor.putInt(SP_EDITOR_DRAWER_SELECTED_ITEM, drawerSelectedItem); editor.commit(); Bundle arguments; switch (drawerSelectedItem) { case 1: profilesFilterType = EditorProfileListFragment.FILTER_TYPE_ALL; fragment = new EditorProfileListFragment(); arguments = new Bundle(); arguments.putInt(EditorProfileListFragment.FILTER_TYPE_ARGUMENT, profilesFilterType); fragment.setArguments(arguments); getFragmentManager().beginTransaction() .replace(R.id.editor_list_container, fragment, "EditorProfileListFragment").commit(); if (removePreferences) onStartProfilePreferences(null, EditorProfileListFragment.EDIT_MODE_EDIT, profilesFilterType); break; case 2: profilesFilterType = EditorProfileListFragment.FILTER_TYPE_SHOW_IN_ACTIVATOR; fragment = new EditorProfileListFragment(); arguments = new Bundle(); arguments.putInt(EditorProfileListFragment.FILTER_TYPE_ARGUMENT, profilesFilterType); fragment.setArguments(arguments); getFragmentManager().beginTransaction() .replace(R.id.editor_list_container, fragment, "EditorProfileListFragment").commit(); if (removePreferences) onStartProfilePreferences(null, EditorProfileListFragment.EDIT_MODE_EDIT, profilesFilterType); break; case 3: profilesFilterType = EditorProfileListFragment.FILTER_TYPE_NO_SHOW_IN_ACTIVATOR; fragment = new EditorProfileListFragment(); arguments = new Bundle(); arguments.putInt(EditorProfileListFragment.FILTER_TYPE_ARGUMENT, profilesFilterType); fragment.setArguments(arguments); getFragmentManager().beginTransaction() .replace(R.id.editor_list_container, fragment, "EditorProfileListFragment").commit(); if (removePreferences) onStartProfilePreferences(null, EditorProfileListFragment.EDIT_MODE_EDIT, profilesFilterType); break; case 4: eventsFilterType = EditorEventListFragment.FILTER_TYPE_ALL; fragment = new EditorEventListFragment(); arguments = new Bundle(); arguments.putInt(EditorEventListFragment.FILTER_TYPE_ARGUMENT, eventsFilterType); arguments.putInt(EditorEventListFragment.ORDER_TYPE_ARGUMENT, eventsOrderType); fragment.setArguments(arguments); getFragmentManager().beginTransaction() .replace(R.id.editor_list_container, fragment, "EditorEventListFragment").commit(); if (removePreferences) onStartEventPreferences(null, EditorEventListFragment.EDIT_MODE_EDIT, eventsFilterType, eventsOrderType); break; case 5: eventsFilterType = EditorEventListFragment.FILTER_TYPE_RUNNING; fragment = new EditorEventListFragment(); arguments = new Bundle(); arguments.putInt(EditorEventListFragment.FILTER_TYPE_ARGUMENT, eventsFilterType); arguments.putInt(EditorEventListFragment.ORDER_TYPE_ARGUMENT, eventsOrderType); fragment.setArguments(arguments); getFragmentManager().beginTransaction() .replace(R.id.editor_list_container, fragment, "EditorEventListFragment").commit(); if (removePreferences) onStartEventPreferences(null, EditorEventListFragment.EDIT_MODE_EDIT, eventsFilterType, eventsOrderType); break; case 6: eventsFilterType = EditorEventListFragment.FILTER_TYPE_PAUSED; fragment = new EditorEventListFragment(); arguments = new Bundle(); arguments.putInt(EditorEventListFragment.FILTER_TYPE_ARGUMENT, eventsFilterType); arguments.putInt(EditorEventListFragment.ORDER_TYPE_ARGUMENT, eventsOrderType); fragment.setArguments(arguments); getFragmentManager().beginTransaction() .replace(R.id.editor_list_container, fragment, "EditorEventListFragment").commit(); if (removePreferences) onStartEventPreferences(null, EditorEventListFragment.EDIT_MODE_EDIT, eventsFilterType, eventsOrderType); break; case 7: eventsFilterType = EditorEventListFragment.FILTER_TYPE_STOPPED; fragment = new EditorEventListFragment(); arguments = new Bundle(); arguments.putInt(EditorEventListFragment.FILTER_TYPE_ARGUMENT, eventsFilterType); arguments.putInt(EditorEventListFragment.ORDER_TYPE_ARGUMENT, eventsOrderType); fragment.setArguments(arguments); getFragmentManager().beginTransaction() .replace(R.id.editor_list_container, fragment, "EditorEventListFragment").commit(); if (removePreferences) onStartEventPreferences(null, EditorEventListFragment.EDIT_MODE_EDIT, eventsFilterType, eventsOrderType); break; } } // header is position=0 drawerListView.setItemChecked(drawerSelectedItem, true); // Get the title and icon followed by the position setTitle(drawerItemsTitle[drawerSelectedItem-1]); //setIcon(drawerItemsIcon[drawerSelectedItem-1]); drawerHeaderFilterImage.setImageResource(drawerItemsIcon[drawerSelectedItem-1]); drawerHeaderFilterTitle.setText(drawerItemsTitle[drawerSelectedItem-1]); // show/hide order if (drawerSelectedItem <= COUNT_DRAWER_PROFILE_ITEMS) { orderLabel.setVisibility(View.GONE); orderSpinner.setVisibility(View.GONE); } else { orderLabel.setVisibility(View.VISIBLE); orderSpinner.setVisibility(View.VISIBLE); } // set filter statusbar title setStatusBarTitle(); // Close drawer if (GlobalData.applicationEditorAutoCloseDrawer && (!orientationChange)) drawerLayout.closeDrawer(drawerRoot); } private void changeEventOrder(int position, boolean orientationChange) { orderSelectedItem = position; Log.e("EditorProfilesActivity.changeEventOrder","orderSelectedItem="+orderSelectedItem); Log.e("EditorProfilesActivity.changeEventOrder","orientationChange="+orientationChange); // save into shared preferences SharedPreferences preferences = getSharedPreferences(GlobalData.APPLICATION_PREFS_NAME, Activity.MODE_PRIVATE); Editor editor = preferences.edit(); editor.putInt(SP_EDITOR_ORDER_SELECTED_ITEM, orderSelectedItem); editor.commit(); //Log.e("EditorProfilesActivity.changeEventOrder","xxx"); eventsOrderType = EditorEventListFragment.ORDER_TYPE_EVENT_NAME; switch (position) { case 0: eventsOrderType = EditorEventListFragment.ORDER_TYPE_EVENT_NAME; break; case 1: eventsOrderType = EditorEventListFragment.ORDER_TYPE_PROFILE_NAME; break; case 2: eventsOrderType = EditorEventListFragment.ORDER_TYPE_PRIORITY; break; } setStatusBarTitle(); Fragment fragment = getFragmentManager().findFragmentById(R.id.editor_list_container); if ((fragment != null) && (fragment instanceof EditorEventListFragment)) { ((EditorEventListFragment)fragment).changeListOrder(eventsOrderType); } orderSpinner.setSelection(orderSelectedItem); // Close drawer if (GlobalData.applicationEditorAutoCloseDrawer && (!orientationChange)) drawerLayout.closeDrawer(drawerRoot); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == GlobalData.REQUEST_CODE_ACTIVATE_PROFILE) { EditorProfileListFragment fragment = (EditorProfileListFragment)getFragmentManager().findFragmentById(R.id.editor_list_container); if (fragment != null) fragment.doOnActivityResult(requestCode, resultCode, data); } else if (requestCode == GlobalData.REQUEST_CODE_PROFILE_PREFERENCES) { if ((resultCode == RESULT_OK) && (data != null)) { // redraw list fragment after finish ProfilePreferencesFragmentActivity long profile_id = data.getLongExtra(GlobalData.EXTRA_PROFILE_ID, 0); int newProfileMode = data.getIntExtra(GlobalData.EXTRA_NEW_PROFILE_MODE, EditorProfileListFragment.EDIT_MODE_UNDEFINED); if (profile_id > 0) { Profile profile = getDataWrapper().getDatabaseHandler().getProfile(profile_id); // generate bitmaps profile.generateIconBitmap(getBaseContext(), false, 0); profile.generatePreferencesIndicator(getBaseContext(), false, 0); // redraw list fragment , notifications, widgets after finish ProfilePreferencesFragmentActivity onRedrawProfileListFragment(profile, newProfileMode); } else if (profile_id == GlobalData.DEFAULT_PROFILE_ID) { // refresh activity for changes of default profile GUIData.reloadActivity(this, false); } } } else if (requestCode == GlobalData.REQUEST_CODE_EVENT_PREFERENCES) { if ((resultCode == RESULT_OK) && (data != null)) { // redraw list fragment after finish EventPreferencesFragmentActivity long event_id = data.getLongExtra(GlobalData.EXTRA_EVENT_ID, 0L); int newEventMode = data.getIntExtra(GlobalData.EXTRA_NEW_EVENT_MODE, EditorEventListFragment.EDIT_MODE_UNDEFINED); //Log.e("EditorProfilesActivity.onActivityResult","event_id="+event_id); //Log.e("EditorProfilesActivity.onActivityResult","newEventMode="+newEventMode); if (event_id > 0) { Event event = getDataWrapper().getDatabaseHandler().getEvent(event_id); //Log.e("EditorProfilesActivity.onActivityResult","event._id="+event._id); // redraw list fragment , notifications, widgets after finish ProfilePreferencesFragmentActivity onRedrawEventListFragment(event, newEventMode); } } } else if (requestCode == GlobalData.REQUEST_CODE_APPLICATION_PREFERENCES) { if (resultCode == RESULT_OK) { boolean restart = data.getBooleanExtra(GlobalData.EXTRA_RESET_EDITOR, false); if (restart) { // refresh activity for special changes GUIData.reloadActivity(this, true); } } } else if (requestCode == GlobalData.REQUEST_CODE_REMOTE_EXPORT) { //Log.e("EditorProfilesActivity.onActivityResult","resultCode="+resultCode); if (resultCode == RESULT_OK) { doImportData(GUIData.REMOTE_EXPORT_PATH); } } else { // send other activity results into preference fragment if (drawerSelectedItem <= COUNT_DRAWER_PROFILE_ITEMS) { ProfilePreferencesFragment fragment = (ProfilePreferencesFragment)getFragmentManager().findFragmentById(R.id.editor_detail_container); if (fragment != null) fragment.doOnActivityResult(requestCode, resultCode, data); } else { EventPreferencesFragment fragment = (EventPreferencesFragment)getFragmentManager().findFragmentById(R.id.editor_detail_container); if (fragment != null) fragment.doOnActivityResult(requestCode, resultCode, data); } } } @Override public boolean dispatchKeyEvent(KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) { // handle your back button code here if (mTwoPane) { if (drawerSelectedItem <= COUNT_DRAWER_PROFILE_ITEMS) { ProfilePreferencesFragment fragment = (ProfilePreferencesFragment)getFragmentManager().findFragmentById(R.id.editor_detail_container); if ((fragment != null) && (fragment.isActionModeActive())) { fragment.finishActionMode(ProfilePreferencesFragment.BUTTON_CANCEL); return true; // consumes the back key event - ActionMode is not finished } else return super.dispatchKeyEvent(event); } else { EventPreferencesFragment fragment = (EventPreferencesFragment)getFragmentManager().findFragmentById(R.id.editor_detail_container); if ((fragment != null) && (fragment.isActionModeActive())) { fragment.finishActionMode(EventPreferencesFragment.BUTTON_CANCEL); return true; // consumes the back key event - ActionMode is not finished } else return super.dispatchKeyEvent(event); } } else return super.dispatchKeyEvent(event); } return super.dispatchKeyEvent(event); } @Override public void onBackPressed() { if (drawerLayout.isDrawerOpen(drawerRoot)) drawerLayout.closeDrawer(drawerRoot); else super.onBackPressed(); } private void importExportErrorDialog(int importExport) { AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); String resString; if (importExport == 1) resString = getResources().getString(R.string.import_profiles_alert_title); else resString = getResources().getString(R.string.export_profiles_alert_title); dialogBuilder.setTitle(resString); if (importExport == 1) resString = getResources().getString(R.string.import_profiles_alert_error); else resString = getResources().getString(R.string.export_profiles_alert_error); dialogBuilder.setMessage(resString + "!"); //dialogBuilder.setIcon(android.R.drawable.ic_dialog_alert); dialogBuilder.setPositiveButton(android.R.string.ok, null); dialogBuilder.show(); } @SuppressWarnings({ "unchecked" }) private boolean importApplicationPreferences(File src, int what) { boolean res = false; ObjectInputStream input = null; try { input = new ObjectInputStream(new FileInputStream(src)); Editor prefEdit; if (what == 1) prefEdit = getSharedPreferences(GlobalData.APPLICATION_PREFS_NAME, Activity.MODE_PRIVATE).edit(); else prefEdit = getSharedPreferences(GlobalData.DEFAULT_PROFILE_PREFS_NAME, Activity.MODE_PRIVATE).edit(); prefEdit.clear(); Map<String, ?> entries = (Map<String, ?>) input.readObject(); for (Entry<String, ?> entry : entries.entrySet()) { Object v = entry.getValue(); String key = entry.getKey(); if (v instanceof Boolean) prefEdit.putBoolean(key, ((Boolean) v).booleanValue()); else if (v instanceof Float) prefEdit.putFloat(key, ((Float) v).floatValue()); else if (v instanceof Integer) prefEdit.putInt(key, ((Integer) v).intValue()); else if (v instanceof Long) prefEdit.putLong(key, ((Long) v).longValue()); else if (v instanceof String) prefEdit.putString(key, ((String) v)); if (what == 1) { if (key.equals(GlobalData.PREF_APPLICATION_THEME)) { if (((String)v).equals("light")) prefEdit.putString(key, "material"); } } } prefEdit.commit(); res = true; } catch (FileNotFoundException e) { // no error, this is OK //e.printStackTrace(); res = true; } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); }finally { try { if (input != null) { input.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return res; } private void doImportData(String applicationDataPath) { final Activity activity = this; final String _applicationDataPath = applicationDataPath; class ImportAsyncTask extends AsyncTask<Void, Integer, Integer> { private ProgressDialog dialog; private DataWrapper dataWrapper; ImportAsyncTask() { this.dialog = new ProgressDialog(activity); this.dataWrapper = getDataWrapper(); } @Override protected void onPreExecute() { super.onPreExecute(); lockScreenOrientation(); this.dialog.setMessage(getResources().getString(R.string.import_profiles_alert_title)); this.dialog.setCancelable(false); this.dialog.setIndeterminate(false); this.dialog.show(); // check root, this set GlobalData.rooted for doInBackgroud() GlobalData.isRooted(false); } @Override protected Integer doInBackground(Void... params) { this.dataWrapper.stopAllEvents(true, false); int ret = this.dataWrapper.getDatabaseHandler().importDB(_applicationDataPath); if (ret == 1) { // check for hardware capability and update data ret = this.dataWrapper.getDatabaseHandler().updateForHardware(getBaseContext()); } if (ret == 1) { File sd = Environment.getExternalStorageDirectory(); File exportFile = new File(sd, _applicationDataPath + "/" + GUIData.EXPORT_APP_PREF_FILENAME); if (!importApplicationPreferences(exportFile, 1)) ret = 0; else { exportFile = new File(sd, _applicationDataPath + "/" + GUIData.EXPORT_DEF_PROFILE_PREF_FILENAME); if (!importApplicationPreferences(exportFile, 2)) ret = 0; } } return ret; } @Override protected void onPostExecute(Integer result) { super.onPostExecute(result); if (this.dialog.isShowing()) this.dialog.dismiss(); unlockScreenOrientation(); if (result == 1) { GlobalData.loadPreferences(getBaseContext()); dataWrapper.invalidateProfileList(); dataWrapper.invalidateEventList(); dataWrapper.getActivateProfileHelper().showNotification(null, ""); dataWrapper.getActivateProfileHelper().updateWidget(); GlobalData.setEventsBlocked(getBaseContext(), false); // toast notification Toast msg = Toast.makeText(getBaseContext(), getResources().getString(R.string.toast_import_ok), Toast.LENGTH_SHORT); msg.show(); SharedPreferences preferences = getSharedPreferences(GlobalData.APPLICATION_PREFS_NAME, Activity.MODE_PRIVATE); Editor editor = preferences.edit(); editor.putInt(SP_EDITOR_DRAWER_SELECTED_ITEM, 1); editor.putInt(SP_EDITOR_ORDER_SELECTED_ITEM, 0); editor.commit(); // restart events // startneme eventy if (GlobalData.getGlobalEventsRuning(getBaseContext())) { Intent intent = new Intent(); intent.setAction(RestartEventsBroadcastReceiver.INTENT_RESTART_EVENTS); getBaseContext().sendBroadcast(intent); } // refresh activity GUIData.reloadActivity(activity, true); } else { importExportErrorDialog(1); } } private void lockScreenOrientation() { int currentOrientation = activity.getResources().getConfiguration().orientation; if (currentOrientation == Configuration.ORIENTATION_PORTRAIT) { activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } else { activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } } private void unlockScreenOrientation() { activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR); } } new ImportAsyncTask().execute(); } private void importDataAlert(boolean remoteExport) { final boolean _remoteExport = remoteExport; AlertDialog.Builder dialogBuilder2 = new AlertDialog.Builder(this); if (remoteExport) { dialogBuilder2.setTitle(getResources().getString(R.string.import_profiles_from_phoneprofiles_alert_title2)); dialogBuilder2.setMessage(getResources().getString(R.string.import_profiles_alert_message)); //dialogBuilder2.setIcon(android.R.drawable.ic_dialog_alert); } else { dialogBuilder2.setTitle(getResources().getString(R.string.import_profiles_alert_title)); dialogBuilder2.setMessage(getResources().getString(R.string.import_profiles_alert_message)); //dialogBuilder2.setIcon(android.R.drawable.ic_dialog_alert); } dialogBuilder2.setPositiveButton(R.string.alert_button_yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (_remoteExport) { // start RemoteExportDataActivity Intent intent = new Intent("phoneprofiles.intent.action.EXPORTDATA"); final PackageManager packageManager = getPackageManager(); List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); if (list.size() > 0) startActivityForResult(intent, GlobalData.REQUEST_CODE_REMOTE_EXPORT); else importExportErrorDialog(1); } else doImportData(GlobalData.EXPORT_PATH); } }); dialogBuilder2.setNegativeButton(R.string.alert_button_no, null); dialogBuilder2.show(); } private void importData() { // test whether the PhoneProfile is installed PackageManager packageManager = getBaseContext().getPackageManager(); Intent phoneProfiles = packageManager.getLaunchIntentForPackage("sk.henrichg.phoneprofiles"); if (phoneProfiles != null) { // PhoneProfiles is istalled AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); dialogBuilder.setTitle(getResources().getString(R.string.import_profiles_from_phoneprofiles_alert_title)); dialogBuilder.setMessage(getResources().getString(R.string.import_profiles_from_phoneprofiles_alert_message)); //dialogBuilder.setIcon(android.R.drawable.ic_dialog_alert); dialogBuilder.setPositiveButton(R.string.alert_button_yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { importDataAlert(true); } }); dialogBuilder.setNegativeButton(R.string.alert_button_no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { importDataAlert(false); } }); dialogBuilder.show(); } else importDataAlert(false); } private boolean exportApplicationPreferences(File dst, int what) { boolean res = false; ObjectOutputStream output = null; try { output = new ObjectOutputStream(new FileOutputStream(dst)); SharedPreferences pref; if (what == 1) pref = getSharedPreferences(GlobalData.APPLICATION_PREFS_NAME, Activity.MODE_PRIVATE); else pref = getSharedPreferences(GlobalData.DEFAULT_PROFILE_PREFS_NAME, Activity.MODE_PRIVATE); output.writeObject(pref.getAll()); res = true; } catch (FileNotFoundException e) { // this is OK //e.printStackTrace(); res = true; } catch (IOException e) { e.printStackTrace(); }finally { try { if (output != null) { output.flush(); output.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return res; } private void exportData() { AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); dialogBuilder.setTitle(getResources().getString(R.string.export_profiles_alert_title)); dialogBuilder.setMessage(getResources().getString(R.string.export_profiles_alert_message)); //dialogBuilder.setIcon(android.R.drawable.ic_dialog_alert); final Activity activity = this; dialogBuilder.setPositiveButton(R.string.alert_button_yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { class ExportAsyncTask extends AsyncTask<Void, Integer, Integer> { private ProgressDialog dialog; private DataWrapper dataWrapper; ExportAsyncTask() { this.dialog = new ProgressDialog(activity); this.dataWrapper = getDataWrapper(); } @Override protected void onPreExecute() { super.onPreExecute(); lockScreenOrientation(); this.dialog.setMessage(getResources().getString(R.string.export_profiles_alert_title)); this.dialog.setCancelable(false); this.dialog.setIndeterminate(false); this.dialog.show(); } @Override protected Integer doInBackground(Void... params) { int ret = dataWrapper.getDatabaseHandler().exportDB(); if (ret == 1) { File sd = Environment.getExternalStorageDirectory(); File exportFile = new File(sd, GlobalData.EXPORT_PATH + "/" + GUIData.EXPORT_APP_PREF_FILENAME); if (!exportApplicationPreferences(exportFile, 1)) ret = 0; else { exportFile = new File(sd, GlobalData.EXPORT_PATH + "/" + GUIData.EXPORT_DEF_PROFILE_PREF_FILENAME); if (!exportApplicationPreferences(exportFile, 2)) ret = 0; } } return ret; } @Override protected void onPostExecute(Integer result) { super.onPostExecute(result); if (dialog.isShowing()) dialog.dismiss(); unlockScreenOrientation(); if (result == 1) { // toast notification Toast msg = Toast.makeText(getBaseContext(), getResources().getString(R.string.toast_export_ok), Toast.LENGTH_SHORT); msg.show(); } else { importExportErrorDialog(2); } } private void lockScreenOrientation() { int currentOrientation = activity.getResources().getConfiguration().orientation; if (currentOrientation == Configuration.ORIENTATION_PORTRAIT) { activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } else { activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } } private void unlockScreenOrientation() { activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR); } } new ExportAsyncTask().execute(); } }); dialogBuilder.setNegativeButton(R.string.alert_button_no, null); dialogBuilder.show(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. drawerToggle.syncState(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); savedInstanceStateChanged = true; if (mTwoPane) { SharedPreferences preferences = getSharedPreferences(GlobalData.APPLICATION_PREFS_NAME, Activity.MODE_PRIVATE); if (drawerSelectedItem <= COUNT_DRAWER_PROFILE_ITEMS) { if ((editModeProfile != EditorProfileListFragment.EDIT_MODE_INSERT) && (editModeProfile != EditorProfileListFragment.EDIT_MODE_DUPLICATE)) { FragmentManager fragmentManager = getFragmentManager(); Fragment fragment = fragmentManager.findFragmentByTag("ProfilePreferencesFragment"); if (fragment != null) { Editor editor = preferences.edit(); editor.putInt(SP_RESET_PREFERENCES_FRAGMENT, RESET_PREFERENCE_FRAGMENT_RESET_PROFILE); editor.putLong(SP_RESET_PREFERENCES_FRAGMENT_DATA_ID, ((ProfilePreferencesFragment)fragment).profile_id); editor.putInt(SP_RESET_PREFERENCES_FRAGMENT_EDIT_MODE, editModeProfile); editor.commit(); } } else { Editor editor = preferences.edit(); editor.putInt(SP_RESET_PREFERENCES_FRAGMENT, RESET_PREFERENCE_FRAGMENT_REMOVE); editor.putLong(SP_RESET_PREFERENCES_FRAGMENT_DATA_ID, 0); editor.putInt(SP_RESET_PREFERENCES_FRAGMENT_EDIT_MODE, editModeProfile); editor.commit(); } } else { if ((editModeEvent != EditorProfileListFragment.EDIT_MODE_INSERT) && (editModeEvent != EditorProfileListFragment.EDIT_MODE_DUPLICATE)) { FragmentManager fragmentManager = getFragmentManager(); Fragment fragment = fragmentManager.findFragmentByTag("EventPreferencesFragment"); if (fragment != null) { Editor editor = preferences.edit(); editor.putInt(SP_RESET_PREFERENCES_FRAGMENT, RESET_PREFERENCE_FRAGMENT_RESET_EVENT); editor.putLong(SP_RESET_PREFERENCES_FRAGMENT_DATA_ID, ((EventPreferencesFragment)fragment).event_id); editor.putInt(SP_RESET_PREFERENCES_FRAGMENT_EDIT_MODE, editModeEvent); editor.commit(); } } else { Editor editor = preferences.edit(); editor.putInt(SP_RESET_PREFERENCES_FRAGMENT, RESET_PREFERENCE_FRAGMENT_REMOVE); editor.putLong(SP_RESET_PREFERENCES_FRAGMENT_DATA_ID, 0); editor.putInt(SP_RESET_PREFERENCES_FRAGMENT_EDIT_MODE, editModeEvent); editor.commit(); } } } } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); /* // activity will restarted // Pass any configuration change to the drawer toggles drawerToggle.onConfigurationChanged(newConfig); */ getBaseContext().getResources().updateConfiguration(newConfig, getBaseContext().getResources().getDisplayMetrics()); GUIData.reloadActivity(this, false); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); /* drawerSelectedItem = savedInstanceState.getInt("editor_drawer_selected_item", -1); selectDrawerItem(drawerSelectedItem, false); orderSelectedItem = savedInstanceState.getInt("editor_order_selected_item", -1); changeEventOrder(orderSelectedItem); */ } @Override public void setTitle(CharSequence title) { getSupportActionBar().setTitle(title); } /* public void setIcon(int iconRes) { getSupportActionBar().setIcon(iconRes); } */ private void setStatusBarTitle() { // set filter statusbar title String text = ""; if (drawerSelectedItem <= COUNT_DRAWER_PROFILE_ITEMS) { text = drawerItemsSubtitle[drawerSelectedItem-1]; } else { String[] orderItems = getResources().getStringArray(R.array.drawerOrderEvents); text = drawerItemsSubtitle[drawerSelectedItem-1] + "; " + orderItems[orderSelectedItem]; } filterStatusbarTitle.setText(text); drawerHeaderFilterSubtitle.setText(text); } public void onStartProfilePreferences(Profile profile, int editMode, int filterType) { editModeProfile = editMode; onFinishProfilePreferencesActionMode(); if (mTwoPane) { // In two-pane mode, show the detail view in this activity by // adding or replacing the detail fragment using a // fragment transaction. if ((profile != null) || (editMode == EditorProfileListFragment.EDIT_MODE_INSERT) || (editMode == EditorProfileListFragment.EDIT_MODE_DUPLICATE)) { Bundle arguments = new Bundle(); if (editMode == EditorProfileListFragment.EDIT_MODE_INSERT) arguments.putLong(GlobalData.EXTRA_PROFILE_ID, 0); else arguments.putLong(GlobalData.EXTRA_PROFILE_ID, profile._id); arguments.putInt(GlobalData.EXTRA_NEW_PROFILE_MODE, editMode); arguments.putInt(GlobalData.EXTRA_PREFERENCES_STARTUP_SOURCE, GlobalData.PREFERENCES_STARTUP_SOURCE_FRAGMENT); ProfilePreferencesFragment fragment = new ProfilePreferencesFragment(); fragment.setArguments(arguments); getFragmentManager().beginTransaction() .replace(R.id.editor_detail_container, fragment, "ProfilePreferencesFragment").commit(); } else { Fragment fragment = getFragmentManager().findFragmentById(R.id.editor_detail_container); if (fragment != null) { getFragmentManager().beginTransaction() .remove(fragment).commit(); } } } else { // In single-pane mode, simply start the profile preferences activity // for the profile position. if (((profile != null) || (editMode == EditorProfileListFragment.EDIT_MODE_INSERT) || (editMode == EditorProfileListFragment.EDIT_MODE_DUPLICATE)) && (editMode != EditorProfileListFragment.EDIT_MODE_DELETE)) { Intent intent = new Intent(getBaseContext(), ProfilePreferencesFragmentActivity.class); if (editMode == EditorProfileListFragment.EDIT_MODE_INSERT) intent.putExtra(GlobalData.EXTRA_PROFILE_ID, 0); else intent.putExtra(GlobalData.EXTRA_PROFILE_ID, profile._id); intent.putExtra(GlobalData.EXTRA_NEW_PROFILE_MODE, editMode); startActivityForResult(intent, GlobalData.REQUEST_CODE_PROFILE_PREFERENCES); } } } public void onRestartProfilePreferences(Profile profile, int newProfileMode) { if (mTwoPane) { if ((newProfileMode != EditorProfileListFragment.EDIT_MODE_INSERT) && (newProfileMode != EditorProfileListFragment.EDIT_MODE_DUPLICATE)) { // restart profile preferences fragmentu Bundle arguments = new Bundle(); arguments.putLong(GlobalData.EXTRA_PROFILE_ID, profile._id); arguments.putInt(GlobalData.EXTRA_NEW_PROFILE_MODE, editModeProfile); arguments.putInt(GlobalData.EXTRA_PREFERENCES_STARTUP_SOURCE, GlobalData.PREFERENCES_STARTUP_SOURCE_FRAGMENT); ProfilePreferencesFragment fragment = new ProfilePreferencesFragment(); fragment.setArguments(arguments); getFragmentManager().beginTransaction() .replace(R.id.editor_detail_container, fragment, "ProfilePreferencesFragment").commit(); } else { Fragment fragment = getFragmentManager().findFragmentById(R.id.editor_detail_container); if (fragment != null) { getFragmentManager().beginTransaction() .remove(fragment).commit(); } } } else { SharedPreferences preferences = getSharedPreferences(GlobalData.APPLICATION_PREFS_NAME, Activity.MODE_PRIVATE); if ((newProfileMode != EditorProfileListFragment.EDIT_MODE_INSERT) && (newProfileMode != EditorProfileListFragment.EDIT_MODE_DUPLICATE)) { Editor editor = preferences.edit(); editor.putInt(SP_RESET_PREFERENCES_FRAGMENT, RESET_PREFERENCE_FRAGMENT_RESET_PROFILE); editor.putLong(SP_RESET_PREFERENCES_FRAGMENT_DATA_ID, profile._id); editor.putInt(SP_RESET_PREFERENCES_FRAGMENT_EDIT_MODE, editModeProfile); editor.commit(); } else { Editor editor = preferences.edit(); editor.putInt(SP_RESET_PREFERENCES_FRAGMENT, RESET_PREFERENCE_FRAGMENT_REMOVE); editor.putLong(SP_RESET_PREFERENCES_FRAGMENT_DATA_ID, profile._id); editor.putInt(SP_RESET_PREFERENCES_FRAGMENT_EDIT_MODE, editModeProfile); editor.commit(); } } } public void onRedrawProfileListFragment(Profile profile, int newProfileMode) { // redraw headeru list fragmentu, notifikacie a widgetov EditorProfileListFragment fragment = (EditorProfileListFragment)getFragmentManager().findFragmentById(R.id.editor_list_container); if (fragment != null) { //Log.e("EditorProfilesActivity.onRedrawProfileListFragment","profile._showInActivator="+profile._showInActivator); // update profile, this rewrite profile in profileList fragment.dataWrapper.updateProfile(profile); boolean newProfile = ((newProfileMode == EditorProfileListFragment.EDIT_MODE_INSERT) || (newProfileMode == EditorProfileListFragment.EDIT_MODE_DUPLICATE)); fragment.updateListView(profile, newProfile); Profile activeProfile = fragment.dataWrapper.getActivatedProfile(); fragment.updateHeader(activeProfile); fragment.dataWrapper.getActivateProfileHelper().showNotification(activeProfile, ""); fragment.dataWrapper.getActivateProfileHelper().updateWidget(); } onRestartProfilePreferences(profile, newProfileMode); } public void onFinishProfilePreferencesActionMode() { //if (mTwoPane) { Fragment fragment = getFragmentManager().findFragmentById(R.id.editor_detail_container); if (fragment != null) { if (fragment instanceof ProfilePreferencesFragment) { ((ProfilePreferencesFragment)fragment).finishActionMode(EventPreferencesFragment.BUTTON_CANCEL); } else { ((EventPreferencesFragment)fragment).finishActionMode(EventPreferencesFragment.BUTTON_CANCEL); } } } public void onPreferenceAttached(PreferenceScreen root, int xmlId) { return; } public void onFinishEventPreferencesActionMode() { //if (mTwoPane) { Fragment fragment = getFragmentManager().findFragmentById(R.id.editor_detail_container); if (fragment != null) { if (fragment instanceof ProfilePreferencesFragment) ((ProfilePreferencesFragment)fragment).finishActionMode(EventPreferencesFragment.BUTTON_CANCEL); else ((EventPreferencesFragment)fragment).finishActionMode(EventPreferencesFragment.BUTTON_CANCEL); } } public void onStartEventPreferences(Event event, int editMode, int filterType, int orderType) { editModeEvent = editMode; if (mTwoPane) { // In two-pane mode, show the detail view in this activity by // adding or replacing the detail fragment using a // fragment transaction. onFinishEventPreferencesActionMode(); if ((event != null) || (editMode == EditorEventListFragment.EDIT_MODE_INSERT) || (editMode == EditorEventListFragment.EDIT_MODE_DUPLICATE)) { Bundle arguments = new Bundle(); if (editMode == EditorEventListFragment.EDIT_MODE_INSERT) arguments.putLong(GlobalData.EXTRA_EVENT_ID, 0L); else arguments.putLong(GlobalData.EXTRA_EVENT_ID, event._id); arguments.putInt(GlobalData.EXTRA_NEW_EVENT_MODE, editMode); arguments.putInt(GlobalData.EXTRA_PREFERENCES_STARTUP_SOURCE, GlobalData.PREFERENCES_STARTUP_SOURCE_FRAGMENT); EventPreferencesFragment fragment = new EventPreferencesFragment(); fragment.setArguments(arguments); getFragmentManager().beginTransaction() .replace(R.id.editor_detail_container, fragment, "EventPreferencesFragment").commit(); } else { Fragment fragment = getFragmentManager().findFragmentById(R.id.editor_detail_container); if (fragment != null) { getFragmentManager().beginTransaction() .remove(fragment).commit(); } } } else { // In single-pane mode, simply start the profile preferences activity // for the event id. if (((event != null) || (editMode == EditorEventListFragment.EDIT_MODE_INSERT) || (editMode == EditorEventListFragment.EDIT_MODE_DUPLICATE)) && (editMode != EditorEventListFragment.EDIT_MODE_DELETE)) { Intent intent = new Intent(getBaseContext(), EventPreferencesFragmentActivity.class); if (editMode == EditorEventListFragment.EDIT_MODE_INSERT) intent.putExtra(GlobalData.EXTRA_EVENT_ID, 0L); else intent.putExtra(GlobalData.EXTRA_EVENT_ID, event._id); intent.putExtra(GlobalData.EXTRA_NEW_EVENT_MODE, editMode); startActivityForResult(intent, GlobalData.REQUEST_CODE_EVENT_PREFERENCES); } } } public void onRedrawEventListFragment(Event event, int newEventMode) { // redraw headeru list fragmentu, notifikacie a widgetov EditorEventListFragment fragment = (EditorEventListFragment)getFragmentManager().findFragmentById(R.id.editor_list_container); if (fragment != null) { // update event, this rewrite event in eventList fragment.dataWrapper.updateEvent(event); boolean newEvent = ((newEventMode == EditorEventListFragment.EDIT_MODE_INSERT) || (newEventMode == EditorEventListFragment.EDIT_MODE_DUPLICATE)); fragment.updateListView(event, newEvent); } onRestartEventPreferences(event, newEventMode); } public void onRestartEventPreferences(Event event, int newEventMode) { if (mTwoPane) { if ((newEventMode != EditorEventListFragment.EDIT_MODE_INSERT) && (newEventMode != EditorEventListFragment.EDIT_MODE_DUPLICATE)) { // restart event preferences fragmentu Bundle arguments = new Bundle(); arguments.putLong(GlobalData.EXTRA_EVENT_ID, event._id); arguments.putInt(GlobalData.EXTRA_NEW_EVENT_MODE, editModeEvent); arguments.putInt(GlobalData.EXTRA_PREFERENCES_STARTUP_SOURCE, GlobalData.PREFERENCES_STARTUP_SOURCE_FRAGMENT); EventPreferencesFragment fragment = new EventPreferencesFragment(); fragment.setArguments(arguments); getFragmentManager().beginTransaction() .replace(R.id.editor_detail_container, fragment, "EventPreferencesFragment").commit(); } else { Fragment fragment = getFragmentManager().findFragmentById(R.id.editor_detail_container); if (fragment != null) { getFragmentManager().beginTransaction() .remove(fragment).commit(); } } } else { SharedPreferences preferences = getSharedPreferences(GlobalData.APPLICATION_PREFS_NAME, Activity.MODE_PRIVATE); if ((newEventMode != EditorEventListFragment.EDIT_MODE_INSERT) && (newEventMode != EditorEventListFragment.EDIT_MODE_DUPLICATE)) { Editor editor = preferences.edit(); editor.putInt(SP_RESET_PREFERENCES_FRAGMENT, RESET_PREFERENCE_FRAGMENT_RESET_EVENT); editor.putLong(SP_RESET_PREFERENCES_FRAGMENT_DATA_ID, event._id); editor.putInt(SP_RESET_PREFERENCES_FRAGMENT_EDIT_MODE, editModeEvent); editor.commit(); } else { Editor editor = preferences.edit(); editor.putInt(SP_RESET_PREFERENCES_FRAGMENT, RESET_PREFERENCE_FRAGMENT_REMOVE); editor.putLong(SP_RESET_PREFERENCES_FRAGMENT_DATA_ID, event._id); editor.putInt(SP_RESET_PREFERENCES_FRAGMENT_EDIT_MODE, editModeEvent); editor.commit(); } } } @Override public void onShowActionModeInEventPreferences() { Fragment fragment = getFragmentManager().findFragmentById(R.id.editor_list_container); if (fragment != null) { if (fragment instanceof EditorProfileListFragment) { ((EditorProfileListFragment)fragment).fabButton.show(); } else { ((EditorEventListFragment)fragment).fabButton.show(); } } drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); } @Override public void onShowActionModeInProfilePreferences() { Fragment fragment = getFragmentManager().findFragmentById(R.id.editor_list_container); if (fragment != null) { if (fragment instanceof EditorProfileListFragment) { ((EditorProfileListFragment)fragment).fabButton.hide(); } else { ((EditorEventListFragment)fragment).fabButton.hide(); } } drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); } @Override public void onHideActionModeInEventPreferences() { Fragment fragment = getFragmentManager().findFragmentById(R.id.editor_list_container); if (fragment != null) { if (fragment instanceof EditorProfileListFragment) { ((EditorProfileListFragment)fragment).fabButton.show(); } else { ((EditorEventListFragment)fragment).fabButton.show(); } } drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED); } @Override public void onHideActionModeInProfilePreferences() { Fragment fragment = getFragmentManager().findFragmentById(R.id.editor_list_container); if (fragment != null) { if (fragment instanceof EditorProfileListFragment) { ((EditorProfileListFragment)fragment).fabButton.show(); } else { ((EditorEventListFragment)fragment).fabButton.show(); } } drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED); } public static ApplicationsCache getApplicationsCache() { return applicationsCache; } public static void createApplicationsCache() { if ((!savedInstanceStateChanged) || (applicationsCache == null)) { if (applicationsCache != null) applicationsCache.clearCache(true); applicationsCache = new ApplicationsCache(); } } public static void createContactsCache() { if ((!savedInstanceStateChanged) || (contactsCache == null)) { if (contactsCache != null) contactsCache.clearCache(true); contactsCache = new ContactsCache(); } } public static ContactsCache getContactsCache() { return contactsCache; } public static void createContactGroupsCache() { if ((!savedInstanceStateChanged) || (contactGroupsCache == null)) { if (contactGroupsCache != null) contactGroupsCache.clearCache(true); contactGroupsCache = new ContactGroupsCache(); } } public static ContactGroupsCache getContactGroupsCache() { return contactGroupsCache; } private DataWrapper getDataWrapper() { Fragment fragment = getFragmentManager().findFragmentById(R.id.editor_list_container); if (fragment != null) { //Log.e("EditorProfilesActivity.getDataWrapper","COUNT_DRAWER_PROFILE_ITEMS="+COUNT_DRAWER_PROFILE_ITEMS); //Log.e("EditorProfilesActivity.getDataWrapper","drawerSelectedItem="+drawerSelectedItem); if (fragment instanceof EditorProfileListFragment) return ((EditorProfileListFragment)fragment).dataWrapper; else return ((EditorEventListFragment)fragment).dataWrapper; } else return null; } public void setEventsRunStopIndicator() { if (GlobalData.getGlobalEventsRuning(getBaseContext())) { if (GlobalData.getEventsBlocked(getBaseContext())) eventsRunStopIndicator.setImageResource(R.drawable.ic_run_events_indicator_manual_activation); else eventsRunStopIndicator.setImageResource(R.drawable.ic_run_events_indicator_running); } else eventsRunStopIndicator.setImageResource(R.drawable.ic_run_events_indicator_stoppped); } public void refreshGUI() { setEventsRunStopIndicator(); Fragment fragment = getFragmentManager().findFragmentById(R.id.editor_list_container); if (fragment != null) { //Log.e("EditorProfilesActivity.getDataWrapper","COUNT_DRAWER_PROFILE_ITEMS="+COUNT_DRAWER_PROFILE_ITEMS); //Log.e("EditorProfilesActivity.getDataWrapper","drawerSelectedItem="+drawerSelectedItem); if (fragment instanceof EditorProfileListFragment) ((EditorProfileListFragment)fragment).refreshGUI(); else ((EditorEventListFragment)fragment).refreshGUI(); } } /* private void setWindowContentOverlayCompat() { if (android.os.Build.VERSION.SDK_INT >= 20) { // Get the content view View contentView = findViewById(android.R.id.content); // Make sure it's a valid instance of a FrameLayout if (contentView instanceof FrameLayout) { TypedValue tv = new TypedValue(); // Get the windowContentOverlay value of the current theme if (getTheme().resolveAttribute( android.R.attr.windowContentOverlay, tv, true)) { // If it's a valid resource, set it as the foreground drawable // for the content view if (tv.resourceId != 0) { ((FrameLayout) contentView).setForeground( getResources().getDrawable(tv.resourceId)); } } } } } */ }
package sk.henrichg.phoneprofilesplus; import android.annotation.SuppressLint; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Configuration; import android.graphics.Color; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceScreen; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.afollestad.materialdialogs.MaterialDialog; import com.readystatesoftware.systembartint.SystemBarTintManager; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.List; import java.util.Map; import java.util.Map.Entry; import sk.henrichg.phoneprofilesplus.EditorEventListFragment.OnFinishEventPreferencesActionMode; import sk.henrichg.phoneprofilesplus.EditorEventListFragment.OnStartEventPreferences; import sk.henrichg.phoneprofilesplus.EditorProfileListFragment.OnFinishProfilePreferencesActionMode; import sk.henrichg.phoneprofilesplus.EditorProfileListFragment.OnStartProfilePreferences; import sk.henrichg.phoneprofilesplus.EventPreferencesFragment.OnHideActionModeInEventPreferences; import sk.henrichg.phoneprofilesplus.EventPreferencesFragment.OnRedrawEventListFragment; import sk.henrichg.phoneprofilesplus.EventPreferencesFragment.OnRestartEventPreferences; import sk.henrichg.phoneprofilesplus.EventPreferencesFragment.OnShowActionModeInEventPreferences; import sk.henrichg.phoneprofilesplus.ProfilePreferencesFragment.OnHideActionModeInProfilePreferences; import sk.henrichg.phoneprofilesplus.ProfilePreferencesFragment.OnRedrawProfileListFragment; import sk.henrichg.phoneprofilesplus.ProfilePreferencesFragment.OnRestartProfilePreferences; import sk.henrichg.phoneprofilesplus.ProfilePreferencesFragment.OnShowActionModeInProfilePreferences; public class EditorProfilesActivity extends ActionBarActivity implements OnStartProfilePreferences, OnRestartProfilePreferences, OnRedrawProfileListFragment, OnFinishProfilePreferencesActionMode, OnStartEventPreferences, OnRestartEventPreferences, OnRedrawEventListFragment, OnFinishEventPreferencesActionMode, OnShowActionModeInProfilePreferences, OnShowActionModeInEventPreferences, OnHideActionModeInProfilePreferences, OnHideActionModeInEventPreferences { private static EditorProfilesActivity instance; private ImageView eventsRunStopIndicator; private static boolean savedInstanceStateChanged; private static ApplicationsCache applicationsCache; private static ContactsCache contactsCache; private static ContactGroupsCache contactGroupsCache; private int editModeProfile; private int editModeEvent; private static final String SP_RESET_PREFERENCES_FRAGMENT = "editor_restet_preferences_fragment"; private static final String SP_RESET_PREFERENCES_FRAGMENT_DATA_ID = "editor_restet_preferences_fragment_data_id"; private static final String SP_RESET_PREFERENCES_FRAGMENT_EDIT_MODE = "editor_restet_preferences_fragment_edit_mode"; private static final int RESET_PREFERENCE_FRAGMENT_RESET_PROFILE = 1; private static final int RESET_PREFERENCE_FRAGMENT_RESET_EVENT = 2; private static final int RESET_PREFERENCE_FRAGMENT_REMOVE = 3; private static final String SP_EDITOR_DRAWER_SELECTED_ITEM = "editor_drawer_selected_item"; private static final String SP_EDITOR_ORDER_SELECTED_ITEM = "editor_order_selected_item"; /** * Whether or not the activity is in two-pane mode, i.e. running on a tablet * device. */ public static boolean mTwoPane; DrawerLayout drawerLayout; ScrimInsetsFrameLayout drawerRoot; ListView drawerListView; ActionBarDrawerToggle drawerToggle; TextView filterStatusbarTitle; TextView orderLabel; Spinner orderSpinner; ImageView drawerHeaderFilterImage; TextView drawerHeaderFilterTitle; TextView drawerHeaderFilterSubtitle; String[] drawerItemsTitle; String[] drawerItemsSubtitle; Integer[] drawerItemsIcon; EditorDrawerListAdapter drawerAdapter; private int drawerSelectedItem = 2; private int orderSelectedItem = 2; // priority private int profilesFilterType = EditorProfileListFragment.FILTER_TYPE_SHOW_IN_ACTIVATOR; private int eventsFilterType = EditorEventListFragment.FILTER_TYPE_ALL; private int eventsOrderType = EditorEventListFragment.ORDER_TYPE_EVENT_NAME; private static final int COUNT_DRAWER_PROFILE_ITEMS = 3; @SuppressLint("NewApi") @Override protected void onCreate(Bundle savedInstanceState) { //Log.e("$$$ PPP","EditorProfilesActivity.onCreate"); GUIData.setTheme(this, false, true); GUIData.setLanguage(getBaseContext()); super.onCreate(savedInstanceState); instance = this; savedInstanceStateChanged = (savedInstanceState != null); createApplicationsCache(); createContactsCache(); createContactGroupsCache(); setContentView(R.layout.activity_editor_list_onepane); if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) && (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)) { Window w = getWindow(); // in Activity's onCreate() for instance //w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); // create our manager instance after the content view is set SystemBarTintManager tintManager = new SystemBarTintManager(this); // enable status bar tint tintManager.setStatusBarTintEnabled(true); // set a custom tint color for status bar if (GlobalData.applicationTheme.equals("material")) tintManager.setStatusBarTintColor(Color.parseColor("#ff237e9f")); else tintManager.setStatusBarTintColor(Color.parseColor("#ff202020")); } //if (android.os.Build.VERSION.SDK_INT >= 21) // getWindow().setNavigationBarColor(R.attr.colorPrimary); //setWindowContentOverlayCompat(); /* // add profile list into list container EditorProfileListFragment fragment = new EditorProfileListFragment(); getSupportFragmentManager().beginTransaction() .replace(R.id.editor_list_container, fragment, "EditorProfileListFragment").commit(); */ if (findViewById(R.id.editor_detail_container) != null) { // The detail container view will be present only in the // large-screen layouts (res/values-large and // res/values-sw600dp). If this view is present, then the // activity should be in two-pane mode. mTwoPane = true; if (savedInstanceState == null) onStartProfilePreferences(null, EditorProfileListFragment.EDIT_MODE_EDIT, profilesFilterType); else { // for 7 inch tablets lauout changed: // - portrait - one pane // - landscape - two pane // onRestartProfilePreferences is called, when user save/not save profile // preference changes (Back button, or Cancel in ActionMode) // In this method, editmode and profile_id is saved into shared preferences // And when orientaion changed into lanscape mode, profile preferences fragment // must by recreated due profile preference changes SharedPreferences preferences = getSharedPreferences(GlobalData.APPLICATION_PREFS_NAME, Activity.MODE_PRIVATE); int resetMode = preferences.getInt(SP_RESET_PREFERENCES_FRAGMENT, 0); if (resetMode == RESET_PREFERENCE_FRAGMENT_RESET_PROFILE) { // restart profile preferences fragmentu long profile_id = preferences.getLong(SP_RESET_PREFERENCES_FRAGMENT_DATA_ID, 0); int editMode = preferences.getInt(SP_RESET_PREFERENCES_FRAGMENT_EDIT_MODE, EditorProfileListFragment.EDIT_MODE_UNDEFINED); Bundle arguments = new Bundle(); arguments.putLong(GlobalData.EXTRA_PROFILE_ID, profile_id); arguments.putInt(GlobalData.EXTRA_NEW_PROFILE_MODE, editMode); arguments.putInt(GlobalData.EXTRA_PREFERENCES_STARTUP_SOURCE, GlobalData.PREFERENCES_STARTUP_SOURCE_FRAGMENT); ProfilePreferencesFragment fragment = new ProfilePreferencesFragment(); fragment.setArguments(arguments); getFragmentManager().beginTransaction() .replace(R.id.editor_detail_container, fragment, "ProfilePreferencesFragment").commit(); } if (resetMode == RESET_PREFERENCE_FRAGMENT_RESET_EVENT) { // restart event preferences fragmentu long event_id = preferences.getLong(SP_RESET_PREFERENCES_FRAGMENT_DATA_ID, 0); int editMode = preferences.getInt(SP_RESET_PREFERENCES_FRAGMENT_EDIT_MODE, EditorProfileListFragment.EDIT_MODE_UNDEFINED); Bundle arguments = new Bundle(); arguments.putLong(GlobalData.EXTRA_EVENT_ID, event_id); arguments.putInt(GlobalData.EXTRA_NEW_EVENT_MODE, editMode); arguments.putInt(GlobalData.EXTRA_PREFERENCES_STARTUP_SOURCE, GlobalData.PREFERENCES_STARTUP_SOURCE_FRAGMENT); EventPreferencesFragment fragment = new EventPreferencesFragment(); fragment.setArguments(arguments); getFragmentManager().beginTransaction() .replace(R.id.editor_detail_container, fragment, "EventPreferencesFragment").commit(); } else if (resetMode == RESET_PREFERENCE_FRAGMENT_REMOVE) { Fragment fragment = getFragmentManager().findFragmentById(R.id.editor_detail_container); if (fragment != null) { getFragmentManager().beginTransaction() .remove(fragment).commit(); } } // remove preferences Editor editor = preferences.edit(); editor.remove(SP_RESET_PREFERENCES_FRAGMENT); editor.remove(SP_RESET_PREFERENCES_FRAGMENT_DATA_ID); editor.remove(SP_RESET_PREFERENCES_FRAGMENT_EDIT_MODE); editor.commit(); } } else { mTwoPane = false; FragmentManager fragmentManager = getFragmentManager(); Fragment fragment = fragmentManager.findFragmentByTag("ProfilePreferencesFragment"); if (fragment != null) fragmentManager.beginTransaction() .remove(fragment).commit(); fragment = fragmentManager.findFragmentByTag("EventPreferencesFragment"); if (fragment != null) fragmentManager.beginTransaction() .remove(fragment).commit(); fragmentManager.executePendingTransactions(); } drawerLayout = (DrawerLayout) findViewById(R.id.editor_list_drawer_layout); drawerRoot = (ScrimInsetsFrameLayout) findViewById(R.id.editor_drawer_root); // set status bar background for Activity body layout if (GlobalData.applicationTheme.equals("material")) drawerLayout.setStatusBarBackground(R.color.profile_all_primaryDark); else if (GlobalData.applicationTheme.equals("dark")) drawerLayout.setStatusBarBackground(R.color.profile_all_primaryDark_dark); else if (GlobalData.applicationTheme.equals("dlight")) drawerLayout.setStatusBarBackground(R.color.profile_all_primaryDark_dark); drawerListView = (ListView) findViewById(R.id.editor_drawer_list); View headerView = ((LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.editor_drawer_list_header, null, false); drawerListView.addHeaderView(headerView, null, false); drawerHeaderFilterImage = (ImageView) findViewById(R.id.editor_drawer_list_header_icon); drawerHeaderFilterTitle = (TextView) findViewById(R.id.editor_drawer_list_header_title); drawerHeaderFilterSubtitle = (TextView) findViewById(R.id.editor_drawer_list_header_subtitle); int drawerShadowId; if (GlobalData.applicationTheme.equals("dark")) drawerShadowId = R.drawable.drawer_shadow_dark; else drawerShadowId = R.drawable.drawer_shadow; drawerLayout.setDrawerShadow(drawerShadowId, GravityCompat.START); // actionbar titles drawerItemsTitle = new String[] { getResources().getString(R.string.editor_drawer_title_profiles), getResources().getString(R.string.editor_drawer_title_profiles), getResources().getString(R.string.editor_drawer_title_profiles), getResources().getString(R.string.editor_drawer_title_events), getResources().getString(R.string.editor_drawer_title_events), getResources().getString(R.string.editor_drawer_title_events), getResources().getString(R.string.editor_drawer_title_events) }; // drawer item titles drawerItemsSubtitle = new String[] { getResources().getString(R.string.editor_drawer_list_item_profiles_all), getResources().getString(R.string.editor_drawer_list_item_profiles_show_in_activator), getResources().getString(R.string.editor_drawer_list_item_profiles_no_show_in_activator), getResources().getString(R.string.editor_drawer_list_item_events_all), getResources().getString(R.string.editor_drawer_list_item_events_running), getResources().getString(R.string.editor_drawer_list_item_events_paused), getResources().getString(R.string.editor_drawer_list_item_events_stopped) }; drawerItemsIcon = new Integer[] { R.drawable.ic_events_drawer_profile_filter_2, R.drawable.ic_events_drawer_profile_filter_0, R.drawable.ic_events_drawer_profile_filter_1, R.drawable.ic_events_drawer_event_filter_2, R.drawable.ic_events_drawer_event_filter_0, R.drawable.ic_events_drawer_event_filter_1, R.drawable.ic_events_drawer_event_filter_3, }; // Pass string arrays to EditorDrawerListAdapter // use action bar themed context //drawerAdapter = new EditorDrawerListAdapter(drawerListView, getSupportActionBar().getThemedContext(), drawerItemsTitle, drawerItemsSubtitle, drawerItemsIcon); drawerAdapter = new EditorDrawerListAdapter(drawerListView, getBaseContext(), drawerItemsTitle, drawerItemsSubtitle, drawerItemsIcon); // Set the MenuListAdapter to the ListView drawerListView.setAdapter(drawerAdapter); // Capture listview menu item click drawerListView.setOnItemClickListener(new DrawerItemClickListener()); Toolbar toolbar = (Toolbar)findViewById(R.id.editor_tollbar); setSupportActionBar(toolbar); // Enable ActionBar app icon to behave as action to toggle nav drawer getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); // ActionBarDrawerToggle ties together the the proper interactions // between the sliding drawer and the action bar app icon /*int drawerIconId; if (GlobalData.applicationTheme.equals("light")) drawerIconId = R.drawable.ic_drawer; else drawerIconId = R.drawable.ic_drawer_dark;*/ drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.editor_drawer_open, R.string.editor_drawer_open) { public void onDrawerClosed(View view) { super.onDrawerClosed(view); } public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); } // this disable animation @Override public void onDrawerSlide(View drawerView, float slideOffset) { if(drawerView!=null && drawerView == drawerRoot){ super.onDrawerSlide(drawerView, 0); }else{ super.onDrawerSlide(drawerView, slideOffset); } } }; drawerLayout.setDrawerListener(drawerToggle); filterStatusbarTitle = (TextView) findViewById(R.id.editor_filter_title); orderLabel = (TextView) findViewById(R.id.editor_drawer_order_title); orderSpinner = (Spinner) findViewById(R.id.editor_drawer_order); ArrayAdapter<CharSequence> orderSpinneAadapter = ArrayAdapter.createFromResource( //getSupportActionBar().getThemedContext(), getBaseContext(), R.array.drawerOrderEvents, //android.R.layout.simple_spinner_item); R.layout.editor_drawer_spinner); orderSpinneAadapter.setDropDownViewResource(android.support.v7.appcompat.R.layout.support_simple_spinner_dropdown_item); orderSpinneAadapter.setDropDownViewResource(R.layout.editor_drawer_spinner_dropdown); orderSpinner.setAdapter(orderSpinneAadapter); orderSpinner.setOnItemSelectedListener(new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (position != orderSelectedItem) changeEventOrder(position, false); } public void onNothingSelected(AdapterView<?> parent) { } }); //getSupportActionBar().setDisplayShowTitleEnabled(false); //getSupportActionBar().setTitle(R.string.title_activity_phone_profiles); /* // Create an array adapter to populate dropdownlist ArrayAdapter<CharSequence> navigationAdapter = ArrayAdapter.createFromResource(getSupportActionBar().getThemedContext(), R.array.phoneProfilesNavigator, R.layout.sherlock_spinner_item); // Enabling dropdown list navigation for the action bar getSupportActionBar().setNavigationMode(com.actionbarsherlock.app.ActionBar.NAVIGATION_MODE_LIST); // Defining Navigation listener ActionBar.OnNavigationListener navigationListener = new ActionBar.OnNavigationListener() { public boolean onNavigationItemSelected(int itemPosition, long itemId) { switch(itemPosition) { case 0: EditorProfileListFragment profileFragment = new EditorProfileListFragment(); getSupportFragmentManager().beginTransaction() .replace(R.id.editor_list_container, profileFragment, "EditorProfileListFragment").commit(); onStartProfilePreferences(-1, false); break; case 1: EditorEventListFragment eventFragment = new EditorEventListFragment(); getSupportFragmentManager().beginTransaction() .replace(R.id.editor_list_container, eventFragment, "EditorEventListFragment").commit(); onStartEventPreferences(-1, false); break; } return false; } }; // Setting dropdown items and item navigation listener for the actionbar getSupportActionBar().setListNavigationCallbacks(navigationAdapter, navigationListener); navigationAdapter.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item); */ eventsRunStopIndicator = (ImageView)findViewById(R.id.editor_list_run_stop_indicator); // set drawer item and order if ((savedInstanceState != null) || (GlobalData.applicationEditorSaveEditorState)) { SharedPreferences preferences = getSharedPreferences(GlobalData.APPLICATION_PREFS_NAME, Activity.MODE_PRIVATE); drawerSelectedItem = preferences.getInt(SP_EDITOR_DRAWER_SELECTED_ITEM, 2); orderSelectedItem = preferences.getInt(SP_EDITOR_ORDER_SELECTED_ITEM, 2); // priority } // first must be set eventsOrderType changeEventOrder(orderSelectedItem, savedInstanceState != null); selectDrawerItem(drawerSelectedItem, false, savedInstanceState != null); refreshGUI(); } public static EditorProfilesActivity getInstance() { return instance; } @Override protected void onStart() { //Log.e("$$$ PPP","EditorProfilesActivity.onStart"); super.onStart(); } @Override protected void onStop() { //Log.e("$$$ PPP","EditorProfilesActivity.onStop"); super.onStop(); if (instance == this) instance = null; } @Override protected void onResume() { //Log.e("$$$ PPP","EditorProfilesActivity.onResume"); //Debug.stopMethodTracing(); super.onResume(); if (instance == null) { instance = this; refreshGUI(); } } @Override protected void onDestroy() { if (!savedInstanceStateChanged) { // no destroy caches on orientation change if (applicationsCache != null) applicationsCache.clearCache(true); applicationsCache = null; if (contactsCache != null) contactsCache.clearCache(true); contactsCache = null; } super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.activity_editor_profiles, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { // change global events run/stop menu item title MenuItem menuItem = menu.findItem(R.id.menu_run_stop_events); if (menuItem != null) { if (GlobalData.getGlobalEventsRuning(getApplicationContext())) { menuItem.setTitle(R.string.menu_stop_events); } else { menuItem.setTitle(R.string.menu_run_events); } } boolean isPPHInstalled = PhoneProfilesHelper.isPPHelperInstalled(getApplicationContext(), PhoneProfilesHelper.PPHELPER_CURRENT_VERSION); menuItem = menu.findItem(R.id.menu_pphelper_install); if (menuItem != null) { //menuItem.setVisible(GlobalData.isRooted(true) && (!isPPHInstalled)); menuItem.setVisible(!isPPHInstalled); if (PhoneProfilesHelper.PPHelperVersion != -1) { menuItem.setTitle(R.string.menu_phoneprofilehepler_upgrade); } else { menuItem.setTitle(R.string.menu_phoneprofilehepler_install); } } menuItem = menu.findItem(R.id.menu_pphelper_uninstall); if (menuItem != null) { //menuItem.setVisible(GlobalData.isRooted(true) && (PhoneProfilesHelper.PPHelperVersion != -1)); menuItem.setVisible(PhoneProfilesHelper.PPHelperVersion != -1); } menuItem = menu.findItem(R.id.menu_restart_events); if (menuItem != null) { menuItem.setVisible(GlobalData.getGlobalEventsRuning(getApplicationContext())); } return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent intent; switch (item.getItemId()) { case android.R.id.home: if (drawerLayout.isDrawerOpen(drawerRoot)) { drawerLayout.closeDrawer(drawerRoot); } else { drawerLayout.openDrawer(drawerRoot); } return super.onOptionsItemSelected(item); case R.id.menu_restart_events: getDataWrapper().getDatabaseHandler().addActivityLog(DatabaseHandler.ALTYPE_RESTARTEVENTS, null, null, null, 0); // ignoruj manualnu aktivaciu profilu // a odblokuj forceRun eventy getDataWrapper().restartEventsWithAlert(this); return true; case R.id.menu_run_stop_events: DataWrapper dataWrapper = getDataWrapper(); if (GlobalData.getGlobalEventsRuning(getApplicationContext())) { dataWrapper.getDatabaseHandler().addActivityLog(DatabaseHandler.ALTYPE_RUNEVENTS_DISABLE, null, null, null, 0); // no setup for next start dataWrapper.removeAllEventDelays(); // no set system events, unblock all events, no activate return profile dataWrapper.pauseAllEvents(true, false, false); GlobalData.setGlobalEventsRuning(getApplicationContext(), false); // stop Wifi scanner WifiScanAlarmBroadcastReceiver.initialize(getApplicationContext()); WifiScanAlarmBroadcastReceiver.removeAlarm(getApplicationContext(), false); // stop bluetooth scanner BluetoothScanAlarmBroadcastReceiver.initialize(getApplicationContext()); BluetoothScanAlarmBroadcastReceiver.removeAlarm(getApplicationContext(), false); } else { dataWrapper.getDatabaseHandler().addActivityLog(DatabaseHandler.ALTYPE_RUNEVENTS_ENABLE, null, null, null, 0); GlobalData.setGlobalEventsRuning(getApplicationContext(), true); // setup for next start dataWrapper.firstStartEvents(false); } invalidateOptionsMenu(); refreshGUI(); return true; case R.id.menu_activity_log: intent = new Intent(getBaseContext(), ActivityLogActivity.class); startActivity(intent); return true; case R.id.menu_default_profile: // start preferences activity for default profile intent = new Intent(getBaseContext(), ProfilePreferencesFragmentActivity.class); intent.putExtra(GlobalData.EXTRA_PROFILE_ID, GlobalData.DEFAULT_PROFILE_ID); intent.putExtra(GlobalData.EXTRA_NEW_PROFILE_MODE, EditorProfileListFragment.EDIT_MODE_EDIT); startActivityForResult(intent, GlobalData.REQUEST_CODE_PROFILE_PREFERENCES); return true; case R.id.menu_settings: intent = new Intent(getBaseContext(), PhoneProfilesPreferencesActivity.class); startActivityForResult(intent, GlobalData.REQUEST_CODE_APPLICATION_PREFERENCES); return true; case R.id.menu_pphelper_install: PhoneProfilesHelper.installPPHelper(this, false); return true; case R.id.menu_pphelper_uninstall: PhoneProfilesHelper.uninstallPPHelper(this); return true; case R.id.menu_export: exportData(); return true; case R.id.menu_import: importData(); return true; case R.id.menu_exit: GlobalData.setApplicationStarted(getApplicationContext(), false); // stop all events getDataWrapper().stopAllEvents(false, false); // zrusenie notifikacie getDataWrapper().getActivateProfileHelper().removeNotification(); SearchCalendarEventsBroadcastReceiver.removeAlarm(getApplicationContext()); WifiScanAlarmBroadcastReceiver.removeAlarm(getApplicationContext(), false); stopService(new Intent(getApplicationContext(), ReceiversService.class)); stopService(new Intent(getApplicationContext(), KeyguardService.class)); getDataWrapper().getDatabaseHandler().addActivityLog(DatabaseHandler.ALTYPE_APPLICATIONEXIT, null, null, null, 0); finish(); return true; default: return super.onOptionsItemSelected(item); } } // fix for bug in LG stock ROM Android <= 4.1 @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_MENU) && (Build.VERSION.SDK_INT <= 16) && (Build.MANUFACTURER.compareTo("LGE") == 0)) { return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_MENU) && (Build.VERSION.SDK_INT <= 16) && (Build.MANUFACTURER.compareTo("LGE") == 0)) { openOptionsMenu(); return true; } return super.onKeyUp(keyCode, event); } // ListView click listener in the navigation drawer private class DrawerItemClickListener implements ListView.OnItemClickListener { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // header is position=0 if (position > 0) selectDrawerItem(position, true, false); } } private void selectDrawerItem(int position, boolean removePreferences, boolean orientationChange) { Fragment fragment = getFragmentManager().findFragmentById(R.id.editor_list_container); if (position == 0) position = 2; if ((position != drawerSelectedItem) || (fragment == null)) { drawerSelectedItem = position; // save into shared preferences SharedPreferences preferences = getSharedPreferences(GlobalData.APPLICATION_PREFS_NAME, Activity.MODE_PRIVATE); Editor editor = preferences.edit(); editor.putInt(SP_EDITOR_DRAWER_SELECTED_ITEM, drawerSelectedItem); editor.commit(); Bundle arguments; switch (drawerSelectedItem) { case 1: profilesFilterType = EditorProfileListFragment.FILTER_TYPE_ALL; fragment = new EditorProfileListFragment(); arguments = new Bundle(); arguments.putInt(EditorProfileListFragment.FILTER_TYPE_ARGUMENT, profilesFilterType); fragment.setArguments(arguments); getFragmentManager().beginTransaction() .replace(R.id.editor_list_container, fragment, "EditorProfileListFragment").commit(); if (removePreferences) onStartProfilePreferences(null, EditorProfileListFragment.EDIT_MODE_EDIT, profilesFilterType); break; case 2: profilesFilterType = EditorProfileListFragment.FILTER_TYPE_SHOW_IN_ACTIVATOR; fragment = new EditorProfileListFragment(); arguments = new Bundle(); arguments.putInt(EditorProfileListFragment.FILTER_TYPE_ARGUMENT, profilesFilterType); fragment.setArguments(arguments); getFragmentManager().beginTransaction() .replace(R.id.editor_list_container, fragment, "EditorProfileListFragment").commit(); if (removePreferences) onStartProfilePreferences(null, EditorProfileListFragment.EDIT_MODE_EDIT, profilesFilterType); break; case 3: profilesFilterType = EditorProfileListFragment.FILTER_TYPE_NO_SHOW_IN_ACTIVATOR; fragment = new EditorProfileListFragment(); arguments = new Bundle(); arguments.putInt(EditorProfileListFragment.FILTER_TYPE_ARGUMENT, profilesFilterType); fragment.setArguments(arguments); getFragmentManager().beginTransaction() .replace(R.id.editor_list_container, fragment, "EditorProfileListFragment").commit(); if (removePreferences) onStartProfilePreferences(null, EditorProfileListFragment.EDIT_MODE_EDIT, profilesFilterType); break; case 4: eventsFilterType = EditorEventListFragment.FILTER_TYPE_ALL; fragment = new EditorEventListFragment(); arguments = new Bundle(); arguments.putInt(EditorEventListFragment.FILTER_TYPE_ARGUMENT, eventsFilterType); arguments.putInt(EditorEventListFragment.ORDER_TYPE_ARGUMENT, eventsOrderType); fragment.setArguments(arguments); getFragmentManager().beginTransaction() .replace(R.id.editor_list_container, fragment, "EditorEventListFragment").commit(); if (removePreferences) onStartEventPreferences(null, EditorEventListFragment.EDIT_MODE_EDIT, eventsFilterType, eventsOrderType); break; case 5: eventsFilterType = EditorEventListFragment.FILTER_TYPE_RUNNING; fragment = new EditorEventListFragment(); arguments = new Bundle(); arguments.putInt(EditorEventListFragment.FILTER_TYPE_ARGUMENT, eventsFilterType); arguments.putInt(EditorEventListFragment.ORDER_TYPE_ARGUMENT, eventsOrderType); fragment.setArguments(arguments); getFragmentManager().beginTransaction() .replace(R.id.editor_list_container, fragment, "EditorEventListFragment").commit(); if (removePreferences) onStartEventPreferences(null, EditorEventListFragment.EDIT_MODE_EDIT, eventsFilterType, eventsOrderType); break; case 6: eventsFilterType = EditorEventListFragment.FILTER_TYPE_PAUSED; fragment = new EditorEventListFragment(); arguments = new Bundle(); arguments.putInt(EditorEventListFragment.FILTER_TYPE_ARGUMENT, eventsFilterType); arguments.putInt(EditorEventListFragment.ORDER_TYPE_ARGUMENT, eventsOrderType); fragment.setArguments(arguments); getFragmentManager().beginTransaction() .replace(R.id.editor_list_container, fragment, "EditorEventListFragment").commit(); if (removePreferences) onStartEventPreferences(null, EditorEventListFragment.EDIT_MODE_EDIT, eventsFilterType, eventsOrderType); break; case 7: eventsFilterType = EditorEventListFragment.FILTER_TYPE_STOPPED; fragment = new EditorEventListFragment(); arguments = new Bundle(); arguments.putInt(EditorEventListFragment.FILTER_TYPE_ARGUMENT, eventsFilterType); arguments.putInt(EditorEventListFragment.ORDER_TYPE_ARGUMENT, eventsOrderType); fragment.setArguments(arguments); getFragmentManager().beginTransaction() .replace(R.id.editor_list_container, fragment, "EditorEventListFragment").commit(); if (removePreferences) onStartEventPreferences(null, EditorEventListFragment.EDIT_MODE_EDIT, eventsFilterType, eventsOrderType); break; } } // header is position=0 drawerListView.setItemChecked(drawerSelectedItem, true); // Get the title and icon followed by the position setTitle(drawerItemsTitle[drawerSelectedItem-1]); //setIcon(drawerItemsIcon[drawerSelectedItem-1]); drawerHeaderFilterImage.setImageResource(drawerItemsIcon[drawerSelectedItem-1]); drawerHeaderFilterTitle.setText(drawerItemsTitle[drawerSelectedItem-1]); // show/hide order if (drawerSelectedItem <= COUNT_DRAWER_PROFILE_ITEMS) { orderLabel.setVisibility(View.GONE); orderSpinner.setVisibility(View.GONE); } else { orderLabel.setVisibility(View.VISIBLE); orderSpinner.setVisibility(View.VISIBLE); } // set filter statusbar title setStatusBarTitle(); // Close drawer if (GlobalData.applicationEditorAutoCloseDrawer && (!orientationChange)) drawerLayout.closeDrawer(drawerRoot); } private void changeEventOrder(int position, boolean orientationChange) { orderSelectedItem = position; // save into shared preferences SharedPreferences preferences = getSharedPreferences(GlobalData.APPLICATION_PREFS_NAME, Activity.MODE_PRIVATE); Editor editor = preferences.edit(); editor.putInt(SP_EDITOR_ORDER_SELECTED_ITEM, orderSelectedItem); editor.commit(); eventsOrderType = EditorEventListFragment.ORDER_TYPE_EVENT_NAME; switch (position) { case 0: eventsOrderType = EditorEventListFragment.ORDER_TYPE_EVENT_NAME; break; case 1: eventsOrderType = EditorEventListFragment.ORDER_TYPE_PROFILE_NAME; break; case 2: eventsOrderType = EditorEventListFragment.ORDER_TYPE_PRIORITY; break; } setStatusBarTitle(); Fragment fragment = getFragmentManager().findFragmentById(R.id.editor_list_container); if ((fragment != null) && (fragment instanceof EditorEventListFragment)) { ((EditorEventListFragment)fragment).changeListOrder(eventsOrderType); } orderSpinner.setSelection(orderSelectedItem); // Close drawer if (GlobalData.applicationEditorAutoCloseDrawer && (!orientationChange)) drawerLayout.closeDrawer(drawerRoot); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == GlobalData.REQUEST_CODE_ACTIVATE_PROFILE) { EditorProfileListFragment fragment = (EditorProfileListFragment)getFragmentManager().findFragmentById(R.id.editor_list_container); if (fragment != null) fragment.doOnActivityResult(requestCode, resultCode, data); } else if (requestCode == GlobalData.REQUEST_CODE_PROFILE_PREFERENCES) { if ((resultCode == RESULT_OK) && (data != null)) { // redraw list fragment after finish ProfilePreferencesFragmentActivity long profile_id = data.getLongExtra(GlobalData.EXTRA_PROFILE_ID, 0); int newProfileMode = data.getIntExtra(GlobalData.EXTRA_NEW_PROFILE_MODE, EditorProfileListFragment.EDIT_MODE_UNDEFINED); if (profile_id > 0) { Profile profile = getDataWrapper().getDatabaseHandler().getProfile(profile_id); // generate bitmaps profile.generateIconBitmap(getBaseContext(), false, 0); profile.generatePreferencesIndicator(getBaseContext(), false, 0); // redraw list fragment , notifications, widgets after finish ProfilePreferencesFragmentActivity onRedrawProfileListFragment(profile, newProfileMode); } else if (profile_id == GlobalData.DEFAULT_PROFILE_ID) { // refresh activity for changes of default profile GUIData.reloadActivity(this, false); } } } else if (requestCode == GlobalData.REQUEST_CODE_EVENT_PREFERENCES) { if ((resultCode == RESULT_OK) && (data != null)) { // redraw list fragment after finish EventPreferencesFragmentActivity long event_id = data.getLongExtra(GlobalData.EXTRA_EVENT_ID, 0L); int newEventMode = data.getIntExtra(GlobalData.EXTRA_NEW_EVENT_MODE, EditorEventListFragment.EDIT_MODE_UNDEFINED); if (event_id > 0) { Event event = getDataWrapper().getDatabaseHandler().getEvent(event_id); // redraw list fragment , notifications, widgets after finish ProfilePreferencesFragmentActivity onRedrawEventListFragment(event, newEventMode); } } } else if (requestCode == GlobalData.REQUEST_CODE_APPLICATION_PREFERENCES) { if (resultCode == RESULT_OK) { boolean restart = data.getBooleanExtra(GlobalData.EXTRA_RESET_EDITOR, false); if (restart) { // refresh activity for special changes GUIData.reloadActivity(this, true); } } } else if (requestCode == GlobalData.REQUEST_CODE_REMOTE_EXPORT) { if (resultCode == RESULT_OK) { doImportData(GUIData.REMOTE_EXPORT_PATH); } } else { // send other activity results into preference fragment if (drawerSelectedItem <= COUNT_DRAWER_PROFILE_ITEMS) { ProfilePreferencesFragment fragment = (ProfilePreferencesFragment)getFragmentManager().findFragmentById(R.id.editor_detail_container); if (fragment != null) fragment.doOnActivityResult(requestCode, resultCode, data); } else { EventPreferencesFragment fragment = (EventPreferencesFragment)getFragmentManager().findFragmentById(R.id.editor_detail_container); if (fragment != null) fragment.doOnActivityResult(requestCode, resultCode, data); } } } @Override public boolean dispatchKeyEvent(KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) { // handle your back button code here if (mTwoPane) { if (drawerSelectedItem <= COUNT_DRAWER_PROFILE_ITEMS) { ProfilePreferencesFragment fragment = (ProfilePreferencesFragment)getFragmentManager().findFragmentById(R.id.editor_detail_container); if ((fragment != null) && (fragment.isActionModeActive())) { fragment.finishActionMode(ProfilePreferencesFragment.BUTTON_CANCEL); return true; // consumes the back key event - ActionMode is not finished } else return super.dispatchKeyEvent(event); } else { EventPreferencesFragment fragment = (EventPreferencesFragment)getFragmentManager().findFragmentById(R.id.editor_detail_container); if ((fragment != null) && (fragment.isActionModeActive())) { fragment.finishActionMode(EventPreferencesFragment.BUTTON_CANCEL); return true; // consumes the back key event - ActionMode is not finished } else return super.dispatchKeyEvent(event); } } else return super.dispatchKeyEvent(event); } return super.dispatchKeyEvent(event); } @Override public void onBackPressed() { if (drawerLayout.isDrawerOpen(drawerRoot)) drawerLayout.closeDrawer(drawerRoot); else super.onBackPressed(); } private void importExportErrorDialog(int importExport) { MaterialDialog.Builder dialogBuilder = new MaterialDialog.Builder(this); if (importExport == 1) { dialogBuilder.title(R.string.import_profiles_alert_title) .content(R.string.import_profiles_alert_error); } else { dialogBuilder.title(R.string.export_profiles_alert_title) .content(R.string.export_profiles_alert_error); } dialogBuilder.positiveText(android.R.string.ok) .disableDefaultFonts(); dialogBuilder.show(); /* AlertDialogWrapper.Builder dialogBuilder = new AlertDialogWrapper.Builder(this); String resString; if (importExport == 1) resString = getResources().getString(R.string.import_profiles_alert_title); else resString = getResources().getString(R.string.export_profiles_alert_title); dialogBuilder.setTitle(resString); if (importExport == 1) resString = getResources().getString(R.string.import_profiles_alert_error); else resString = getResources().getString(R.string.export_profiles_alert_error); dialogBuilder.setMessage(resString + "!"); //dialogBuilder.setIcon(android.R.drawable.ic_dialog_alert); dialogBuilder.setPositiveButton(android.R.string.ok, null); dialogBuilder.show(); */ } @SuppressWarnings({ "unchecked" }) private boolean importApplicationPreferences(File src, int what) { boolean res = false; ObjectInputStream input = null; try { input = new ObjectInputStream(new FileInputStream(src)); Editor prefEdit; if (what == 1) prefEdit = getSharedPreferences(GlobalData.APPLICATION_PREFS_NAME, Activity.MODE_PRIVATE).edit(); else prefEdit = getSharedPreferences(GlobalData.DEFAULT_PROFILE_PREFS_NAME, Activity.MODE_PRIVATE).edit(); prefEdit.clear(); Map<String, ?> entries = (Map<String, ?>) input.readObject(); for (Entry<String, ?> entry : entries.entrySet()) { Object v = entry.getValue(); String key = entry.getKey(); if (v instanceof Boolean) prefEdit.putBoolean(key, ((Boolean) v).booleanValue()); else if (v instanceof Float) prefEdit.putFloat(key, ((Float) v).floatValue()); else if (v instanceof Integer) prefEdit.putInt(key, ((Integer) v).intValue()); else if (v instanceof Long) prefEdit.putLong(key, ((Long) v).longValue()); else if (v instanceof String) prefEdit.putString(key, ((String) v)); if (what == 1) { if (key.equals(GlobalData.PREF_APPLICATION_THEME)) { if (((String)v).equals("light")) prefEdit.putString(key, "material"); } } } prefEdit.commit(); res = true; } catch (FileNotFoundException e) { // no error, this is OK //e.printStackTrace(); res = true; } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); }finally { try { if (input != null) { input.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return res; } private void doImportData(String applicationDataPath) { final Activity activity = this; final String _applicationDataPath = applicationDataPath; class ImportAsyncTask extends AsyncTask<Void, Integer, Integer> { private MaterialDialog dialog; private DataWrapper dataWrapper; ImportAsyncTask() { this.dialog = new MaterialDialog.Builder(activity) .content(R.string.import_profiles_alert_title) .disableDefaultFonts() .progress(true, 0) .build(); this.dataWrapper = getDataWrapper(); } @Override protected void onPreExecute() { super.onPreExecute(); lockScreenOrientation(); this.dialog.setCancelable(false); this.dialog.show(); Fragment fragment = getFragmentManager().findFragmentById(R.id.editor_list_container); if (fragment != null) { if (fragment instanceof EditorProfileListFragment) ((EditorProfileListFragment)fragment).removeAdapter(); else ((EditorEventListFragment)fragment).removeAdapter(); } // check root, this set GlobalData.rooted for doInBackgroud() GlobalData.isRooted(false); } @Override protected Integer doInBackground(Void... params) { this.dataWrapper.stopAllEvents(true, false); int ret = this.dataWrapper.getDatabaseHandler().importDB(_applicationDataPath); if (ret == 1) { // check for hardware capability and update data ret = this.dataWrapper.getDatabaseHandler().updateForHardware(getApplicationContext()); } if (ret == 1) { File sd = Environment.getExternalStorageDirectory(); File exportFile = new File(sd, _applicationDataPath + "/" + GUIData.EXPORT_APP_PREF_FILENAME); if (!importApplicationPreferences(exportFile, 1)) ret = 0; else { exportFile = new File(sd, _applicationDataPath + "/" + GUIData.EXPORT_DEF_PROFILE_PREF_FILENAME); if (!importApplicationPreferences(exportFile, 2)) ret = 0; } } return ret; } @Override protected void onPostExecute(Integer result) { super.onPostExecute(result); if (this.dialog.isShowing()) this.dialog.dismiss(); unlockScreenOrientation(); if (result == 1) { GlobalData.loadPreferences(getApplicationContext()); dataWrapper.invalidateProfileList(); dataWrapper.invalidateEventList(); dataWrapper.updateNotificationAndWidgets(null, ""); //dataWrapper.getActivateProfileHelper().showNotification(null, ""); //dataWrapper.getActivateProfileHelper().updateWidget(); GlobalData.setEventsBlocked(getApplicationContext(), false); dataWrapper.getDatabaseHandler().unblockAllEvents(); GlobalData.setForceRunEventRunning(getApplicationContext(), false); SharedPreferences preferences = getSharedPreferences(GlobalData.APPLICATION_PREFS_NAME, Activity.MODE_PRIVATE); Editor editor = preferences.edit(); editor.putInt(SP_EDITOR_DRAWER_SELECTED_ITEM, 1); editor.putInt(SP_EDITOR_ORDER_SELECTED_ITEM, 0); editor.commit(); // restart events // startneme eventy if (GlobalData.getGlobalEventsRuning(getApplicationContext())) { /* Intent intent = new Intent(); intent.setAction(RestartEventsBroadcastReceiver.INTENT_RESTART_EVENTS); getBaseContext().sendBroadcast(intent); */ dataWrapper.restartEventsWithDelay(); } dataWrapper.getDatabaseHandler().addActivityLog(DatabaseHandler.ALTYPE_DATAIMPORT, null, null, null, 0); // toast notification Toast msg = Toast.makeText(getApplicationContext(), getResources().getString(R.string.toast_import_ok), Toast.LENGTH_SHORT); msg.show(); // refresh activity GUIData.reloadActivity(activity, true); } else { importExportErrorDialog(1); } } private void lockScreenOrientation() { int currentOrientation = activity.getResources().getConfiguration().orientation; if (currentOrientation == Configuration.ORIENTATION_PORTRAIT) { activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } else { activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } } private void unlockScreenOrientation() { activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR); } } new ImportAsyncTask().execute(); } private void importDataAlert(boolean remoteExport) { final boolean _remoteExport = remoteExport; MaterialDialog.Builder dialogBuilder = new MaterialDialog.Builder(this); if (remoteExport) { dialogBuilder.title(R.string.import_profiles_from_phoneprofiles_alert_title2); dialogBuilder.content(R.string.import_profiles_alert_message); } else { dialogBuilder.title(R.string.import_profiles_alert_title); dialogBuilder.content(R.string.import_profiles_alert_message); } dialogBuilder.positiveText(R.string.alert_button_yes) .negativeText(R.string.alert_button_no) .disableDefaultFonts(); dialogBuilder.callback(new MaterialDialog.ButtonCallback() { @Override public void onPositive(MaterialDialog dialog) { if (_remoteExport) { // start RemoteExportDataActivity Intent intent = new Intent("phoneprofiles.intent.action.EXPORTDATA"); final PackageManager packageManager = getPackageManager(); List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); if (list.size() > 0) startActivityForResult(intent, GlobalData.REQUEST_CODE_REMOTE_EXPORT); else importExportErrorDialog(1); } else doImportData(GlobalData.EXPORT_PATH); } }); dialogBuilder.show(); /* AlertDialogWrapper.Builder dialogBuilder2 = new AlertDialogWrapper.Builder(this); if (remoteExport) { dialogBuilder2.setTitle(getResources().getString(R.string.import_profiles_from_phoneprofiles_alert_title2)); dialogBuilder2.setMessage(getResources().getString(R.string.import_profiles_alert_message)); //dialogBuilder2.setIcon(android.R.drawable.ic_dialog_alert); } else { dialogBuilder2.setTitle(getResources().getString(R.string.import_profiles_alert_title)); dialogBuilder2.setMessage(getResources().getString(R.string.import_profiles_alert_message)); //dialogBuilder2.setIcon(android.R.drawable.ic_dialog_alert); } dialogBuilder2.setPositiveButton(R.string.alert_button_yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (_remoteExport) { // start RemoteExportDataActivity Intent intent = new Intent("phoneprofiles.intent.action.EXPORTDATA"); final PackageManager packageManager = getPackageManager(); List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); if (list.size() > 0) startActivityForResult(intent, GlobalData.REQUEST_CODE_REMOTE_EXPORT); else importExportErrorDialog(1); } else doImportData(GlobalData.EXPORT_PATH); } }); dialogBuilder2.setNegativeButton(R.string.alert_button_no, null); dialogBuilder2.show(); */ } private void importData() { // test whether the PhoneProfile is installed PackageManager packageManager = getApplicationContext().getPackageManager(); Intent phoneProfiles = packageManager.getLaunchIntentForPackage("sk.henrichg.phoneprofiles"); if (phoneProfiles != null) { // PhoneProfiles is istalled MaterialDialog.Builder dialogBuilder = new MaterialDialog.Builder(this) .title(R.string.import_profiles_from_phoneprofiles_alert_title) .content(R.string.import_profiles_from_phoneprofiles_alert_message) .positiveText(R.string.alert_button_yes) .negativeText(R.string.alert_button_no) .disableDefaultFonts(); dialogBuilder.callback(new MaterialDialog.ButtonCallback() { @Override public void onPositive(MaterialDialog dialog) { importDataAlert(true); } @Override public void onNegative(MaterialDialog dialog) { importDataAlert(false); } }); dialogBuilder.show(); /* AlertDialogWrapper.Builder dialogBuilder = new AlertDialogWrapper.Builder(this); dialogBuilder.setTitle(getResources().getString(R.string.import_profiles_from_phoneprofiles_alert_title)); dialogBuilder.setMessage(getResources().getString(R.string.import_profiles_from_phoneprofiles_alert_message)); //dialogBuilder.setIcon(android.R.drawable.ic_dialog_alert); dialogBuilder.setPositiveButton(R.string.alert_button_yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { importDataAlert(true); } }); dialogBuilder.setNegativeButton(R.string.alert_button_no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { importDataAlert(false); } }); dialogBuilder.show(); */ } else importDataAlert(false); } private boolean exportApplicationPreferences(File dst, int what) { boolean res = false; ObjectOutputStream output = null; try { output = new ObjectOutputStream(new FileOutputStream(dst)); SharedPreferences pref; if (what == 1) pref = getSharedPreferences(GlobalData.APPLICATION_PREFS_NAME, Activity.MODE_PRIVATE); else pref = getSharedPreferences(GlobalData.DEFAULT_PROFILE_PREFS_NAME, Activity.MODE_PRIVATE); output.writeObject(pref.getAll()); res = true; } catch (FileNotFoundException e) { // this is OK //e.printStackTrace(); res = true; } catch (IOException e) { e.printStackTrace(); }finally { try { if (output != null) { output.flush(); output.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return res; } private void exportData() { final Activity activity = this; MaterialDialog.Builder dialogBuilder = new MaterialDialog.Builder(this) .title(R.string.export_profiles_alert_title) .content(R.string.export_profiles_alert_message) .positiveText(R.string.alert_button_yes) .negativeText(R.string.alert_button_no) .disableDefaultFonts(); dialogBuilder.callback(new MaterialDialog.ButtonCallback() { @Override public void onPositive(MaterialDialog dialog) { class ExportAsyncTask extends AsyncTask<Void, Integer, Integer> { private MaterialDialog dialog; private DataWrapper dataWrapper; ExportAsyncTask() { this.dialog = new MaterialDialog.Builder(activity) .content(R.string.export_profiles_alert_title) .disableDefaultFonts() .progress(true, 0) .build(); this.dataWrapper = getDataWrapper(); } @Override protected void onPreExecute() { super.onPreExecute(); lockScreenOrientation(); this.dialog.setCancelable(false); this.dialog.show(); } @Override protected Integer doInBackground(Void... params) { int ret = dataWrapper.getDatabaseHandler().exportDB(); if (ret == 1) { File sd = Environment.getExternalStorageDirectory(); File exportFile = new File(sd, GlobalData.EXPORT_PATH + "/" + GUIData.EXPORT_APP_PREF_FILENAME); if (!exportApplicationPreferences(exportFile, 1)) ret = 0; else { exportFile = new File(sd, GlobalData.EXPORT_PATH + "/" + GUIData.EXPORT_DEF_PROFILE_PREF_FILENAME); if (!exportApplicationPreferences(exportFile, 2)) ret = 0; } } return ret; } @Override protected void onPostExecute(Integer result) { super.onPostExecute(result); if (dialog.isShowing()) dialog.dismiss(); unlockScreenOrientation(); if (result == 1) { // toast notification Toast msg = Toast.makeText(getApplicationContext(), getResources().getString(R.string.toast_export_ok), Toast.LENGTH_SHORT); msg.show(); } else { importExportErrorDialog(2); } } private void lockScreenOrientation() { int currentOrientation = activity.getResources().getConfiguration().orientation; if (currentOrientation == Configuration.ORIENTATION_PORTRAIT) { activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } else { activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } } private void unlockScreenOrientation() { activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR); } } new ExportAsyncTask().execute(); } }); dialogBuilder.show(); /* AlertDialogWrapper.Builder dialogBuilder = new AlertDialogWrapper.Builder(this); dialogBuilder.setTitle(getResources().getString(R.string.export_profiles_alert_title)); dialogBuilder.setMessage(getResources().getString(R.string.export_profiles_alert_message)); //dialogBuilder.setIcon(android.R.drawable.ic_dialog_alert); final Activity activity = this; dialogBuilder.setPositiveButton(R.string.alert_button_yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { class ExportAsyncTask extends AsyncTask<Void, Integer, Integer> { private MaterialDialog dialog; private DataWrapper dataWrapper; ExportAsyncTask() { this.dialog = new MaterialDialog.Builder(activity) .content(R.string.export_profiles_alert_title) .disableDefaultFonts() .progress(true, 0) .build(); this.dataWrapper = getDataWrapper(); } @Override protected void onPreExecute() { super.onPreExecute(); lockScreenOrientation(); this.dialog.setCancelable(false); this.dialog.show(); } @Override protected Integer doInBackground(Void... params) { int ret = dataWrapper.getDatabaseHandler().exportDB(); if (ret == 1) { File sd = Environment.getExternalStorageDirectory(); File exportFile = new File(sd, GlobalData.EXPORT_PATH + "/" + GUIData.EXPORT_APP_PREF_FILENAME); if (!exportApplicationPreferences(exportFile, 1)) ret = 0; else { exportFile = new File(sd, GlobalData.EXPORT_PATH + "/" + GUIData.EXPORT_DEF_PROFILE_PREF_FILENAME); if (!exportApplicationPreferences(exportFile, 2)) ret = 0; } } return ret; } @Override protected void onPostExecute(Integer result) { super.onPostExecute(result); if (dialog.isShowing()) dialog.dismiss(); unlockScreenOrientation(); if (result == 1) { // toast notification Toast msg = Toast.makeText(getApplicationContext(), getResources().getString(R.string.toast_export_ok), Toast.LENGTH_SHORT); msg.show(); } else { importExportErrorDialog(2); } } private void lockScreenOrientation() { int currentOrientation = activity.getResources().getConfiguration().orientation; if (currentOrientation == Configuration.ORIENTATION_PORTRAIT) { activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } else { activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } } private void unlockScreenOrientation() { activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR); } } new ExportAsyncTask().execute(); } }); dialogBuilder.setNegativeButton(R.string.alert_button_no, null); dialogBuilder.show(); */ } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. drawerToggle.syncState(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); savedInstanceStateChanged = true; if (mTwoPane) { SharedPreferences preferences = getSharedPreferences(GlobalData.APPLICATION_PREFS_NAME, Activity.MODE_PRIVATE); if (drawerSelectedItem <= COUNT_DRAWER_PROFILE_ITEMS) { if ((editModeProfile != EditorProfileListFragment.EDIT_MODE_INSERT) && (editModeProfile != EditorProfileListFragment.EDIT_MODE_DUPLICATE)) { FragmentManager fragmentManager = getFragmentManager(); Fragment fragment = fragmentManager.findFragmentByTag("ProfilePreferencesFragment"); if (fragment != null) { Editor editor = preferences.edit(); editor.putInt(SP_RESET_PREFERENCES_FRAGMENT, RESET_PREFERENCE_FRAGMENT_RESET_PROFILE); editor.putLong(SP_RESET_PREFERENCES_FRAGMENT_DATA_ID, ((ProfilePreferencesFragment)fragment).profile_id); editor.putInt(SP_RESET_PREFERENCES_FRAGMENT_EDIT_MODE, editModeProfile); editor.commit(); } } else { Editor editor = preferences.edit(); editor.putInt(SP_RESET_PREFERENCES_FRAGMENT, RESET_PREFERENCE_FRAGMENT_REMOVE); editor.putLong(SP_RESET_PREFERENCES_FRAGMENT_DATA_ID, 0); editor.putInt(SP_RESET_PREFERENCES_FRAGMENT_EDIT_MODE, editModeProfile); editor.commit(); } } else { if ((editModeEvent != EditorProfileListFragment.EDIT_MODE_INSERT) && (editModeEvent != EditorProfileListFragment.EDIT_MODE_DUPLICATE)) { FragmentManager fragmentManager = getFragmentManager(); Fragment fragment = fragmentManager.findFragmentByTag("EventPreferencesFragment"); if (fragment != null) { Editor editor = preferences.edit(); editor.putInt(SP_RESET_PREFERENCES_FRAGMENT, RESET_PREFERENCE_FRAGMENT_RESET_EVENT); editor.putLong(SP_RESET_PREFERENCES_FRAGMENT_DATA_ID, ((EventPreferencesFragment)fragment).event_id); editor.putInt(SP_RESET_PREFERENCES_FRAGMENT_EDIT_MODE, editModeEvent); editor.commit(); } } else { Editor editor = preferences.edit(); editor.putInt(SP_RESET_PREFERENCES_FRAGMENT, RESET_PREFERENCE_FRAGMENT_REMOVE); editor.putLong(SP_RESET_PREFERENCES_FRAGMENT_DATA_ID, 0); editor.putInt(SP_RESET_PREFERENCES_FRAGMENT_EDIT_MODE, editModeEvent); editor.commit(); } } } } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); /* // activity will restarted // Pass any configuration change to the drawer toggles drawerToggle.onConfigurationChanged(newConfig); */ getBaseContext().getResources().updateConfiguration(newConfig, getBaseContext().getResources().getDisplayMetrics()); GUIData.reloadActivity(this, false); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); /* drawerSelectedItem = savedInstanceState.getInt("editor_drawer_selected_item", -1); selectDrawerItem(drawerSelectedItem, false); orderSelectedItem = savedInstanceState.getInt("editor_order_selected_item", -1); changeEventOrder(orderSelectedItem); */ } @Override public void setTitle(CharSequence title) { getSupportActionBar().setTitle(title); } /* public void setIcon(int iconRes) { getSupportActionBar().setIcon(iconRes); } */ private void setStatusBarTitle() { // set filter statusbar title String text = ""; if (drawerSelectedItem <= COUNT_DRAWER_PROFILE_ITEMS) { text = drawerItemsSubtitle[drawerSelectedItem-1]; } else { String[] orderItems = getResources().getStringArray(R.array.drawerOrderEvents); text = drawerItemsSubtitle[drawerSelectedItem-1] + "; " + orderItems[orderSelectedItem]; } filterStatusbarTitle.setText(text); drawerHeaderFilterSubtitle.setText(text); } public void onStartProfilePreferences(Profile profile, int editMode, int filterType) { editModeProfile = editMode; onFinishProfilePreferencesActionMode(); if (mTwoPane) { // In two-pane mode, show the detail view in this activity by // adding or replacing the detail fragment using a // fragment transaction. if ((profile != null) || (editMode == EditorProfileListFragment.EDIT_MODE_INSERT) || (editMode == EditorProfileListFragment.EDIT_MODE_DUPLICATE)) { Bundle arguments = new Bundle(); if (editMode == EditorProfileListFragment.EDIT_MODE_INSERT) arguments.putLong(GlobalData.EXTRA_PROFILE_ID, 0); else arguments.putLong(GlobalData.EXTRA_PROFILE_ID, profile._id); arguments.putInt(GlobalData.EXTRA_NEW_PROFILE_MODE, editMode); arguments.putInt(GlobalData.EXTRA_PREFERENCES_STARTUP_SOURCE, GlobalData.PREFERENCES_STARTUP_SOURCE_FRAGMENT); ProfilePreferencesFragment fragment = new ProfilePreferencesFragment(); fragment.setArguments(arguments); getFragmentManager().beginTransaction() .replace(R.id.editor_detail_container, fragment, "ProfilePreferencesFragment").commit(); } else { Fragment fragment = getFragmentManager().findFragmentById(R.id.editor_detail_container); if (fragment != null) { getFragmentManager().beginTransaction() .remove(fragment).commit(); } } } else { // In single-pane mode, simply start the profile preferences activity // for the profile position. if (((profile != null) || (editMode == EditorProfileListFragment.EDIT_MODE_INSERT) || (editMode == EditorProfileListFragment.EDIT_MODE_DUPLICATE)) && (editMode != EditorProfileListFragment.EDIT_MODE_DELETE)) { Intent intent = new Intent(getBaseContext(), ProfilePreferencesFragmentActivity.class); if (editMode == EditorProfileListFragment.EDIT_MODE_INSERT) intent.putExtra(GlobalData.EXTRA_PROFILE_ID, 0); else intent.putExtra(GlobalData.EXTRA_PROFILE_ID, profile._id); intent.putExtra(GlobalData.EXTRA_NEW_PROFILE_MODE, editMode); startActivityForResult(intent, GlobalData.REQUEST_CODE_PROFILE_PREFERENCES); } } } public void onRestartProfilePreferences(Profile profile, int newProfileMode) { if (mTwoPane) { if ((newProfileMode != EditorProfileListFragment.EDIT_MODE_INSERT) && (newProfileMode != EditorProfileListFragment.EDIT_MODE_DUPLICATE)) { // restart profile preferences fragmentu Bundle arguments = new Bundle(); arguments.putLong(GlobalData.EXTRA_PROFILE_ID, profile._id); arguments.putInt(GlobalData.EXTRA_NEW_PROFILE_MODE, editModeProfile); arguments.putInt(GlobalData.EXTRA_PREFERENCES_STARTUP_SOURCE, GlobalData.PREFERENCES_STARTUP_SOURCE_FRAGMENT); ProfilePreferencesFragment fragment = new ProfilePreferencesFragment(); fragment.setArguments(arguments); getFragmentManager().beginTransaction() .replace(R.id.editor_detail_container, fragment, "ProfilePreferencesFragment").commit(); } else { Fragment fragment = getFragmentManager().findFragmentById(R.id.editor_detail_container); if (fragment != null) { getFragmentManager().beginTransaction() .remove(fragment).commit(); } } } else { SharedPreferences preferences = getSharedPreferences(GlobalData.APPLICATION_PREFS_NAME, Activity.MODE_PRIVATE); if ((newProfileMode != EditorProfileListFragment.EDIT_MODE_INSERT) && (newProfileMode != EditorProfileListFragment.EDIT_MODE_DUPLICATE)) { Editor editor = preferences.edit(); editor.putInt(SP_RESET_PREFERENCES_FRAGMENT, RESET_PREFERENCE_FRAGMENT_RESET_PROFILE); editor.putLong(SP_RESET_PREFERENCES_FRAGMENT_DATA_ID, profile._id); editor.putInt(SP_RESET_PREFERENCES_FRAGMENT_EDIT_MODE, editModeProfile); editor.commit(); } else { Editor editor = preferences.edit(); editor.putInt(SP_RESET_PREFERENCES_FRAGMENT, RESET_PREFERENCE_FRAGMENT_REMOVE); editor.putLong(SP_RESET_PREFERENCES_FRAGMENT_DATA_ID, profile._id); editor.putInt(SP_RESET_PREFERENCES_FRAGMENT_EDIT_MODE, editModeProfile); editor.commit(); } } } public void onRedrawProfileListFragment(Profile profile, int newProfileMode) { // redraw headeru list fragmentu, notifikacie a widgetov EditorProfileListFragment fragment = (EditorProfileListFragment)getFragmentManager().findFragmentById(R.id.editor_list_container); if (fragment != null) { // update profile, this rewrite profile in profileList fragment.dataWrapper.updateProfile(profile); boolean newProfile = ((newProfileMode == EditorProfileListFragment.EDIT_MODE_INSERT) || (newProfileMode == EditorProfileListFragment.EDIT_MODE_DUPLICATE)); fragment.updateListView(profile, newProfile); Profile activeProfile = fragment.dataWrapper.getActivatedProfile(); fragment.updateHeader(activeProfile); fragment.dataWrapper.getActivateProfileHelper().showNotification(activeProfile, ""); fragment.dataWrapper.getActivateProfileHelper().updateWidget(); } onRestartProfilePreferences(profile, newProfileMode); } public void onFinishProfilePreferencesActionMode() { //if (mTwoPane) { Fragment fragment = getFragmentManager().findFragmentById(R.id.editor_detail_container); if (fragment != null) { if (fragment instanceof ProfilePreferencesFragment) { ((ProfilePreferencesFragment)fragment).finishActionMode(EventPreferencesFragment.BUTTON_CANCEL); } else { ((EventPreferencesFragment)fragment).finishActionMode(EventPreferencesFragment.BUTTON_CANCEL); } } } public void onPreferenceAttached(PreferenceScreen root, int xmlId) { return; } public void onFinishEventPreferencesActionMode() { //if (mTwoPane) { Fragment fragment = getFragmentManager().findFragmentById(R.id.editor_detail_container); if (fragment != null) { if (fragment instanceof ProfilePreferencesFragment) ((ProfilePreferencesFragment)fragment).finishActionMode(EventPreferencesFragment.BUTTON_CANCEL); else ((EventPreferencesFragment)fragment).finishActionMode(EventPreferencesFragment.BUTTON_CANCEL); } } public void onStartEventPreferences(Event event, int editMode, int filterType, int orderType) { editModeEvent = editMode; if (mTwoPane) { // In two-pane mode, show the detail view in this activity by // adding or replacing the detail fragment using a // fragment transaction. onFinishEventPreferencesActionMode(); if ((event != null) || (editMode == EditorEventListFragment.EDIT_MODE_INSERT) || (editMode == EditorEventListFragment.EDIT_MODE_DUPLICATE)) { Bundle arguments = new Bundle(); if (editMode == EditorEventListFragment.EDIT_MODE_INSERT) arguments.putLong(GlobalData.EXTRA_EVENT_ID, 0L); else arguments.putLong(GlobalData.EXTRA_EVENT_ID, event._id); arguments.putInt(GlobalData.EXTRA_NEW_EVENT_MODE, editMode); arguments.putInt(GlobalData.EXTRA_PREFERENCES_STARTUP_SOURCE, GlobalData.PREFERENCES_STARTUP_SOURCE_FRAGMENT); EventPreferencesFragment fragment = new EventPreferencesFragment(); fragment.setArguments(arguments); getFragmentManager().beginTransaction() .replace(R.id.editor_detail_container, fragment, "EventPreferencesFragment").commit(); } else { Fragment fragment = getFragmentManager().findFragmentById(R.id.editor_detail_container); if (fragment != null) { getFragmentManager().beginTransaction() .remove(fragment).commit(); } } } else { // In single-pane mode, simply start the profile preferences activity // for the event id. if (((event != null) || (editMode == EditorEventListFragment.EDIT_MODE_INSERT) || (editMode == EditorEventListFragment.EDIT_MODE_DUPLICATE)) && (editMode != EditorEventListFragment.EDIT_MODE_DELETE)) { Intent intent = new Intent(getBaseContext(), EventPreferencesFragmentActivity.class); if (editMode == EditorEventListFragment.EDIT_MODE_INSERT) intent.putExtra(GlobalData.EXTRA_EVENT_ID, 0L); else intent.putExtra(GlobalData.EXTRA_EVENT_ID, event._id); intent.putExtra(GlobalData.EXTRA_NEW_EVENT_MODE, editMode); startActivityForResult(intent, GlobalData.REQUEST_CODE_EVENT_PREFERENCES); } } } public void onRedrawEventListFragment(Event event, int newEventMode) { // redraw headeru list fragmentu, notifikacie a widgetov EditorEventListFragment fragment = (EditorEventListFragment)getFragmentManager().findFragmentById(R.id.editor_list_container); if (fragment != null) { // update event, this rewrite event in eventList fragment.dataWrapper.updateEvent(event); boolean newEvent = ((newEventMode == EditorEventListFragment.EDIT_MODE_INSERT) || (newEventMode == EditorEventListFragment.EDIT_MODE_DUPLICATE)); fragment.updateListView(event, newEvent); } onRestartEventPreferences(event, newEventMode); } public void onRestartEventPreferences(Event event, int newEventMode) { if (mTwoPane) { if ((newEventMode != EditorEventListFragment.EDIT_MODE_INSERT) && (newEventMode != EditorEventListFragment.EDIT_MODE_DUPLICATE)) { // restart event preferences fragmentu Bundle arguments = new Bundle(); arguments.putLong(GlobalData.EXTRA_EVENT_ID, event._id); arguments.putInt(GlobalData.EXTRA_NEW_EVENT_MODE, editModeEvent); arguments.putInt(GlobalData.EXTRA_PREFERENCES_STARTUP_SOURCE, GlobalData.PREFERENCES_STARTUP_SOURCE_FRAGMENT); EventPreferencesFragment fragment = new EventPreferencesFragment(); fragment.setArguments(arguments); getFragmentManager().beginTransaction() .replace(R.id.editor_detail_container, fragment, "EventPreferencesFragment").commit(); } else { Fragment fragment = getFragmentManager().findFragmentById(R.id.editor_detail_container); if (fragment != null) { getFragmentManager().beginTransaction() .remove(fragment).commit(); } } } else { SharedPreferences preferences = getSharedPreferences(GlobalData.APPLICATION_PREFS_NAME, Activity.MODE_PRIVATE); if ((newEventMode != EditorEventListFragment.EDIT_MODE_INSERT) && (newEventMode != EditorEventListFragment.EDIT_MODE_DUPLICATE)) { Editor editor = preferences.edit(); editor.putInt(SP_RESET_PREFERENCES_FRAGMENT, RESET_PREFERENCE_FRAGMENT_RESET_EVENT); editor.putLong(SP_RESET_PREFERENCES_FRAGMENT_DATA_ID, event._id); editor.putInt(SP_RESET_PREFERENCES_FRAGMENT_EDIT_MODE, editModeEvent); editor.commit(); } else { Editor editor = preferences.edit(); editor.putInt(SP_RESET_PREFERENCES_FRAGMENT, RESET_PREFERENCE_FRAGMENT_REMOVE); editor.putLong(SP_RESET_PREFERENCES_FRAGMENT_DATA_ID, event._id); editor.putInt(SP_RESET_PREFERENCES_FRAGMENT_EDIT_MODE, editModeEvent); editor.commit(); } } } @Override public void onShowActionModeInEventPreferences() { Fragment fragment = getFragmentManager().findFragmentById(R.id.editor_list_container); if (fragment != null) { if (fragment instanceof EditorProfileListFragment) { ((EditorProfileListFragment)fragment).fabButton.show(); } else { ((EditorEventListFragment)fragment).fabButton.show(); } } drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); } @Override public void onShowActionModeInProfilePreferences() { Fragment fragment = getFragmentManager().findFragmentById(R.id.editor_list_container); if (fragment != null) { if (fragment instanceof EditorProfileListFragment) { ((EditorProfileListFragment)fragment).fabButton.hide(); } else { ((EditorEventListFragment)fragment).fabButton.hide(); } } drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); } @Override public void onHideActionModeInEventPreferences() { Fragment fragment = getFragmentManager().findFragmentById(R.id.editor_list_container); if (fragment != null) { if (fragment instanceof EditorProfileListFragment) { ((EditorProfileListFragment)fragment).fabButton.show(); } else { ((EditorEventListFragment)fragment).fabButton.show(); } } drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED); } @Override public void onHideActionModeInProfilePreferences() { Fragment fragment = getFragmentManager().findFragmentById(R.id.editor_list_container); if (fragment != null) { if (fragment instanceof EditorProfileListFragment) { ((EditorProfileListFragment)fragment).fabButton.show(); } else { ((EditorEventListFragment)fragment).fabButton.show(); } } drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED); } public static ApplicationsCache getApplicationsCache() { return applicationsCache; } public static void createApplicationsCache() { if ((!savedInstanceStateChanged) || (applicationsCache == null)) { if (applicationsCache != null) applicationsCache.clearCache(true); applicationsCache = new ApplicationsCache(); } } public static void createContactsCache() { if ((!savedInstanceStateChanged) || (contactsCache == null)) { if (contactsCache != null) contactsCache.clearCache(true); contactsCache = new ContactsCache(); } } public static ContactsCache getContactsCache() { return contactsCache; } public static void createContactGroupsCache() { if ((!savedInstanceStateChanged) || (contactGroupsCache == null)) { if (contactGroupsCache != null) contactGroupsCache.clearCache(true); contactGroupsCache = new ContactGroupsCache(); } } public static ContactGroupsCache getContactGroupsCache() { return contactGroupsCache; } private DataWrapper getDataWrapper() { Fragment fragment = getFragmentManager().findFragmentById(R.id.editor_list_container); if (fragment != null) { if (fragment instanceof EditorProfileListFragment) return ((EditorProfileListFragment)fragment).dataWrapper; else return ((EditorEventListFragment)fragment).dataWrapper; } else return null; } public void setEventsRunStopIndicator() { if (GlobalData.getGlobalEventsRuning(getApplicationContext())) { if (GlobalData.getEventsBlocked(getApplicationContext())) eventsRunStopIndicator.setImageResource(R.drawable.ic_run_events_indicator_manual_activation); else eventsRunStopIndicator.setImageResource(R.drawable.ic_run_events_indicator_running); } else eventsRunStopIndicator.setImageResource(R.drawable.ic_run_events_indicator_stoppped); } public void refreshGUI() { setEventsRunStopIndicator(); Fragment fragment = getFragmentManager().findFragmentById(R.id.editor_list_container); if (fragment != null) { if (fragment instanceof EditorProfileListFragment) ((EditorProfileListFragment)fragment).refreshGUI(); else ((EditorEventListFragment)fragment).refreshGUI(); } } /* private void setWindowContentOverlayCompat() { if (android.os.Build.VERSION.SDK_INT >= 20) { // Get the content view View contentView = findViewById(android.R.id.content); // Make sure it's a valid instance of a FrameLayout if (contentView instanceof FrameLayout) { TypedValue tv = new TypedValue(); // Get the windowContentOverlay value of the current theme if (getTheme().resolveAttribute( android.R.attr.windowContentOverlay, tv, true)) { // If it's a valid resource, set it as the foreground drawable // for the content view if (tv.resourceId != 0) { ((FrameLayout) contentView).setForeground( getResources().getDrawable(tv.resourceId)); } } } } } */ }
package com.intellij.codeInsight.documentation; import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.codeInsight.hint.HintManagerImpl; import com.intellij.codeInsight.lookup.LookupEx; import com.intellij.codeInsight.lookup.LookupManager; import com.intellij.icons.AllIcons; import com.intellij.ide.DataManager; import com.intellij.ide.actions.BaseNavigateToSourceAction; import com.intellij.ide.actions.ExternalJavaDocAction; import com.intellij.ide.actions.WindowAction; import com.intellij.ide.util.PropertiesComponent; import com.intellij.lang.documentation.CompositeDocumentationProvider; import com.intellij.lang.documentation.DocumentationMarkup; import com.intellij.lang.documentation.DocumentationProvider; import com.intellij.lang.documentation.ExternalDocumentationHandler; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.AnActionListener; import com.intellij.openapi.actionSystem.impl.ActionButton; import com.intellij.openapi.actionSystem.impl.ActionManagerImpl; import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl; import com.intellij.openapi.actionSystem.impl.MenuItemPresentationFactory; import com.intellij.openapi.application.ApplicationBundle; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.colors.ColorKey; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.colors.EditorColorsUtil; import com.intellij.openapi.editor.ex.EditorSettingsExternalizable; import com.intellij.openapi.editor.ex.util.EditorUtil; import com.intellij.openapi.keymap.KeymapUtil; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.module.ModuleType; import com.intellij.openapi.module.ModuleTypeManager; import com.intellij.openapi.options.FontSize; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.*; import com.intellij.openapi.ui.popup.JBPopup; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.ui.popup.util.PopupUtil; import com.intellij.openapi.util.DimensionService; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.openapi.wm.ToolWindowId; import com.intellij.openapi.wm.ex.ToolWindowManagerEx; import com.intellij.openapi.wm.ex.WindowManagerEx; import com.intellij.pom.Navigatable; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.SmartPointerManager; import com.intellij.psi.SmartPsiElementPointer; import com.intellij.psi.util.PsiModificationTracker; import com.intellij.reference.SoftReference; import com.intellij.ui.*; import com.intellij.ui.awt.RelativePoint; import com.intellij.ui.components.JBLayeredPane; import com.intellij.ui.components.JBScrollPane; import com.intellij.ui.popup.AbstractPopup; import com.intellij.ui.popup.PopupPositionManager; import com.intellij.ui.scale.JBUIScale; import com.intellij.ui.scale.ScaleContext; import com.intellij.util.ArrayUtilRt; import com.intellij.util.ImageLoader; import com.intellij.util.Url; import com.intellij.util.Urls; import com.intellij.util.ui.*; import com.intellij.util.ui.accessibility.ScreenReader; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.ide.BuiltInServerManager; import javax.swing.*; import javax.swing.border.Border; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.swing.plaf.TextUI; import javax.swing.text.*; import javax.swing.text.html.HTML; import javax.swing.text.html.HTMLDocument; import javax.swing.text.html.HTMLEditorKit; import javax.swing.text.html.ImageView; import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; import java.awt.image.RenderedImage; import java.awt.image.renderable.RenderContext; import java.awt.image.renderable.RenderableImage; import java.awt.image.renderable.RenderableImageProducer; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.List; import java.util.*; public class DocumentationComponent extends JPanel implements Disposable, DataProvider, WidthBasedLayout { private static final Logger LOG = Logger.getInstance(DocumentationComponent.class); private static final String DOCUMENTATION_TOPIC_ID = "reference.toolWindows.Documentation"; private static final Color DOCUMENTATION_COLOR = new JBColor(new Color(0xf7f7f7), new Color(0x46484a)); private static final JBColor BORDER_COLOR = new JBColor(new Color(0xadadad), new Color(0x616366)); public static final ColorKey COLOR_KEY = ColorKey.createColorKey("DOCUMENTATION_COLOR", DOCUMENTATION_COLOR); public static final Color SECTION_COLOR = Gray.get(0x90); private static final Highlighter.HighlightPainter LINK_HIGHLIGHTER = new LinkHighlighter(); private static final int PREFERRED_HEIGHT_MAX_EM = 10; private static final JBDimension MAX_DEFAULT = new JBDimension(650, 500); private static final JBDimension MIN_DEFAULT = new JBDimension(300, Registry.is("editor.new.mouse.hover.popups") ? 36 : 20); private final ExternalDocAction myExternalDocAction; private DocumentationManager myManager; private SmartPsiElementPointer<PsiElement> myElement; private long myModificationCount; public static final String QUICK_DOC_FONT_SIZE_PROPERTY = "quick.doc.font.size"; private final Stack<Context> myBackStack = new Stack<>(); private final Stack<Context> myForwardStack = new Stack<>(); private final ActionToolbarImpl myToolBar; private volatile boolean myIsEmpty; private boolean mySizeTrackerRegistered; private JSlider myFontSizeSlider; private final JComponent mySettingsPanel; private boolean myIgnoreFontSizeSliderChange; private String myExternalUrl; private DocumentationProvider myProvider; private Reference<Component> myReferenceComponent; private final MyDictionary<String, Image> myImageProvider = new MyDictionary<String, Image>() { @Override public Image get(Object key) { return getImageByKeyImpl(key); } }; private Runnable myToolwindowCallback; private final ActionButton myCorner; private final MyScrollPane myScrollPane; private final JEditorPane myEditorPane; private String myText; // myEditorPane.getText() surprisingly crashes.., let's cache the text private String myDecoratedText; // myEditorPane.getText() surprisingly crashes.., let's cache the text private final JComponent myControlPanel; private boolean myControlPanelVisible; private int myHighlightedLink = -1; private Object myHighlightingTag; private final boolean myStoreSize; private boolean myManuallyResized; private AbstractPopup myHint; private final Map<KeyStroke, ActionListener> myKeyboardActions = new HashMap<>(); @NotNull public static DocumentationComponent createAndFetch(@NotNull Project project, @NotNull PsiElement element, @NotNull Disposable disposable) { DocumentationManager manager = DocumentationManager.getInstance(project); DocumentationComponent component = new DocumentationComponent(manager); Disposer.register(disposable, component); manager.fetchDocInfo(element, component); return component; } public DocumentationComponent(DocumentationManager manager) { this(manager, true); } public DocumentationComponent(DocumentationManager manager, boolean storeSize) { myManager = manager; myIsEmpty = true; myStoreSize = storeSize; myEditorPane = new JEditorPane(UIUtil.HTML_MIME, "") { { enableEvents(AWTEvent.KEY_EVENT_MASK); } @Override protected void processKeyEvent(KeyEvent e) { KeyStroke keyStroke = KeyStroke.getKeyStrokeForEvent(e); ActionListener listener = myKeyboardActions.get(keyStroke); if (listener != null) { listener.actionPerformed(new ActionEvent(DocumentationComponent.this, 0, "")); e.consume(); return; } super.processKeyEvent(e); } Point initialClick; @Override protected void processMouseEvent(MouseEvent e) { if (e.getID() == MouseEvent.MOUSE_PRESSED && myHint != null) { //DocumentationComponent.this.requestFocus(); initialClick = null; StyledDocument document = (StyledDocument)getDocument(); int x = e.getX(); int y = e.getY(); if (!hasTextAt(document, x, y) && !hasTextAt(document, x + 3, y) && !hasTextAt(document, x - 3, y) && !hasTextAt(document, x, y + 3) && !hasTextAt(document, x, y - 3)) { initialClick = e.getPoint(); } } super.processMouseEvent(e); } private boolean hasTextAt(StyledDocument document, int x, int y) { Element element = document.getCharacterElement(viewToModel(new Point(x, y))); try { String text = document.getText(element.getStartOffset(), element.getEndOffset() - element.getStartOffset()); if (StringUtil.isEmpty(text.trim())) { return false; } } catch (BadLocationException ignored) { return false; } return true; } @Override protected void processMouseMotionEvent(MouseEvent e) { if (e.getID() == MouseEvent.MOUSE_DRAGGED && myHint != null && initialClick != null) { Point location = myHint.getLocationOnScreen(); myHint.setLocation(new Point(location.x + e.getX() - initialClick.x, location.y + e.getY() - initialClick.y)); e.consume(); return; } super.processMouseMotionEvent(e); } @Override protected void paintComponent(Graphics g) { GraphicsUtil.setupAntialiasing(g); super.paintComponent(g); } @Override public void setDocument(Document doc) { super.setDocument(doc); doc.putProperty("IgnoreCharsetDirective", Boolean.TRUE); if (doc instanceof StyledDocument) { doc.putProperty("imageCache", myImageProvider); } } }; boolean newLayout = Registry.is("editor.new.mouse.hover.popups"); DataProvider helpDataProvider = dataId -> PlatformDataKeys.HELP_ID.is(dataId) ? DOCUMENTATION_TOPIC_ID : null; myEditorPane.putClientProperty(DataManager.CLIENT_PROPERTY_DATA_PROVIDER, helpDataProvider); myText = ""; myDecoratedText = ""; myEditorPane.setEditable(false); if (ScreenReader.isActive()) { // Note: Making the caret visible is merely for convenience myEditorPane.getCaret().setVisible(true); } else { myEditorPane.putClientProperty("caretWidth", 0); // do not reserve space for caret (making content one pixel narrower than component) if (newLayout) { UIUtil.doNotScrollToCaret(myEditorPane); } } myEditorPane.setBackground(EditorColorsUtil.getGlobalOrDefaultColor(COLOR_KEY)); HTMLEditorKit editorKit = new JBHtmlEditorKit(true) { @Override public ViewFactory getViewFactory() { return new JBHtmlFactory() { @Override public View create(Element elem) { AttributeSet attrs = elem.getAttributes(); if ("icon".equals(elem.getName())) { Object src = attrs.getAttribute(HTML.Attribute.SRC); Icon icon = src != null ? IconLoader.findIcon((String)src, false) : null; if (icon == null) { ModuleType<?> id = ModuleTypeManager.getInstance().findByID((String)src); if (id != null) icon = id.getIcon(); } if (icon != null) { return new MyIconView(elem, icon); } } View view = super.create(elem); if (view instanceof ImageView) { // we have to work with raw image, apply scaling manually return new MyScalingImageView(elem); } return view; } }; } }; prepareCSS(editorKit); myEditorPane.setEditorKit(editorKit); myEditorPane.setBorder(JBUI.Borders.empty()); myScrollPane = new MyScrollPane(); myScrollPane.putClientProperty(DataManager.CLIENT_PROPERTY_DATA_PROVIDER, helpDataProvider); FocusListener focusAdapter = new FocusAdapter() { @Override public void focusLost(FocusEvent e) { Component previouslyFocused = WindowManagerEx.getInstanceEx().getFocusedComponent(manager.getProject(getElement())); if (previouslyFocused != myEditorPane) { if (myHint != null && !myHint.isDisposed()) myHint.cancel(); } } }; myEditorPane.addFocusListener(focusAdapter); Disposer.register(this, new Disposable() { @Override public void dispose() { myEditorPane.removeFocusListener(focusAdapter); } }); setLayout(new BorderLayout()); mySettingsPanel = createSettingsPanel(); //add(myScrollPane, BorderLayout.CENTER); setOpaque(true); myScrollPane.setBorder(JBUI.Borders.empty()); DefaultActionGroup actions = new DefaultActionGroup(); BackAction back = new BackAction(); ForwardAction forward = new ForwardAction(); EditDocumentationSourceAction edit = new EditDocumentationSourceAction(); myExternalDocAction = new ExternalDocAction(); actions.add(back); actions.add(forward); actions.add(edit); try { String backKey = ScreenReader.isActive() ? "alt LEFT" : "LEFT"; CustomShortcutSet backShortcutSet = new CustomShortcutSet(KeyboardShortcut.fromString(backKey), KeymapUtil.parseMouseShortcut("button4")); String forwardKey = ScreenReader.isActive() ? "alt RIGHT" : "RIGHT"; CustomShortcutSet forwardShortcutSet = new CustomShortcutSet(KeyboardShortcut.fromString(forwardKey), KeymapUtil.parseMouseShortcut("button5")); back.registerCustomShortcutSet(backShortcutSet, this); forward.registerCustomShortcutSet(forwardShortcutSet, this); // mouse actions are checked only for exact component over which click was performed, // so we need to register shortcuts for myEditorPane as well back.registerCustomShortcutSet(backShortcutSet, myEditorPane); forward.registerCustomShortcutSet(forwardShortcutSet, myEditorPane); } catch (InvalidDataException e) { LOG.error(e); } myExternalDocAction.registerCustomShortcutSet(CustomShortcutSet.fromString("UP"), this); myExternalDocAction.registerCustomShortcutSet(ActionManager.getInstance().getAction(IdeActions.ACTION_EXTERNAL_JAVADOC).getShortcutSet(), myEditorPane); edit.registerCustomShortcutSet(CommonShortcuts.getEditSource(), this); ActionPopupMenu contextMenu = ((ActionManagerImpl)ActionManager.getInstance()).createActionPopupMenu( ActionPlaces.JAVADOC_TOOLBAR, actions, new MenuItemPresentationFactory(true)); PopupHandler popupHandler = new PopupHandler() { @Override public void invokePopup(Component comp, int x, int y) { contextMenu.getComponent().show(comp, x, y); } }; myEditorPane.addMouseListener(popupHandler); Disposer.register(this, () -> myEditorPane.removeMouseListener(popupHandler)); new NextLinkAction().registerCustomShortcutSet(CustomShortcutSet.fromString("TAB"), this); new PreviousLinkAction().registerCustomShortcutSet(CustomShortcutSet.fromString("shift TAB"), this); new ActivateLinkAction().registerCustomShortcutSet(CustomShortcutSet.fromString("ENTER"), this); DefaultActionGroup toolbarActions = new DefaultActionGroup(); toolbarActions.add(actions); toolbarActions.addAction(new ShowAsToolwindowAction()).setAsSecondary(true); toolbarActions.addAction(new MyShowSettingsAction(true)).setAsSecondary(true); toolbarActions.addAction(new ShowToolbarAction()).setAsSecondary(true); toolbarActions.addAction(new RestoreDefaultSizeAction()).setAsSecondary(true); myToolBar = new ActionToolbarImpl(ActionPlaces.JAVADOC_TOOLBAR, toolbarActions, true) { Point initialClick; @Override protected void processMouseEvent(MouseEvent e) { if (e.getID() == MouseEvent.MOUSE_PRESSED && myHint != null) { initialClick = e.getPoint(); } super.processMouseEvent(e); } @Override protected void processMouseMotionEvent(MouseEvent e) { if (e.getID() == MouseEvent.MOUSE_DRAGGED && myHint != null && initialClick != null) { Point location = myHint.getLocationOnScreen(); myHint.setLocation(new Point(location.x + e.getX() - initialClick.x, location.y + e.getY() - initialClick.y)); e.consume(); return; } super.processMouseMotionEvent(e); } }; myToolBar.setSecondaryActionsIcon(AllIcons.Actions.More, true); JLayeredPane layeredPane = new JBLayeredPane() { @Override public void doLayout() { Rectangle r = getBounds(); for (Component component : getComponents()) { if (component instanceof JScrollPane) { component.setBounds(0, 0, r.width, r.height); } else { Dimension d = component.getPreferredSize(); component.setBounds(r.width - d.width - 2, r.height - d.height - (newLayout ? 7 : 3), d.width, d.height); } } } @Override public Dimension getPreferredSize() { Dimension size = myScrollPane.getPreferredSize(); if (myHint == null && myManager != null && myManager.myToolWindow == null) { int em = myEditorPane.getFont().getSize(); int prefHeightMax = PREFERRED_HEIGHT_MAX_EM * em; return new Dimension(size.width, Math.min(prefHeightMax, size.height + (needsToolbar() ? myControlPanel.getPreferredSize().height : 0))); } return size; } }; layeredPane.add(myScrollPane); layeredPane.setLayer(myScrollPane, 0); DefaultActionGroup gearActions = new MyGearActionGroup(); ShowAsToolwindowAction showAsToolwindowAction = new ShowAsToolwindowAction(); gearActions.add(showAsToolwindowAction); gearActions.add(new MyShowSettingsAction(false)); gearActions.add(new ShowToolbarAction()); gearActions.add(new RestoreDefaultSizeAction()); gearActions.addSeparator(); gearActions.addAll(actions); Presentation presentation = new Presentation(); presentation.setIcon(AllIcons.Actions.More); presentation.putClientProperty(ActionButton.HIDE_DROPDOWN_ICON, Boolean.TRUE); myCorner = new ActionButton(gearActions, presentation, ActionPlaces.UNKNOWN, new Dimension(20, 20)) { @Override protected DataContext getDataContext() { return DataManager.getInstance().getDataContext(myCorner); } }; myCorner.setNoIconsInPopup(true); showAsToolwindowAction.registerCustomShortcutSet(KeymapUtil.getActiveKeymapShortcuts("QuickJavaDoc"), myCorner); layeredPane.add(myCorner); layeredPane.setLayer(myCorner, JLayeredPane.POPUP_LAYER); add(layeredPane, BorderLayout.CENTER); myControlPanel = myToolBar.getComponent(); myControlPanel.setBorder(IdeBorderFactory.createBorder(newLayout ? UIUtil.getTooltipSeparatorColor() : JBColor.border(), SideBorder.BOTTOM)); myControlPanelVisible = false; HyperlinkListener hyperlinkListener = new HyperlinkListener() { @Override public void hyperlinkUpdate(HyperlinkEvent e) { HyperlinkEvent.EventType type = e.getEventType(); if (type == HyperlinkEvent.EventType.ACTIVATED) { manager.navigateByLink(DocumentationComponent.this, e.getDescription()); } } }; myEditorPane.addHyperlinkListener(hyperlinkListener); Disposer.register(this, new Disposable() { @Override public void dispose() { myEditorPane.removeHyperlinkListener(hyperlinkListener); } }); if (myHint != null) { Disposer.register(myHint, this); } else if (myManager.myToolWindow != null) { Disposer.register(myManager.myToolWindow.getContentManager(), this); } registerActions(); updateControlState(); } @Override public void setBackground(Color color) { super.setBackground(color); if (Registry.is("editor.new.mouse.hover.popups")) { if (myEditorPane != null) myEditorPane.setBackground(color); if (myControlPanel != null) myControlPanel.setBackground(color); } } public AnAction[] getActions() { return myToolBar.getActions().stream().filter((action -> !(action instanceof Separator))).toArray(AnAction[]::new); } public AnAction getFontSizeAction() { return new MyShowSettingsAction(false); } public void removeCornerMenu() { myCorner.setVisible(false); } public void setToolwindowCallback(Runnable callback) { myToolwindowCallback = callback; } public void showExternalDoc() { DataContext dataContext = DataManager.getInstance().getDataContext(this); myExternalDocAction.actionPerformed(AnActionEvent.createFromDataContext(ActionPlaces.UNKNOWN, null, dataContext)); } @Override public boolean requestFocusInWindow() { // With a screen reader active, set the focus directly to the editor because // it makes it easier for users to read/navigate the documentation contents. if (ScreenReader.isActive()) { return myEditorPane.requestFocusInWindow(); } else { return myScrollPane.requestFocusInWindow(); } } @Override public void requestFocus() { // With a screen reader active, set the focus directly to the editor because // it makes it easier for users to read/navigate the documentation contents. IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> { if (ScreenReader.isActive()) { IdeFocusManager.getGlobalInstance().requestFocus(myEditorPane, true); } else { IdeFocusManager.getGlobalInstance().requestFocus(myScrollPane, true); } }); } private static void prepareCSS(HTMLEditorKit editorKit) { boolean newLayout = Registry.is("editor.new.mouse.hover.popups"); Color borderColor = newLayout ? UIUtil.getTooltipSeparatorColor() : ColorUtil.mix(DOCUMENTATION_COLOR, BORDER_COLOR, 0.5); int leftPadding = newLayout ? 8 : 7; int definitionTopPadding = newLayout ? 4 : 3; int htmlBottomPadding = newLayout ? 8 : 5; String editorFontName = StringUtil.escapeQuotes(EditorColorsManager.getInstance().getGlobalScheme().getEditorFontName()); editorKit.getStyleSheet().addRule("code {font-family:\"" + editorFontName + "\"}"); editorKit.getStyleSheet().addRule("pre {font-family:\"" + editorFontName + "\"}"); editorKit.getStyleSheet().addRule(".pre {font-family:\"" + editorFontName + "\"}"); editorKit.getStyleSheet().addRule("html { padding-bottom: " + htmlBottomPadding + "px; }"); editorKit.getStyleSheet().addRule("h1, h2, h3, h4, h5, h6 { margin-top: 0; padding-top: 1px; }"); editorKit.getStyleSheet().addRule("a { color: #" + ColorUtil.toHex(getLinkColor()) + "; text-decoration: none;}"); editorKit.getStyleSheet().addRule(".definition { padding: " + definitionTopPadding + "px 17px 1px " + leftPadding + "px; border-bottom: thin solid #" + ColorUtil.toHex(borderColor) + "; }"); editorKit.getStyleSheet().addRule(".definition-only { padding: " + definitionTopPadding + "px 17px 0 " + leftPadding + "px; }"); if (newLayout) { editorKit.getStyleSheet().addRule(".definition-only pre { margin-bottom: 0 }"); } editorKit.getStyleSheet().addRule(".content { padding: 5px 16px 0 " + leftPadding + "px; max-width: 100% }"); editorKit.getStyleSheet().addRule(".content-only { padding: 8px 16px 0 " + leftPadding + "px; max-width: 100% }"); editorKit.getStyleSheet().addRule(".bottom { padding: 3px 16px 0 " + leftPadding + "px; }"); editorKit.getStyleSheet().addRule(".bottom-no-content { padding: 5px 16px 0 " + leftPadding + "px; }"); editorKit.getStyleSheet().addRule("p { padding: 1px 0 2px 0; }"); editorKit.getStyleSheet().addRule("ol { padding: 0 16px 0 0; }"); editorKit.getStyleSheet().addRule("ul { padding: 0 16px 0 0; }"); editorKit.getStyleSheet().addRule("li { padding: 1px 0 2px 0; }"); editorKit.getStyleSheet().addRule(".grayed { color: #909090; display: inline;}"); editorKit.getStyleSheet().addRule(".centered { text-align: center}"); // sections table editorKit.getStyleSheet().addRule(".sections { padding: 0 16px 0 " + leftPadding + "px; border-spacing: 0; }"); editorKit.getStyleSheet().addRule("tr { margin: 0 0 0 0; padding: 0 0 0 0; }"); if (newLayout) { editorKit.getStyleSheet().addRule("table p { padding-bottom: 0}"); editorKit.getStyleSheet().addRule("td { margin: 4px 0 0 0; padding: 0 0 0 0; }"); } else { editorKit.getStyleSheet().addRule("td { margin: 2px 0 3.5px 0; padding: 0 0 0 0; }"); } editorKit.getStyleSheet().addRule("th { text-align: left; }"); editorKit.getStyleSheet().addRule(".section { color: " + ColorUtil.toHtmlColor(SECTION_COLOR) + "; padding-right: 4px}"); } private static Color getLinkColor() { return JBUI.CurrentTheme.Link.linkColor(); } @Override public Object getData(@NotNull @NonNls String dataId) { if (DocumentationManager.SELECTED_QUICK_DOC_TEXT.getName().equals(dataId)) { // Javadocs often contain &nbsp; symbols (non-breakable white space). We don't want to copy them as is and replace // with raw white spaces. See IDEA-86633 for more details. String selectedText = myEditorPane.getSelectedText(); return selectedText == null ? null : selectedText.replace((char)160, ' '); } return null; } private JComponent createSettingsPanel() { JPanel result = new JPanel(new FlowLayout(FlowLayout.RIGHT, 3, 0)); result.add(new JLabel(ApplicationBundle.message("label.font.size"))); myFontSizeSlider = new JSlider(SwingConstants.HORIZONTAL, 0, FontSize.values().length - 1, 3); myFontSizeSlider.setMinorTickSpacing(1); myFontSizeSlider.setPaintTicks(true); myFontSizeSlider.setPaintTrack(true); myFontSizeSlider.setSnapToTicks(true); UIUtil.setSliderIsFilled(myFontSizeSlider, true); result.add(myFontSizeSlider); result.setBorder(BorderFactory.createLineBorder(JBColor.border(), 1)); myFontSizeSlider.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if (myIgnoreFontSizeSliderChange) { return; } setQuickDocFontSize(FontSize.values()[myFontSizeSlider.getValue()]); applyFontProps(); // resize popup according to new font size, if user didn't set popup size manually if (!myManuallyResized && myHint != null && myHint.getDimensionServiceKey() == null) showHint(); } }); String tooltipText = ApplicationBundle.message("quickdoc.tooltip.font.size.by.wheel"); result.setToolTipText(tooltipText); myFontSizeSlider.setToolTipText(tooltipText); result.setVisible(false); result.setOpaque(true); myFontSizeSlider.setOpaque(true); return result; } @NotNull public static FontSize getQuickDocFontSize() { String strValue = PropertiesComponent.getInstance().getValue(QUICK_DOC_FONT_SIZE_PROPERTY); if (strValue != null) { try { return FontSize.valueOf(strValue); } catch (IllegalArgumentException iae) { // ignore, fall back to default font. } } return FontSize.SMALL; } public void setQuickDocFontSize(@NotNull FontSize fontSize) { PropertiesComponent.getInstance().setValue(QUICK_DOC_FONT_SIZE_PROPERTY, fontSize.toString()); } private void setFontSizeSliderSize(FontSize fontSize) { myIgnoreFontSizeSliderChange = true; try { FontSize[] sizes = FontSize.values(); for (int i = 0; i < sizes.length; i++) { if (fontSize == sizes[i]) { myFontSizeSlider.setValue(i); break; } } } finally { myIgnoreFontSizeSliderChange = false; } } public boolean isEmpty() { return myIsEmpty; } public void startWait() { myIsEmpty = true; } private void setControlPanelVisible() { if (myControlPanelVisible) return; add(myControlPanel, BorderLayout.NORTH); myControlPanelVisible = true; } public void setHint(JBPopup hint) { myHint = (AbstractPopup)hint; } public JBPopup getHint() { return myHint; } public JComponent getComponent() { return myEditorPane; } @Nullable public PsiElement getElement() { return myElement != null ? myElement.getElement() : null; } private void setElement(SmartPsiElementPointer<PsiElement> element) { myElement = element; myModificationCount = getCurrentModificationCount(); } public boolean isUpToDate() { return getElement() != null && myModificationCount == getCurrentModificationCount(); } private long getCurrentModificationCount() { return myElement != null ? PsiModificationTracker.SERVICE.getInstance(myElement.getProject()).getModificationCount() : -1; } public void setText(@NotNull String text, @Nullable PsiElement element, @Nullable DocumentationProvider provider) { setData(element, text, null, null, provider); } public void replaceText(@NotNull String text, @Nullable PsiElement element) { PsiElement current = getElement(); if (current == null || !current.getManager().areElementsEquivalent(current, element)) return; restoreContext(saveContext().withText(text)); } public void clearHistory() { myForwardStack.clear(); myBackStack.clear(); } private void pushHistory() { if (myElement != null) { myBackStack.push(saveContext()); myForwardStack.clear(); } } public void setData(@Nullable PsiElement element, @NotNull String text, @Nullable String effectiveExternalUrl, @Nullable String ref, @Nullable DocumentationProvider provider) { pushHistory(); myExternalUrl = effectiveExternalUrl; myProvider = provider; SmartPsiElementPointer<PsiElement> pointer = null; if (element != null && element.isValid()) { pointer = SmartPointerManager.getInstance(element.getProject()).createSmartPsiElementPointer(element); } setDataInternal(pointer, text, new Rectangle(0, 0), ref); } private void setDataInternal(@Nullable SmartPsiElementPointer<PsiElement> element, @NotNull String text, @NotNull Rectangle viewRect, @Nullable String ref) { myIsEmpty = false; if (myManager == null) return; myText = text; setElement(element); myDecoratedText = decorate(text); showHint(viewRect, ref); } protected void showHint(@NotNull Rectangle viewRect, @Nullable String ref) { String refToUse; Rectangle viewRectToUse; if (DocumentationManagerProtocol.KEEP_SCROLLING_POSITION_REF.equals(ref)) { refToUse = null; viewRectToUse = myScrollPane.getViewport().getViewRect(); } else { refToUse = ref; viewRectToUse = viewRect; } updateControlState(); highlightLink(-1); myEditorPane.setText(myDecoratedText); applyFontProps(); showHint(); //noinspection SSBasedInspection SwingUtilities.invokeLater(() -> { myEditorPane.scrollRectToVisible(viewRectToUse); // if ref is defined but is not found in document, this provides a default location if (refToUse != null) { UIUtil.scrollToReference(myEditorPane, refToUse); } else if (ScreenReader.isActive()) { myEditorPane.setCaretPosition(0); } }); } protected void showHint() { if (myHint == null) return; setHintSize(); DataContext dataContext = getDataContext(); PopupPositionManager.positionPopupInBestPosition(myHint, myManager.getEditor(), dataContext, PopupPositionManager.Position.RIGHT, PopupPositionManager.Position.LEFT); Window window = myHint.getPopupWindow(); if (window != null) window.setFocusableWindowState(true); registerSizeTracker(); } private DataContext getDataContext() { Component referenceComponent; if (myReferenceComponent == null) { referenceComponent = IdeFocusManager.getInstance(myManager.myProject).getFocusOwner(); myReferenceComponent = new WeakReference<>(referenceComponent); } else { referenceComponent = SoftReference.dereference(myReferenceComponent); if (referenceComponent == null || ! referenceComponent.isShowing()) referenceComponent = myHint.getComponent(); } return DataManager.getInstance().getDataContext(referenceComponent); } private void setHintSize() { Dimension hintSize; if (!myManuallyResized && myHint.getDimensionServiceKey() == null) { hintSize = getOptimalSize(); } else { if (myManuallyResized) { hintSize = myHint.getSize(); JBInsets.removeFrom(hintSize, myHint.getContent().getInsets()); } else { hintSize = DimensionService.getInstance().getSize(DocumentationManager.NEW_JAVADOC_LOCATION_AND_SIZE, myManager.myProject); } if (hintSize == null) { hintSize = new Dimension(MIN_DEFAULT); } else { hintSize.width = Math.max(hintSize.width, MIN_DEFAULT.width); hintSize.height = Math.max(hintSize.height, MIN_DEFAULT.height); } } myHint.setSize(hintSize); } public Dimension getOptimalSize() { int width = getPreferredWidth(); int height = getPreferredHeight(width); return new Dimension(width, height); } @Override public int getPreferredWidth() { int minWidth = JBUIScale.scale(300); int maxWidth = getPopupAnchor() != null ? JBUIScale.scale(435) : MAX_DEFAULT.width; int width = definitionPreferredWidth(); if (width < 0) { // no definition found width = myEditorPane.getPreferredSize().width; } else { width = Math.max(width, myEditorPane.getMinimumSize().width); } Insets insets = getInsets(); return Math.min(maxWidth, Math.max(minWidth, width)) + insets.left + insets.right; } @Override public int getPreferredHeight(int width) { myEditorPane.setBounds(0, 0, width, MAX_DEFAULT.height); myEditorPane.setText(myDecoratedText); Dimension preferredSize = myEditorPane.getPreferredSize(); int height = preferredSize.height + (needsToolbar() ? myControlPanel.getPreferredSize().height : 0); JScrollBar scrollBar = myScrollPane.getHorizontalScrollBar(); int reservedForScrollBar = width < preferredSize.width && scrollBar.isOpaque() ? scrollBar.getPreferredSize().height : 0; Insets insets = getInsets(); return Math.min(MAX_DEFAULT.height, Math.max(MIN_DEFAULT.height, height)) + insets.top + insets.bottom + reservedForScrollBar; } private Component getPopupAnchor() { LookupEx lookup = myManager == null ? null : LookupManager.getActiveLookup(myManager.getEditor()); if (lookup != null && lookup.getCurrentItem() != null && lookup.getComponent().isShowing()) { return lookup.getComponent(); } Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); JBPopup popup = PopupUtil.getPopupContainerFor(focusOwner); if (popup != null && popup != myHint && !popup.isDisposed()) { return popup.getContent(); } return null; } private void registerSizeTracker() { AbstractPopup hint = myHint; if (hint == null || mySizeTrackerRegistered) return; mySizeTrackerRegistered = true; hint.addResizeListener(this::onManualResizing, this); ApplicationManager.getApplication().getMessageBus().connect(this).subscribe(AnActionListener.TOPIC, new AnActionListener() { @Override public void afterActionPerformed(@NotNull AnAction action, @NotNull DataContext dataContext, @NotNull AnActionEvent event) { if (action instanceof WindowAction) onManualResizing(); } }); } private void onManualResizing() { myManuallyResized = true; if (myStoreSize && myHint != null) { myHint.setDimensionServiceKey(DocumentationManager.NEW_JAVADOC_LOCATION_AND_SIZE); myHint.storeDimensionSize(); } } private int definitionPreferredWidth() { TextUI ui = myEditorPane.getUI(); View view = ui.getRootView(myEditorPane); View definition = findDefinition(view); return definition != null ? (int)definition.getPreferredSpan(View.X_AXIS) : -1; } private static View findDefinition(View view) { if ("definition".equals(view.getElement().getAttributes().getAttribute(HTML.Attribute.CLASS))) { return view; } for (int i = 0; i < view.getViewCount(); i++) { View definition = findDefinition(view.getView(i)); if (definition != null) return definition; } return null; } private String decorate(String text) { text = StringUtil.replaceIgnoreCase(text, "</html>", ""); text = StringUtil.replaceIgnoreCase(text, "</body>", ""); text = StringUtil.replaceIgnoreCase(text, DocumentationMarkup.SECTIONS_START + DocumentationMarkup.SECTIONS_END, ""); text = StringUtil.replaceIgnoreCase(text, DocumentationMarkup.SECTIONS_START + "<p>" + DocumentationMarkup.SECTIONS_END, ""); boolean hasContent = text.contains(DocumentationMarkup.CONTENT_START); if (!hasContent) { if (!text.contains(DocumentationMarkup.DEFINITION_START)) { int bodyStart = findContentStart(text); if (bodyStart > 0) { text = text.substring(0, bodyStart) + DocumentationMarkup.CONTENT_START + text.substring(bodyStart) + DocumentationMarkup.CONTENT_END; } else { text = DocumentationMarkup.CONTENT_START + text + DocumentationMarkup.CONTENT_END; } hasContent = true; } else if (!text.contains(DocumentationMarkup.SECTIONS_START)){ text = StringUtil.replaceIgnoreCase(text, DocumentationMarkup.DEFINITION_START, "<div class='definition-only'><pre>"); } } if (Registry.is("editor.new.mouse.hover.popups") && !text.contains(DocumentationMarkup.DEFINITION_START)) { text = text.replace("class='content'", "class='content-only'"); } String location = getLocationText(); if (location != null) { text = text + getBottom(hasContent) + location + "</div>"; } String links = getExternalText(myManager, getElement(), myExternalUrl, myProvider); if (links != null) { text = text + getBottom(location != null) + links; } //workaround for Swing html renderer not removing empty paragraphs before non-inline tags text = text.replaceAll("<p>\\s*(<(?:[uo]l|h\\d|p))", "$1"); text = addExternalLinksIcon(text); return text; } @Nullable private static String getExternalText(@NotNull DocumentationManager manager, @Nullable PsiElement element, @Nullable String externalUrl, @Nullable DocumentationProvider provider) { if (element == null || provider == null) return null; PsiElement originalElement = DocumentationManager.getOriginalElement(element); if (!shouldShowExternalDocumentationLink(provider, element, originalElement)) { return null; } String title = manager.getTitle(element); if (title != null) { title = StringUtil.escapeXmlEntities(title); } if (externalUrl == null) { List<String> urls = provider.getUrlFor(element, originalElement); if (urls != null) { boolean hasBadUrl = false; StringBuilder result = new StringBuilder(); for (String url : urls) { String link = getLink(title, url); if (link == null) { hasBadUrl = true; break; } if (result.length() > 0) result.append("<p>"); result.append(link); } if (!hasBadUrl) return result.toString(); } else { return null; } } else { String link = getLink(title, externalUrl); if (link != null) return link; } return "<a href='external_doc'>External documentation" + (title == null ? "" : (" for `" + title + "`")) + "<icon src='AllIcons.Ide.External_link_arrow'></a></div>"; } private static String getLink(String title, String url) { StringBuilder result = new StringBuilder(); String hostname = getHostname(url); if (hostname == null) { return null; } result.append("<a href='").append(url).append("'>"); if (title == null) { result.append("Documentation"); } else { result.append("`").append(title).append("`"); } result.append(" on ").append(hostname).append("</a>"); return result.toString(); } static boolean shouldShowExternalDocumentationLink(DocumentationProvider provider, PsiElement element, PsiElement originalElement) { if (provider instanceof CompositeDocumentationProvider) { List<DocumentationProvider> providers = ((CompositeDocumentationProvider)provider).getProviders(); for (DocumentationProvider p : providers) { if (p instanceof ExternalDocumentationHandler) { return ((ExternalDocumentationHandler)p).canHandleExternal(element, originalElement); } } } else if (provider instanceof ExternalDocumentationHandler) { return ((ExternalDocumentationHandler)provider).canHandleExternal(element, originalElement); } return true; } private static String getHostname(String url) { try { return new URL(url).toURI().getHost(); } catch (URISyntaxException | MalformedURLException ignored) { } return null; } private static int findContentStart(String text) { int index = StringUtil.indexOfIgnoreCase(text, "<body>", 0); if (index >= 0) return index + 6; index = StringUtil.indexOfIgnoreCase(text, "</head>", 0); if (index >= 0) return index + 7; index = StringUtil.indexOfIgnoreCase(text, "</style>", 0); if (index >= 0) return index + 8; index = StringUtil.indexOfIgnoreCase(text, "<html>", 0); if (index >= 0) return index + 6; return -1; } @NotNull private static String getBottom(boolean hasContent) { return "<div class='" + (hasContent ? "bottom" : "bottom-no-content") + "'>"; } private static String addExternalLinksIcon(String text) { return text.replaceAll("(<a\\s*href=[\"']http[^>]*>)([^>]*)(</a>)", "$1$2<icon src='AllIcons.Ide.External_link_arrow'>$3"); } private String getLocationText() { PsiElement element = getElement(); if (element != null) { PsiFile file = element.getContainingFile(); VirtualFile vfile = file == null ? null : file.getVirtualFile(); if (vfile == null) return null; ProjectFileIndex fileIndex = ProjectRootManager.getInstance(element.getProject()).getFileIndex(); Module module = fileIndex.getModuleForFile(vfile); if (module != null) { if (ModuleManager.getInstance(element.getProject()).getModules().length == 1) return null; return "<icon src='" + ModuleType.get(module).getId() + "'>&nbsp;" + module.getName().replace("<", "&lt;"); } else { List<OrderEntry> entries = fileIndex.getOrderEntriesForFile(vfile); for (OrderEntry order : entries) { if (order instanceof LibraryOrderEntry || order instanceof JdkOrderEntry) { return "<icon src='AllIcons.Nodes.PpLibFolder" + "'>&nbsp;" + order.getPresentableName().replace("<", "&lt;"); } } } } return null; } private void applyFontProps() { Document document = myEditorPane.getDocument(); if (!(document instanceof StyledDocument)) { return; } String fontName = Registry.is("documentation.component.editor.font") ? EditorColorsManager.getInstance().getGlobalScheme().getEditorFontName() : myEditorPane.getFont().getFontName(); // changing font will change the doc's CSS as myEditorPane has JEditorPane.HONOR_DISPLAY_PROPERTIES via UIUtil.getHTMLEditorKit myEditorPane.setFont(UIUtil.getFontWithFallback(fontName, Font.PLAIN, JBUIScale.scale(getQuickDocFontSize().getSize()))); } @Nullable private Image getImageByKeyImpl(Object key) { if (myManager == null || key == null) return null; PsiElement element = getElement(); if (element == null) return null; URL url = (URL)key; Image inMemory = myManager.getElementImage(element, url.toExternalForm()); if (inMemory != null) { return inMemory; } Url parsedUrl = Urls.parseEncoded(url.toExternalForm()); BuiltInServerManager builtInServerManager = BuiltInServerManager.getInstance(); if (parsedUrl != null && builtInServerManager.isOnBuiltInWebServer(parsedUrl)) { try { url = new URL(builtInServerManager.addAuthToken(parsedUrl).toExternalForm()); } catch (MalformedURLException e) { LOG.warn(e); } } URL imageUrl = url; return Toolkit.getDefaultToolkit().createImage(new RenderableImageProducer(new RenderableImage() { private Image myImage; private boolean myImageLoaded; @Override public Vector<RenderableImage> getSources() { return null; } @Override public Object getProperty(String name) { return null; } @Override public String[] getPropertyNames() { return ArrayUtilRt.EMPTY_STRING_ARRAY; } @Override public boolean isDynamic() { return false; } @Override public float getWidth() { return getImage().getWidth(null); } @Override public float getHeight() { return getImage().getHeight(null); } @Override public float getMinX() { return 0; } @Override public float getMinY() { return 0; } @Override public RenderedImage createScaledRendering(int w, int h, RenderingHints hints) { return createDefaultRendering(); } @Override public RenderedImage createDefaultRendering() { return (RenderedImage)getImage(); } @Override public RenderedImage createRendering(RenderContext renderContext) { return createDefaultRendering(); } private Image getImage() { if (!myImageLoaded) { Image image = ImageLoader.loadFromUrl(imageUrl); myImage = ImageUtil.toBufferedImage(image != null ? image : ((ImageIcon)UIManager.getLookAndFeelDefaults().get("html.missingImage")).getImage()); myImageLoaded = true; } return myImage; } }, null)); } private void goBack() { if (myBackStack.isEmpty()) return; Context context = myBackStack.pop(); myForwardStack.push(saveContext()); restoreContext(context); } private void goForward() { if (myForwardStack.isEmpty()) return; Context context = myForwardStack.pop(); myBackStack.push(saveContext()); restoreContext(context); } private Context saveContext() { Rectangle rect = myScrollPane.getViewport().getViewRect(); return new Context(myElement, myText, myExternalUrl, myProvider, rect, myHighlightedLink); } private void restoreContext(@NotNull Context context) { myExternalUrl = context.externalUrl; myProvider = context.provider; setDataInternal(context.element, context.text, context.viewRect, null); highlightLink(context.highlightedLink); if (myManager != null) { PsiElement element = context.element.getElement(); if (element != null) { myManager.updateToolWindowTabName(element); } } } private void updateControlState() { if (needsToolbar()) { myToolBar.updateActionsImmediately(); // update faster setControlPanelVisible(); removeCornerMenu(); } else { myControlPanelVisible = false; remove(myControlPanel); if (myManager.myToolWindow != null) return; myCorner.setVisible(true); } } public boolean needsToolbar() { return myManager.myToolWindow == null && Registry.is("documentation.show.toolbar"); } private static class MyGearActionGroup extends DefaultActionGroup implements HintManagerImpl.ActionToIgnore { MyGearActionGroup(@NotNull AnAction... actions) { super(actions); setPopup(true); } } private class BackAction extends AnAction implements HintManagerImpl.ActionToIgnore { BackAction() { super(CodeInsightBundle.message("javadoc.action.back"), null, AllIcons.Actions.Back); } @Override public void actionPerformed(@NotNull AnActionEvent e) { goBack(); } @Override public void update(@NotNull AnActionEvent e) { Presentation presentation = e.getPresentation(); presentation.setEnabled(!myBackStack.isEmpty()); if (!isToolbar(e)) { presentation.setVisible(presentation.isEnabled()); } } } private class ForwardAction extends AnAction implements HintManagerImpl.ActionToIgnore { ForwardAction() { super(CodeInsightBundle.message("javadoc.action.forward"), null, AllIcons.Actions.Forward); } @Override public void actionPerformed(@NotNull AnActionEvent e) { goForward(); } @Override public void update(@NotNull AnActionEvent e) { Presentation presentation = e.getPresentation(); presentation.setEnabled(!myForwardStack.isEmpty()); if (!isToolbar(e)) { presentation.setVisible(presentation.isEnabled()); } } } private class EditDocumentationSourceAction extends BaseNavigateToSourceAction { private EditDocumentationSourceAction() { super(true); getTemplatePresentation().setIcon(AllIcons.Actions.EditSource); getTemplatePresentation().setText("Edit Source"); } @Override public void actionPerformed(@NotNull AnActionEvent e) { super.actionPerformed(e); JBPopup hint = myHint; if (hint != null && hint.isVisible()) { hint.cancel(); } } @Nullable @Override protected Navigatable[] getNavigatables(DataContext dataContext) { SmartPsiElementPointer<PsiElement> element = myElement; if (element != null) { PsiElement psiElement = element.getElement(); return psiElement instanceof Navigatable ? new Navigatable[]{(Navigatable)psiElement} : null; } return null; } } private static boolean isToolbar(@NotNull AnActionEvent e) { return ActionPlaces.JAVADOC_TOOLBAR.equals(e.getPlace()); } private class ExternalDocAction extends AnAction implements HintManagerImpl.ActionToIgnore { private ExternalDocAction() { super(CodeInsightBundle.message("javadoc.action.view.external"), null, AllIcons.Actions.PreviousOccurence); registerCustomShortcutSet(ActionManager.getInstance().getAction(IdeActions.ACTION_EXTERNAL_JAVADOC).getShortcutSet(), null); } @Override public void actionPerformed(@NotNull AnActionEvent e) { if (myElement == null) { return; } PsiElement element = myElement.getElement(); PsiElement originalElement = DocumentationManager.getOriginalElement(element); ExternalJavaDocAction.showExternalJavadoc(element, originalElement, myExternalUrl, e.getDataContext()); } @Override public void update(@NotNull AnActionEvent e) { Presentation presentation = e.getPresentation(); presentation.setEnabled(hasExternalDoc()); } } private boolean hasExternalDoc() { boolean enabled = false; if (myElement != null && myProvider != null) { PsiElement element = myElement.getElement(); PsiElement originalElement = DocumentationManager.getOriginalElement(element); enabled = element != null && CompositeDocumentationProvider.hasUrlsFor(myProvider, element, originalElement); } return enabled; } private void registerActions() { // With screen readers, we want the default keyboard behavior inside // the document text editor, i.e. the caret moves with cursor keys, etc. if (!ScreenReader.isActive()) { myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JScrollBar scrollBar = myScrollPane.getVerticalScrollBar(); int value = scrollBar.getValue() - scrollBar.getUnitIncrement(-1); value = Math.max(value, 0); scrollBar.setValue(value); } }); myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JScrollBar scrollBar = myScrollPane.getVerticalScrollBar(); int value = scrollBar.getValue() + scrollBar.getUnitIncrement(+1); value = Math.min(value, scrollBar.getMaximum()); scrollBar.setValue(value); } }); myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JScrollBar scrollBar = myScrollPane.getHorizontalScrollBar(); int value = scrollBar.getValue() - scrollBar.getUnitIncrement(-1); value = Math.max(value, 0); scrollBar.setValue(value); } }); myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JScrollBar scrollBar = myScrollPane.getHorizontalScrollBar(); int value = scrollBar.getValue() + scrollBar.getUnitIncrement(+1); value = Math.min(value, scrollBar.getMaximum()); scrollBar.setValue(value); } }); myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JScrollBar scrollBar = myScrollPane.getVerticalScrollBar(); int value = scrollBar.getValue() - scrollBar.getBlockIncrement(-1); value = Math.max(value, 0); scrollBar.setValue(value); } }); myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JScrollBar scrollBar = myScrollPane.getVerticalScrollBar(); int value = scrollBar.getValue() + scrollBar.getBlockIncrement(+1); value = Math.min(value, scrollBar.getMaximum()); scrollBar.setValue(value); } }); myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, 0), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JScrollBar scrollBar = myScrollPane.getHorizontalScrollBar(); scrollBar.setValue(0); } }); myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_END, 0), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JScrollBar scrollBar = myScrollPane.getHorizontalScrollBar(); scrollBar.setValue(scrollBar.getMaximum()); } }); myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, InputEvent.CTRL_MASK), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JScrollBar scrollBar = myScrollPane.getVerticalScrollBar(); scrollBar.setValue(0); } }); myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_END, InputEvent.CTRL_MASK), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JScrollBar scrollBar = myScrollPane.getVerticalScrollBar(); scrollBar.setValue(scrollBar.getMaximum()); } }); } } public String getText() { return myText; } public String getDecoratedText() { return myDecoratedText; } @Override public void dispose() { myEditorPane.getCaret().setVisible(false); // Caret, if blinking, has to be deactivated. myBackStack.clear(); myForwardStack.clear(); myKeyboardActions.clear(); myElement = null; myManager = null; myHint = null; } private int getLinkCount() { HTMLDocument document = (HTMLDocument)myEditorPane.getDocument(); int linkCount = 0; for (HTMLDocument.Iterator it = document.getIterator(HTML.Tag.A); it.isValid(); it.next()) { if (it.getAttributes().isDefined(HTML.Attribute.HREF)) linkCount++; } return linkCount; } @Nullable private HTMLDocument.Iterator getLink(int n) { if (n >= 0) { HTMLDocument document = (HTMLDocument)myEditorPane.getDocument(); int linkCount = 0; for (HTMLDocument.Iterator it = document.getIterator(HTML.Tag.A); it.isValid(); it.next()) { if (it.getAttributes().isDefined(HTML.Attribute.HREF) && linkCount++ == n) return it; } } return null; } private void highlightLink(int n) { myHighlightedLink = n; Highlighter highlighter = myEditorPane.getHighlighter(); HTMLDocument.Iterator link = getLink(n); if (link != null) { int startOffset = link.getStartOffset(); int endOffset = link.getEndOffset(); try { if (myHighlightingTag == null) { myHighlightingTag = highlighter.addHighlight(startOffset, endOffset, LINK_HIGHLIGHTER); } else { highlighter.changeHighlight(myHighlightingTag, startOffset, endOffset); } myEditorPane.setCaretPosition(startOffset); if (Registry.is("editor.new.mouse.hover.popups") && !ScreenReader.isActive()) { // scrolling to target location explicitly, as we've disabled auto-scrolling to caret myEditorPane.scrollRectToVisible(myEditorPane.modelToView(startOffset)); } } catch (BadLocationException e) { LOG.warn("Error highlighting link", e); } } else if (myHighlightingTag != null) { highlighter.removeHighlight(myHighlightingTag); myHighlightingTag = null; } } private void activateLink(int n) { HTMLDocument.Iterator link = getLink(n); if (link != null) { String href = (String)link.getAttributes().getAttribute(HTML.Attribute.HREF); myManager.navigateByLink(this, href); } } private static class Context { final SmartPsiElementPointer<PsiElement> element; final String text; final String externalUrl; final DocumentationProvider provider; final Rectangle viewRect; final int highlightedLink; Context(SmartPsiElementPointer<PsiElement> element, String text, String externalUrl, DocumentationProvider provider, Rectangle viewRect, int highlightedLink) { this.element = element; this.text = text; this.externalUrl = externalUrl; this.provider = provider; this.viewRect = viewRect; this.highlightedLink = highlightedLink; } @NotNull Context withText(@NotNull String text) { return new Context(element, text, externalUrl, provider, viewRect, highlightedLink); } } private class MyShowSettingsAction extends AnAction implements HintManagerImpl.ActionToIgnore { private final boolean myOnToolbar; MyShowSettingsAction(boolean onToolbar) { super("Adjust font size..."); myOnToolbar = onToolbar; } @Override public void update(@NotNull AnActionEvent e) { if (myManager == null || myOnToolbar && myManager.myToolWindow != null) { e.getPresentation().setEnabledAndVisible(false); } } @Override public void actionPerformed(@NotNull AnActionEvent e) { JBPopup popup = JBPopupFactory.getInstance().createComponentPopupBuilder(mySettingsPanel, myFontSizeSlider).createPopup(); setFontSizeSliderSize(getQuickDocFontSize()); mySettingsPanel.setVisible(true); Point location = MouseInfo.getPointerInfo().getLocation(); popup.show(new RelativePoint(new Point(location.x - mySettingsPanel.getPreferredSize().width / 2, location.y - mySettingsPanel.getPreferredSize().height / 2))); } } private abstract static class MyDictionary<K, V> extends Dictionary<K, V> { @Override public int size() { throw new UnsupportedOperationException(); } @Override public boolean isEmpty() { throw new UnsupportedOperationException(); } @Override public Enumeration<K> keys() { throw new UnsupportedOperationException(); } @Override public Enumeration<V> elements() { throw new UnsupportedOperationException(); } @Override public V put(K key, V value) { throw new UnsupportedOperationException(); } @Override public V remove(Object key) { throw new UnsupportedOperationException(); } } private class PreviousLinkAction extends AnAction implements HintManagerImpl.ActionToIgnore { @Override public void actionPerformed(@NotNull AnActionEvent e) { int linkCount = getLinkCount(); if (linkCount <= 0) return; highlightLink(myHighlightedLink < 0 ? (linkCount - 1) : (myHighlightedLink + linkCount - 1) % linkCount); } } private class NextLinkAction extends AnAction implements HintManagerImpl.ActionToIgnore { @Override public void actionPerformed(@NotNull AnActionEvent e) { int linkCount = getLinkCount(); if (linkCount <= 0) return; highlightLink((myHighlightedLink + 1) % linkCount); } } private class ActivateLinkAction extends AnAction implements HintManagerImpl.ActionToIgnore { @Override public void actionPerformed(@NotNull AnActionEvent e) { activateLink(myHighlightedLink); } } private static class LinkHighlighter implements Highlighter.HighlightPainter { private static final Stroke STROKE = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1, new float[]{1}, 0); @Override public void paint(Graphics g, int p0, int p1, Shape bounds, JTextComponent c) { try { Rectangle target = c.getUI().getRootView(c).modelToView(p0, Position.Bias.Forward, p1, Position.Bias.Backward, bounds).getBounds(); Graphics2D g2d = (Graphics2D)g.create(); try { g2d.setStroke(STROKE); g2d.setColor(c.getSelectionColor()); g2d.drawRect(target.x, target.y, target.width - 1, target.height - 1); } finally { g2d.dispose(); } } catch (Exception e) { LOG.warn("Error painting link highlight", e); } } } private class ShowToolbarAction extends ToggleAction implements HintManagerImpl.ActionToIgnore { ShowToolbarAction() { super("Show Toolbar"); } @Override public void update(@NotNull AnActionEvent e) { super.update(e); if (myManager == null || myManager.myToolWindow != null) { e.getPresentation().setEnabledAndVisible(false); } } @Override public boolean isSelected(@NotNull AnActionEvent e) { return Registry.get("documentation.show.toolbar").asBoolean(); } @Override public void setSelected(@NotNull AnActionEvent e, boolean state) { Registry.get("documentation.show.toolbar").setValue(state); updateControlState(); showHint(); } } private class MyScrollPane extends JBScrollPane { MyScrollPane() { super(myEditorPane, VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_AS_NEEDED); setLayout(new Layout() { @Override public void layoutContainer(Container parent) { super.layoutContainer(parent); if (!myCorner.isVisible()) return; if (vsb != null) { Rectangle bounds = vsb.getBounds(); vsb.setBounds(bounds.x, bounds.y, bounds.width, bounds.height - myCorner.getPreferredSize().height - 3); } if (hsb != null) { Rectangle bounds = hsb.getBounds(); int vsbOffset = vsb != null ? vsb.getBounds().width : 0; hsb.setBounds(bounds.x, bounds.y, bounds.width - myCorner.getPreferredSize().width - 3 + vsbOffset, bounds.height); } } }); } @Override public Border getViewportBorder() { return null; } @Override protected void processMouseWheelEvent(MouseWheelEvent e) { if (!EditorSettingsExternalizable.getInstance().isWheelFontChangeEnabled() || !EditorUtil.isChangeFontSize(e)) { super.processMouseWheelEvent(e); return; } int rotation = e.getWheelRotation(); if (rotation == 0) return; int change = Math.abs(rotation); boolean increase = rotation <= 0; FontSize newFontSize = getQuickDocFontSize(); for (; change > 0; change if (increase) { newFontSize = newFontSize.larger(); } else { newFontSize = newFontSize.smaller(); } } if (newFontSize == getQuickDocFontSize()) { return; } setQuickDocFontSize(newFontSize); applyFontProps(); setFontSizeSliderSize(newFontSize); } } private class ShowAsToolwindowAction extends AnAction implements HintManagerImpl.ActionToIgnore { ShowAsToolwindowAction() { super("Open as Tool Window"); } @Override public void update(@NotNull AnActionEvent e) { Presentation presentation = e.getPresentation(); if (myManager == null) { presentation.setEnabledAndVisible(false); } else { presentation .setIcon(ToolWindowManagerEx.getInstanceEx(myManager.myProject).getLocationIcon(ToolWindowId.DOCUMENTATION, EmptyIcon.ICON_16)); presentation.setEnabledAndVisible(myToolwindowCallback != null); } } @Override public void actionPerformed(@NotNull AnActionEvent e) { myToolwindowCallback.run(); } } private class RestoreDefaultSizeAction extends AnAction implements HintManagerImpl.ActionToIgnore { RestoreDefaultSizeAction() { super("Restore Size"); } @Override public void update(@NotNull AnActionEvent e) { e.getPresentation().setEnabledAndVisible(myHint != null && (myManuallyResized || myHint.getDimensionServiceKey() != null)); } @Override public void actionPerformed(@NotNull AnActionEvent e) { myManuallyResized = false; if (myStoreSize) { DimensionService.getInstance().setSize(DocumentationManager.NEW_JAVADOC_LOCATION_AND_SIZE, null, myManager.myProject); myHint.setDimensionServiceKey(null); } showHint(); } } private class MyScalingImageView extends ImageView { private MyScalingImageView(Element elem) {super(elem);} @Override public float getMaximumSpan(int axis) { return super.getMaximumSpan(axis) / JBUIScale.sysScale(myEditorPane); } @Override public float getMinimumSpan(int axis) { return super.getMinimumSpan(axis) / JBUIScale.sysScale(myEditorPane); } @Override public float getPreferredSpan(int axis) { return super.getPreferredSpan(axis) / JBUIScale.sysScale(myEditorPane); } @Override public void paint(Graphics g, Shape a) { Rectangle bounds = a.getBounds(); int width = (int)super.getPreferredSpan(View.X_AXIS); int height = (int)super.getPreferredSpan(View.Y_AXIS); if (width <= 0 || height <= 0) return; @SuppressWarnings("UndesirableClassUsage") BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D graphics = image.createGraphics(); super.paint(graphics, new Rectangle(image.getWidth(), image.getHeight())); StartupUiUtil.drawImage(g, ImageUtil.ensureHiDPI(image, ScaleContext.create(myEditorPane)), bounds.x, bounds.y, null); } } private static class MyIconView extends View { private final Icon myViewIcon; private MyIconView(Element elem, Icon viewIcon) { super(elem); myViewIcon = viewIcon; } @Override public float getPreferredSpan(int axis) { switch (axis) { case View.X_AXIS: return myViewIcon.getIconWidth(); case View.Y_AXIS: return myViewIcon.getIconHeight(); default: throw new IllegalArgumentException("Invalid axis: " + axis); } } @Override public String getToolTipText(float x, float y, Shape allocation) { return (String)super.getElement().getAttributes().getAttribute(HTML.Attribute.ALT); } @Override public void paint(Graphics g, Shape allocation) { myViewIcon.paintIcon(null, g, allocation.getBounds().x, allocation.getBounds().y - 4); } @Override public Shape modelToView(int pos, Shape a, Position.Bias b) throws BadLocationException { int p0 = getStartOffset(); int p1 = getEndOffset(); if ((pos >= p0) && (pos <= p1)) { Rectangle r = a.getBounds(); if (pos == p1) { r.x += r.width; } r.width = 0; return r; } throw new BadLocationException(pos + " not in range " + p0 + "," + p1, pos); } @Override public int viewToModel(float x, float y, Shape a, Position.Bias[] bias) { Rectangle alloc = (Rectangle)a; if (x < alloc.x + (alloc.width / 2f)) { bias[0] = Position.Bias.Forward; return getStartOffset(); } bias[0] = Position.Bias.Backward; return getEndOffset(); } } }
package org.jetbrains.plugins.javaFX.fxml.codeInsight; import com.intellij.ide.IdeBundle; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.ElementColorProvider; import com.intellij.psi.*; import com.intellij.psi.impl.JavaConstantExpressionEvaluator; import com.intellij.psi.util.PsiTypesUtil; import com.intellij.util.ArrayUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.javaFX.fxml.JavaFxCommonNames; import java.awt.*; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.Locale; import java.util.Set; import java.util.StringJoiner; import java.util.function.IntFunction; /** * @author Pavel.Dolgov */ public class JavaFxColorProvider implements ElementColorProvider { private static final String COLOR = "color"; private static final String RGB = "rgb"; private static final String GRAY = "gray"; private static final String GRAY_RGB = "grayRgb"; private static final String HSB = "hsb"; private static final Set<String> FACTORY_METHODS = ContainerUtil.immutableSet(COLOR, RGB, GRAY, GRAY_RGB, HSB); private static final String DECIMAL_FORMAT_PATTERN = " private static final DecimalFormatSymbols DECIMAL_FORMAT_SYMBOLS = new DecimalFormatSymbols(Locale.US); // use '.' as a decimal separator @Override public Color getColorFrom(@NotNull PsiElement element) { if (element instanceof PsiNewExpression) { PsiNewExpression newExpression = (PsiNewExpression)element; if (isColorClass(PsiTypesUtil.getPsiClass(newExpression.getType()))) { PsiExpressionList argumentList = newExpression.getArgumentList(); if (argumentList != null) { PsiExpression[] args = argumentList.getExpressions(); if (args.length == 4) { Object[] values = getArgumentValues(args); return getScaledRgbColor(values[0], values[1], values[2], values[3]); } } } } if (element instanceof PsiMethodCallExpression) { PsiMethodCallExpression methodCall = (PsiMethodCallExpression)element; PsiReferenceExpression methodExpression = methodCall.getMethodExpression(); String methodName = methodExpression.getReferenceName(); if (FACTORY_METHODS.contains(methodName)) { PsiElement resolved = methodExpression.resolve(); if (resolved instanceof PsiMethod) { PsiMethod method = (PsiMethod)resolved; if (method.hasModifierProperty(PsiModifier.STATIC)) { if (isColorClass(method.getContainingClass())) { return getColor(methodName, methodCall.getArgumentList()); } } } } } return null; } private static boolean isColorClass(@Nullable PsiClass aClass) { return aClass != null && JavaFxCommonNames.JAVAFX_SCENE_COLOR.equals(aClass.getQualifiedName()); } @Nullable private static Color getColor(@Nullable String methodName, @NotNull PsiExpressionList argumentList) { Object[] values = getArgumentValues(argumentList.getExpressions()); if (COLOR.equals(methodName)) { switch (values.length) { case 4: return getScaledRgbColor(values[0], values[1], values[2], values[3]); case 3: return getScaledRgbColor(values[0], values[1], values[2], Double.valueOf(1)); } } else if (RGB.equals(methodName)) { switch (values.length) { case 4: return getRgbColor(values[0], values[1], values[2], values[3]); case 3: return getRgbColor(values[0], values[1], values[2], Double.valueOf(1)); } } else if (GRAY.equals(methodName)) { switch (values.length) { case 2: return getScaledRgbColor(values[0], values[0], values[0], values[1]); case 1: return getScaledRgbColor(values[0], values[0], values[0], Double.valueOf(1)); } } else if (GRAY_RGB.equals(methodName)) { switch (values.length) { case 2: return getRgbColor(values[0], values[0], values[0], values[1]); case 1: return getRgbColor(values[0], values[0], values[0], Double.valueOf(1)); } } else if (HSB.equals(methodName)) { switch (values.length) { case 4: return getHsbColor(values[0], values[1], values[2], values[3]); case 3: return getHsbColor(values[0], values[1], values[2], Double.valueOf(1)); } } return null; } @NotNull private static Object[] getArgumentValues(@NotNull PsiExpression[] argumentExpressions) { return ContainerUtil.map(argumentExpressions, expression -> JavaConstantExpressionEvaluator.computeConstantExpression(expression, false), ArrayUtil.EMPTY_OBJECT_ARRAY); } @Nullable private static Color getScaledRgbColor(@Nullable Object redValue, @Nullable Object greenValue, @Nullable Object blueValue, @Nullable Object alphaValue) { Integer red = getScaledComponent(redValue); Integer green = getScaledComponent(greenValue); Integer blue = getScaledComponent(blueValue); Integer alpha = getScaledComponent(alphaValue); if (red != null && green != null && blue != null && alpha != null) { //noinspection UseJBColor return new Color(red, green, blue, alpha); } return null; } @Nullable private static Color getRgbColor(@Nullable Object redValue, @Nullable Object greenValue, @Nullable Object blueValue, @Nullable Object alphaValue) { Integer red = getComponent(redValue); Integer green = getComponent(greenValue); Integer blue = getComponent(blueValue); Integer alpha = getScaledComponent(alphaValue); if (red != null && green != null && blue != null && alpha != null) { //noinspection UseJBColor return new Color(red, green, blue, alpha); } return null; } private static Integer getComponent(Object value) { if (value instanceof Number) { int component = ((Number)value).intValue(); if (component >= 0 && component <= 255) { return component; } } return null; } private static Integer getScaledComponent(Object value) { if (value instanceof Number) { double doubleValue = ((Number)value).doubleValue(); int component = (int)(doubleValue * 255 + 0.5); if (component >= 0 && component <= 255) { return component; } } return null; } private static Float getHsbComponent(Object value, boolean checkRange) { if (value instanceof Number) { float component = ((Number)value).floatValue(); if (!checkRange || component >= 0.0f && component <= 1.0f) { return component; } } return null; } @Override public void setColorTo(@NotNull PsiElement element, @NotNull Color color) { Runnable command = null; if (element instanceof PsiNewExpression) { final PsiNewExpression expr = (PsiNewExpression)element; PsiExpressionList argumentList = expr.getArgumentList(); assert argumentList != null; command = () -> replaceConstructorArgs(color, argumentList); } if (element instanceof PsiMethodCallExpression) { PsiMethodCallExpression methodCall = (PsiMethodCallExpression)element; PsiReferenceExpression methodExpression = methodCall.getMethodExpression(); String methodName = methodExpression.getReferenceName(); if (COLOR.equals(methodName) || GRAY.equals(methodName)) { command = () -> replaceColor(methodCall, getScaledRgbCallText(color)); } else if (RGB.equals(methodName) || GRAY_RGB.equals(methodName)) { command = () -> replaceColor(methodCall, getRgbCallText(color)); } else if (HSB.equals(methodName)) { command = () -> replaceColor(methodCall, getHsbCallText(color)); } } if (command != null) { Document document = PsiDocumentManager.getInstance(element.getProject()).getDocument(element.getContainingFile()); CommandProcessor.getInstance() .executeCommand(element.getProject(), command, IdeBundle.message("change.color.command.text"), null, document); } } private static void replaceConstructorArgs(@NotNull Color color, PsiExpressionList argumentList) { PsiElementFactory factory = JavaPsiFacade.getElementFactory(argumentList.getProject()); String text = JavaFxCommonNames.JAVAFX_SCENE_COLOR + "(" + formatScaledComponent(color.getRed()) + "," + formatScaledComponent(color.getGreen()) + "," + formatScaledComponent(color.getBlue()) + "," + formatScaledComponent(color.getAlpha()) + ")"; PsiMethodCallExpression newCall = (PsiMethodCallExpression)factory.createExpressionFromText(text, argumentList); argumentList.replace(newCall.getArgumentList()); } private static void replaceColor(@NotNull PsiMethodCallExpression methodCall, @NotNull String callText) { PsiElementFactory factory = JavaPsiFacade.getElementFactory(methodCall.getProject()); PsiMethodCallExpression newCall = (PsiMethodCallExpression)factory.createExpressionFromText(callText, methodCall); methodCall.getArgumentList().replace(newCall.getArgumentList()); PsiElement nameElement = methodCall.getMethodExpression().getReferenceNameElement(); assert nameElement != null; PsiElement newNameElement = newCall.getMethodExpression().getReferenceNameElement(); assert newNameElement != null; nameElement.replace(newNameElement); } private static Color getHsbColor(Object hValue, Object sValue, Object bValue, Object alphaValue) { Float h = getHsbComponent(hValue, false); Float s = getHsbComponent(sValue, true); Float b = getHsbComponent(bValue, true); Integer alpha = getScaledComponent(alphaValue); if (h != null && s != null && b != null && alpha != null) { Color hsbColor = Color.getHSBColor(h / 360.0f, s, b); //noinspection UseJBColor return alpha == 255 ? hsbColor : new Color(hsbColor.getRed(), hsbColor.getGreen(), hsbColor.getBlue(), alpha); } return null; } @NotNull private static String getScaledRgbCallText(@NotNull Color color) { return getCallText(color, COLOR, GRAY, JavaFxColorProvider::formatScaledComponent); } @NotNull private static String getRgbCallText(@NotNull Color color) { return getCallText(color, RGB, GRAY_RGB, String::valueOf); } @NotNull private static String getCallText(@NotNull Color color, String colorMethodName, String grayMethodName, IntFunction<String> formatter) { String methodName; StringJoiner args = new StringJoiner(",", "(", ")"); if (color.getRed() == color.getGreen() && color.getRed() == color.getBlue()) { methodName = grayMethodName; args.add(formatter.apply(color.getRed())); } else { methodName = colorMethodName; args.add(formatter.apply(color.getRed())); args.add(formatter.apply(color.getGreen())); args.add(formatter.apply(color.getBlue())); } if (color.getAlpha() != 255) { args.add(formatScaledComponent(color.getAlpha())); } return methodName + args; } @NotNull private static String formatScaledComponent(int colorComponent) { DecimalFormat df = new DecimalFormat(DECIMAL_FORMAT_PATTERN, DECIMAL_FORMAT_SYMBOLS); // not thread safe - can't have a constant return df.format(colorComponent / 255.0); } private static String getHsbCallText(Color color) { float[] hsb = Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null); DecimalFormat df = new DecimalFormat(DECIMAL_FORMAT_PATTERN, DECIMAL_FORMAT_SYMBOLS); StringJoiner args = new StringJoiner(",", "(", ")"); args.add(df.format(hsb[0] * 360)); args.add(df.format(hsb[1])); args.add(df.format(hsb[2])); if (color.getAlpha() != 255) { args.add(formatScaledComponent(color.getAlpha())); } return HSB + args; } }
package org.eclipse.xtext.xtext.ecoreInference; import java.util.Set; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.EDataType; import org.eclipse.emf.ecore.EEnum; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.ecore.EcoreFactory; import org.eclipse.emf.ecore.EcorePackage; import org.eclipse.xtext.EcoreUtil2; import org.eclipse.xtext.EcoreUtil2.FindResult; import org.eclipse.xtext.util.Strings; /** * @author Jan Khnlein - Initial contribution and API * @author Heiko Behrens * */ public abstract class EClassifierInfo { private final EClassifier eClassifier; private final boolean isGenerated; private EClassifierInfo(EClassifier metaType, boolean isGenerated) { super(); this.isGenerated = isGenerated; this.eClassifier = metaType; } public static EClassifierInfo createEClassInfo(EClass eClass, boolean isGenerated, Set<String> generatedEPackageURIs) { return new EClassInfo(eClass, isGenerated, generatedEPackageURIs); } public static EClassifierInfo createEDataTypeInfo(EDataType eDataType, boolean isGenerated) { return new EDataTypeInfo(eDataType, isGenerated); } public EClassifier getEClassifier() { return eClassifier; } public boolean isGenerated() { return isGenerated; } public boolean isAssignableFrom(EClassifierInfo subTypeInfo) { return getEClassifier().equals(subTypeInfo.getEClassifier()); } public abstract boolean addSupertype(EClassifierInfo superTypeInfo); public abstract boolean addFeature(String featureName, EClassifierInfo featureType, boolean isMultivalue, boolean isContainment, EObject parserElement) throws TransformationException; public static class EClassInfo extends EClassifierInfo { private Set<String> generatedEPackageURIs; public EClassInfo(EClassifier metaType, boolean isGenerated, Set<String> generatedEPackageURIs) { super(metaType, isGenerated); this.generatedEPackageURIs = generatedEPackageURIs; } @Override public boolean isAssignableFrom(EClassifierInfo subTypeInfo) { return super.isAssignableFrom(subTypeInfo) || (subTypeInfo instanceof EClassInfo) && (getEClass().isSuperTypeOf((EClass) subTypeInfo.getEClassifier()) || EcorePackage.Literals.EOBJECT == getEClass()); } @Override public boolean addSupertype(EClassifierInfo superTypeInfo) { EClass eClass = getEClass(); EClass superEClass = (EClass) superTypeInfo.getEClassifier(); if (superEClass.isSuperTypeOf(eClass)) { return true; } if (!isGenerated()) { throw new IllegalStateException("Type " + this.getEClassifier().getName() + " is not generated and cannot be modified."); } if (!(superTypeInfo instanceof EClassInfo)) { throw new IllegalArgumentException("superTypeInfo must represent EClass"); } if (eClass.equals(superEClass)) // cannot add class as it's own superclass // this usually happens due to a rule call return false; return eClass.getESuperTypes().add(superEClass); } @Override public boolean addFeature(String featureName, EClassifierInfo featureType, boolean isMultivalue, boolean isContainment, EObject parserElement) throws TransformationException { EClassifier featureClassifier = featureType.getEClassifier(); return addFeature(featureName, featureClassifier, isMultivalue, isContainment, parserElement); } public boolean addFeature(EStructuralFeature prototype) { try { boolean isContainment = false; if (prototype instanceof EReference) { EReference reference = (EReference) prototype; isContainment = reference.isContainment(); } return addFeature(prototype.getName(), prototype.getEType(), prototype.isMany(), isContainment, null); } catch (TransformationException e) { throw new IllegalArgumentException(e.getMessage()); } } private boolean addFeature(String featureName, EClassifier featureClassifier, boolean isMultivalue, boolean isContainment, EObject parserElement) throws TransformationException { if (!isGenerated()) { if (!EcoreUtil2.containsCompatibleFeature(getEClass(), featureName, isMultivalue, featureClassifier)) { throw new TransformationException(TransformationErrorCode.CannotCreateTypeInSealedMetamodel, "Cannot find compatible feature "+featureName+" in sealed EClass "+getEClass().getName()+" from imported package "+getEClass().getEPackage().getNsURI()+".", parserElement); } return true; } EStructuralFeature newFeature = createFeatureWith(featureName, featureClassifier, isMultivalue, isContainment); FindResult containsSemanticallyEqualFeature = EcoreUtil2.containsSemanticallyEqualFeature(getEClass(), newFeature); switch (containsSemanticallyEqualFeature) { case FeatureDoesNotExist: if (!isGenerated()) throw new TransformationException(TransformationErrorCode.CannotCreateTypeInSealedMetamodel, "Cannot create feature in sealed metamodel.", parserElement); return getEClass().getEStructuralFeatures().add(newFeature); case FeatureExists: // do nothing return false; default: // do nothing } // feature with same name exists, but has a different, // potentially incompatible configuration EStructuralFeature existingFeature = getEClass().getEStructuralFeature(featureName); if (!EcoreUtil2.isFeatureSemanticallyEqualApartFromType(newFeature, existingFeature)) throw new TransformationException(TransformationErrorCode.FeatureWithDifferentConfigurationAlreadyExists, "A feature '" + newFeature.getName() + "' with a different cardinality or containment " + "configuration already exists in type '" + getEClass().getName() + "'.", parserElement); EClassifier compatibleType = EcoreUtil2 .getCompatibleType(existingFeature.getEType(), newFeature.getEType()); if (compatibleType == null) throw new TransformationException(TransformationErrorCode.NoCompatibleFeatureTypeAvailable, "Cannot find compatible type for features", parserElement); if (isGenerated(existingFeature)) { existingFeature.setEType(compatibleType); } else { throw new TransformationException(TransformationErrorCode.FeatureWithDifferentConfigurationAlreadyExists, "Incompatible return type to existing feature", parserElement); } return true; } /** * @param existingFeature * @return */ private boolean isGenerated(EStructuralFeature existingFeature) { return generatedEPackageURIs.contains(existingFeature.getEContainingClass().getEPackage().getNsURI()); } private EStructuralFeature createFeatureWith(String featureName, EClassifier featureClassifier, boolean isMultivalue, boolean isContainment) { EStructuralFeature newFeature; if (featureClassifier instanceof EClass) { EReference reference = EcoreFactory.eINSTANCE.createEReference(); reference.setContainment(isContainment); newFeature = reference; } else { newFeature = EcoreFactory.eINSTANCE.createEAttribute(); } newFeature.setName(featureName); newFeature.setEType(featureClassifier); newFeature.setLowerBound(0); newFeature.setUpperBound(isMultivalue ? -1 : 1); newFeature.setUnique(!isMultivalue || (isContainment && featureClassifier instanceof EClass)); if (newFeature.getEType() instanceof EEnum) { newFeature.setDefaultValue(null); } return newFeature; } public EClass getEClass() { return ((EClass) getEClassifier()); } } public static class EDataTypeInfo extends EClassifierInfo { public EDataTypeInfo(EClassifier metaType, boolean isGenerated) { super(metaType, isGenerated); } @Override public boolean addSupertype(EClassifierInfo superTypeInfo) { throw new UnsupportedOperationException("Cannot add supertype " + Strings.emptyIfNull(superTypeInfo.getEClassifier().getName()) + " to simple datatype " + Strings.emptyIfNull(this.getEClassifier().getName())); } @Override public boolean addFeature(String featureName, EClassifierInfo featureType, boolean isMultivalue, boolean isContainment, EObject parserElement) throws TransformationException { throw new UnsupportedOperationException("Cannot add feature " + featureName + " to simple datatype " + Strings.emptyIfNull(this.getEClassifier().getName())); } } }
package com.opengamma.component; import java.util.HashMap; import java.util.Map; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionGroup; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang.StringUtils; import com.opengamma.OpenGammaRuntimeException; import com.opengamma.util.StartupUtils; /** * Main entry point for OpenGamma component-based servers. * <p> * This class starts an OpenGamma JVM process using the specified config file. * A {@link OpenGammaComponentServerMonitor monitor} thread will also be started. * <p> * Two types of config file format are recognized - properties and INI. * A properties file must be in the standard Java format and contain a key "MANAGER.NEXT.FILE" * which is the resource location of the main INI file. * The INI file is described in {@link ComponentConfigIniLoader}. */ public class OpenGammaComponentServer { /** * The server name property. * DO NOT deduplicate with the same value in ComponentManager. * This constant is used to set a system property before ComponentManager is class loaded. */ private static final String OPENGAMMA_SERVER_NAME = "og.server.name"; /** * Help command line option. */ private static final String HELP_OPTION = "help"; /** * Verbose command line option. */ private static final String VERBOSE_OPTION = "verbose"; /** * Quiet command line option. */ private static final String QUIET_OPTION = "quiet"; /** * Load-only command line option. */ private static final String LOAD_ONLY_OPTION = "load-only"; /** * Property-display command line option. */ private static final String PROPERTY_DISPLAY_OPTION = "property-display"; /** * Command line options. */ private static final Options OPTIONS = getOptions(); /** * The logger in use. */ private ComponentLogger _logger = ComponentLogger.Console.VERBOSE; static { StartupUtils.init(); } /** * Main method to start an OpenGamma JVM process. * * @param args the arguments */ public static void main(String[] args) { // CSIGNORE if (!new OpenGammaComponentServer().run(args)) { System.exit(0); } } /** * Runs the server. * * @param args the arguments, not null * @return true if the server is started, false if there was a problem */ public boolean run(String[] args) { CommandLine cmdLine; try { cmdLine = (new PosixParser()).parse(OPTIONS, args); } catch (ParseException ex) { _logger.logError(ex.getMessage()); usage(); return false; } if (cmdLine.hasOption(HELP_OPTION)) { usage(); return false; } int verbosity = 2; if (cmdLine.hasOption(VERBOSE_OPTION)) { verbosity = 3; } else if (cmdLine.hasOption(QUIET_OPTION)) { verbosity = 0; } _logger = createLogger(verbosity); args = cmdLine.getArgs(); if (args.length == 0) { _logger.logError("No config file specified"); usage(); return false; } Map<String, String> properties = new HashMap<String, String>(); if (args.length > 1) { for (int i = 1; i < args.length; i++) { String arg = args[i]; int equalsPosition = arg.indexOf('='); if (equalsPosition < 0) { throw new OpenGammaRuntimeException("Invalid property format, must be key=value (no spaces)"); } String key = arg.substring(0, equalsPosition).trim(); String value = arg.substring(equalsPosition + 1).trim(); if (key.length() == 0) { throw new IllegalArgumentException("Invalid empty property key"); } if (properties.containsKey(key)) { throw new IllegalArgumentException("Invalid property, key '" + key + "' specified twice"); } properties.put(key, value); } } String configFile = args[0]; if (cmdLine.hasOption(PROPERTY_DISPLAY_OPTION)) { return displayProperty(configFile, properties, cmdLine.getOptionValue(PROPERTY_DISPLAY_OPTION)); } else if (cmdLine.hasOption(LOAD_ONLY_OPTION)) { return loadOnly(configFile, properties); } else { return run(configFile, properties); } } /** * Loads the config files without starting the server. * * @param configFile the config file, not null * @param properties the properties read from the command line, not null * @return false always */ protected boolean loadOnly(String configFile, Map<String, String> properties) { _logger.logDebug(" Config locator: " + configFile); try { ComponentManager manager = buildManager(configFile, properties); manager.load(configFile); } catch (Exception ex) { _logger.logError(ex); return false; } return false; } /** * Displays the value of the property from the config files without starting the server. * * @param configFile the config file, not null * @param properties the properties read from the command line, not null * @param property the property to display, not null * @return false always */ protected boolean displayProperty(String configFile, Map<String, String> properties, String property) { try { String value = queryProperty(configFile, properties, property); if (value == null) { System.out.println("NO-SUCH-PROPERTY"); } else { System.out.println(value); } } catch (Exception ex) { _logger.logError(ex); return false; } return false; } /** * Queries the value of the property from the config files without starting the server. * * @param configFile the config file, not null * @param properties the properties read from the command line, not null * @param property the property to display, not null * @return the property value, null if no such property * @throws RuntimeException if an error occurs */ protected String queryProperty(String configFile, Map<String, String> properties, String property) { ComponentManager manager = buildManager(configFile, properties); manager.load(configFile); return manager.getProperties().get(property); } /** * Runs the server with config file. * * @param configFile the config file, not null * @param properties the properties read from the command line, not null * @return true if the server was started, false if there was a problem */ protected boolean run(String configFile, Map<String, String> properties) { long start = System.nanoTime(); _logger.logInfo("======== STARTING OPENGAMMA ========"); _logger.logDebug(" Config locator: " + configFile); try { ComponentManager manager = buildManager(configFile, properties); serverStarting(manager); manager.start(configFile); } catch (Exception ex) { _logger.logError(ex); _logger.logError("======== OPENGAMMA STARTUP FAILED ========"); return false; } long end = System.nanoTime(); _logger.logInfo("======== OPENGAMMA STARTED in " + ((end - start) / 1000000) + "ms ========"); return true; } /** * Builds the component manager. * * @param configFile the config file, not null * @param properties the properties read from the command line, not null * @return the manager, not null */ protected ComponentManager buildManager(String configFile, Map<String, String> properties) { String serverName = extractServerName(configFile); System.setProperty(OPENGAMMA_SERVER_NAME, serverName); ComponentManager manager = createManager(serverName); manager.getProperties().putAll(properties); return manager; } /** * Extracts the server name. * <p> * This examines the first part of the file name and the last directory, * merging these with a dash. * * @param fileName the name to extract from, not null * @return the server name, not null */ protected String extractServerName(String fileName) { if (fileName.contains(":")) { fileName = StringUtils.substringAfter(fileName, ":"); } fileName = FilenameUtils.removeExtension(fileName); String first = FilenameUtils.getName(FilenameUtils.getPathNoEndSeparator(fileName)); String second = FilenameUtils.getName(fileName); if (StringUtils.isEmpty(first) || first.equals(second) || second.startsWith(first + "-")) { return second; } return first + "-" + second; } /** * Called just before the server is started. The default implementation here * creates a monitor thread that allows the server to be stopped remotely. * * @param manager the component manager */ protected void serverStarting(final ComponentManager manager) { OpenGammaComponentServerMonitor.create(manager.getRepository()); } /** * Creates the logger. * * @param verbosity the verbosity required, 0=errors, 3=debug * @return the logger, not null */ protected ComponentLogger createLogger(int verbosity) { return new ComponentLogger.Console(verbosity); } /** * Creates the component manager. * * @param serverName the server name, not null * @return the manager, not null */ protected ComponentManager createManager(String serverName) { return new ComponentManager(serverName, _logger); } private void usage() { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.setWidth(100); helpFormatter.printHelp(getClass().getSimpleName() + " [options] configFile", OPTIONS); } private static Options getOptions() { Options options = new Options(); options.addOption(new Option("h", HELP_OPTION, false, "print this help message")); options.addOptionGroup(new OptionGroup() .addOption(new Option("l", LOAD_ONLY_OPTION, false, "load the config, but do not start the server")) .addOption(new Option("p", PROPERTY_DISPLAY_OPTION, true, "displays the calculated value of a property"))); options.addOptionGroup(new OptionGroup() .addOption(new Option("q", QUIET_OPTION, false, "be quiet during startup")) .addOption(new Option("v", VERBOSE_OPTION, false, "be verbose during startup"))); return options; } }
package org.asynchttpclient.providers.grizzly; import org.glassfish.grizzly.CompletionHandler; import org.glassfish.grizzly.Connection; import org.glassfish.grizzly.EmptyCompletionHandler; import org.glassfish.grizzly.GrizzlyFuture; import org.glassfish.grizzly.connectionpool.EndpointKey; import org.glassfish.grizzly.connectionpool.MultiEndpointPool; import org.glassfish.grizzly.connectionpool.SingleEndpointPool; import org.glassfish.grizzly.utils.DelayedExecutor; import java.io.IOException; import java.net.SocketAddress; /** * Extension of standard Grizzly {@link MultiEndpointPool}. * * @since 2.0 * @author The Grizzly Team */ public class ConnectionPool extends MultiEndpointPool<SocketAddress>{ private final Object lock = new Object(); public ConnectionPool(final int maxConnectionsPerEndpoint, final int maxConnectionsTotal, final DelayedExecutor delayedExecutor, final long connectTimeoutMillis, final long keepAliveTimeoutMillis, final long keepAliveCheckIntervalMillis) { super(null, maxConnectionsPerEndpoint, maxConnectionsTotal, delayedExecutor, connectTimeoutMillis, keepAliveTimeoutMillis, keepAliveCheckIntervalMillis, -1, -1); } protected SingleEndpointPool<SocketAddress> obtainSingleEndpointPool( final EndpointKey<SocketAddress> endpointKey) throws IOException { SingleEndpointPool<SocketAddress> sePool = endpointToPoolMap.get(endpointKey); if (sePool == null) { synchronized (poolSync) { checkNotClosed(); if (isMaxCapacityReached()) { throw new MaxCapacityException(); } sePool = endpointToPoolMap.get(endpointKey); if (sePool == null) { sePool = createSingleEndpointPool(endpointKey); endpointToPoolMap.put(endpointKey, sePool); } } } return sePool; } @Override public GrizzlyFuture<Connection> take(final EndpointKey<SocketAddress> endpointKey) { synchronized (lock) { final GrizzlyFuture<Connection> f = super.take(endpointKey); f.addCompletionHandler(new EmptyCompletionHandler<Connection>() { @Override public void completed(Connection result) { if (Utils.isSpdyConnection(result)) { release(result); } super.completed(result); } }); return f; } } @Override public void take(final EndpointKey<SocketAddress> endpointKey, final CompletionHandler<Connection> completionHandler) { synchronized (lock) { if (completionHandler == null) { throw new IllegalStateException("CompletionHandler argument cannot be null."); } super.take(endpointKey, new CompletionHandler<Connection>() { @Override public void cancelled() { completionHandler.cancelled(); } @Override public void failed(Throwable throwable) { completionHandler.failed(throwable); } @Override public void completed(Connection result) { release(result); completionHandler.completed(result); } @Override public void updated(Connection result) { completionHandler.updated(result); } }); } } @Override public boolean release(Connection connection) { synchronized (lock) { return super.release(connection); } } public static final class MaxCapacityException extends IOException { public MaxCapacityException() { super("Maximum pool capacity has been reached"); } } }
// This source code implements specifications defined by the Java // Community Process. In order to remain compliant with the specification // DO NOT add / change / or delete method signatures! package javax.activation; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; public class DataHandler implements Transferable { private DataSource _ds; public DataHandler(DataSource ds) { _ds = ds; } public DataHandler(Object data, String type) { _ds = new ObjectDataSource(data, type); } static class ObjectDataSource implements DataSource { private Object _data; private String _type; public Object getContent() { return _data; } /** * Store an object as a data source type * @param data the object * @param type the mimeType */ public ObjectDataSource(Object data, String type) { _data = data; _type = type; } /* (non-Javadoc) * @see javax.activation.DataSource#getInputStream() */ public InputStream getInputStream() throws IOException { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see javax.activation.DataSource#getOutputStream() */ public OutputStream getOutputStream() throws IOException { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see javax.activation.DataSource#getContentType() */ public String getContentType() { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see javax.activation.DataSource#getName() */ public String getName() { // TODO Auto-generated method stub return null; } } public DataHandler(URL url) { /*@todo implement*/ } public DataSource getDataSource() { return _ds; } public String getName() { /*@todo implement*/ return null; } public String getContentType() { return _ds.getContentType(); } public InputStream getInputStream() throws IOException { return _ds.getInputStream(); } public void writeTo(OutputStream os) throws IOException { // TODO implement } public OutputStream getOutputStream() throws IOException { return _ds.getOutputStream(); } public synchronized DataFlavor[] getTransferDataFlavors() { /*@todo implement*/ return null; } public boolean isDataFlavorSupported(DataFlavor flavor) { /*@todo implement*/ return false; } public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { /*@todo implement*/ return null; } public synchronized void setCommandMap(CommandMap commandMap) { /*@todo implement*/ } public CommandInfo[] getPreferredCommands() { /*@todo implement*/ return null; } public CommandInfo[] getAllCommands() { /*@todo implement*/ return null; } public CommandInfo getCommand(String cmdName) { /*@todo implement*/ return null; } public Object getContent() throws IOException { if (_ds instanceof ObjectDataSource) { return ((ObjectDataSource) _ds).getContent(); } else { // TODO not yet implemented throw new IOException("TODO Not yet implemented"); } } public Object getBean(CommandInfo cmdinfo) { /*@todo implement*/ return null; } public static synchronized void setDataContentHandlerFactory(DataContentHandlerFactory newFactory) { } }
package org.wiztools.restclient.ui.reqbody; import java.awt.BorderLayout; import java.awt.Component; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.MessageFormat; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import javax.annotation.PostConstruct; import javax.inject.Inject; import javax.swing.*; import javax.swing.table.AbstractTableModel; import org.wiztools.restclient.bean.*; import org.wiztools.restclient.ui.RESTView; import org.wiztools.restclient.ui.UIUtil; /** * * @author subwiz */ public class ReqBodyPanelMultipart extends JPanel implements ReqBodyPanel { @Inject private RESTView view; @Inject private AddMultipartFileDialog jd_addFileDialog; @Inject private AddMultipartStringDialog jd_addStringDialog; private final JButton jb_string = new JButton("String"); private final JButton jb_file = new JButton("File"); private final JButton jb_config = new JButton(UIUtil.getIconFromClasspath("org/wiztools/restclient/cog.png")); private final JMenuItem rbBrowserCompatible = new JRadioButtonMenuItem("Browser Compatible"); private final JMenuItem rbRFC6532 = new JRadioButtonMenuItem("RFC 6532"); private final JMenuItem rbStrict = new JRadioButtonMenuItem("Strict"); private final MultipartTableModel model = new MultipartTableModel(); private final JTable jt = new JTable(model); private class MultipartTableModel extends AbstractTableModel { private final String[] columnNames = new String[]{"Type", "Content-type", "Name", "Part"}; private final LinkedList<ReqEntityPart> list = new LinkedList<>(); @Override public int getRowCount() { return list.size(); } @Override public int getColumnCount() { return 4; } @Override public String getColumnName(int columnIndex) { return columnNames[columnIndex]; } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return false; } @Override public Object getValueAt(int rowIndex, int columnIndex) { ReqEntityPart part = list.get(rowIndex); if(columnIndex == 0) { if(part instanceof ReqEntityStringPart) { return "String"; } else if(part instanceof ReqEntityFilePart) { return "File"; } } else if(columnIndex == 1) { return part.getContentType(); } else if(columnIndex == 2) { return part.getName(); } else { if(part instanceof ReqEntityStringPart) { return ((ReqEntityStringPart)part).getPart(); } else if(part instanceof ReqEntityFilePart) { return ((ReqEntityFilePart)part).getPart(); } } throw new IllegalArgumentException("Should never come here!"); } public void addPartFirst(ReqEntityPart part) { list.addFirst(part); fireTableDataChanged(); } public void addPartLast(ReqEntityPart part) { list.addLast(part); fireTableDataChanged(); } public ReqEntityPart getEntityInRow(int row) { return list.get(row); } public void removeRow(int row) { list.remove(row); fireTableDataChanged(); } public void clear() { list.clear(); fireTableDataChanged(); } } @PostConstruct protected void init() { // Listeners: final AddMultipartPartListener listener = new AddMultipartPartListener() { @Override public void addPart(ReqEntityPart part) { model.addPartFirst(part); } }; jd_addStringDialog.addMultipartPartListener(listener); jd_addFileDialog.addMultipartPartListener(listener); // Table popup: JPopupMenu menu = new JPopupMenu(); JMenuItem jmi_rm = new JMenuItem("Delete selected"); jmi_rm.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final int[] rows = jt.getSelectedRows(); Arrays.sort(rows); if(rows != null && rows.length > 0) { int i = 0; for(int row: rows) { row = row - i; // the number of rows previously deleted should be accounted for! model.removeRow(row); i++; } view.setStatusMessage(MessageFormat.format("Deleted {0} row(s)", i)); } else { view.setStatusMessage("No row(s) selected!"); } } }); menu.add(jmi_rm); JMenuItem jmi_view = new JMenuItem("Quick view"); jmi_view.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { quickView(); } }); menu.add(jmi_view); jt.setComponentPopupMenu(menu); // Config Popup: final JPopupMenu jpmConfig = new JPopupMenu(); { ButtonGroup group = new ButtonGroup(); rbBrowserCompatible.setSelected(true); group.add(rbBrowserCompatible); jpmConfig.add(rbBrowserCompatible); group.add(rbRFC6532); jpmConfig.add(rbRFC6532); group.add(rbStrict); jpmConfig.add(rbStrict); } // Layouts: setLayout(new BorderLayout()); { // North: JPanel jp_border = new JPanel(new BorderLayout(0, 0)); JPanel jp_center = new JPanel(new FlowLayout(FlowLayout.LEFT)); jp_center.add(new JLabel("Add Part: ")); { // String button: jb_string.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { jd_addStringDialog.setVisible(true); } }); jp_center.add(jb_string); } { // file button: jb_file.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { jd_addFileDialog.setVisible(true); } }); jp_center.add(jb_file); } jp_border.add(jp_center, BorderLayout.CENTER); JPanel jp_east = new JPanel(new FlowLayout(FlowLayout.RIGHT)); { // config button: jb_config.setToolTipText("Set multipart mode"); jb_config.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { jpmConfig.show(jb_config, jb_config.getBounds().x, jb_config.getBounds().y + jb_config.getBounds().height); } }); jp_east.add(jb_config); } jp_border.add(jp_east, BorderLayout.EAST); add(jp_border, BorderLayout.NORTH); } // Center: JScrollPane jsp = new JScrollPane(jt); add(jsp, BorderLayout.CENTER); } private void quickView() { final int row = jt.getSelectedRow(); if(row != -1) { ReqEntityPart entity = model.getEntityInRow(row); view.showMessage("Quick View", entity.toString()); } } @Override public void enableBody() { jb_string.setEnabled(true); jb_file.setEnabled(true); jt.setEnabled(true); } @Override public void disableBody() { jb_string.setEnabled(false); jb_file.setEnabled(false); jt.setEnabled(false); } @Override public void clear() { rbBrowserCompatible.setSelected(true); model.clear(); } @Override public void setEntity(ReqEntity entity) { if(entity instanceof ReqEntityMultipart) { ReqEntityMultipart e = (ReqEntityMultipart) entity; MultipartMode format = e.getMode(); switch(format) { case BROWSER_COMPATIBLE: rbBrowserCompatible.setSelected(true); break; case RFC_6532: rbRFC6532.setSelected(true); break; case STRICT: rbStrict.setSelected(true); break; default: rbStrict.setSelected(true); } List<ReqEntityPart> parts = e.getBody(); for(ReqEntityPart part: parts) { model.addPartLast(part); } } } @Override public ReqEntity getEntity() { MultipartMode format = null; if(rbBrowserCompatible.isSelected()) { format = MultipartMode.BROWSER_COMPATIBLE; } else if(rbRFC6532.isSelected()) { format = MultipartMode.RFC_6532; } else if(rbStrict.isSelected()) { format = MultipartMode.STRICT; } ReqEntity entity = new ReqEntityMultipartBean( (LinkedList<ReqEntityPart>)model.list.clone(), format); return entity; } @Override public Component getComponent() { return this; } }
package net.runelite.client.plugins.loottracker; import com.google.common.base.Strings; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.function.BiConsumer; import java.util.function.ToLongFunction; import java.util.stream.Collectors; import javax.annotation.Nullable; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.SwingConstants; import javax.swing.border.EmptyBorder; import lombok.AccessLevel; import lombok.Getter; import net.runelite.api.ItemID; import net.runelite.client.game.ItemManager; import net.runelite.client.ui.ColorScheme; import net.runelite.client.ui.FontManager; import net.runelite.client.util.AsyncBufferedImage; import net.runelite.client.util.ImageUtil; import net.runelite.client.util.QuantityFormatter; import net.runelite.client.util.Text; import net.runelite.http.api.loottracker.LootRecordType; class LootTrackerBox extends JPanel { private static final int ITEMS_PER_ROW = 5; private static final int TITLE_PADDING = 5; private final JPanel itemContainer = new JPanel(); private final JLabel priceLabel = new JLabel(); private final JLabel subTitleLabel = new JLabel(); private final JPanel logTitle = new JPanel(); private final ItemManager itemManager; @Getter(AccessLevel.PACKAGE) private final String id; private final LootRecordType lootRecordType; private final LootTrackerPriceType priceType; private final boolean showPriceType; private int kills; @Getter private final List<LootTrackerItem> items = new ArrayList<>(); private long totalPrice; private final boolean hideIgnoredItems; private final BiConsumer<String, Boolean> onItemToggle; LootTrackerBox( final ItemManager itemManager, final String id, final LootRecordType lootRecordType, @Nullable final String subtitle, final boolean hideIgnoredItems, final LootTrackerPriceType priceType, final boolean showPriceType, final BiConsumer<String, Boolean> onItemToggle, final BiConsumer<String, Boolean> onEventToggle, final boolean eventIgnored) { this.id = id; this.lootRecordType = lootRecordType; this.itemManager = itemManager; this.onItemToggle = onItemToggle; this.hideIgnoredItems = hideIgnoredItems; this.priceType = priceType; this.showPriceType = showPriceType; setLayout(new BorderLayout(0, 1)); setBorder(new EmptyBorder(5, 0, 0, 0)); logTitle.setLayout(new BoxLayout(logTitle, BoxLayout.X_AXIS)); logTitle.setBorder(new EmptyBorder(7, 7, 7, 7)); logTitle.setBackground(eventIgnored ? ColorScheme.DARKER_GRAY_HOVER_COLOR : ColorScheme.DARKER_GRAY_COLOR.darker()); JLabel titleLabel = new JLabel(); titleLabel.setText(Text.removeTags(id)); titleLabel.setFont(FontManager.getRunescapeSmallFont()); titleLabel.setForeground(Color.WHITE); // Set a size to make BoxLayout truncate the name titleLabel.setMinimumSize(new Dimension(1, titleLabel.getPreferredSize().height)); logTitle.add(titleLabel); subTitleLabel.setFont(FontManager.getRunescapeSmallFont()); subTitleLabel.setForeground(ColorScheme.LIGHT_GRAY_COLOR); if (!Strings.isNullOrEmpty(subtitle)) { subTitleLabel.setText(subtitle); } logTitle.add(Box.createRigidArea(new Dimension(TITLE_PADDING, 0))); logTitle.add(subTitleLabel); logTitle.add(Box.createHorizontalGlue()); logTitle.add(Box.createRigidArea(new Dimension(TITLE_PADDING, 0))); priceLabel.setFont(FontManager.getRunescapeSmallFont()); priceLabel.setForeground(ColorScheme.LIGHT_GRAY_COLOR); logTitle.add(priceLabel); add(logTitle, BorderLayout.NORTH); add(itemContainer, BorderLayout.CENTER); // Create popup menu for ignoring the loot event final JPopupMenu popupMenu = new JPopupMenu(); popupMenu.setBorder(new EmptyBorder(5, 5, 5, 5)); this.setComponentPopupMenu(popupMenu); final JMenuItem toggle = new JMenuItem(eventIgnored ? "Include loot" : "Hide loot"); toggle.addActionListener(e -> onEventToggle.accept(id, !eventIgnored)); popupMenu.add(toggle); } /** * Returns total amount of kills * * @return total amount of kills */ private int getTotalKills() { return kills; } /** * Checks if this box matches specified record * * @param record loot record * @return true if match is made */ boolean matches(final LootTrackerRecord record) { return record.getTitle().equals(id) && record.getType() == lootRecordType; } /** * Checks if this box matches specified id and type * * @param id other record id * @param type other record type * @return true if match is made */ boolean matches(final String id, final LootRecordType type) { if (id == null) { return true; } return this.id.equals(id) && lootRecordType == type; } /** * Adds an record's data into a loot box. */ void addKill(final LootTrackerRecord record) { if (!matches(record)) { throw new IllegalArgumentException(record.toString()); } kills += record.getKills(); outer: for (LootTrackerItem item : record.getItems()) { final int mappedItemId = LootTrackerMapping.map(item.getId(), item.getName()); // Combine it into an existing item if one already exists for (int idx = 0; idx < items.size(); ++idx) { LootTrackerItem i = items.get(idx); if (mappedItemId == i.getId()) { items.set(idx, new LootTrackerItem(i.getId(), i.getName(), i.getQuantity() + item.getQuantity(), i.getGePrice(), i.getHaPrice(), i.isIgnored())); continue outer; } } final LootTrackerItem mappedItem = mappedItemId == item.getId() ? item // reuse existing item : new LootTrackerItem(mappedItemId, item.getName(), item.getQuantity(), item.getGePrice(), item.getHaPrice(), item.isIgnored()); items.add(mappedItem); } } void rebuild() { buildItems(); String priceTypeString = " "; if (showPriceType) { priceTypeString = priceType == LootTrackerPriceType.HIGH_ALCHEMY ? "HA: " : "GE: "; } priceLabel.setText(priceTypeString + QuantityFormatter.quantityToStackSize(totalPrice) + " gp"); priceLabel.setToolTipText(QuantityFormatter.formatNumber(totalPrice) + " gp"); final long kills = getTotalKills(); if (kills > 1) { subTitleLabel.setText("x " + kills); subTitleLabel.setToolTipText(QuantityFormatter.formatNumber(totalPrice / kills) + " gp (average)"); } validate(); repaint(); } void collapse() { if (!isCollapsed()) { itemContainer.setVisible(false); applyDimmer(false, logTitle); } } void expand() { if (isCollapsed()) { itemContainer.setVisible(true); applyDimmer(true, logTitle); } } boolean isCollapsed() { return !itemContainer.isVisible(); } private void applyDimmer(boolean brighten, JPanel panel) { for (Component component : panel.getComponents()) { Color color = component.getForeground(); component.setForeground(brighten ? color.brighter() : color.darker()); } } /** * This method creates stacked items from the item list, calculates total price and then * displays all the items in the UI. */ private void buildItems() { totalPrice = 0; List<LootTrackerItem> items = this.items; if (hideIgnoredItems) { items = items.stream().filter(item -> !item.isIgnored()).collect(Collectors.toList()); } boolean isHidden = items.isEmpty(); setVisible(!isHidden); if (isHidden) { return; } ToLongFunction<LootTrackerItem> getPrice = priceType == LootTrackerPriceType.HIGH_ALCHEMY ? LootTrackerItem::getTotalHaPrice : LootTrackerItem::getTotalGePrice; totalPrice = items.stream() .mapToLong(getPrice) .sum(); items.sort(Comparator.comparingLong(getPrice).reversed()); // Calculates how many rows need to be display to fit all items final int rowSize = ((items.size() % ITEMS_PER_ROW == 0) ? 0 : 1) + items.size() / ITEMS_PER_ROW; itemContainer.removeAll(); itemContainer.setLayout(new GridLayout(rowSize, ITEMS_PER_ROW, 1, 1)); for (int i = 0; i < rowSize * ITEMS_PER_ROW; i++) { final JPanel slotContainer = new JPanel(); slotContainer.setBackground(ColorScheme.DARKER_GRAY_COLOR); if (i < items.size()) { final LootTrackerItem item = items.get(i); final JLabel imageLabel = new JLabel(); imageLabel.setToolTipText(buildToolTip(item)); imageLabel.setVerticalAlignment(SwingConstants.CENTER); imageLabel.setHorizontalAlignment(SwingConstants.CENTER); AsyncBufferedImage itemImage = itemManager.getImage(item.getId(), item.getQuantity(), item.getQuantity() > 1); if (item.isIgnored()) { Runnable addTransparency = () -> { BufferedImage transparentImage = ImageUtil.alphaOffset(itemImage, .3f); imageLabel.setIcon(new ImageIcon(transparentImage)); }; itemImage.onLoaded(addTransparency); addTransparency.run(); } else { itemImage.addTo(imageLabel); } slotContainer.add(imageLabel); // Create popup menu final JPopupMenu popupMenu = new JPopupMenu(); popupMenu.setBorder(new EmptyBorder(5, 5, 5, 5)); slotContainer.setComponentPopupMenu(popupMenu); final JMenuItem toggle = new JMenuItem("Toggle item"); toggle.addActionListener(e -> { item.setIgnored(!item.isIgnored()); onItemToggle.accept(item.getName(), item.isIgnored()); }); popupMenu.add(toggle); } itemContainer.add(slotContainer); } itemContainer.repaint(); } private static String buildToolTip(LootTrackerItem item) { final String name = item.getName(); final int quantity = item.getQuantity(); final long gePrice = item.getTotalGePrice(); final long haPrice = item.getTotalHaPrice(); final String ignoredLabel = item.isIgnored() ? " - Ignored" : ""; final StringBuilder sb = new StringBuilder("<html>"); sb.append(name).append(" x ").append(QuantityFormatter.formatNumber(quantity)).append(ignoredLabel); if (item.getId() == ItemID.COINS_995) { sb.append("</html>"); return sb.toString(); } sb.append("<br>GE: ").append(QuantityFormatter.quantityToStackSize(gePrice)); if (quantity > 1) { sb.append(" (").append(QuantityFormatter.quantityToStackSize(item.getGePrice())).append(" ea)"); } if (item.getId() == ItemID.PLATINUM_TOKEN) { sb.append("</html>"); return sb.toString(); } sb.append("<br>HA: ").append(QuantityFormatter.quantityToStackSize(haPrice)); if (quantity > 1) { sb.append(" (").append(QuantityFormatter.quantityToStackSize(item.getHaPrice())).append(" ea)"); } sb.append("</html>"); return sb.toString(); } }
package com.cagricelebi.securechat.web.servlet; import com.cagricelebi.securechat.lib.util.Helper; import com.cagricelebi.securechat.lib.dao.UserDao; import com.cagricelebi.securechat.lib.logging.Logger; import com.cagricelebi.securechat.lib.model.User; import java.io.IOException; import javax.inject.Inject; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * * @author azureel */ @WebServlet(name = "LoginServlet", urlPatterns = {"/login"}) public class LoginServlet extends HttpServlet { private static final Logger logger = Logger.getLogger(LoginServlet.class); @Inject UserDao userDao; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); try { if (Helper.isEmpty(password) || Helper.isEmpty(password)) { RequestDispatcher requestDispatcher = request.getRequestDispatcher("/login.jsp"); requestDispatcher.forward(request, response); return; } User user = userDao.login(username, password.toCharArray()); if (user == null) { request.setAttribute("message", "Wrong username or password."); RequestDispatcher requestDispatcher = request.getRequestDispatcher("/login.jsp"); requestDispatcher.forward(request, response); return; } HttpSession session = request.getSession(true); session.setAttribute("user", user); ServletContext servletContext = getServletContext(); String contextPath = servletContext.getContextPath(); response.sendRedirect(contextPath + "/home"); } catch (Exception e) { logger.error(e); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
package de.larmic.butterfaces.component.showcase.tree; import de.larmic.butterfaces.component.partrenderer.StringUtils; import de.larmic.butterfaces.component.showcase.AbstractInputShowcase; import de.larmic.butterfaces.component.showcase.example.AbstractCodeExample; import de.larmic.butterfaces.component.showcase.example.JavaCodeExample; import de.larmic.butterfaces.component.showcase.example.XhtmlCodeExample; import de.larmic.butterfaces.component.showcase.text.FacetType; import de.larmic.butterfaces.model.tree.Node; import javax.faces.model.SelectItem; import javax.faces.view.ViewScoped; import javax.inject.Named; import java.io.Serializable; import java.util.ArrayList; import java.util.List; @Named @ViewScoped @SuppressWarnings("serial") public class TreeBoxShowcase extends AbstractInputShowcase implements Serializable { private final ShowcaseTreeNode showcaseTreeNode = new ShowcaseTreeNode(); private FacetType selectedFacetType = FacetType.NONE; private String placeholder = "Enter text..."; private boolean autoFocus; private boolean hideRootNode; @Override protected Object initValue() { return null; } @Override public String getReadableValue() { return this.getValue() != null ? ((Node) this.getValue()).getTitle() : null; } @Override public void buildCodeExamples(final List<AbstractCodeExample> codeExamples) { codeExamples.add(buildXhtmlCodeExample()); codeExamples.add(createMyBeanCodeExample()); if (isValidation()) { codeExamples.add(buildValidatorCodeExample()); } generateDemoCSS(codeExamples); } private XhtmlCodeExample buildXhtmlCodeExample() { final XhtmlCodeExample xhtmlCodeExample = new XhtmlCodeExample(false); xhtmlCodeExample.appendInnerContent(" <b:treeBox id=\"input\""); xhtmlCodeExample.appendInnerContent(" label=\"" + this.getLabel() + "\""); xhtmlCodeExample.appendInnerContent(" hideLabel=\"" + isHideLabel() + "\""); xhtmlCodeExample.appendInnerContent(" value=\"" + this.getValue() + "\""); xhtmlCodeExample.appendInnerContent(" values=\"#{myBean.values}\""); xhtmlCodeExample.appendInnerContent(" placeholder=\"" + this.getPlaceholder() + "\""); xhtmlCodeExample.appendInnerContent(" styleClass=\"" + StringUtils.getNotNullValue(this.getStyleClass(), "") + "\""); xhtmlCodeExample.appendInnerContent(" readonly=\"" + this.isReadonly() + "\""); xhtmlCodeExample.appendInnerContent(" disabled=\"" + this.isDisabled() + "\""); xhtmlCodeExample.appendInnerContent(" required=\"" + this.isRequired() + "\""); xhtmlCodeExample.appendInnerContent(" autoFocus=\"" + this.isAutoFocus() + "\""); xhtmlCodeExample.appendInnerContent(" rendered=\"" + this.isRendered() + "\">"); this.addAjaxTag(xhtmlCodeExample, "change"); if (this.isValidation()) { xhtmlCodeExample.appendInnerContent(" <f:validator validatorId=\"treeBoxValidator\" />"); } if (StringUtils.isNotEmpty(getTooltip())) { xhtmlCodeExample.appendInnerContent(" <b:tooltip>"); xhtmlCodeExample.appendInnerContent(" " + getTooltip()); xhtmlCodeExample.appendInnerContent(" </b:tooltip>"); } xhtmlCodeExample.appendInnerContent(" </b:treeBox>\n", false); this.addOutputExample(xhtmlCodeExample); return xhtmlCodeExample; } private JavaCodeExample createMyBeanCodeExample() { final JavaCodeExample myBean = new JavaCodeExample("MyBean.java", "mybean", "treeBox.demo", "MyBean", true); myBean.addImport("import de.larmic.butterfaces.model.tree.Node"); myBean.addImport("import de.larmic.butterfaces.model.tree.DefaultNodeImpl"); myBean.addImport("import javax.faces.view.ViewScoped"); myBean.addImport("import javax.inject.Named"); myBean.appendInnerContent(" private Node rootNode;\n"); myBean.appendInnerContent(" public Node getValues() {"); myBean.appendInnerContent(" if (rootNode == null) {"); //if (selectedTreeTemplateType == TreeTemplateType.CUSTOM) { // myBean.appendInnerContent(" final Node firstChild = new DefaultNodeImpl(\"firstChild\", new NodeData());"); //} else { myBean.appendInnerContent(" final Node firstChild = new DefaultNodeImpl(\"firstChild\");"); myBean.appendInnerContent(" firstChild.setDescription(\"23 unread\");"); if (showcaseTreeNode.getSelectedIconType() == TreeIconType.GLYPHICON) { myBean.appendInnerContent(" firstChild.setGlyphiconIcon(\"glyphicon glyphicon-folder-open\");"); } else if (showcaseTreeNode.getSelectedIconType() == TreeIconType.IMAGE) { myBean.appendInnerContent(" firstChild.setImageIcon(\"some/path/16.png\");"); } //if (selectedTreeTemplateType == TreeTemplateType.CUSTOM) { // myBean.appendInnerContent(" final Node secondChild = new DefaultNodeImpl(\"second\", new NodeData());"); //} else { myBean.appendInnerContent(" final Node secondChild = new DefaultNodeImpl(\"second\");"); if (showcaseTreeNode.getSelectedIconType() == TreeIconType.GLYPHICON) { myBean.appendInnerContent(" secondChild.setGlyphiconIcon(\"glyphicon glyphicon-folder-open\");"); } else if (showcaseTreeNode.getSelectedIconType() == TreeIconType.IMAGE) { myBean.appendInnerContent(" secondChild.setImageIcon(\"some/path/16.png\");"); } //if (selectedTreeTemplateType == TreeTemplateType.CUSTOM) { // myBean.appendInnerContent(" secondChild.getSubNodes().add(new DefaultNodeImpl(\"...\"), new NodeData())"); //} else { myBean.appendInnerContent(" secondChild.getSubNodes().add(new DefaultNodeImpl(\"...\"))"); myBean.appendInnerContent(" ..."); //if (selectedTreeTemplateType == TreeTemplateType.CUSTOM) { // myBean.appendInnerContent(" rootNode = new DefaultNodeImpl(\"rootNode\", new NodeData());"); //} else { myBean.appendInnerContent(" rootNode = new DefaultNodeImpl(\"rootNode\");"); if (showcaseTreeNode.getSelectedIconType() == TreeIconType.IMAGE) { myBean.appendInnerContent(" rootNode.setImageIcon(\"some/path/16.png\");"); } else if (showcaseTreeNode.getSelectedIconType() == TreeIconType.GLYPHICON) { myBean.appendInnerContent(" rootNode.setGlyphiconIcon(\"glyphicon glyphicon-folder-open\");"); } myBean.appendInnerContent(" rootNode.getSubNodes().add(firstChild);"); myBean.appendInnerContent(" rootNode.getSubNodes().add(secondChild);"); myBean.appendInnerContent(" }"); myBean.appendInnerContent(" return rootNode;"); myBean.appendInnerContent(" }"); return myBean; } private AbstractCodeExample buildValidatorCodeExample() { final JavaCodeExample codeExample = new JavaCodeExample("TreeBoxValidator.java", "validator", "treeBox", "TreeBoxValidator", false, "@FacesValidator"); codeExample.addInterfaces("Validator"); codeExample.addImport("de.larmic.butterfaces.model.tree.Node"); codeExample.addImport("javax.faces.application.FacesMessage"); codeExample.addImport("javax.faces.component.UIComponent"); codeExample.addImport("javax.faces.context.FacesContext"); codeExample.addImport("javax.faces.validator.FacesValidator"); codeExample.addImport("javax.faces.validator.Validator"); codeExample.addImport("javax.faces.validator.ValidatorException"); codeExample.appendInnerContent(" private static final String ERROR_MESSAGE = \"Selecting root node is not allowed\";\n"); codeExample.appendInnerContent(" @Override"); codeExample.appendInnerContent(" public void validate(FacesContext context,"); codeExample.appendInnerContent(" UIComponent component,"); codeExample.appendInnerContent(" Object value) throws ValidatorException {"); codeExample.appendInnerContent(" if (value instanceof Node"); codeExample.appendInnerContent(" && \"rootNode\".equals(((Node) value).getTitle())) {"); codeExample.appendInnerContent(" final FacesMessage message = new FacesMessage(ERROR_MESSAGE);"); codeExample.appendInnerContent(" throw new ValidatorException(message);"); codeExample.appendInnerContent(" }"); codeExample.appendInnerContent(" }"); return codeExample; } public List<SelectItem> getAvailableFacetTypes() { final List<SelectItem> items = new ArrayList<>(); for (final FacetType type : FacetType.values()) { items.add(new SelectItem(type, type.label)); } return items; } public String getPlaceholder() { return this.placeholder; } public void setPlaceholder(final String placeholder) { this.placeholder = placeholder; } public boolean isAutoFocus() { return autoFocus; } public void setAutoFocus(boolean autoFocus) { this.autoFocus = autoFocus; } public ShowcaseTreeNode getShowcaseTreeNode() { return showcaseTreeNode; } public void setHideRootNode(boolean hideRootNode) { this.hideRootNode = hideRootNode; } public boolean isHideRootNode() { return hideRootNode; } public FacetType getSelectedFacetType() { return selectedFacetType; } public void setSelectedFacetType(FacetType selectedFacetType) { this.selectedFacetType = selectedFacetType; } }
package org.jasig.portal; import org.jasig.portal.channels.CError; import javax.servlet.http.*; import java.util.Hashtable; import java.util.Enumeration; import java.util.Map; import org.xml.sax.*; import org.w3c.dom.*; import java.io.*; // this class shall have the burden of squeezing content // out of channels. // future prospects: // - Wrap IChannel classes // this should be done by parsing through // HTML that IChannel can output // - more complex caching ? // - Validation and timeouts // these two are needed for smooth operation of the portal // sometimes channels will timeout with information retreival // then the content should be skipped public class ChannelManager { private HttpServletRequest req; private HttpServletResponse res; private UserLayoutManager ulm; private PortalControlStructures pcs; private Hashtable channelTable; private Hashtable rendererTable; private String channelTarget; private Hashtable targetParams; public static String channelAddressingPathElement="channel"; public ChannelManager () { channelTable = new Hashtable (); rendererTable = new Hashtable (); } public ChannelManager (HttpServletRequest request, HttpServletResponse response, UserLayoutManager manager) { this (); this.req = request; this.res = response; this.ulm=manager; pcs=new PortalControlStructures(); pcs.setUserLayoutManager(ulm); pcs.setHttpServletRequest(req); pcs.setHttpServletResponse(res); pcs.setChannelManager(this); } public void setUserLayoutManager(UserLayoutManager m) { ulm=m; } public void setReqNRes (HttpServletRequest request, HttpServletResponse response) { this.req = request; this.res = response; this.pcs.setHttpServletRequest(request); this.pcs.setHttpServletResponse(response); rendererTable.clear (); processRequestChannelParameters (request); } /** * Look through request parameters for "channelTarget" and * pass corresponding actions/params to the channel * @param the request object */ private void processRequestChannelParameters (HttpServletRequest req) { // clear the previous settings channelTarget = null; targetParams = new Hashtable (); String sp=req.getServletPath(); if(sp!=null) { int si1=sp.indexOf(this.channelAddressingPathElement+"/"); if(si1!=-1) { si1+=channelAddressingPathElement.length()+1; int si2=sp.indexOf("/",si1); if(si2!=-1) { channelTarget=sp.substring(si1,si2); if(channelTarget==null) { Logger.log(Logger.ERROR,"ChannelManager.processRequestChannelParameters() : malformed channel address. Null channel target ID."); return; } Logger.log(Logger.DEBUG,"ChannelManager::processRequestChannelParameters() : channelTarget=\""+channelTarget+"\"."); Enumeration en = req.getParameterNames (); if (en != null) { while (en.hasMoreElements ()) { String pName= (String) en.nextElement (); if (!pName.equals ("channelTarget")) targetParams.put (pName, req.getParameterValues(pName)); } } // check if the channel is an IPrivilegedChannel, and if it is, // pass portal control structures and runtime data. Object chObj; if ((chObj=channelTable.get(channelTarget)) == null) { try { chObj=instantiateChannel(channelTarget); } catch (Exception e) { CError errorChannel=new CError(CError.SET_STATIC_DATA_EXCEPTION,e,channelTarget,null); channelTable.put(channelTarget,errorChannel); chObj=errorChannel; Logger.log(Logger.ERROR,"ChannelManager::processRequestChannelParameters() : unable to pass find/create an instance of a channel. Bogus ID ? ! (id=\""+channelTarget+"\")."); } } if(chObj!=null && (chObj instanceof IPrivilegedChannel)) { IPrivilegedChannel isc=(IPrivilegedChannel) chObj; try { isc.setPortalControlStructures(pcs); } catch (Exception e) { channelTable.remove(isc); CError errorChannel=new CError(CError.SET_PCS_EXCEPTION,e,channelTarget,isc); channelTable.put(channelTarget,errorChannel); isc=errorChannel; // set portal control structures try { errorChannel.setPortalControlStructures(pcs); } catch (Exception e2) { // things are looking bad for our hero StringWriter sw=new StringWriter(); e2.printStackTrace(new PrintWriter(sw)); sw.flush(); Logger.log(Logger.ERROR,"ChannelManager::outputChannels : Error channel threw ! "+sw.toString()); } } ChannelRuntimeData rd = new ChannelRuntimeData (); rd.setParameters(targetParams); rd.setHttpRequest (req); /* String reqURI = req.getRequestURI (); reqURI = reqURI.substring (reqURI.lastIndexOf ("/") + 1, reqURI.length ()); rd.setBaseActionURL (reqURI + "?channelTarget=" + channelTarget + "&");*/ rd.setBaseActionURL(req.getContextPath()+"/channel/"+channelTarget+"/channelTarget.uP"); try { isc.setRuntimeData (rd); } catch (Exception e) { channelTable.remove(isc); CError errorChannel=new CError(CError.SET_RUNTIME_DATA_EXCEPTION,e,channelTarget,isc); channelTable.put(channelTarget,errorChannel); isc=errorChannel; // demand output try { ChannelRuntimeData erd = new ChannelRuntimeData (); erd.setHttpRequest (req); erd.setBaseActionURL(req.getContextPath()+"/channel/"+channelTarget+"/channelTarget.uP"); errorChannel.setPortalControlStructures(pcs); errorChannel.setRuntimeData (erd); } catch (Exception e2) { // things are looking bad for our hero StringWriter sw=new StringWriter(); e2.printStackTrace(new PrintWriter(sw)); sw.flush(); Logger.log(Logger.ERROR,"ChannelManager::outputChannels : Error channel threw ! "+sw.toString()); } } } } } } } public IChannel instantiateChannel(String chanID) { if (channelTable.get(chanID) != null) { // reinstantiation channelTable.remove(chanID); } // get channel information from the user layout manager Element elChannel=(Element) ulm.getCleanNode(chanID); if(elChannel!=null) { String className=elChannel.getAttribute("class"); long timeOut=java.lang.Long.parseLong(elChannel.getAttribute("timeout")); Hashtable params=new Hashtable(); NodeList paramsList=elChannel.getElementsByTagName("parameter"); int nnodes=paramsList.getLength(); for(int i=0;i<nnodes;i++) { Element param=(Element) paramsList.item(i); params.put(param.getAttribute("name"),param.getAttribute("value")); } try { return instantiateChannel(chanID,className,timeOut,params); } catch (Exception ex) { Logger.log(Logger.ERROR,"ChannelManager::instantiateChannel() : unable to instantiate channel class \""+className+"\". "+ex); return null; } } else return null; } private IChannel instantiateChannel(String chanID, String className, long timeOut, Hashtable params) throws Exception { IChannel ch=null; ch = (org.jasig.portal.IChannel) Class.forName (className).newInstance (); // construct a ChannelStaticData object ChannelStaticData sd = new ChannelStaticData (); sd.setChannelID (chanID); sd.setTimeout (timeOut); sd.setParameters (params); ch.setStaticData (sd); channelTable.put (chanID,ch); return ch; } /** * Start rendering the channel in a separate thread. * This function retreives a particular channel from cache, passes parameters to the * channel and then creates a new ChannelRenderer object to render the channel in a * separate thread. * @param chanID channel ID (unique) * @param className name of the channel class * @param params a table of parameters */ public void startChannelRendering (String chanID, String className, long timeOut, Hashtable params) { // see if the channel is cached IChannel ch; if ((ch = (IChannel) channelTable.get (chanID)) == null) { try { ch=instantiateChannel(chanID,className,timeOut,params); } catch (Exception e) { CError errorChannel=new CError(CError.SET_STATIC_DATA_EXCEPTION,e,chanID,null); channelTable.put(chanID,errorChannel); ch=errorChannel; } } ChannelRuntimeData rd=null; if(!chanID.equals(channelTarget)) { if((ch instanceof IPrivilegedChannel)) { // send the control structures try { ((IPrivilegedChannel) ch).setPortalControlStructures(pcs); } catch (Exception e) { channelTable.remove(ch); CError errorChannel=new CError(CError.SET_PCS_EXCEPTION,e,chanID,ch); channelTable.put(chanID,errorChannel); ch=errorChannel; // set portal control structures try { errorChannel.setPortalControlStructures(pcs); } catch (Exception e2) { // things are looking bad for our hero StringWriter sw=new StringWriter(); e2.printStackTrace(new PrintWriter(sw)); sw.flush(); Logger.log(Logger.ERROR,"ChannelManager::outputChannels : Error channel threw ! "+sw.toString()); } } } rd = new ChannelRuntimeData (); rd.setHttpRequest (req); rd.setBaseActionURL(req.getContextPath()+"/channel/"+chanID+"/channelTarget.uP"); } else { if(!(ch instanceof IPrivilegedChannel)) { rd = new ChannelRuntimeData (); rd.setParameters(targetParams); rd.setHttpRequest (req); rd.setBaseActionURL(req.getContextPath()+"/channel/"+chanID+"/channelTarget.uP"); } } ChannelRenderer cr = new ChannelRenderer (ch,rd); cr.setTimeout (timeOut); cr.startRendering (); rendererTable.put (chanID,cr); } /** * Output channel content. * Note that startChannelRendering had to be invoked on this channel prior to calling this function. * @param chanID unique channel ID * @param dh document handler that will receive channel content */ public void outputChannel (String chanID, DocumentHandler dh) { ChannelRenderer cr; if ((cr = (ChannelRenderer) rendererTable.get (chanID)) != null) { rendererTable.remove(chanID); ChannelSAXStreamFilter custodian = new ChannelSAXStreamFilter (dh); try { int out = cr.outputRendering (custodian); if(out==cr.RENDERING_TIMED_OUT) { // rendering has timed out IChannel badChannel=(IChannel) channelTable.get(chanID); channelTable.remove(badChannel); CError errorChannel=new CError(CError.TIMEOUT_EXCEPTION,(Exception) null,chanID,badChannel); channelTable.put(chanID,errorChannel); // demand output try { ChannelRuntimeData rd = new ChannelRuntimeData (); rd.setHttpRequest (req); rd.setBaseActionURL(req.getContextPath()+"/channel/"+chanID+"/channelTarget.uP"); errorChannel.setRuntimeData (rd); errorChannel.setPortalControlStructures(pcs); errorChannel.renderXML(dh); } catch (Exception e) { // things are looking bad for our hero StringWriter sw=new StringWriter(); e.printStackTrace(new PrintWriter(sw)); sw.flush(); Logger.log(Logger.ERROR,"ChannelManager::outputChannels : Error channel threw ! "+sw.toString()); } } } catch (InternalPortalException ipe) { // this implies that the channel has thrown an exception during // renderXML() call. No events had been placed onto the DocumentHandler, // so that an Error channel can be rendered in place. Exception channelException=ipe.getException(); if(channelException!=null) { // see if the renderXML() has thrown a PortalException // hand it over to the Error channel IChannel badChannel=(IChannel) channelTable.get(chanID); channelTable.remove(badChannel); CError errorChannel=new CError(CError.RENDER_TIME_EXCEPTION,channelException,chanID,badChannel); channelTable.put(chanID,errorChannel); // demand output try { ChannelRuntimeData rd = new ChannelRuntimeData (); rd.setHttpRequest (req); rd.setBaseActionURL(req.getContextPath()+"/channel/"+chanID+"/channelTarget.uP"); errorChannel.setRuntimeData (rd); errorChannel.setPortalControlStructures(pcs); errorChannel.renderXML(dh); } catch (Exception e) { // things are looking bad for our hero StringWriter sw=new StringWriter(); e.printStackTrace(new PrintWriter(sw)); sw.flush(); Logger.log(Logger.ERROR,"ChannelManager::outputChannels : Error channel threw ! "+sw.toString()); } } else { Logger.log(Logger.ERROR,"ChannelManager::outputChannels() : received InternalPortalException that doesn't carry a channel exception inside !?"); } } catch (Exception e) { // This implies that the channel has been successful in completing renderXML() // method, but somewhere down the line things went wrong. Most likely, // a buffer output routine threw. This means that we are likely to have partial // output in the document handler. Really bad ! Logger.log(Logger.ERROR,"ChannelManager::outputChannel() : post-renderXML() processing threw!"+e); } } else { Logger.log (Logger.ERROR,"ChannelManager::outputChannel() : ChannelRenderer for chanID=\""+chanID+"\" is absent from cache !!!"); } } /** * passes Layout-level event to a channel * @param channel ID * @param LayoutEvent object */ public void passLayoutEvent (String chanID, LayoutEvent le) { IChannel ch= (IChannel) channelTable.get (chanID); if (ch != null) { ch.receiveEvent (le); } else Logger.log (Logger.ERROR, "ChannelManager::passLayoutEvent() : trying to pass an event to a channel that is not in cache. (cahnel=\"" + chanID + "\")"); } /** * Directly places a channel instance into the hashtable of active channels. * This is designed to be used by the error channel only. */ public void addChannelInstance(String channelID,IChannel channelInstance) { if(channelTable.get(channelID)!=null) channelTable.remove(channelID); channelTable.put(channelID,channelInstance); } }
package de.ptb.epics.eve.editor.views.motoraxisview; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Iterator; import java.util.List; import org.apache.log4j.Logger; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.events.VerifyListener; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.ViewPart; import de.ptb.epics.eve.data.scandescription.Axis; import de.ptb.epics.eve.data.scandescription.ScanModule; import de.ptb.epics.eve.data.scandescription.errors.AxisError; import de.ptb.epics.eve.data.scandescription.errors.IModelError; /** * <code>MotorAxisStartStopStedwidthComposite</code> is a composite to define * Start, Stop, Stepwidth and Stepcount of the motor axis. (Shown if Step * Function is either Add or Multiply) * * @author Hartmut Scherr * @author Marcus Michalsky */ public class MotorAxisStartStopStepwidthComposite extends Composite { // logging private static Logger logger = Logger.getLogger(MotorAxisStartStopStepwidthComposite.class.getName()); // the underlying model the composite takes the data from private Axis currentAxis; private MotorAxisView motorAxisView; // start elements private Button autoFillStartRadioButton; private AutoFillStartRadioButtonSelectionListener autoFillStartRadioButtonSelectionListener; private CCombo startCombo; private ComboVerifyListener startComboVerifyListener; private StartComboModifyListener startComboModifyListener; private StartComboSelectionListener startComboSelectionListener; private Label startErrorLabel; // end of: start elements // stop elements private Button autoFillStopRadioButton; private AutoFillStopRadioButtonSelectionListener autoFillStopRadioButtonSelectionListener; private CCombo stopCombo; private ComboVerifyListener stopComboVerifyListener; private StopComboModifyListener stopComboModifyListener; private StopComboSelectionListener stopComboSelectionListener; private Label stopErrorLabel; // end of: stop elements // step width elements private Button autoFillStepwidthRadioButton; private AutoFillStepwidthRadioButtonSelectionListener autoFillStepwidthRadioButtonSelectionListener; private Text stepwidthText; private TextDoubleVerifyListener stepwidthTextVerifyListener; private StepwidthTextModifyListener stepwidthTextModifyListener; private Label stepwidthErrorLabel; // end of: step width elements // step count elements private Button autoFillStepcountRadioButton; private AutoFillStepcountRadioButtonSelectionListener autoFillStepcountRadioButtonSelectionListener; private Text stepcountText; private TextNumberVerifyListener stepcountTextVerifyListener; private StepcountTextModifyListener stepcountTextModifyListener; private Label stepcountErrorLabel; // end of step count elements private Button mainAxisCheckBox; private MainAxisCheckBoxSelectionListener mainAxisCheckBoxSelectionListener; /** * Constructs a <code>MotorAxisStartStopStepwidthComposite</code>. * * @param parent the parent composite * @param style the style * @param parentView the view this composite is contained in */ public MotorAxisStartStopStepwidthComposite(final Composite parent, final int style, final ViewPart parentView) { super(parent, style); this.motorAxisView = (MotorAxisView) parentView; // the composite gets a 3 column grid GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 3; this.setLayout(gridLayout); // initialize start elements this.autoFillStartRadioButton = new Button(this, SWT.RADIO); this.autoFillStartRadioButton.setText("Start:"); this.autoFillStartRadioButton.setToolTipText( "Mark to enable auto-fill for start value."); this.autoFillStartRadioButtonSelectionListener = new AutoFillStartRadioButtonSelectionListener(); this.autoFillStartRadioButton.addSelectionListener( autoFillStartRadioButtonSelectionListener); this.startCombo = new CCombo(this, SWT.BORDER); this.startComboVerifyListener = new ComboVerifyListener(); this.startCombo.addVerifyListener(startComboVerifyListener); this.startComboModifyListener = new StartComboModifyListener(); this.startCombo.addModifyListener(startComboModifyListener); this.startComboSelectionListener = new StartComboSelectionListener(); this.startCombo.addSelectionListener(startComboSelectionListener); GridData gridData = new GridData(); gridData.horizontalAlignment = GridData.FILL; gridData.grabExcessHorizontalSpace = true; this.startCombo.setLayoutData(gridData); this.startErrorLabel = new Label(this, SWT.NONE); // end of: initialize start elements // initialize stop elements this.autoFillStopRadioButton = new Button(this, SWT.RADIO); this.autoFillStopRadioButton.setText("Stop:"); this.autoFillStopRadioButton.setToolTipText( "Mark to enable auto-fill for stop value."); this.autoFillStopRadioButtonSelectionListener = new AutoFillStopRadioButtonSelectionListener(); this.autoFillStopRadioButton.addSelectionListener( autoFillStartRadioButtonSelectionListener); this.stopCombo = new CCombo(this, SWT.BORDER); this.stopComboVerifyListener = new ComboVerifyListener(); this.stopCombo.addVerifyListener(stopComboVerifyListener); this.stopComboModifyListener = new StopComboModifyListener(); this.stopCombo.addModifyListener(stopComboModifyListener); this.stopComboSelectionListener = new StopComboSelectionListener(); this.stopCombo.addSelectionListener(stopComboSelectionListener); gridData = new GridData(); gridData.horizontalAlignment = GridData.FILL; gridData.grabExcessHorizontalSpace = true; this.stopCombo.setLayoutData(gridData); this.stopErrorLabel = new Label(this, SWT.NONE); // end of: initialize stop elements // initialize step width elements this.autoFillStepwidthRadioButton = new Button(this, SWT.RADIO); this.autoFillStepwidthRadioButton.setText("Stepwidth:"); this.autoFillStepwidthRadioButton.setToolTipText( "Mark to enable auto-fill for stepwidth value."); this.autoFillStepwidthRadioButtonSelectionListener = new AutoFillStepwidthRadioButtonSelectionListener(); this.autoFillStepwidthRadioButton.addSelectionListener( autoFillStepwidthRadioButtonSelectionListener); this.stepwidthText = new Text(this, SWT.BORDER); this.stepwidthTextVerifyListener = new TextDoubleVerifyListener(); this.stepwidthText.addVerifyListener(stepwidthTextVerifyListener); this.stepwidthTextModifyListener = new StepwidthTextModifyListener(); this.stepwidthText.addModifyListener(stepwidthTextModifyListener); gridData = new GridData(); gridData.horizontalAlignment = GridData.FILL; gridData.grabExcessHorizontalSpace = true; this.stepwidthText.setLayoutData(gridData); this.stepwidthErrorLabel = new Label(this, SWT.NONE); // end of: initialize step width elements // initialize step count elements this.autoFillStepcountRadioButton = new Button(this, SWT.RADIO); this.autoFillStepcountRadioButton.setText("Stepcount:"); this.autoFillStepcountRadioButton.setToolTipText( "Mark to enable auto-fill for step count."); this.autoFillStepcountRadioButtonSelectionListener = new AutoFillStepcountRadioButtonSelectionListener(); this.autoFillStepcountRadioButton.addSelectionListener( autoFillStepcountRadioButtonSelectionListener); this.stepcountText = new Text(this, SWT.BORDER); this.stepcountTextVerifyListener = new TextNumberVerifyListener(); this.stepcountText.addVerifyListener(stepcountTextVerifyListener); this.stepcountTextModifyListener = new StepcountTextModifyListener(); this.stepcountText.addModifyListener(stepcountTextModifyListener); gridData = new GridData(); gridData.horizontalAlignment = GridData.FILL; gridData.grabExcessHorizontalSpace = true; this.stepcountText.setLayoutData(gridData); this.stepcountErrorLabel = new Label(this, SWT.NONE); // end of: initialize step count elements this.mainAxisCheckBox = new Button(this, SWT.CHECK); this.mainAxisCheckBox.setText("main axis"); gridData = new GridData(); gridData.horizontalAlignment = GridData.FILL; gridData.grabExcessHorizontalSpace = true; gridData.horizontalSpan = 3; this.mainAxisCheckBox.setLayoutData(gridData); this.mainAxisCheckBoxSelectionListener = new MainAxisCheckBoxSelectionListener(); this.mainAxisCheckBox.addSelectionListener( mainAxisCheckBoxSelectionListener); this.startCombo.setEnabled(false); this.stopCombo.setEnabled(false); this.stepwidthText.setEnabled(false); this.stepcountText.setEnabled(false); this.mainAxisCheckBox.setEnabled(false); } /** * calculate the height to see all entries of this composite * * @return the needed height of Composite to see all entries */ public int getTargetHeight() { return (mainAxisCheckBox.getBounds().y + mainAxisCheckBox.getBounds().height + 5); } /** * calculate the width to see all entries of this composite * * @return the needed width of Composite to see all entries */ public int getTargetWidth() { return (mainAxisCheckBox.getBounds().x + mainAxisCheckBox.getBounds().width + 5); } /** * Sets the {@link de.ptb.epics.eve.data.scandescription.Axis}. * * @param axis the {@link de.ptb.epics.eve.data.scandescription.Axis} that * should be set * @param stepcount the step count (generally the step count of the axis, * except when a main axis is set which is then used instead) * @param stepcount the step count of the main axis */ public void setCurrentAxis(final Axis axis, final double stepcount) { if(axis != null) logger.debug("set axis to: " + axis.getMotorAxis().getID()); else logger.debug("set axis to: null"); removeListeners(); this.currentAxis = axis; if(this.currentAxis != null) { if(this.currentAxis.getMotorAxis().getGoto().isDiscrete()) { this.startCombo.setItems(this.currentAxis.getMotorAxis(). getGoto().getDiscreteValues(). toArray(new String[0])); this.startCombo.setEditable(false); this.stopCombo.setItems(this.currentAxis.getMotorAxis(). getGoto().getDiscreteValues(). toArray(new String[0])); this.stopCombo.setEditable(false); } else { this.startCombo.setEditable(true); this.startCombo.setVisibleItemCount(0); this.stopCombo.setEditable(true); this.stopCombo.setVisibleItemCount(0); } this.startCombo.setText(this.currentAxis.getStart() != null ? this.currentAxis.getStart() : ""); this.startCombo.setSelection(new Point(0,0)); this.stopCombo.setText(this.currentAxis.getStop() != null ? this.currentAxis.getStop() : ""); this.stopCombo.setSelection(new Point(0,0)); this.stepwidthText.setText(this.currentAxis.getStepwidth() != null ? this.currentAxis.getStepwidth() : ""); // set the tooltips switch( this.currentAxis.getMotorAxis().getPosition().getType()) { case DATETIME: String tooltip = "The input format are yyyy-MM-dd HH:mm:ss.SSS or \n" + "HH:mm:ss.SSS"; this.startCombo.setToolTipText(tooltip); this.stopCombo.setToolTipText(tooltip); String tooltip2 = "The input format is HH:mm:ss.SSS"; this.stepwidthText.setToolTipText(tooltip2); break; case INT: this.startCombo.setToolTipText("the input format is integer"); this.stopCombo.setToolTipText("the input format is integer"); this.stepwidthText.setToolTipText("the input format is integer"); break; default: this.startCombo.setToolTipText("the input format is double"); this.stopCombo.setToolTipText("the input format is double"); this.stepwidthText.setToolTipText("the input format is double"); break; } if(stepcount != -1.0 && !axis.isMainAxis()) { if(this.currentAxis.getMotorAxis().getGoto().isDiscrete()) { Integer stepInt = (int)stepcount; this.stepcountText.setText(Integer.toString(stepInt)); } else { this.stepcountText.setText(Double.toString(stepcount)); } } else { if(this.currentAxis.getMotorAxis().getGoto().isDiscrete()) { Integer stepInt = (int)currentAxis.getStepCount(); this.stepcountText.setText(Integer.toString(stepInt)); } else { this.stepcountText.setText(Double.toString(currentAxis.getStepCount())); } } this.mainAxisCheckBox.setSelection(this.currentAxis.isMainAxis()); this.startCombo.setEnabled(true); this.stopCombo.setEnabled(true); this.stepwidthText.setEnabled(true); if(stepcount != -1.0 && !axis.isMainAxis()) { this.stepcountText.setEnabled(false); this.autoFillStepcountRadioButton.setEnabled(false); // Stepwidth RadioButton wird voreingestellt this.autoFillStepwidthRadioButton.setSelection(true); this.stepwidthText.setEnabled(false); } else { // Stepcount RadioButton wird voreingestellt this.autoFillStepcountRadioButton.setSelection(true); this.autoFillStepcountRadioButton.setEnabled(false); this.stepcountText.setEnabled(false); } if(this.mainAxisCheckBox.getSelection() || stepcount == -1.0) { this.mainAxisCheckBox.setEnabled(true); } checkForErrors(); } addListeners(); } private void checkForErrors() { // reset errors this.startErrorLabel.setImage(null); this.startErrorLabel.setToolTipText(""); this.stopErrorLabel.setImage(null); this.stopErrorLabel.setToolTipText(""); this.stepwidthErrorLabel.setImage(null); this.stepwidthErrorLabel.setToolTipText(""); this.stepcountErrorLabel.setImage(null); this.stepcountErrorLabel.setToolTipText(""); final Iterator<IModelError> it = this.currentAxis.getModelErrors().iterator(); while(it.hasNext()) { final IModelError modelError = it.next(); if(modelError instanceof AxisError) { final AxisError axisError = (AxisError)modelError; switch(axisError.getErrorType()) { case START_NOT_SET: this.startErrorLabel.setImage(PlatformUI.getWorkbench(). getSharedImages().getImage( ISharedImages.IMG_OBJS_ERROR_TSK)); this.startErrorLabel.setToolTipText( "Start values has not been set!"); // update and resize View with getParent().layout() this.startErrorLabel.getParent().layout(); break; case START_VALUE_NOT_POSSIBLE: this.startErrorLabel.setImage(PlatformUI.getWorkbench(). getSharedImages().getImage( ISharedImages.IMG_OBJS_ERROR_TSK)); this.startErrorLabel.setToolTipText( "Start values not possible!"); this.startErrorLabel.getParent().layout(); break; case STOP_NOT_SET: this.stopErrorLabel.setImage(PlatformUI.getWorkbench(). getSharedImages().getImage( ISharedImages.IMG_OBJS_ERROR_TSK)); this.stopErrorLabel.setToolTipText( "Stop values hat not been set!"); this.stopErrorLabel.getParent().layout(); break; case STOP_VALUE_NOT_POSSIBLE: this.stopErrorLabel.setImage(PlatformUI.getWorkbench(). getSharedImages().getImage( ISharedImages.IMG_OBJS_ERROR_TSK)); this.stopErrorLabel.setToolTipText( "Stop values not possible!"); this.stopErrorLabel.getParent().layout(); break; case STEPWIDTH_NOT_SET: this.stepwidthErrorLabel.setImage(PlatformUI. getWorkbench().getSharedImages(). getImage( ISharedImages.IMG_OBJS_ERROR_TSK)); this.stepwidthErrorLabel.setToolTipText( "Stepwidth values hat not been set!"); this.stepwidthErrorLabel.getParent().layout(); break; case STEPCOUNT_NOT_SET: this.stepcountErrorLabel.setImage(PlatformUI. getWorkbench().getSharedImages(). getImage( ISharedImages.IMG_OBJS_ERROR_TSK)); this.stepcountErrorLabel.setToolTipText( "Stepwidth values hat not been set!"); this.stepcountErrorLabel.getParent().layout(); break; } } } } private void autoFill() { boolean startOk = true; boolean stopOk = true; boolean stepwidthOk = true; boolean stepcountOk = true; for (IModelError error: this.currentAxis.getModelErrors()) { if( error instanceof AxisError) { final AxisError axisError = (AxisError)error; switch(axisError.getErrorType()) { case START_NOT_SET: case START_VALUE_NOT_POSSIBLE: startOk = false; break; case STOP_NOT_SET: case STOP_VALUE_NOT_POSSIBLE: stopOk = false; break; case STEPWIDTH_NOT_SET: stepwidthOk = false; break; case STEPCOUNT_NOT_SET: stepcountOk = false; break; } } } if( this.currentAxis != null ) { if( this.autoFillStartRadioButton.getSelection() ) { if ( stopOk && stepwidthOk && stepcountOk) { // Alle Werte OK, Start-Wert kann berechnet werden if( !this.currentAxis.getMotorAxis().getGoto().isDiscrete() ) { double stop; double stepwidth; double stepcount; switch( this.currentAxis.getMotorAxis().getPosition().getType()) { case DATETIME: // in die Zahl als sogenannter float Wert // Bei der Eingabe von der Zeit in z.B. 00:00:00.5 macht die Funktion // getTimeInMillis() aus der Zeit 00:00:00.005 int addStop = 0; int addStepwidth = 0; int stopJahr = 0; // 1 = Format von Jahr = yyyy-MM-dd HH:mm:ss.SSS // 0 = Format von Jahr = HH:mm:ss(.SSS) DateFormat stopDate = DateFormat.getTimeInstance(); DateFormat stepwidthDate = DateFormat.getTimeInstance(); if (this.stopCombo.getText().matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}([.]\\d{1,3})?$")) { stopDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); stopJahr = 1; //Nachkommazahl bestimmen //Stelle des Punktes int indexP = this.stopCombo.getText().indexOf('.'); double nachkomma = Double.parseDouble(this.stopCombo.getText().substring(indexP)); int nachMinus = Integer.parseInt(this.stopCombo.getText().substring(indexP + 1)); addStop = (int) (nachkomma * 1000 - nachMinus); } else if (this.stopCombo.getText().matches("\\d+:\\d+:\\d+?$")) { stopDate = new SimpleDateFormat("HH:mm:ss"); } else if (this.stopCombo.getText().matches("\\d+:\\d+:\\d+([.]\\d{1,3})?$")) { stopDate = new SimpleDateFormat("HH:mm:ss.SSS"); //Nachkommazahl bestimmen //Stelle des Punktes int indexP = this.stopCombo.getText().indexOf('.'); double nachkomma = Double.parseDouble(this.stopCombo.getText().substring(indexP)); int nachMinus = Integer.parseInt(this.stopCombo.getText().substring(indexP + 1)); addStop = (int) (nachkomma * 1000 - nachMinus); } if (this.stepwidthText.getText().matches("\\d+:\\d+:\\d+?$")) { stepwidthDate = new SimpleDateFormat("HH:mm:ss"); } else if (this.stepwidthText.getText().matches("\\d+:\\d+:\\d+([.]\\d{1,3})?$")) { stepwidthDate = new SimpleDateFormat("HH:mm:ss.SSS"); //Nachkommazahl bestimmen //Stelle des Punktes int indexP = this.stepwidthText.getText().indexOf('.'); double nachkomma = Double.parseDouble(this.stepwidthText.getText().substring(indexP)); int nachMinus = Integer.parseInt(this.stepwidthText.getText().substring(indexP + 1)); addStepwidth = (int) (nachkomma * 1000 - nachMinus); } stop = 0; stepwidth = 0; try { stopDate.setLenient(false); stopDate.parse(this.stopCombo.getText()); Calendar stopTime = stopDate.getCalendar(); stop = stopTime.getTimeInMillis() + addStop + 3600000; stepwidthDate.setLenient(false); stepwidthDate.parse(this.stepwidthText.getText()); Calendar stepwidthTime = stepwidthDate.getCalendar(); stepwidth = stepwidthTime.getTimeInMillis() + addStepwidth + 3600000; } catch (final ParseException ef ){ logger.error(ef.getMessage(), ef); } stepcount = Double.parseDouble( this.stepcountText.getText() ); //calculate new value for start double start = stop - (stepwidth * stepcount); if (stopJahr == 1) { Calendar startTime = Calendar.getInstance(); startTime.setTimeInMillis((long)(start - 3600000)); String startString = String.format("%s-%02d-%02d %02d:%02d:%02d.%03d", startTime.get(Calendar.YEAR), startTime.get(Calendar.MONTH) + 1, startTime.get(Calendar.DATE), startTime.get(Calendar.HOUR_OF_DAY), startTime.get(Calendar.MINUTE), startTime.get(Calendar.SECOND), startTime.get(Calendar.MILLISECOND)); this.startCombo.setText(startString); currentAxis.setStart(this.startCombo.getText()); } else if (start < 0) { // start value not valid this.startCombo.setText("not calculable"); currentAxis.setStart(this.startCombo.getText()); } else { // convert start in calender value Calendar startTime = Calendar.getInstance(); startTime.setTimeInMillis((long)(start - 3600000)); // convert calender Time in an output string String startString = String.format("%02d:%02d:%02d.%03d", startTime.get(Calendar.HOUR_OF_DAY), startTime.get(Calendar.MINUTE), startTime.get(Calendar.SECOND), startTime.get(Calendar.MILLISECOND)); this.startCombo.setText(startString); currentAxis.setStart(this.startCombo.getText()); } break; case INT: stop = Integer.parseInt( this.stopCombo.getText() ); stepwidth = Integer.parseInt( this.stepwidthText.getText() ); stepcount = Double.parseDouble( this.stepcountText.getText() ); start = stop - (stepwidth * stepcount); int startInt = (int)start; this.startCombo.setText( "" + startInt ); currentAxis.setStart(this.startCombo.getText()); break; default: stop = Double.parseDouble( this.stopCombo.getText() ); stepwidth = Double.parseDouble( this.stepwidthText.getText() ); stepcount = Double.parseDouble( this.stepcountText.getText() ); this.startCombo.setText( "" + (stop - (stepwidth * stepcount) ) ); currentAxis.setStart(this.startCombo.getText()); break; } } else { List< String > values = this.currentAxis.getMotorAxis().getGoto().getDiscreteValues(); final int stop = values.indexOf( this.stopCombo.getText() ); final int stepwidth = Integer.parseInt( this.stepwidthText.getText() ); final int stepcount = Integer.parseInt( this.stepcountText.getText() ); int index = ( stop - (stepwidth * stepcount) ); if( index < 0 ) { this.startCombo.deselectAll(); currentAxis.setStart(null); } else if( index >= values.size() ) { this.startCombo.deselectAll(); currentAxis.setStart(null); } else { this.startCombo.setText( values.get( index ) ); this.startCombo.setSelection(new Point(0,0)); currentAxis.setStart(this.startCombo.getText()); } } } } else if( this.autoFillStopRadioButton.getSelection() ) { if ( startOk && stepwidthOk && stepcountOk) { if( !this.currentAxis.getMotorAxis().getGoto().isDiscrete() ) { double start; double stepwidth; double stepcount; switch( this.currentAxis.getMotorAxis().getPosition().getType()) { case DATETIME: // in die Zahl als sogenannter float Wert // Bei der Eingabe von der Zeit in z.B. 00:00:00.5 macht die Funktion // getTimeInMillis() aus der Zeit 00:00:00.005 int addStart = 0; int addStepwidth = 0; int startJahr = 0; // 1 = Format von Jahr = yyyy-MM-dd HH:mm:ss.SSS // 0 = Format von Jahr = HH:mm:ss(.SSS) DateFormat startDate = DateFormat.getTimeInstance(); DateFormat stepwidthDate = DateFormat.getTimeInstance(); if (this.startCombo.getText().matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}([.]\\d{1,3})?$")) { startDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); startJahr = 1; //Nachkommazahl bestimmen //Stelle des Punktes int indexP = this.startCombo.getText().indexOf('.'); double nachkomma = Double.parseDouble(this.startCombo.getText().substring(indexP)); int nachMinus = Integer.parseInt(this.startCombo.getText().substring(indexP + 1)); addStart = (int) (nachkomma * 1000 - nachMinus); } else if (this.startCombo.getText().matches("\\d+:\\d+:\\d+?$")) { startDate = new SimpleDateFormat("HH:mm:ss"); } else if (this.startCombo.getText().matches("\\d+:\\d+:\\d+([.]\\d{1,3})?$")) { startDate = new SimpleDateFormat("HH:mm:ss.SSS"); //Nachkommazahl bestimmen //Stelle des Punktes int indexP = this.startCombo.getText().indexOf('.'); double nachkomma = Double.parseDouble(this.startCombo.getText().substring(indexP)); int nachMinus = Integer.parseInt(this.startCombo.getText().substring(indexP + 1)); addStart = (int) (nachkomma * 1000 - nachMinus); } if (this.stepwidthText.getText().matches("\\d+:\\d+:\\d+?$")) { stepwidthDate = new SimpleDateFormat("HH:mm:ss"); } else if (this.stepwidthText.getText().matches("\\d+:\\d+:\\d+([.]\\d{1,3})?$")) { stepwidthDate = new SimpleDateFormat("HH:mm:ss.SSS"); //Nachkommazahl bestimmen //Stelle des Punktes int indexP = this.stepwidthText.getText().indexOf('.'); double nachkomma = Double.parseDouble(this.stepwidthText.getText().substring(indexP)); int nachMinus = Integer.parseInt(this.stepwidthText.getText().substring(indexP + 1)); addStepwidth = (int) (nachkomma * 1000 - nachMinus); } start = 0; stepwidth = 0; try { startDate.setLenient(false); startDate.parse(this.startCombo.getText()); Calendar startTime = startDate.getCalendar(); start = startTime.getTimeInMillis() + addStart + 3600000; stepwidthDate.setLenient(false); stepwidthDate.parse(this.stepwidthText.getText()); Calendar stepwidthTime = stepwidthDate.getCalendar(); stepwidth = stepwidthTime.getTimeInMillis() + addStepwidth + 3600000; } catch (final ParseException ef ){ logger.error(ef.getMessage(), ef); } stepcount = Double.parseDouble( this.stepcountText.getText() ); //calculate new value for stop double stop = start + (stepwidth * stepcount); if (startJahr == 1) { Calendar stopTime = Calendar.getInstance(); stopTime.setTimeInMillis((long)(stop - 3600000)); // convert calender Time in an output string String stopString = String.format("%s-%02d-%02d %02d:%02d:%02d.%03d", stopTime.get(Calendar.YEAR), stopTime.get(Calendar.MONTH) + 1, stopTime.get(Calendar.DATE), stopTime.get(Calendar.HOUR_OF_DAY), stopTime.get(Calendar.MINUTE), stopTime.get(Calendar.SECOND), stopTime.get(Calendar.MILLISECOND)); this.stopCombo.setText(stopString); currentAxis.setStop(this.stopCombo.getText()); } else if (stop >= 86400000) { // stop value not valid, more than 24 hours this.stopCombo.setText("not calculable, more than 24 hours"); currentAxis.setStop(this.stopCombo.getText()); } else { // convert stop in calender value Calendar stopTime = Calendar.getInstance(); stopTime.setTimeInMillis((long)(stop - 3600000)); // convert calender Time in an output string String stopString = String.format("%02d:%02d:%02d.%03d", stopTime.get(Calendar.HOUR_OF_DAY), stopTime.get(Calendar.MINUTE), stopTime.get(Calendar.SECOND), stopTime.get(Calendar.MILLISECOND)); this.stopCombo.setText(stopString); currentAxis.setStop(this.stopCombo.getText()); } break; case INT: start = Integer.parseInt( this.startCombo.getText() ); stepwidth = Integer.parseInt( this.stepwidthText.getText() ); stepcount = Double.parseDouble( this.stepcountText.getText() ); stop = start + (stepwidth * stepcount); int stopInt = (int)stop; this.stopCombo.setText( "" + stopInt ); currentAxis.setStop(this.stopCombo.getText()); break; default: start = Double.parseDouble( this.startCombo.getText() ); stepwidth = Double.parseDouble( this.stepwidthText.getText() ); stepcount = Double.parseDouble( this.stepcountText.getText() ); this.stopCombo.setText( "" + (start + (stepwidth * stepcount) ) ); currentAxis.setStop(this.stopCombo.getText()); break; } } else { List< String > values = this.currentAxis.getMotorAxis().getGoto().getDiscreteValues(); final int start = values.indexOf( this.startCombo.getText() ); final int stepwidth = Integer.parseInt( this.stepwidthText.getText() ); final int stepcount = Integer.parseInt( this.stepcountText.getText() ); int index = ( start + (stepwidth * stepcount) ); if( index < 0 ) { this.stopCombo.deselectAll(); currentAxis.setStop(null); } else if( index >= values.size() ) { this.stopCombo.deselectAll(); currentAxis.setStop(null); } else { this.stopCombo.setText( values.get( index ) ); this.stopCombo.setSelection(new Point(0,0)); currentAxis.setStop(this.stopCombo.getText()); } } } } else if( this.autoFillStepwidthRadioButton.getSelection() ) { if ( startOk && stopOk && stepcountOk) { if( !this.currentAxis.getMotorAxis().getGoto().isDiscrete() ) { double start; double stop; double stepcount; switch( this.currentAxis.getMotorAxis().getPosition().getType()) { case DATETIME: // in die Zahl als sogenannter float Wert // Bei der Eingabe von der Zeit in z.B. 00:00:00.5 macht die Funktion // getTimeInMillis() aus der Zeit 00:00:00.005 int addStart = 0; int addStop = 0; int startJahr = 0; // 1 = Format von Jahr = yyyy-MM-dd HH:mm:ss.SSS int stopJahr = 0; // 0 = Format von Jahr = HH:mm:ss(.SSS) DateFormat startDate = DateFormat.getTimeInstance(); DateFormat stopDate = DateFormat.getTimeInstance(); if (this.startCombo.getText().matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}([.]\\d{1,3})?$")) { startDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); startJahr = 1; //Nachkommazahl bestimmen //Stelle des Punktes int indexP = this.startCombo.getText().indexOf('.'); double nachkomma = Double.parseDouble(this.startCombo.getText().substring(indexP)); int nachMinus = Integer.parseInt(this.startCombo.getText().substring(indexP + 1)); addStart = (int) (nachkomma * 1000 - nachMinus); } else if (this.startCombo.getText().matches("\\d+:\\d+:\\d+?$")) { startDate = new SimpleDateFormat("HH:mm:ss"); startJahr = 0; } else if (this.startCombo.getText().matches("\\d+:\\d+:\\d+([.]\\d{1,3})?$")) { startDate = new SimpleDateFormat("HH:mm:ss.SSS"); startJahr = 0; //Nachkommazahl bestimmen //Stelle des Punktes int indexP = this.startCombo.getText().indexOf('.'); double nachkomma = Double.parseDouble(this.startCombo.getText().substring(indexP)); int nachMinus = Integer.parseInt(this.startCombo.getText().substring(indexP + 1)); addStart = (int) (nachkomma * 1000 - nachMinus); } if (this.stopCombo.getText().matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}([.]\\d{1,3})?$")) { stopDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); stopJahr = 1; //Nachkommazahl bestimmen //Stelle des Punktes int indexP = this.stopCombo.getText().indexOf('.'); double nachkomma = Double.parseDouble(this.stopCombo.getText().substring(indexP)); int nachMinus = Integer.parseInt(this.stopCombo.getText().substring(indexP + 1)); addStop = (int) (nachkomma * 1000 - nachMinus); } else if (this.stopCombo.getText().matches("\\d+:\\d+:\\d+?$")) { stopDate = new SimpleDateFormat("HH:mm:ss"); stopJahr = 0; } else if (this.stopCombo.getText().matches("\\d+:\\d+:\\d+([.]\\d{1,3})?$")) { stopDate = new SimpleDateFormat("HH:mm:ss.SSS"); stopJahr = 0; //Nachkommazahl bestimmen //Stelle des Punktes int indexP = this.stopCombo.getText().indexOf('.'); double nachkomma = Double.parseDouble(this.stopCombo.getText().substring(indexP)); int nachMinus = Integer.parseInt(this.stopCombo.getText().substring(indexP + 1)); addStop = (int) (nachkomma * 1000 - nachMinus); } start = 0; stop = 0; // Wenn startJahr != stopJahr dann wird nicht weitergemacht, weil die Formate nicht gleich sind if (startJahr != stopJahr) return; try { startDate.setLenient(false); startDate.parse(this.startCombo.getText()); Calendar startTime = startDate.getCalendar(); start = startTime.getTimeInMillis() + addStart + 3600000; stopDate.setLenient(false); stopDate.parse(this.stopCombo.getText()); Calendar stopTime = stopDate.getCalendar(); stop = stopTime.getTimeInMillis() + addStop + 3600000; } catch (final ParseException ef ){ logger.error(ef.getMessage(), ef); } stepcount = Double.parseDouble( this.stepcountText.getText() ); //calculate new value for stop if ((stop - start == 0) || (stepcount == 0)) { this.stepwidthText.setText( "0" ); currentAxis.setStepwidth(this.stepwidthText.getText()); } else { double stepwidth = (stop - start) / stepcount; // convert stop in calender value Calendar stepwidthTime = Calendar.getInstance(); stepwidthTime.setTimeInMillis((long)(stepwidth - 3600000)); // convert calender Time in an output string String stepwidthString = String.format("%02d:%02d:%02d.%03d", stepwidthTime.get(Calendar.HOUR_OF_DAY), stepwidthTime.get(Calendar.MINUTE), stepwidthTime.get(Calendar.SECOND), stepwidthTime.get(Calendar.MILLISECOND)); this.stepwidthText.setText(stepwidthString); currentAxis.setStepwidth(this.stepwidthText.getText()); } break; case INT: start = Integer.parseInt( this.startCombo.getText() ); stop = Integer.parseInt( this.stopCombo.getText() ); stepcount = Double.parseDouble( this.stepcountText.getText() ); if ((stop - start == 0) || (stepcount == 0)) { this.stepwidthText.setText( "0" ); currentAxis.setStepwidth(this.stepwidthText.getText()); } else { int stepwidthInt = (int)((stop - start) / stepcount); this.stepwidthText.setText( "" + stepwidthInt ); currentAxis.setStepwidth(this.stepwidthText.getText()); } break; default: start = Double.parseDouble( this.startCombo.getText() ); stop = Double.parseDouble( this.stopCombo.getText() ); stepcount = Double.parseDouble( this.stepcountText.getText() ); if ((stop - start == 0) || (stepcount == 0)) { this.stepwidthText.setText( "0" ); currentAxis.setStepwidth(this.stepwidthText.getText()); } else { this.stepwidthText.setText( "" + (( stop - start) / stepcount ) ); currentAxis.setStepwidth(this.stepwidthText.getText()); } break; } } else { List< String > values = this.currentAxis.getMotorAxis().getGoto().getDiscreteValues(); final int start = values.indexOf( this.startCombo.getText() ); final int stop = values.indexOf( this.stopCombo.getText() ); final int stepcount = Integer.parseInt( this.stepcountText.getText() ); if (stepcount != 0) { if ( !this.stepwidthText.getText().equals("")) { // stepwidth Eintrag schon vorhanden final double stepwidth_d = Double.parseDouble( this.stepwidthText.getText() ); final int stepwidth = (int)stepwidth_d; if ( stepwidth == (( stop - start) / stepcount )) { // Wert wird nicht nochmal gesetzt } else { this.stepwidthText.setText( "" + (( stop - start) / stepcount ) ); currentAxis.setStepwidth(this.stepwidthText.getText()); } } else { this.stepwidthText.setText( "" + ( (stop - start ) / stepcount ) ); currentAxis.setStepwidth(this.stepwidthText.getText()); } } } } } else if( this.autoFillStepcountRadioButton.getSelection() ) { if ( startOk && stopOk && stepwidthOk) { if( !this.currentAxis.getMotorAxis().getGoto().isDiscrete() ) { double start; double stop; double stepwidth; // in die Zahl als sogenannter float Wert // Bei der Eingabe von der Zeit in z.B. 00:00:00.5 macht die Funktion // getTimeInMillis() aus der Zeit 00:00:00.005 int addStart = 0; int addStop = 0; int addStepwidth = 0; int startJahr = 0; // 1 = Format von Jahr = yyyy-MM-dd HH:mm:ss.SSS int stopJahr = 0; // 0 = Format von Jahr = HH:mm:ss(.SSS) switch( this.currentAxis.getMotorAxis().getPosition().getType()) { case DATETIME: DateFormat startDate = DateFormat.getTimeInstance(); DateFormat stopDate = DateFormat.getTimeInstance(); DateFormat stepwidthDate = DateFormat.getTimeInstance(); if (this.startCombo.getText().matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}([.]\\d{1,3})?$")) { startDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); startJahr = 1; //Nachkommazahl bestimmen //Stelle des Punktes int indexP = this.startCombo.getText().indexOf('.'); double nachkomma = Double.parseDouble(this.startCombo.getText().substring(indexP)); int nachMinus = Integer.parseInt(this.startCombo.getText().substring(indexP + 1)); addStart = (int) (nachkomma * 1000 - nachMinus); } else if (this.startCombo.getText().matches("\\d+:\\d+:\\d+?$")) { startDate = new SimpleDateFormat("HH:mm:ss"); startJahr = 0; } else if (this.startCombo.getText().matches("\\d+:\\d+:\\d+([.]\\d{1,3})?$")) { startDate = new SimpleDateFormat("HH:mm:ss.SSS"); startJahr = 0; //Nachkommazahl bestimmen //Stelle des Punktes int indexP = this.startCombo.getText().indexOf('.'); double nachkomma = Double.parseDouble(this.startCombo.getText().substring(indexP)); int nachMinus = Integer.parseInt(this.startCombo.getText().substring(indexP + 1)); addStart = (int) (nachkomma * 1000 - nachMinus); } if (this.stopCombo.getText().matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}([.]\\d{1,3})?$")) { stopDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); stopJahr = 1; //Nachkommazahl bestimmen //Stelle des Punktes int indexP = this.stopCombo.getText().indexOf('.'); double nachkomma = Double.parseDouble(this.stopCombo.getText().substring(indexP)); int nachMinus = Integer.parseInt(this.stopCombo.getText().substring(indexP + 1)); addStop = (int) (nachkomma * 1000 - nachMinus); } else if (this.stopCombo.getText().matches("\\d+:\\d+:\\d+?$")) { stopDate = new SimpleDateFormat("HH:mm:ss"); stopJahr = 0; } else if (this.stopCombo.getText().matches("\\d+:\\d+:\\d+([.]\\d{1,3})?$")) { stopDate = new SimpleDateFormat("HH:mm:ss.SSS"); stopJahr = 0; //Nachkommazahl bestimmen //Stelle des Punktes int indexP = this.stopCombo.getText().indexOf('.'); double nachkomma = Double.parseDouble(this.stopCombo.getText().substring(indexP)); int nachMinus = Integer.parseInt(this.stopCombo.getText().substring(indexP + 1)); addStop = (int) (nachkomma * 1000 - nachMinus); } if (this.stepwidthText.getText().matches("\\d+:\\d+:\\d+?$")) { stepwidthDate = new SimpleDateFormat("HH:mm:ss"); } else if (this.stepwidthText.getText().matches("\\d+:\\d+:\\d+([.]\\d{1,3})?$")) { stepwidthDate = new SimpleDateFormat("HH:mm:ss.SSS"); //Nachkommazahl bestimmen //Stelle des Punktes int indexP = this.stepwidthText.getText().indexOf('.'); double nachkomma = Double.parseDouble(this.stepwidthText.getText().substring(indexP)); int nachMinus = Integer.parseInt(this.stepwidthText.getText().substring(indexP + 1)); addStepwidth = (int) (nachkomma * 1000 - nachMinus); } start = 0; stop = 0; stepwidth = 0; // Wenn startJahr != stopJahr dann wird nicht weitergemacht, weil die Formate nicht gleich sind if (startJahr != stopJahr) return; try { startDate.setLenient(false); startDate.parse(this.startCombo.getText()); Calendar startTime = startDate.getCalendar(); start = startTime.getTimeInMillis() + addStart + 3600000; stopDate.setLenient(false); stopDate.parse(this.stopCombo.getText()); Calendar stopTime = stopDate.getCalendar(); stop = stopTime.getTimeInMillis() + addStop + 3600000; stepwidthDate.setLenient(false); stepwidthDate.parse(this.stepwidthText.getText()); Calendar stepwidthTime = stepwidthDate.getCalendar(); stepwidth = stepwidthTime.getTimeInMillis() + addStepwidth + 3600000; // Wenn Start > Stop beenden if (start > stop) return; } catch (final ParseException ef ){ logger.error(ef.getMessage(), ef); } break; default: start = Double.parseDouble( this.startCombo.getText() ); stop = Double.parseDouble( this.stopCombo.getText() ); stepwidth = Double.parseDouble( this.stepwidthText.getText() ); break; } if ((start - stop) > 0) { if (stepwidth > 0) { // Vorzeichen von Stepwidth umdrehen! switch( this.currentAxis.getMotorAxis().getPosition().getType()) { case INT: int stepwidthInt = (int)(stepwidth * -1); this.stepwidthText.setText( "" + stepwidthInt ); currentAxis.setStepwidth(this.stepwidthText.getText()); break; default: stepwidth = stepwidth * -1; this.stepwidthText.setText( "" + stepwidth ); currentAxis.setStepwidth(this.stepwidthText.getText()); break; } } } if ((start - stop) < 0) { switch( this.currentAxis.getMotorAxis().getPosition().getType()) { case DATETIME: // stop time less than start time is not possible break; case INT: if (stepwidth < 0) { int stepwidthInt = (int)(stepwidth * -1); this.stepwidthText.setText( "" + stepwidthInt ); currentAxis.setStepwidth(this.stepwidthText.getText()); } break; default: if (stepwidth < 0) { // Vorzeichen von Stepwidth umdrehen! stepwidth = stepwidth * -1; this.stepwidthText.setText( "" + stepwidth ); currentAxis.setStepwidth(this.stepwidthText.getText()); } break; } } if ( !this.stepcountText.getText().equals("")) { // stepcount Eintrag schon vorhanden final double stepcount = Double.parseDouble( this.stepcountText.getText() ); if ((stop - start == 0) || (stepwidth == 0)) { if ( stepcount == 0) { // Wert wird nicht nochmal gesetzt } else { this.stepcountText.setText( "0" ); currentAxis.setStepCount(0); } } else if ( stepcount == (( stop - start) / stepwidth )) { // Wert wird nicht nochmal gesetzt } else { this.stepcountText.setText( "" + (( stop - start) / stepwidth ) ); currentAxis.setStepCount(Double.parseDouble( this.stepcountText.getText() )); } } else { this.stepcountText.setText( "" + ( (stop - start) / stepwidth ) ); currentAxis.setStepCount(Double.parseDouble( this.stepcountText.getText() )); } } else { List< String > values = this.currentAxis.getMotorAxis().getGoto().getDiscreteValues(); final int start = values.indexOf( this.startCombo.getText() ); final int stop = values.indexOf( this.stopCombo.getText() ); int stepwidth; try { stepwidth = Integer.parseInt( this.stepwidthText.getText() ); } catch (NumberFormatException e) { stepwidth = 0; } if ((start - stop) > 0) { if (stepwidth < 0) { // Vorzeichen von Stepwidth umdrehen! stepwidth = stepwidth * -1; this.stepwidthText.setText( "" + (int)stepwidth ); this.stepwidthText.setSelection(2); currentAxis.setStepwidth(this.stepwidthText.getText()); } } if ((start - stop) < 0) { if (stepwidth < 0) { // Vorzeichen von Stepwidth umdrehen! stepwidth = stepwidth * -1; this.stepwidthText.setText( "" + (int)stepwidth ); this.stepwidthText.setSelection(1); currentAxis.setStepwidth(this.stepwidthText.getText()); } } if (stepwidth != 0) { if ( !this.stepcountText.getText().equals("") ) { // stepcount Eintrag schon vorhanden final double stepcount_d = Double.parseDouble( this.stepcountText.getText() ); final int stepcount = (int)stepcount_d; if ( stepcount == (( stop - start) / stepwidth )) { // Wert wird nicht nochmal gesetzt } else { this.stepcountText.setText( "" + (( stop - start) / stepwidth ) ); currentAxis.setStepCount(Double.parseDouble(this.stepcountText.getText())); } } else { this.stepcountText.setText( "" + (( stop - start) / stepwidth ) ); currentAxis.setStepCount(Double.parseDouble(this.stepcountText.getText())); } } } } } } } /* * If stepcount of main axis changes, stepwidth of all other axis recalculated. */ private void recalculateStepwidth() { if (currentAxis.isMainAxis()) { ScanModule scanModul = currentAxis.getScanModule(); Axis[] axis = scanModul.getAxes(); for( int i = 0; i < axis.length; ++i ) { if( !axis[i].isMainAxis() ) { // Axis ist keine mainAxis und wird neu berechnet if( !axis[i].getMotorAxis().getGoto().isDiscrete() ) { // Achse i ist eine normale Achse final double start = Double.parseDouble(axis[i].getStart()); final double stop = Double.parseDouble( axis[i].getStop() ); final double stepwidth = Double.parseDouble( axis[i].getStepwidth() ); final double stepcount = Double.parseDouble( stepcountText.getText() ); if ((stop - start == 0) || (stepcount == 0)) { if ( stepwidth == 0) { // Wert wird nicht nochmal gesetzt } else { axis[i].setStepwidth( "0" ); } } else if ( stepwidth == (( stop - start) / stepcount )) { // Wert wird nicht nochmal gesetzt } else { axis[i].setStepwidth("" + (( stop - start) / stepcount ) ); } } else { // Achse i ist eine diskrete Achse int start = 0; int stop = 0; String[] werte = axis[i].getMotorAxis().getGoto().getDiscreteValues().toArray( new String[0] ); for( int j = 0; j < werte.length; ++j ) { if (werte[j].equals(axis[i].getStart())) { start = j; } if (werte[j].equals(axis[i].getStop())) { stop = j; } } final double stepwidth_d = Double.parseDouble( axis[i].getStepwidth() ); final int stepwidth = (int)stepwidth_d; final double stepcount_d = Double.parseDouble( stepcountText.getText() ); final int stepcount = (int)stepcount_d; if ((stop - start == 0) || (stepcount == 0)) { if ( stepwidth == 0) { // Wert wird nicht nochmal gesetzt } else { axis[i].setStepwidth( "0" ); } } else if ( stepwidth == (( stop - start) / stepcount )) { // Wert wird nicht nochmal gesetzt } else { axis[i].setStepwidth("" + (( stop - start) / stepcount ) ); } } } } } } private void addListeners() { autoFillStartRadioButton.addSelectionListener( autoFillStartRadioButtonSelectionListener); autoFillStopRadioButton.addSelectionListener( autoFillStopRadioButtonSelectionListener); autoFillStepwidthRadioButton.addSelectionListener( autoFillStepwidthRadioButtonSelectionListener); autoFillStepcountRadioButton.addSelectionListener( autoFillStepcountRadioButtonSelectionListener); if( this.currentAxis.getMotorAxis().getGoto().isDiscrete()) { startCombo.addSelectionListener(startComboSelectionListener); stopCombo.addSelectionListener(stopComboSelectionListener); } else { startCombo.addModifyListener(startComboModifyListener); startCombo.addVerifyListener(startComboVerifyListener); stopCombo.addModifyListener(stopComboModifyListener); stopCombo.addVerifyListener(stopComboVerifyListener); } stepwidthText.addModifyListener(stepwidthTextModifyListener); stepwidthText.addVerifyListener(stepwidthTextVerifyListener); stepcountText.addModifyListener(stepcountTextModifyListener); stepcountText.addVerifyListener(stepcountTextVerifyListener); mainAxisCheckBox.addSelectionListener( mainAxisCheckBoxSelectionListener); } private void removeListeners() { autoFillStartRadioButton.removeSelectionListener( autoFillStartRadioButtonSelectionListener); startCombo.removeVerifyListener(startComboVerifyListener); startCombo.removeModifyListener(startComboModifyListener); startCombo.removeSelectionListener(startComboSelectionListener); autoFillStopRadioButton.removeSelectionListener( autoFillStopRadioButtonSelectionListener); stopCombo.removeVerifyListener(stopComboVerifyListener); stopCombo.removeModifyListener(stopComboModifyListener); stopCombo.removeSelectionListener(stopComboSelectionListener); autoFillStepwidthRadioButton.removeSelectionListener( autoFillStepwidthRadioButtonSelectionListener); stepwidthText.removeVerifyListener(stepwidthTextVerifyListener); stepwidthText.removeModifyListener(stepwidthTextModifyListener); autoFillStepcountRadioButton.removeSelectionListener( autoFillStepcountRadioButtonSelectionListener); stepcountText.removeVerifyListener(stepcountTextVerifyListener); stepcountText.removeModifyListener(stepcountTextModifyListener); mainAxisCheckBox.removeSelectionListener( mainAxisCheckBoxSelectionListener); } /** * {@inheritDoc} */ @Override public void dispose() { removeListeners(); super.dispose(); } // Hier kommen jetzt die verschiedenen Listener Klassen /** * <code>SelectionListener</code> of AutoFillStart RadioButton from * <code>MotorAxisStartStopStepwidthComposite</code> */ class AutoFillStartRadioButtonSelectionListener implements SelectionListener { /** * {@inheritDoc} */ @Override public void widgetDefaultSelected( final SelectionEvent e ) { } /** * {@inheritDoc} */ @Override public void widgetSelected( final SelectionEvent e ) { if (autoFillStartRadioButton.getSelection()) { startCombo.setEnabled( false ); } else startCombo.setEnabled( true ); } }; /** * <code>ModifyListener</code> of Start Combo from * <code>MotorAxisStartStopStepwidthComposite</code> */ class StartComboModifyListener implements ModifyListener { /** * {@inheritDoc} */ @Override public void modifyText(ModifyEvent e) { motorAxisView.suspendModelUpdateListener(); removeListeners(); if( currentAxis != null ) { switch ( currentAxis.getMotorAxis().getPosition().getType()) { case DATETIME: if (currentAxis.getMotorAxis().isValuePossible(startCombo.getText())) { currentAxis.setStart(startCombo.getText()); autoFill(); } else { currentAxis.setStart(null); } break; default: // if string is a double set value in model // else set null in model try { Double.parseDouble( startCombo.getText() ); currentAxis.setStart(startCombo.getText()); autoFill(); } catch( final NumberFormatException ex ) { // string is not a double currentAxis.setStart(null); } break; } } checkForErrors(); addListeners(); motorAxisView.resumeModelUpdateListener(); } } /** * * <code>SelectionListener</code> of Start Combo from * <code>MotorAxisStartStopStepwidthComposite</code> */ class StartComboSelectionListener implements SelectionListener { /** * {@inheritDoc} */ @Override public void widgetDefaultSelected(SelectionEvent e) { } /** * {@inheritDoc} */ @Override public void widgetSelected(SelectionEvent e) { motorAxisView.suspendModelUpdateListener(); removeListeners(); if( currentAxis != null ) { currentAxis.setStart(startCombo.getText()); startCombo.setSelection(new Point(0,0)); autoFill(); } checkForErrors(); addListeners(); motorAxisView.resumeModelUpdateListener(); } } /** * <code>SelectionListener</code> of AutoFillStop RadioButton from * <code>MotorAxisStartStopStepwidthComposite</code> */ class AutoFillStopRadioButtonSelectionListener implements SelectionListener { /** * {@inheritDoc} */ @Override public void widgetDefaultSelected( final SelectionEvent e ) { } /** * {@inheritDoc} */ @Override public void widgetSelected( final SelectionEvent e ) { if (autoFillStopRadioButton.getSelection()) { stopCombo.setEnabled( false ); } else stopCombo.setEnabled( true ); } } /** * <code>ModifyListener</code> of Stop Combo from * <code>MotorAxisStartStopStepwidthComposite</code> */ class StopComboModifyListener implements ModifyListener { /** * {@inheritDoc} */ @Override public void modifyText(ModifyEvent e) { motorAxisView.suspendModelUpdateListener(); removeListeners(); if( currentAxis != null ) { switch ( currentAxis.getMotorAxis().getPosition().getType()) { case DATETIME: if (currentAxis.getMotorAxis().isValuePossible(stopCombo.getText())) { currentAxis.setStop(stopCombo.getText()); autoFill(); } else { currentAxis.setStop(null); } break; default: // if string is a double set value in model // else set null in model try { Double.parseDouble( stopCombo.getText() ); currentAxis.setStop(stopCombo.getText()); autoFill(); } catch( final NumberFormatException ex ) { // string is not a double currentAxis.setStop(null); } } checkForErrors(); addListeners(); motorAxisView.resumeModelUpdateListener(); } } } /** * <code>SelectionListener</code> of Stop Combo from * <code>MotorAxisStartStopStepwidthComposite</code> */ class StopComboSelectionListener implements SelectionListener { /** * {@inheritDoc} */ @Override public void widgetDefaultSelected(SelectionEvent e) { } /** * {@inheritDoc} */ @Override public void widgetSelected(SelectionEvent e) { motorAxisView.suspendModelUpdateListener(); removeListeners(); if( currentAxis != null ) { currentAxis.setStop(stopCombo.getText()); stopCombo.setSelection(new Point(0,0)); autoFill(); } checkForErrors(); addListeners(); motorAxisView.resumeModelUpdateListener(); } } /** * <code>SelectionListener</code> of AutoFillStepwidth RadioButton from * <code>MotorAxisStartStopStepwidthComposite</code> */ class AutoFillStepwidthRadioButtonSelectionListener implements SelectionListener { /** * {@inheritDoc} */ @Override public void widgetDefaultSelected( final SelectionEvent e ) { } /** * {@inheritDoc} */ @Override public void widgetSelected( final SelectionEvent e ) { if (autoFillStepwidthRadioButton.getSelection()) { stepwidthText.setEnabled( false ); } else { stepwidthText.setEnabled( true ); } } } /** * <code>ModifyListener</code> of Stepwidth Text from * <code>MotorAxisStartStopStepwidthComposite</code> */ class StepwidthTextModifyListener implements ModifyListener { /** * {@inheritDoc} */ @Override public void modifyText( final ModifyEvent e ) { motorAxisView.suspendModelUpdateListener(); removeListeners(); // if Text is empty, do nothing if( currentAxis != null ) { if( currentAxis.getMotorAxis().getGoto().isDiscrete() ) { try { Integer.parseInt( stepwidthText.getText() ); currentAxis.setStepwidth( stepwidthText.getText() ); autoFill(); } catch( final NumberFormatException ex ) { // string is not an integer currentAxis.setStepwidth(null); } } else { switch ( currentAxis.getMotorAxis().getPosition().getType()) { case DATETIME: if (currentAxis.getMotorAxis().isValuePossible(stepwidthText.getText())) { currentAxis.setStepwidth(stepwidthText.getText()); autoFill(); } else { currentAxis.setStepwidth(null); } break; default: try { double start = Double.parseDouble(startCombo.getText()); double stop = Double.parseDouble(stopCombo.getText()); double stepwidth = Double.parseDouble(stepwidthText.getText()); if (start > stop) { if (stepwidth > 0) { // Vorzeichen von Stepwidth umdrehen! stepwidth = stepwidth * -1; stepwidthText.setText( "" + (int)stepwidth ); stepwidthText.setSelection(2); } if (stepwidthText.getText().equals("0")) { //Vorzeichen umdrehen stepwidthText.setText( "-0" ); stepwidthText.setSelection(2); } } if (start < stop) { if (stepwidth < 0) { // Vorzeichen von Stepwidth umdrehen! stepwidth = stepwidth * -1; stepwidthText.setText( "" + (int)stepwidth ); stepwidthText.setSelection(1); } } Double.parseDouble( stepwidthText.getText() ); currentAxis.setStepwidth(stepwidthText.getText()); autoFill(); } catch( final NumberFormatException ex ) { // string is not a double currentAxis.setStepwidth(null); } } } } checkForErrors(); addListeners(); motorAxisView.resumeModelUpdateListener(); } } /** * <code>SelectionListener</code> of stepcountRadioButton from * <code>MotorAxisStartStopStepwidthComposite</code> */ class AutoFillStepcountRadioButtonSelectionListener implements SelectionListener { /** * {@inheritDoc} */ @Override public void widgetDefaultSelected(final SelectionEvent e) { } /** * {@inheritDoc} */ @Override public void widgetSelected( final SelectionEvent e ) { if (autoFillStepcountRadioButton.getSelection()) { stepcountText.setEnabled( false ); } else { // nur wenn main axis erlaubt ist, darf auch stepcount wieder erlaubt werden if (mainAxisCheckBox.isEnabled()) { stepcountText.setEnabled( true ); autoFillStepcountRadioButton.setEnabled( true ); } } } } /** * <code>ModifyListener</code> of <code>stepcountText</code>. */ class StepcountTextModifyListener implements ModifyListener { /** * {@inheritDoc} */ @Override public void modifyText(final ModifyEvent e) { motorAxisView.suspendModelUpdateListener(); removeListeners(); if( currentAxis != null) { if(currentAxis.getMotorAxis().getGoto().isDiscrete()) { try { Integer.parseInt( stepcountText.getText() ); currentAxis.setStepCount(Integer.parseInt(stepcountText.getText())); recalculateStepwidth(); autoFill(); } catch(final NumberFormatException ex) { // string is not an integer currentAxis.setStepCount(-1.0); } } else { try { Double.parseDouble( stepcountText.getText() ); currentAxis.setStepCount(Double.parseDouble(stepcountText.getText())); recalculateStepwidth(); autoFill(); } catch( final NumberFormatException ex ) { // string is not a double currentAxis.setStepCount(-1.0); } } } checkForErrors(); addListeners(); motorAxisView.resumeModelUpdateListener(); } } /** * <code>SelectionListener</code> of <code>mainAxisCheckBox</code>. */ class MainAxisCheckBoxSelectionListener implements SelectionListener { /** * {@inheritDoc} */ @Override public void widgetDefaultSelected(final SelectionEvent e) { } /** * {@inheritDoc} */ @Override public void widgetSelected(final SelectionEvent e) { motorAxisView.suspendModelUpdateListener(); if(currentAxis != null) { currentAxis.setMainAxis(mainAxisCheckBox.getSelection()); } motorAxisView.resumeModelUpdateListener(); } } /** * <code>VerifyListener</code> of Combo Widget from * <code>MotorAxisStartStopStepwidthComposite</code> */ class ComboVerifyListener implements VerifyListener { /** * {@inheritDoc} */ @Override public void verifyText(VerifyEvent e) { switch (e.keyCode) { case SWT.BS: // Backspace case SWT.DEL: // Delete case SWT.HOME: // Home case SWT.END: // End case SWT.ARROW_LEFT: // Left arrow case SWT.ARROW_RIGHT: // Right arrow case 0: return; } String oldText = ((CCombo)(e.widget)).getText(); switch (currentAxis.getMotorAxis().getPosition().getType()) { case DATETIME: if (!Character.isDigit(e.character)) { if (e.character == '.') { // charecter . is a valid character, if he is not in the old string if (oldText.contains(".")) e.doit = false; } else if (e.character == ':') { // character : is a valid characterm for the timer return; } else if (e.character == '-') { // character - is a valid characterm for the timer, if he is not in the old string return; } else if (e.character == ' ') { // charecter ' ' is a valid character, if he is not in the old string if (oldText.contains(" ")) e.doit = false; } else { e.doit = false; // disallow the action } } break; case INT: if (!Character.isDigit(e.character)) { if (e.character == '-') { // character - is a valid character as first sign and after an e if (oldText.isEmpty()) { // oldText is emtpy, - is valid } else if ((((CCombo)e.widget).getSelection().x) == 0) { // - is the first sign an valid } else { // wenn das letzte Zeichen von oldText ein e ist, ist das minus auch erlaubt int index = oldText.length(); if (oldText.substring(index-1).equals("e")) { // letzte Zeichen ist ein e und damit erlaubt } else e.doit = false; } } else if (e.character == 'e') { // character e is a valid character, if he is not in the old string if (oldText.contains("e")) e.doit = false; } else { e.doit = false; // disallow the action } } break; default: if (!Character.isDigit(e.character)) { if (e.character == '.') { // charecter . is a valid character, if he is not in the old string if (oldText.contains(".")) e.doit = false; } else if (e.character == '-') { // character - is a valid character as first sign and after an e if (oldText.isEmpty()) { // oldText is emtpy, - is valid } else if ((((CCombo)e.widget).getSelection().x) == 0) { // - is the first sign an valid } else { // wenn das letzte Zeichen von oldText ein e ist, ist das minus auch erlaubt int index = oldText.length(); if (oldText.substring(index-1).equals("e")) { // letzte Zeichen ist ein e und damit erlaubt } else e.doit = false; } } else if (e.character == 'e') { // character e is a valid character, if he is not in the old string if (oldText.contains("e")) e.doit = false; } else { e.doit = false; // disallow the action } } break; } } } /** * <code>VerifyListener</code> of Text Widget from * <code>MotorAxisStartStopStepwidthComposite</code> */ class TextDoubleVerifyListener implements VerifyListener { /** * {@inheritDoc} */ @Override public void verifyText(VerifyEvent e) { switch (e.keyCode) { case SWT.BS: // Backspace case SWT.DEL: // Delete case SWT.HOME: // Home case SWT.END: // End case SWT.ARROW_LEFT: // Left arrow case SWT.ARROW_RIGHT: // Right arrow return; } String oldText = ((Text)(e.widget)).getText(); switch (currentAxis.getMotorAxis().getPosition().getType()) { case DATETIME: if (!Character.isDigit(e.character)) { if (e.character == '.') { // charecter . is a valid character, if he is not in the old string if (oldText.contains(".")) e.doit = false; } else if (e.character == ':') { // character : is a valid characterm for the timer return; } else if (e.character == '-') { // character - is a valid characterm for the timer, if he is not in the old string return; } else if (e.character == ' ') { // charecter ' ' is a valid character, if he is not in the old string if (oldText.contains(" ")) e.doit = false; } else { e.doit = false; // disallow the action } } break; case INT: if (!Character.isDigit(e.character)) { if (e.character == '-') { // character - is a valid character as first sign and after an e if (oldText.isEmpty()) { // oldText is emtpy, - is valid } else if ((((Text)e.widget).getSelection().x) == 0) { // - is the first sign an valid } else { // wenn das letzte Zeichen von oldText ein e ist, ist das minus auch erlaubt int index = oldText.length(); if (oldText.substring(index-1).equals("e")) { // letzte Zeichen ist ein e und damit erlaubt } else e.doit = false; } } else if (e.character == 'e') { // character e is a valid character, if he is not in the old string if (oldText.contains("e")) e.doit = false; } else { e.doit = false; // disallow the action } } break; default: if (!Character.isDigit(e.character)) { if (e.character == '.') { // charecter . is a valid character, if he is not in the old string if (oldText.contains(".")) e.doit = false; } else if (e.character == '-') { // character - is a valid character as first sign and after an e if (oldText.isEmpty()) { // oldText is emtpy, - is valid } else if ((((Text)e.widget).getSelection().x) == 0) { // - is the first sign an valid } else { // wenn das letzte Zeichen von oldText ein e ist, ist das minus auch erlaubt int index = oldText.length(); if (oldText.substring(index-1).equals("e")) { // letzte Zeichen ist ein e und damit erlaubt } else e.doit = false; } } else if (e.character == 'e') { // character e is a valid character, if he is not in the old string if (oldText.contains("e")) e.doit = false; } else { e.doit = false; // disallow the action } } break; } } } /** * <code>VerifyListener</code> of Text Widget from * <code>MotorAxisStartStopStepwidthComposite</code> */ class TextNumberVerifyListener implements VerifyListener { /** * {@inheritDoc} */ @Override public void verifyText(VerifyEvent e) { switch (e.keyCode) { case SWT.BS: // Backspace case SWT.DEL: // Delete case SWT.HOME: // Home case SWT.END: // End case SWT.ARROW_LEFT: // Left arrow case SWT.ARROW_RIGHT: // Right arrow return; } String oldText = ((Text)(e.widget)).getText(); if (!Character.isDigit(e.character)) { if (e.character == '.') { // charecter . is a valid character, if he is not in the old string if (oldText.contains(".")) e.doit = false; } else { e.doit = false; // disallow the action } } } } }
package org.rstudio.studio.client.common.presentation; import org.rstudio.core.client.BrowseCap; import org.rstudio.core.client.command.AppCommand; import org.rstudio.core.client.theme.res.ThemeResources; import org.rstudio.core.client.theme.res.ThemeStyles; import org.rstudio.core.client.widget.ScrollableToolbarPopupMenu; import org.rstudio.core.client.widget.Toolbar; import org.rstudio.core.client.widget.ToolbarButton; import org.rstudio.studio.client.RStudioGinjector; import org.rstudio.studio.client.workbench.commands.Commands; import com.google.gwt.event.dom.client.HasClickHandlers; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.MenuItem; import com.google.gwt.user.client.ui.Widget; public class SlideNavigationToolbarMenu implements SlideNavigationMenu { public SlideNavigationToolbarMenu(Toolbar toolbar) { this(toolbar, 200, 300, false); } public SlideNavigationToolbarMenu(Toolbar toolbar, int maxWidth, int heightOffset, boolean separatorAfter) { Commands commands = RStudioGinjector.INSTANCE.getCommands(); AppCommand presHome = commands.presentationHome(); homeButton_ = new ToolbarButton(presHome.getImageResource(), null); homeButton_.setTitle(presHome.getTooltip()); toolbar.addLeftWidget(homeButton_); homeSeparatorWidget_ = toolbar.addLeftSeparator(); titleLabel_.addStyleName(ThemeResources.INSTANCE.themeStyles() .presentationNavigatorLabel()); titleLabel_.getElement().getStyle().setProperty("maxWidth", maxWidth + "px"); menuWidget_ = toolbar.addLeftPopupMenu(titleLabel_, slidesMenu_); heightOffset_ = heightOffset; AppCommand presEdit = commands.presentationEdit(); editSeparatorWidget_ = toolbar.addLeftSeparator(); editButton_ = new ToolbarButton(presEdit.getImageResource(), null); toolbar.addLeftWidget(editButton_); if (separatorAfter) separatorWidget_ = toolbar.addLeftSeparator(); setDropDownVisible(false); } @Override public boolean isVisible() { return titleLabel_.isVisible(); } @Override public void setVisible(boolean visible) { homeButton_.setVisible(visible); homeSeparatorWidget_.setVisible(visible); titleLabel_.setVisible(visible); setDropDownVisible(visible); setEditButtonVisible(visible); if (separatorWidget_ != null) separatorWidget_.setVisible(visible); } @Override public void setCaption(String caption) { titleLabel_.setText(caption); } @Override public void addItem(MenuItem menu) { slidesMenu_.addItem(menu); } @Override public void clear() { slidesMenu_.clearItems(); } @Override public void setDropDownVisible(boolean visible) { menuWidget_.setVisible(isVisible() && visible); } @Override public void setEditButtonVisible(boolean visible) { visible = isVisible() && visible; editButton_.setVisible(visible); editSeparatorWidget_.setVisible(visible); } @Override public HasClickHandlers getHomeButton() { return homeButton_; } @Override public HasClickHandlers getEditButton() { return editButton_; } private class SlidesPopupMenu extends ScrollableToolbarPopupMenu { public SlidesPopupMenu() { addStyleName(ThemeStyles.INSTANCE.statusBarMenu()); } @Override protected int getMaxHeight() { if (BrowseCap.INSTANCE.isInternetExplorer()) { return 300; } else { return Window.getClientHeight() - titleLabel_.getAbsoluteTop() - titleLabel_.getOffsetHeight() - heightOffset_; } } } private ToolbarButton homeButton_; private Widget homeSeparatorWidget_; private ToolbarButton editButton_; private Widget editSeparatorWidget_; private Label titleLabel_ = new Label(); private SlidesPopupMenu slidesMenu_ = new SlidesPopupMenu(); private Widget menuWidget_; private Widget separatorWidget_ = null; private final int heightOffset_ ; }