answer
stringlengths
17
10.2M
package org.herac.tuxguitar.gui.util; import org.eclipse.swt.SWT; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Shell; import org.herac.tuxguitar.gui.TuxGuitar; import org.herac.tuxguitar.gui.editors.TGPainter; import org.herac.tuxguitar.gui.system.config.TGConfigKeys; public class TGSplash { private static TGSplash instance; private Shell shell; private TGSplash(){ super(); } public static TGSplash instance(){ if(instance == null){ instance = new TGSplash(); } return instance; } public void init() { if(TuxGuitar.instance().getConfig().getBooleanConfigValue(TGConfigKeys.SHOW_SPLASH)){ final Image image = TuxGuitar.instance().getIconManager().getAppSplash(); this.shell = new Shell(TuxGuitar.instance().getDisplay(), SWT.NO_TRIM | SWT.NO_BACKGROUND); this.shell.setLayout(new FillLayout()); this.shell.setBounds(getBounds(image)); this.shell.setImage(TuxGuitar.instance().getIconManager().getAppIcon()); this.shell.setText(TuxGuitar.APPLICATION_NAME); this.shell.addPaintListener(new PaintListener() { public void paintControl(PaintEvent e) { TGPainter painter = new TGPainter(e.gc); painter.drawImage(image, 0, 0); } }); this.shell.open(); this.shell.redraw(); this.shell.update(); } } public void finish(){ if(this.shell != null && !this.shell.isDisposed()){ this.shell.close(); this.shell.dispose(); } instance = null; } private Rectangle getBounds(Image image){ Rectangle iBounds = image.getBounds(); Rectangle mBounds = this.shell.getMonitor().getClientArea(); int x = ( ((mBounds.x + mBounds.width) / 2) - (iBounds.width / 2) ); int y = ( ((mBounds.y + mBounds.height) / 2) - (iBounds.height / 2) ); int width = iBounds.width; int height = iBounds.height; return new Rectangle( x , y , width , height); } }
/** * This class is designed to contain common methods for the Consent Withdraw process. * This class will be used in CollectionProtocolRegistration, SpecimenCollectionGroup and Specimen Bizlogic classes. * * @author mandar_deshmukh * */ package edu.wustl.catissuecore.util; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import edu.wustl.catissuecore.bean.ConsentBean; import edu.wustl.catissuecore.bizlogic.CollectionProtocolBizLogic; import edu.wustl.catissuecore.bizlogic.NewSpecimenBizLogic; import edu.wustl.catissuecore.domain.CollectionProtocol; import edu.wustl.catissuecore.domain.CollectionProtocolRegistration; import edu.wustl.catissuecore.domain.ConsentTier; import edu.wustl.catissuecore.domain.ConsentTierResponse; import edu.wustl.catissuecore.domain.ConsentTierStatus; import edu.wustl.catissuecore.domain.ReturnEventParameters; import edu.wustl.catissuecore.domain.Specimen; import edu.wustl.catissuecore.domain.SpecimenCollectionGroup; import edu.wustl.catissuecore.domain.SpecimenPosition; import edu.wustl.catissuecore.domain.User; import edu.wustl.catissuecore.util.global.AppUtility; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.common.audit.AuditManager; import edu.wustl.common.beans.NameValueBean; import edu.wustl.common.beans.SessionDataBean; import edu.wustl.common.bizlogic.IBizLogic; import edu.wustl.common.exception.ApplicationException; import edu.wustl.common.exception.BizLogicException; import edu.wustl.common.factory.AbstractFactoryConfig; import edu.wustl.common.factory.IFactory; import edu.wustl.common.util.global.CommonServiceLocator; import edu.wustl.common.util.global.CommonUtilities; import edu.wustl.common.util.global.Status; import edu.wustl.common.util.logger.Logger; import edu.wustl.dao.DAO; import edu.wustl.dao.exception.DAOException; /** * This class is designed to contain common methods for the Consent Withdraw process. * This class will be used in CollectionProtocolRegistration, SpecimenCollectionGroup and Specimen Bizlogic classes. * * @author mandar_deshmukh * */ public final class ConsentUtil { private static Logger logger = Logger.getCommonLogger(ConsentUtil.class); /* * creates a singleton object * */ private static ConsentUtil consentUtil= new ConsentUtil(); /* * Private constructor. */ private ConsentUtil() { } /* *returns the single object */ public static ConsentUtil getInstance() { return consentUtil; } /** * This method updates the SpecimenCollectionGroup instance by setting all the consent tierstatus to with * @param scg Instance of SpecimenCollectionGroup to be updated. * @param oldScg Instance of OldSpecimenCollectionGroup to be updated. * @param consentTierID Identifier of ConsentTier to be withdrawn. * @param withdrawOption Action to be performed on the withdrawn collectiongroup. * @param dao DAO instance. Used for inserting disposal event. * @param sessionDataBean SessionDataBean instance. Used for inserting disposal event. * @throws ApplicationException * @throws BizLogicException */ public static void updateSCG(SpecimenCollectionGroup scg, SpecimenCollectionGroup oldscg, long consentTierID, String withdrawOption,DAO dao, SessionDataBean sessionDataBean) throws ApplicationException { Collection newScgStatusCollection = new HashSet(); Collection consentTierStatusCollection =scg.getConsentTierStatusCollection(); Iterator itr = consentTierStatusCollection.iterator() ; while(itr.hasNext() ) { ConsentTierStatus consentTierstatus = (ConsentTierStatus)itr.next(); //compare consent tier id of scg with cpr consent tier of response if(consentTierstatus.getConsentTier().getId().longValue() == consentTierID) { consentTierstatus.setStatus(Constants.WITHDRAWN); updateSpecimensInSCG(scg,oldscg,consentTierID,withdrawOption , dao, sessionDataBean ); } ConsentTierStatus persistConsenttier = new ConsentTierStatus(consentTierstatus); newScgStatusCollection.add(persistConsenttier ); // set updated consenttierstatus in scg } scg.setConsentTierStatusCollection(newScgStatusCollection); if(!(withdrawOption.equals(Constants.WITHDRAW_RESPONSE_RESET))) { scg.setActivityStatus(Status.ACTIVITY_STATUS_DISABLED.toString()); } } /** * This method updates the SpecimenCollectionGroup instance by setting all the consent tierstatus to with * @param scg Instance of SpecimenCollectionGroup to be updated. * @param consentTierID Identifier of ConsentTier to be withdrawn. * @param withdrawOption Action to be performed on the withdrawn collectiongroup. * @param dao DAO instance. Used for inserting disposal event. * @param sessionDataBean SessionDataBean instance. Used for inserting disposal event. * @throws ApplicationException * */ public static void updateSCG(SpecimenCollectionGroup scg, long consentTierID, String withdrawOption, DAO dao, SessionDataBean sessionDataBean) throws ApplicationException { updateSCG(scg, scg, consentTierID,withdrawOption,dao, sessionDataBean); } /* * This method updates the specimens for the given SCG and sets the consent status to withdraw. */ private static void updateSpecimensInSCG(SpecimenCollectionGroup scg, SpecimenCollectionGroup oldscg, long consentTierID, String consentWithdrawalOption, DAO dao, SessionDataBean sessionDataBean) throws ApplicationException { try { List specimenCollection =dao.retrieveAttribute(SpecimenCollectionGroup.class,Constants.SYSTEM_IDENTIFIER,scg.getId(),"elements(specimenCollection)"); Collection updatedSpecimenCollection = new HashSet(); if(specimenCollection != null) { Iterator specimenItr = specimenCollection.iterator() ; while(specimenItr.hasNext()) { Specimen specimen = (Specimen)specimenItr.next(); updateSpecimenStatus(specimen, consentWithdrawalOption, consentTierID, dao, sessionDataBean); updatedSpecimenCollection.add(specimen ); } } scg.setSpecimenCollection(updatedSpecimenCollection); } catch(DAOException daoExp) { ConsentUtil.logger.error(daoExp.getMessage(), daoExp); daoExp.printStackTrace() ; throw AppUtility.getApplicationException(daoExp, daoExp.getErrorKeyName(), daoExp.getMsgValues()); } } /** * This method updates the Specimen instance by setting all the consenttierstatus to withdraw. * @param specimen Instance of Specimen to be updated. * @param consentWithdrawalOption Action to be performed on the withdrawn specimen. * @param consentTierID Identifier of ConsentTier to be withdrawn. * @param dao DAO instance. Used for inserting disposal event. * @param sessionDataBean SessionDataBean instance. Used for inserting disposal event. * @throws ApplicationException * @throws BizLogicException */ public static void updateSpecimenStatus(Specimen specimen, String consentWithdrawalOption, long consentTierID, DAO dao, SessionDataBean sessionDataBean) throws ApplicationException { Collection consentTierStatusCollection = specimen.getConsentTierStatusCollection(); Collection updatedSpecimenStatusCollection = new HashSet(); Iterator specimenStatusItr = consentTierStatusCollection.iterator() ; while(specimenStatusItr.hasNext() ) { ConsentTierStatus consentTierstatus = (ConsentTierStatus)specimenStatusItr.next() ; if(consentTierstatus.getConsentTier().getId().longValue() == consentTierID) { if(consentWithdrawalOption != null) { consentTierstatus.setStatus(Constants.WITHDRAWN ); withdrawResponse(specimen, consentWithdrawalOption, dao, sessionDataBean); } } updatedSpecimenStatusCollection.add(consentTierstatus ); } specimen.setConsentTierStatusCollection( updatedSpecimenStatusCollection); updateChildSpecimens(specimen, consentWithdrawalOption, consentTierID, dao, sessionDataBean); } /* * This method performs an action on specimen based on user response. */ /** * @param specimen * @param consentWithdrawalOption * @param dao * @param sessionDataBean */ private static void withdrawResponse(Specimen specimen, String consentWithdrawalOption, DAO dao, SessionDataBean sessionDataBean) { if(Constants.WITHDRAW_RESPONSE_DISCARD.equalsIgnoreCase(consentWithdrawalOption)||Constants.WITHDRAW_RESPONSE_RETURN.equalsIgnoreCase(consentWithdrawalOption)) { addDisposalEvent(specimen, dao, sessionDataBean); } //only if consentWithdrawalOption is not reset or noaction. if(!consentWithdrawalOption.equalsIgnoreCase(Constants.WITHDRAW_RESPONSE_RESET) && !consentWithdrawalOption.equalsIgnoreCase(Constants.WITHDRAW_RESPONSE_NOACTION) ) { updateSpecimen(specimen); } } /** * * @param specimen */ private static void updateSpecimen(Specimen specimen) { specimen.setActivityStatus(Status.ACTIVITY_STATUS_DISABLED.toString()); specimen.setIsAvailable(Boolean.FALSE); specimen.setSpecimenPosition(null); // specimen.setPositionDimensionOne(null); // specimen.setPositionDimensionTwo(null); // specimen.setStorageContainer(null); specimen.setAvailableQuantity(null); specimen.setInitialQuantity(null); } private static void addReturnEvent(Specimen specimen, DAO dao, SessionDataBean sessionDataBean) { try { Collection eventCollection = specimen.getSpecimenEventCollection(); if(!isEventAdded(eventCollection, "ReturnEventParameters")) { ReturnEventParameters returnEvent = new ReturnEventParameters(); returnEvent.setSpecimen(specimen ); dao.insert(returnEvent) ; eventCollection.add(returnEvent); specimen.setSpecimenEventCollection(eventCollection); } } catch(Exception excp) { ConsentUtil.logger.error(excp.getMessage(),excp); excp.printStackTrace(); } } /** * This method will be called to return the Audit manager. * @param sessionDataBean * @return */ private static AuditManager getAuditManager(SessionDataBean sessionDataBean) { logger.debug("Initialize audit manager"); AuditManager auditManager = new AuditManager(); if (sessionDataBean == null) { auditManager.setUserId(null); } else { auditManager.setUserId(sessionDataBean.getUserId()); auditManager.setIpAddress(sessionDataBean.getIpAddress()); } return auditManager; } /* * This method adds a disposal event to the specimen. */ private static void addDisposalEvent(Specimen specimen, DAO dao, SessionDataBean sessionDataBean) { try { Collection eventCollection = specimen.getSpecimenEventCollection(); if(!isEventAdded(eventCollection, "DisposalEventParameters")) { new NewSpecimenBizLogic().disposeSpecimen(sessionDataBean, specimen, dao, Constants.SPECIMEN_DISCARD_DISPOSAL_REASON); } } catch(Exception excp) { ConsentUtil.logger.error(excp.getMessage(),excp); excp.printStackTrace(); } } private static void updateChildSpecimens(Specimen specimen, String consentWithdrawalOption, long consentTierID, DAO dao, SessionDataBean sessionDataBean) throws ApplicationException { try { Long specimenId = (Long)specimen.getId(); List childSpecimens = dao.retrieveAttribute(Specimen.class,Constants.SYSTEM_IDENTIFIER,specimenId, "elements(childSpecimenCollection)"); //Collection childSpecimens = specimen.getChildrenSpecimen(); if(childSpecimens!=null) { Iterator childItr = childSpecimens.iterator(); while(childItr.hasNext() ) { Specimen childSpecimen = (Specimen)childItr.next(); consentWithdrawForchildSpecimens(childSpecimen , dao, sessionDataBean, consentWithdrawalOption, consentTierID); } } } catch (DAOException daoExp) { ConsentUtil.logger.error(daoExp.getMessage(), daoExp); throw AppUtility.getApplicationException(daoExp, daoExp.getErrorKeyName(), daoExp.getMsgValues()); } } private static void consentWithdrawForchildSpecimens(Specimen specimen, DAO dao, SessionDataBean sessionDataBean, String consentWithdrawalOption, long consentTierID) throws ApplicationException { if(specimen!=null) { updateSpecimenStatus(specimen, consentWithdrawalOption, consentTierID, dao, sessionDataBean); Collection childSpecimens = specimen.getChildSpecimenCollection(); Iterator itr = childSpecimens.iterator(); while(itr.hasNext() ) { Specimen childSpecimen = (Specimen)itr.next(); consentWithdrawForchildSpecimens(childSpecimen, dao, sessionDataBean, consentWithdrawalOption, consentTierID); } } } /** * This method is used to copy the consents from parent specimen to the child specimen. * * @param specimen Instance of specimen. It is the child specimen to which the consents will be set. * @param parentSpecimen Instance of specimen. It is the parent specimen from which the consents will be copied. * @throws BizLogicException * @throws DAOException */ public static void setConsentsFromParent(Specimen specimen, Specimen parentSpecimen, DAO dao) throws BizLogicException, DAOException { Collection consentTierStatusCollection = new HashSet(); List parentStatusCollection = dao.retrieveAttribute(Specimen.class,Constants.SYSTEM_IDENTIFIER, parentSpecimen.getId(), "elements(consentTierStatusCollection)"); if(parentStatusCollection != null) { Iterator parentStatusCollectionIterator = parentStatusCollection.iterator(); while(parentStatusCollectionIterator.hasNext() ) { ConsentTierStatus cts = (ConsentTierStatus)parentStatusCollectionIterator.next(); ConsentTierStatus newCts = new ConsentTierStatus(); newCts.setStatus(cts.getStatus()); newCts.setConsentTier(cts.getConsentTier()); consentTierStatusCollection.add(newCts); } } specimen.setConsentTierStatusCollection( consentTierStatusCollection); } /* * This method checks if the given event is already added to the specimen. */ private static boolean isEventAdded(Collection eventCollection, String eventType) { boolean result = false; Iterator eventCollectionIterator = eventCollection.iterator(); while(eventCollectionIterator.hasNext() ) { Object event = eventCollectionIterator.next(); if(event.getClass().getSimpleName().equals(eventType)) { result= true; break; } } return result; } /** * This method updates the specimens status for the given SCG. * @param specimenCollectionGroup * @param oldSpecimenCollectionGroup * @param dao * @param sessionDataBean * @throws BizLogicException * @throws DAOException */ public static void updateSpecimenStatusInSCG(SpecimenCollectionGroup specimenCollectionGroup,SpecimenCollectionGroup oldSpecimenCollectionGroup, DAO dao) throws BizLogicException, DAOException { Collection newConsentTierStatusCollection = specimenCollectionGroup.getConsentTierStatusCollection(); Collection oldConsentTierStatusCollection = oldSpecimenCollectionGroup.getConsentTierStatusCollection(); Iterator itr = newConsentTierStatusCollection.iterator() ; while(itr.hasNext() ) { ConsentTierStatus consentTierStatus = (ConsentTierStatus)itr.next(); String statusValue = consentTierStatus.getStatus(); long consentTierID = consentTierStatus.getConsentTier().getId().longValue(); updateSCGSpecimenCollection(specimenCollectionGroup, oldSpecimenCollectionGroup, consentTierID, statusValue, newConsentTierStatusCollection, oldConsentTierStatusCollection,dao); } } /* * This method updates the specimen consent status. */ private static void updateSCGSpecimenCollection(SpecimenCollectionGroup specimenCollectionGroup, SpecimenCollectionGroup oldSpecimenCollectionGroup, long consentTierID, String statusValue, Collection newSCGConsentCollection, Collection oldSCGConsentCollection,DAO dao) throws BizLogicException, DAOException { List specimenCollection = dao.retrieveAttribute(SpecimenCollectionGroup.class,Constants.SYSTEM_IDENTIFIER, specimenCollectionGroup.getId(),"elements(specimenCollection)"); //oldSpecimenCollectionGroup.getSpecimenCollection(); Collection updatedSpecimenCollection = new HashSet(); String applyChangesTo = specimenCollectionGroup.getApplyChangesTo(); if(specimenCollection != null) { Iterator specimenItr = specimenCollection.iterator() ; while(specimenItr.hasNext() ) { Specimen specimen = (Specimen)specimenItr.next(); updateSpecimenConsentStatus(specimen, applyChangesTo, consentTierID, statusValue, newSCGConsentCollection, oldSCGConsentCollection, dao ); updatedSpecimenCollection.add(specimen ); } } specimenCollectionGroup.setSpecimenCollection(updatedSpecimenCollection ); } public static void updateSpecimenConsentStatus(Specimen specimen, String applyChangesTo, long consentTierID, String statusValue, Collection newConsentCollection, Collection oldConsentCollection,DAO dao) throws BizLogicException { if(applyChangesTo.equalsIgnoreCase(Constants.APPLY_ALL)) { updateSpecimenConsentStatus(specimen, consentTierID, statusValue, applyChangesTo, dao); } else if(applyChangesTo.equalsIgnoreCase(Constants.APPLY)) { //To pass both collections checkConflictingConsents(newConsentCollection, oldConsentCollection, specimen, dao); } } /** * This method updates the Specimen instance by setting all the consenttierstatus to withdraw. * @param specimen Instance of Specimen to be updated. * @param consentWithdrawalOption Action to be performed on the withdrawn specimen. * @param consentTierID Identifier of ConsentTier to be withdrawn. * @throws BizLogicException */ private static void updateSpecimenConsentStatus(Specimen specimen, long consentTierID, String statusValue, String applyChangesTo, DAO dao) throws BizLogicException { Collection consentTierStatusCollection = specimen.getConsentTierStatusCollection(); Collection updatedSpecimenStatusCollection = new HashSet(); Iterator specimenStatusItr = consentTierStatusCollection.iterator() ; while(specimenStatusItr.hasNext() ) { ConsentTierStatus consentTierstatus = (ConsentTierStatus)specimenStatusItr.next() ; if(consentTierstatus.getConsentTier().getId().longValue() == consentTierID) { consentTierstatus.setStatus(statusValue); } updatedSpecimenStatusCollection.add(consentTierstatus); } specimen.setConsentTierStatusCollection(updatedSpecimenStatusCollection); //to update child specimens Collection childSpecimens = specimen.getChildSpecimenCollection(); Iterator childItr = childSpecimens.iterator(); while(childItr.hasNext() ) { Specimen childSpecimen = (Specimen)childItr.next(); consentStatusUpdateForchildSpecimens(childSpecimen , consentTierID, statusValue ,applyChangesTo, dao); } } private static void consentStatusUpdateForchildSpecimens(Specimen specimen, long consentTierID, String statusValue, String applyChangesTo, DAO dao) throws BizLogicException { if(specimen!=null) { updateSpecimenConsentStatus(specimen, consentTierID, statusValue, applyChangesTo, dao); Collection childSpecimens = specimen.getChildSpecimenCollection(); Iterator itr = childSpecimens.iterator(); while(itr.hasNext() ) { Specimen childSpecimen = (Specimen)itr.next(); consentStatusUpdateForchildSpecimens(childSpecimen, consentTierID, statusValue, applyChangesTo, dao); } } } /* * This method verifies the consents of SCG and specimen for any conflicts. * 1. Check for conflciting consent status * a. Create a Map<ConsentTiedId,ConsentStatus> of curent specimen consents * b. Iterate over a oldStatusCollection and check the status against above map * c. If all are matching then set is changable true, else if any obne status failt ot match * set flag false adn break * 2. Set new status to specimen if no conflict from above step * a. Iterate over specimen consent colelction * b. Iterate over nEw consent collection * c. check if Consenttier id of specimen and new colelction is macth if yes change * the status value of specimen consent * d. Put all changed Sepcimen ConsnetStatus object in new collection updatedSpecimenConsentStatusCollection * and set updatedSpecimenConsentStatusCollection in specimen. */ private static void checkConflictingConsents(Collection newConsentCollection, Collection oldConsentCollection, Specimen specimen, DAO dao ) throws BizLogicException { /* if oldSCG.c1 == S.c1 then update specimen with new SCG.c1 * OR * if oldS.c1 == cS.c1 then update child specimen with new S.c1 */ //bug 8381 start Map<Long,ConsentTierStatus> specimenConsentsMap = new HashMap<Long,ConsentTierStatus>(); Collection specimenConsentStatusCollection = specimen.getConsentTierStatusCollection(); Iterator specimenConsentStatusItr = specimenConsentStatusCollection.iterator() ; while(specimenConsentStatusItr.hasNext() ) { ConsentTierStatus specimenConsentStatus = (ConsentTierStatus)specimenConsentStatusItr.next() ; specimenConsentsMap.put(specimenConsentStatus.getConsentTier().getId(), specimenConsentStatus); } boolean isChangable = true; Iterator oldConsentItr = oldConsentCollection.iterator(); while(oldConsentItr.hasNext()) { ConsentTierStatus oldConsentStatus = (ConsentTierStatus)oldConsentItr.next() ; Long consentTierid = oldConsentStatus.getConsentTier().getId(); ConsentTierStatus specimenConsentStatus = specimenConsentsMap.get(consentTierid); if(!oldConsentStatus.getStatus().equals(specimenConsentStatus.getStatus())) { isChangable = false; break; } } if(isChangable) { Collection updatedSpecimenConsentStatusCollection = new HashSet(); Iterator specimenConsentItr = specimenConsentStatusCollection.iterator() ; while(specimenConsentItr.hasNext()) { ConsentTierStatus specimenConsent = (ConsentTierStatus) specimenConsentItr.next(); Iterator newConsentItr = newConsentCollection.iterator(); while(newConsentItr.hasNext() ) { ConsentTierStatus newConsentStatus = (ConsentTierStatus)newConsentItr.next() ; if(newConsentStatus.getConsentTier().getId().longValue() == specimenConsent.getConsentTier().getId().longValue()) { specimenConsent.setStatus(newConsentStatus.getStatus()); } } updatedSpecimenConsentStatusCollection.add(specimenConsent); } specimen.setConsentTierStatusCollection(updatedSpecimenConsentStatusCollection); } //bug 8381 end //to update child specimens Collection childSpecimens = specimen.getChildSpecimenCollection(); Iterator childItr = childSpecimens.iterator(); while(childItr.hasNext() ) { Specimen childSpecimen = (Specimen)childItr.next(); consentStatusUpdateForchildSpecimens(childSpecimen , newConsentCollection, oldConsentCollection, dao); } } private static void consentStatusUpdateForchildSpecimens(Specimen specimen, Collection newConsentCollection, Collection oldConsentCollection, DAO dao) throws BizLogicException { if(specimen!=null) { checkConflictingConsents(newConsentCollection, oldConsentCollection, specimen, dao); Collection childSpecimens = specimen.getChildSpecimenCollection(); Iterator itr = childSpecimens.iterator(); while(itr.hasNext() ) { Specimen childSpecimen = (Specimen)itr.next(); consentStatusUpdateForchildSpecimens(childSpecimen, newConsentCollection, oldConsentCollection, dao); } } } /** * This function is used for retriving Specimen collection group from Collection protocol registration Object * @param specimenObj * @param finalDataList * @throws BizLogicException */ public static void getSpecimenDetails(CollectionProtocolRegistration collectionProtocolRegistration, List finalDataList) throws ApplicationException { IFactory factory = AbstractFactoryConfig.getInstance().getBizLogicFactory(); IBizLogic bizLogic = factory.getBizLogic(Constants.DEFAULT_BIZ_LOGIC); Collection specimencollectionGroup = (Collection)bizLogic.retrieveAttribute(CollectionProtocolRegistration.class.getName(),collectionProtocolRegistration.getId(), "elements(specimenCollectionGroupCollection)"); //Collection specimencollectionGroup = collectionProtocolRegistration.getSpecimenCollectionGroupCollection(); Iterator specimenCollGroupIterator = specimencollectionGroup.iterator(); while(specimenCollGroupIterator.hasNext()) { SpecimenCollectionGroup specimenCollectionGroupObj =(SpecimenCollectionGroup)specimenCollGroupIterator.next(); getDetailsOfSpecimen(specimenCollectionGroupObj, finalDataList); } } /** * This function is used for retriving specimen and sub specimen's attributes. * @param specimenObj * @param finalDataList * @throws BizLogicException */ private static void getDetailsOfSpecimen(SpecimenCollectionGroup specimenCollGroupObj, List finalDataList) throws ApplicationException { // lazy Resolved specimenCollGroupObj.getSpecimenCollection(); IFactory factory = AbstractFactoryConfig.getInstance().getBizLogicFactory(); IBizLogic bizLogic = factory.getBizLogic(Constants.DEFAULT_BIZ_LOGIC); Collection specimenCollection = (Collection)bizLogic.retrieveAttribute(SpecimenCollectionGroup.class.getName(), specimenCollGroupObj.getId(), "elements(specimenCollection)"); Iterator specimenIterator = specimenCollection.iterator(); while(specimenIterator.hasNext()) { Specimen specimenObj =(Specimen)specimenIterator.next(); List specimenDetailList=new ArrayList(); if(specimenObj.getActivityStatus().equals(Status.ACTIVITY_STATUS_ACTIVE.toString())) { specimenDetailList.add(specimenObj.getLabel()); specimenDetailList.add(specimenObj.getSpecimenType()); if(specimenObj.getSpecimenPosition()==null) { specimenDetailList.add(Constants.VIRTUALLY_LOCATED); } else { SpecimenPosition position= (SpecimenPosition)bizLogic.retrieveAttribute(Specimen.class.getName(), specimenObj.getId(),"specimenPosition"); String storageLocation=position.getStorageContainer().getName()+": X-Axis-"+position.getPositionDimensionOne()+", Y-Axis-"+position.getPositionDimensionTwo(); specimenDetailList.add(storageLocation); } specimenDetailList.add(specimenObj.getClassName()); finalDataList.add(specimenDetailList); } } } /** * Adding name,value pair in NameValueBean for Witness Name * @param collProtId Get Witness List for this ID * @return consentWitnessList */ public static List witnessNameList(String collProtId) throws ApplicationException { IFactory factory = AbstractFactoryConfig.getInstance().getBizLogicFactory(); IBizLogic bizLogic = factory.getBizLogic(Constants.DEFAULT_BIZ_LOGIC); Object object = bizLogic.retrieve(CollectionProtocol.class.getName(), Long.valueOf(collProtId)); CollectionProtocol collectionProtocol = (CollectionProtocol) object; //Setting the consent witness String witnessFullName=""; List consentWitnessList = new ArrayList(); consentWitnessList.add(new NameValueBean(Constants.SELECT_OPTION,"-1")); Collection userCollection = null; if(collectionProtocol.getId()!= null) { userCollection = (Collection)bizLogic.retrieveAttribute(CollectionProtocol.class.getName(),collectionProtocol.getId(), "elements(coordinatorCollection)"); } Iterator iter = userCollection.iterator(); while(iter.hasNext()) { User user = (User)iter.next(); witnessFullName = user.getLastName()+", "+user.getFirstName(); consentWitnessList.add(new NameValueBean(witnessFullName,user.getId())); } //Setting the PI User principalInvestigator = (User)bizLogic.retrieveAttribute(CollectionProtocol.class.getName(),collectionProtocol.getId(), "principalInvestigator"); String piFullName=principalInvestigator.getLastName()+", "+principalInvestigator.getFirstName(); consentWitnessList.add(new NameValueBean(piFullName,principalInvestigator.getId())); return consentWitnessList; } /** * This function adds the columns to the List * @return columnList */ public static List<String> columnNames() { List<String> columnList = new ArrayList<String>(); columnList.add(Constants.LABLE); columnList.add(Constants.TYPE); columnList.add(Constants.STORAGE_CONTAINER_LOCATION); columnList.add(Constants.CLASS_NAME); return columnList; } /** * Adding name,value pair in NameValueBean for Witness Name * @param collProtId Get Witness List for this ID * @return consentWitnessList */ public static Collection getConsentList(String collectionProtocolID) throws ApplicationException { IFactory factory = AbstractFactoryConfig.getInstance().getBizLogicFactory(); CollectionProtocolBizLogic collectionProtocolBizLogic = (CollectionProtocolBizLogic)factory.getBizLogic(Constants.COLLECTION_PROTOCOL_FORM_ID); Object object = collectionProtocolBizLogic.retrieve(CollectionProtocol.class.getName(), Long.valueOf(collectionProtocolID)); CollectionProtocol collectionProtocol = (CollectionProtocol) object; return (Collection)collectionProtocolBizLogic.retrieveAttribute(CollectionProtocol.class.getName(), collectionProtocol.getId(), "elements(consentTierCollection)"); } /** * For ConsentTracking Preparing consentResponseForScgValues for populating Dynamic contents on the UI * @param partiResponseCollection This Containes the collection of ConsentTier Response at CPR level * @param statusResponseCollection This Containes the collection of ConsentTier Response at Specimen level * @return tempMap */ public static Map prepareSCGResponseMap(Collection statusResponseCollection, Collection partiResponseCollection,String statusResponse, String statusResponseId) { //Map tempMap = new HashMap(); Map tempMap = new LinkedHashMap();//8905 Map returnMap = null; Set sortedStatusSet = new LinkedHashSet(); List sortStatus = new ArrayList(); //bug 8905 if(statusResponseCollection!=null) { sortStatus.addAll(statusResponseCollection); } Collections.sort(sortStatus,new IdComparator()); sortedStatusSet.addAll(sortStatus); // bug 8905 Long consentTierID; Long consentID; if(partiResponseCollection!=null ||sortedStatusSet!=null) { int counter = 0; Iterator statusResponsIter = sortedStatusSet.iterator(); while(statusResponsIter.hasNext()) { ConsentTierStatus consentTierstatus=(ConsentTierStatus)statusResponsIter.next(); consentTierID=consentTierstatus.getConsentTier().getId(); Iterator participantResponseIter = partiResponseCollection.iterator(); while(participantResponseIter.hasNext()) { ConsentTierResponse consentTierResponse=(ConsentTierResponse)participantResponseIter.next(); consentID=consentTierResponse.getConsentTier().getId(); if(consentTierID.longValue()==consentID.longValue()) { ConsentTier consent = consentTierResponse.getConsentTier(); String idKey="ConsentBean:"+counter+"_consentTierID"; String statementKey="ConsentBean:"+counter+"_statement"; String participantResponsekey = "ConsentBean:"+counter+"_participantResponse"; String participantResponceIdKey="ConsentBean:"+counter+"_participantResponseID"; String statusResponsekey = "ConsentBean:"+counter+statusResponse; String statusResponseIDkey ="ConsentBean:"+counter+statusResponseId; tempMap.put(idKey, consent.getId()); tempMap.put(statementKey,consent.getStatement()); tempMap.put(participantResponsekey, consentTierResponse.getResponse()); tempMap.put(participantResponceIdKey, consentTierResponse.getId()); tempMap.put(statusResponsekey, consentTierstatus.getStatus()); tempMap.put(statusResponseIDkey, consentTierstatus.getId()); counter++; break; } } } returnMap=tempMap; } return returnMap; } /** * @param consentTierResponseCollection * @param iter */ public static void createConsentResponseColl(Collection consentTierResponseCollection, Iterator iter) { List<ConsentTierResponse> consentsList = new ArrayList<ConsentTierResponse>(); while(iter.hasNext()) { ConsentBean consentBean = (ConsentBean)iter.next(); ConsentTierResponse consentTierResponse = new ConsentTierResponse(); //Setting response consentTierResponse.setResponse(consentBean.getParticipantResponse()); logger.debug(":: participant response :"+consentBean.getParticipantResponse()); logger.debug(":: participant response Id :"+consentBean.getParticipantResponseID()); if(consentBean.getParticipantResponseID()!=null&&consentBean.getParticipantResponseID().trim().length()>0) { consentTierResponse.setId(Long.parseLong(consentBean.getParticipantResponseID())); } //Setting consent tier ConsentTier consentTier = new ConsentTier(); consentTier.setId(Long.parseLong(consentBean.getConsentTierID())); consentTier.setStatement(consentBean.getStatement()); consentTierResponse.setConsentTier(consentTier); //consentTierResponseCollection.add(consentTierResponse); consentsList.add(consentTierResponse); } // bug 8905 Comparator consentTierComparator = new IdComparator(); Collections.sort(consentsList, consentTierComparator); Iterator iterList = consentsList.iterator(); while(iterList.hasNext()) { ConsentTierResponse consentTierResponse = (ConsentTierResponse)iterList.next(); consentTierResponseCollection.add(consentTierResponse); } // bug 8905 } /** * This method called to get collection protocol registration. * @param specimen * @return * @throws ApplicationException */ public static CollectionProtocolRegistration getCollectionProtRegistration(Specimen specimen) throws ApplicationException { Long specimenId = (Long) specimen.getId(); String colProtHql = "select scg.collectionProtocolRegistration" + " from edu.wustl.catissuecore.domain.SpecimenCollectionGroup as scg," + " edu.wustl.catissuecore.domain.Specimen as spec " + " where spec.specimenCollectionGroup.id=scg.id and spec.id=" + specimenId; List collectionProtocolRegistrationList = AppUtility.executeQuery(colProtHql); CollectionProtocolRegistration collectionProtocolRegistration = null; if (collectionProtocolRegistrationList != null) { collectionProtocolRegistration = (CollectionProtocolRegistration) collectionProtocolRegistrationList .get(0); } return collectionProtocolRegistration; } /** * This method is called to get signedConsent url. * @param initialURLValue * @param cprObject * @return */ public static String getSignedConsentURL(String initialURLValue, final CollectionProtocolRegistration cprObject) { String signedConsentURL = ""; if (cprObject.getSignedConsentDocumentURL() == null) { if (initialURLValue.equals(Constants.NULL)) { signedConsentURL = ""; } else { signedConsentURL = Constants.HASHED_OUT; } } else { signedConsentURL = CommonUtilities.toString(cprObject.getSignedConsentDocumentURL()); } return signedConsentURL; } /** * This method is called to get consent date. * @param initialSignedConsentDateValue * @param cprObject * @return */ public static String getConsentDate(String initialSignedConsentDateValue, final CollectionProtocolRegistration cprObject) { String consentDate = ""; if (cprObject.getConsentSignatureDate() == null) { if (initialSignedConsentDateValue.equals(Constants.NULL)) { consentDate = ""; } else { consentDate = Constants.HASHED_OUT; } } else { consentDate = CommonUtilities.parseDateToString(cprObject.getConsentSignatureDate(), CommonServiceLocator.getInstance().getDatePattern()); } return consentDate; } /** * This method is called to get witness name. * @param dForm * @param bizLogic * @param initialWitnessValue * @param cprObject * @param witnessName * @return * @throws BizLogicException */ public static String getWitnessName(IBizLogic bizLogic, String initialWitnessValue, final CollectionProtocolRegistration cprObject) throws BizLogicException { String witnessName = ""; User witness = cprObject.getConsentWitness(); if (witness == null) { if (initialWitnessValue.equals(Constants.NULL)) { witnessName = ""; } else { witnessName = Constants.HASHED_OUT; } } else { witness = (User) bizLogic.retrieveAttribute(CollectionProtocolRegistration.class .getName(), cprObject.getId(), "consentWitness"); witnessName = witness.getLastName() + ", " + witness.getFirstName(); } return witnessName; } }
package us.bpsm.edn; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.ObjectStreamException; import java.io.Serializable; import static us.bpsm.edn.Symbol.newSymbol; public final class Keyword implements Named, Comparable<Keyword>, Serializable { private final Symbol sym; /** {@inheritDoc} */ public final String getPrefix() { return sym.getPrefix(); } /** {@inheritDoc} */ public final String getName() { return sym.getName(); } public static Keyword newKeyword(Symbol sym) { return INTERNER.intern(sym, new Keyword(sym)); } /** * Provide a Keyword with the given prefix and name. * <p> * Keywords are interned, which means that any two keywords which are equal * (by value) will also be identical (by reference). * * @param prefix * An empty String or a non-empty String obeying the restrictions * specified by edn. Never null. * @param name * A non-empty string obeying the restrictions specified by edn. * Never null. * @return a Keyword, never null. */ public static Keyword newKeyword(String prefix, String name) { return newKeyword(newSymbol(prefix, name)); } /** * This is equivalent to {@code newKeyword("", name)}. * * @param name * A non-empty string obeying the restrictions specified by edn. * Never null. * @return a Keyword without a prefix, never null. * @see #newKeyword(String, String) */ public static Keyword newKeyword(String name) { return newKeyword(newSymbol(EMPTY, name)); } /** * Return a Keyword with the same prefix and name as {@code sym}. * @param sym a Symbol, never null */ private Keyword(Symbol sym) { if (sym == null) { throw new NullPointerException(); } this.sym = sym; } public String toString() { return ":" + sym.toString(); } public int compareTo(Keyword o) { if (this == o) { return 0; } return sym.compareTo(o.sym); } private static final Interner<Symbol, Keyword> INTERNER = new Interner<Symbol, Keyword>(); private Object writeReplace() { return new SerializationProxy(sym); } private void readObject(ObjectInputStream stream) throws InvalidObjectException { throw new InvalidObjectException("only proxy can be serialized"); } private static class SerializationProxy implements Serializable { private static final long serialVersionUID = 1L; private final Symbol sym; private SerializationProxy(Symbol sym) { this.sym = sym; } private Object readResolve() throws ObjectStreamException { return newKeyword(sym); } } }
package edu.wustl.query.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import edu.wustl.common.query.queryobject.impl.metadata.SelectedColumnsMetadata; import edu.wustl.query.actionForm.CategorySearchForm; import edu.wustl.query.bizlogic.DefineGridViewBizLogic; import edu.wustl.query.util.global.Constants; import edu.wustl.query.util.querysuite.QueryDetails; public class DefineViewAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) throws Exception { CategorySearchForm categorysearchform = (CategorySearchForm) form; HttpSession session = request.getSession(); String isworkflow= request.getParameter(Constants.IS_WORKFLOW); String pageOf= request.getParameter(Constants.PAGE_OF); request.setAttribute(Constants.IS_WORKFLOW, isworkflow); request.setAttribute(Constants.PAGE_OF,pageOf); QueryDetails queryDetails = new QueryDetails(session); SelectedColumnsMetadata selectedColumnsMetadata = new SelectedColumnsMetadata(); DefineGridViewBizLogic defineGridViewBizLogic = new DefineGridViewBizLogic(); defineGridViewBizLogic.getSelectedColumnsMetadata(categorysearchform, queryDetails, selectedColumnsMetadata); session.setAttribute(Constants.SELECTED_COLUMN_META_DATA, selectedColumnsMetadata); return mapping.findForward(Constants.SUCCESS); } }
package view; import com.badlogic.ashley.core.Engine; import com.badlogic.ashley.core.Entity; import com.badlogic.ashley.core.EntitySystem; import components.*; import dataObjects.Profile; import javafx.animation.AnimationTimer; import javafx.scene.Node; import javafx.scene.layout.Pane; import javafx.scene.shape.Circle; import javafx.scene.shape.Rectangle; import javafx.util.Pair; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import systems.UserAgentSystem; import systems.UserMovementSystem; import utils.Constants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.*; import java.sql.Time; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; public class SimulationView extends Pane{ private Engine engine; private ArrayList<EntitySystem> systemArrayList; private ArrayList<Profile> profiles; private int WIDTH = 800, HEIGHT = 600; private HashMap<CityBlockComponent.BlockType, ArrayList<CityBlockComponent>> cityBlocksIndex; private char[][] cityMap; public SimulationView(File file){ setMaxSize(WIDTH, HEIGHT); setMinSize(WIDTH, HEIGHT); setClip(new Rectangle(WIDTH, HEIGHT)); initialize(); if(file==null) { ClassLoader classLoader = getClass().getClassLoader(); file = new File(classLoader.getResource("map.txt").getFile()); } getChildren().addAll(loadCityBlocks(file)); getChildren().addAll(createCells()); getChildren().addAll(createUsers()); startTick(); } private void initialize(){ engine = new Engine(); cityBlocksIndex = new HashMap<>(); for(CityBlockComponent.BlockType b : CityBlockComponent.BlockType.values()){ cityBlocksIndex.put(b, new ArrayList<>()); } long time = 0; try { time = new SimpleDateFormat("HH:mm:ss").parse("00:00:00").getTime(); } catch (ParseException e) { e.printStackTrace(); } //Initialize clock Constants.clock = new Time(time); loadProfiles(); addSystems(); } private void addSystems(){ systemArrayList = new ArrayList<>(); systemArrayList.add(new UserAgentSystem(cityBlocksIndex)); systemArrayList.add(new UserMovementSystem(WIDTH, HEIGHT)); for(EntitySystem es : systemArrayList){ engine.addSystem(es); } } private ArrayList<Node> loadCityBlocks(File file){ int width = WIDTH/Constants.BLOCK_SIZE; int height = HEIGHT/Constants.BLOCK_SIZE; cityMap = new char[height][width]; ArrayList<Node> nodes = new ArrayList<>(); for(int h=0; h<height; h++){ for(int w=0; w<width; w++){ cityMap[h][w] = 'T'; } } try { BufferedReader reader = new BufferedReader(new FileReader(file)); String line = null; int i = 0; while ((line = reader.readLine()) != null){ int j = 0; for(char letter : line.toCharArray()){ if(i<height && j<width){ cityMap[i][j] = letter; //i row, j column } j++; } i++; } reader.close(); } catch (IOException e) { e.printStackTrace(); } for(int i=0; i<height; i++){ for(int j=0; j<width; j++){ //Create entity Rectangle rectangle = new Rectangle(j*Constants.BLOCK_SIZE, i*Constants.BLOCK_SIZE, Constants.BLOCK_SIZE, Constants.BLOCK_SIZE); CityBlockComponent cityBlockComponent = new CityBlockComponent(rectangle, cityMap[i][j], cityBlocksIndex); Entity cityBlock = new Entity(); cityBlock.add(cityBlockComponent); engine.addEntity(cityBlock); nodes.add(rectangle); } } return nodes; } private ArrayList<Node> createCells(){ ArrayList<Node> nodes = new ArrayList<>(); int xBlocks = WIDTH/Constants.BLOCK_SIZE; int yBlocks = HEIGHT/Constants.BLOCK_SIZE; double s = Constants.CELL_BLOCK_RADIUS *Constants.BLOCK_SIZE; double r = Math.cos(Math.toRadians(30))*s; double h = Math.sin(Math.toRadians(30))*s; double blocksPerCell = ((2*Math.cos(Math.toRadians(30))*Constants.CELL_BLOCK_RADIUS)); int numRows = 0, numColumns = 0; //Calculate how many cell rows int yBlocksCovered = 0; while(yBlocksCovered<yBlocks){ if(numRows == 0){ yBlocksCovered += Constants.CELL_BLOCK_RADIUS/2; } else if(numRows%2==0){ yBlocksCovered += Constants.CELL_BLOCK_RADIUS; } else { yBlocksCovered += Constants.CELL_BLOCK_RADIUS*2; } numRows++; } //Calculate how many cell columns double xBlocksCovered = 0; while(xBlocksCovered<xBlocks){ if(numColumns == 0){ xBlocksCovered += blocksPerCell/2; } else { xBlocksCovered += blocksPerCell; } numColumns++; } for(int i=0; i<numColumns; i++){ for(int j=0; j<numRows; j++){ Circle circle; if(j%2==0){ //Even row circle = new Circle(i*2*r, j*(h+s), s); } else{ //Odd row circle = new Circle(i*2*r+r, j*(h+s), s); } CellComponent cellComponent = new CellComponent(circle); Entity cellTower = new Entity(); cellTower.add(cellComponent); engine.addEntity(cellTower); nodes.add(circle); } } return nodes; } private void loadProfiles(){ profiles = new ArrayList<>(); File profilesFile = new File(getClass().getClassLoader().getResource("profiles/profiles.xml").getFile()); try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(profilesFile); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("profile"); for (int prof = 0; prof < nList.getLength(); prof++) { org.w3c.dom.Node nNode = nList.item(prof); if (nNode.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) { Element eElement = (Element) nNode; //Create profile object Profile profile = new Profile( eElement.getAttribute("name"), eElement.getElementsByTagName("workArea").item(0).getTextContent() ); org.w3c.dom.Node scheduleNode = eElement.getElementsByTagName("schedule").item(0); //Obtain schedule tag, get the 0 as there is only one schedule tag per profile if (scheduleNode.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) { NodeList entry = ((Element) scheduleNode).getElementsByTagName("entry"); for(int entryCount=0; entryCount<entry.getLength(); entryCount++){ org.w3c.dom.Node entryNode = entry.item(entryCount); if (entryNode.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) { Element entryElement = (Element) entryNode; //Treat the node as an element org.w3c.dom.Node placesNode = entryElement.getElementsByTagName("places").item(0); //There is only one places tag per entry tag ArrayList<Pair<String, Double>> places = new ArrayList<>(); if(placesNode.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE){ NodeList place = ((Element)placesNode).getElementsByTagName("place"); for(int placeCount=0; placeCount<place.getLength(); placeCount++){ org.w3c.dom.Node placeNode = place.item(placeCount); if(placeNode.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE){ Element placeElement = (Element) placeNode; places.add(new Pair<>( placeElement.getElementsByTagName("area").item(0).getTextContent(), Double.parseDouble(placeElement.getElementsByTagName("probability").item(0).getTextContent()) )); } } } profile.addScheduleEntry( entryElement.getElementsByTagName("start").item(0).getTextContent(), entryElement.getElementsByTagName("end").item(0).getTextContent(), places ); } } } profiles.add(profile); } } } catch (Exception e) { e.printStackTrace(); } } private ArrayList<Node> createUsers(){ int numUsers = 100; ArrayList<Node> nodes = new ArrayList<>(); Random random = new Random(); for(int i=0; i<numUsers; i++){ Circle circle = new Circle(4); UserComponent userComponent = new UserComponent(circle); UserCommitmentComponent userCommitmentComponent = new UserCommitmentComponent(); //Select random profile ProfileComponent profileComponent = new ProfileComponent(profiles.get(random.nextInt(profiles.size())), cityBlocksIndex, circle); Entity user = new Entity(); user.add(userComponent); user.add(userCommitmentComponent); user.add(profileComponent); engine.addEntity(user); nodes.add(circle); } return nodes; } private void startTick(){ //Update canvas new AnimationTimer() { private long lastTime = System.currentTimeMillis(); @Override public void handle(long now) { long currentTime = System.currentTimeMillis(); float delta = (currentTime-lastTime)/1000f; lastTime = currentTime; //System.out.println(delta); //Update clock Constants.clock.setTime((Constants.clock.getTime()+(long)(delta*60000*12))); //System.out.println(Constants.clock); for(EntitySystem es : systemArrayList){ es.update(delta); } } }.start(); } }
package zmq.io; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.util.Arrays; import java.util.function.Function; import java.util.function.Supplier; import zmq.Config; import zmq.Msg; import zmq.Options; import zmq.SocketBase; import zmq.ZError; import zmq.ZMQ; import zmq.io.coder.IDecoder; import zmq.io.coder.IDecoder.Step; import zmq.io.coder.IEncoder; import zmq.io.coder.raw.RawDecoder; import zmq.io.coder.raw.RawEncoder; import zmq.io.coder.v1.V1Decoder; import zmq.io.coder.v1.V1Encoder; import zmq.io.coder.v2.V2Decoder; import zmq.io.coder.v2.V2Encoder; import zmq.io.mechanism.Mechanism; import zmq.io.mechanism.Mechanisms; import zmq.io.net.Address; import zmq.poll.IPollEvents; import zmq.poll.Poller; import zmq.util.Blob; import zmq.util.Errno; import zmq.util.Utils; import zmq.util.ValueReference; import zmq.util.Wire; // This engine handles any socket with SOCK_STREAM semantics, // e.g. TCP socket or an UNIX domain socket. public class StreamEngine implements IEngine, IPollEvents { private final class ProducePongMessage implements Supplier<Msg> { private final byte[] pingContext; public ProducePongMessage(byte[] pingContext) { assert (pingContext != null); this.pingContext = pingContext; } @Override public Msg get() { return producePongMessage(pingContext); } } // Protocol revisions private enum Protocol { V0(-1), V1(0), V2(1), V3(3); private final byte revision; Protocol(int revision) { this.revision = (byte) revision; } } public enum ErrorReason { PROTOCOL, CONNECTION, TIMEOUT, } private IOObject ioObject; // Underlying socket. private SocketChannel fd; // True if this is server's engine. // private boolean asServer; // private Msg txMsg; private Poller.Handle handle; private ByteBuffer inpos; private int insize; private IDecoder decoder; private final ValueReference<ByteBuffer> outpos; private int outsize; private IEncoder encoder; private Metadata metadata; // When true, we are still trying to determine whether // the peer is using versioned protocol, and if so, which // version. When false, normal message flow has started. private boolean handshaking; private static final int SIGNATURE_SIZE = 10; // Size of ZMTP/1.0 and ZMTP/2.0 greeting message private static final int V2_GREETING_SIZE = 12; // Size of ZMTP/3.0 greeting message private static final int V3_GREETING_SIZE = 64; // Expected greeting size. private int greetingSize; // Greeting received from, and sent to peer private final ByteBuffer greetingRecv; private final ByteBuffer greetingSend; // handy reminder of the used ZMTP protocol version private Protocol zmtpVersion; // The session this engine is attached to. private SessionBase session; private Options options; // String representation of endpoint private String endpoint; private boolean plugged; private Supplier<Msg> nextMsg; private Function<Msg, Boolean> processMsg; private boolean ioError; // Indicates whether the engine is to inject a phantom // subscription message into the incoming stream. // Needed to support old peers. private boolean subscriptionRequired; private Mechanism mechanism; // True if the engine couldn't consume the last decoded message. private boolean inputStopped; // True if the engine doesn't have any message to encode. private boolean outputStopped; // ID of the handshake timer private static final int HANDSHAKE_TIMER_ID = 0x40; private static final int HEARTBEAT_TTL_TIMER_ID = 0x80; private static final int HEARTBEAT_IVL_TIMER_ID = 0x81; private static final int HEARTBEAT_TIMEOUT_TIMER_ID = 0x82; // True is linger timer is running. private boolean hasHandshakeTimer; private boolean hasTtlTimer; private boolean hasTimeoutTimer; private boolean hasHeartbeatTimer; private final int heartbeatTimeout; private final byte[] heartbeatContext; // Socket private SocketBase socket; private Address peerAddress; private final Errno errno; public StreamEngine(SocketChannel fd, final Options options, final String endpoint) { this.errno = options.errno; this.fd = fd; this.handshaking = true; greetingSize = V2_GREETING_SIZE; this.options = options; this.endpoint = endpoint; nextMsg = nextIdentity; processMsg = processIdentity; outpos = new ValueReference<>(); greetingRecv = ByteBuffer.allocate(V3_GREETING_SIZE); greetingSend = ByteBuffer.allocate(V3_GREETING_SIZE); // Put the socket into non-blocking mode. try { Utils.unblockSocket(this.fd); } catch (IOException e) { throw new ZError.IOException(e); } peerAddress = Utils.getPeerIpAddress(fd); heartbeatTimeout = heartbeatTimeout(); heartbeatContext = Arrays.copyOf(options.heartbeatContext, options.heartbeatContext.length); } private int heartbeatTimeout() { int timeout = 0; if (options.heartbeatInterval > 0) { timeout = options.heartbeatTimeout; if (timeout == -1) { timeout = options.heartbeatInterval; } } return timeout; } public void destroy() { assert (!plugged); if (fd != null) { try { fd.close(); } catch (IOException e) { assert (false); } fd = null; } if (encoder != null) { encoder.destroy(); } if (decoder != null) { decoder.destroy(); } if (mechanism != null) { mechanism.destroy(); } } @Override public void plug(IOThread ioThread, SessionBase session) { assert (!plugged); plugged = true; // Connect to session object. assert (this.session == null); assert (session != null); this.session = session; socket = session.getSocket(); // Connect to I/O threads poller object. ioObject = new IOObject(ioThread, this); ioObject.plug(); handle = ioObject.addFd(fd); ioError = false; if (options.rawSocket) { decoder = (IDecoder) instantiate(options.decoder, Config.IN_BATCH_SIZE.getValue(), options.maxMsgSize); if (decoder == null) { decoder = new RawDecoder(Config.IN_BATCH_SIZE.getValue()); } encoder = (IEncoder) instantiate(options.encoder, Config.OUT_BATCH_SIZE.getValue(), options.maxMsgSize); if (encoder == null) { encoder = new RawEncoder(errno, Config.OUT_BATCH_SIZE.getValue()); } // disable handshaking for raw socket handshaking = false; nextMsg = pullMsgFromSession; processMsg = pushRawMsgToSession; if (peerAddress != null && !peerAddress.address().isEmpty()) { assert (metadata == null); // Compile metadata metadata = new Metadata(); metadata.set(Metadata.PEER_ADDRESS, peerAddress.address()); } // For raw sockets, send an initial 0-length message to the // application so that it knows a peer has connected. Msg connector = new Msg(); pushRawMsgToSession(connector); session.flush(); } else { // start optional timer, to prevent handshake hanging on no input setHandshakeTimer(); // Send the 'length' and 'flags' fields of the identity message. // The 'length' field is encoded in the long format. greetingSend.put((byte) 0xff); Wire.putUInt64(greetingSend, options.identitySize + 1); greetingSend.put((byte) 0x7f); outpos.set(greetingSend); outsize = greetingSend.position(); greetingSend.flip(); } ioObject.setPollIn(handle); ioObject.setPollOut(handle); // Flush all the data that may have been already received downstream. inEvent(); } private Object instantiate(Class<?> decoder, int size, long max) { if (decoder == null) { return null; } try { return decoder.getConstructor(int.class, long.class).newInstance(size, max); } catch (Exception e) { e.printStackTrace(); return null; } } private void unplug() { assert (plugged); plugged = false; // Cancel all timers. if (hasHandshakeTimer) { ioObject.cancelTimer(HANDSHAKE_TIMER_ID); hasHandshakeTimer = false; } if (hasTtlTimer) { ioObject.cancelTimer(HEARTBEAT_TTL_TIMER_ID); hasTtlTimer = false; } if (hasTimeoutTimer) { ioObject.cancelTimer(HEARTBEAT_TIMEOUT_TIMER_ID); hasTimeoutTimer = false; } if (hasHeartbeatTimer) { ioObject.cancelTimer(HEARTBEAT_IVL_TIMER_ID); hasHeartbeatTimer = false; } if (!ioError) { // Cancel all fd subscriptions. ioObject.removeHandle(handle); handle = null; } // Disconnect from I/O threads poller object. ioObject.unplug(); session = null; } @Override public void terminate() { unplug(); destroy(); } @Override public void inEvent() { assert (!ioError); // If still handshaking, receive and process the greeting message. if (handshaking) { if (!handshake()) { return; } } assert (decoder != null); // If there has been an I/O error, stop polling. if (inputStopped) { ioObject.removeHandle(handle); handle = null; ioError = true; return; } // If there's no data to process in the buffer... if (insize == 0) { // Retrieve the buffer and read as much data as possible. // Note that buffer can be arbitrarily large. However, we assume // the underlying TCP layer has fixed buffer size and thus the // number of bytes read will be always limited. inpos = decoder.getBuffer(); int rc = read(inpos); if (rc == 0) { error(ErrorReason.CONNECTION); } if (rc == -1) { if (!errno.is(ZError.EAGAIN)) { error(ErrorReason.CONNECTION); } return; } // Adjust input size inpos.flip(); insize = rc; } boolean rc = false; ValueReference<Integer> processed = new ValueReference<>(0); while (insize > 0) { // Push the data to the decoder. Step.Result result = decoder.decode(inpos, insize, processed); assert (processed.get() <= insize); insize -= processed.get(); if (result == Step.Result.MORE_DATA) { rc = true; break; } if (result == Step.Result.ERROR) { rc = false; break; } Msg msg = decoder.msg(); rc = processMsg.apply(msg); if (!rc) { break; } } // Tear down the connection if we have failed to decode input data // or the session has rejected the message. if (!rc) { if (!errno.is(ZError.EAGAIN)) { error(ErrorReason.PROTOCOL); return; } inputStopped = true; ioObject.resetPollIn(handle); } // Flush all messages the decoder may have produced. session.flush(); } @Override public void outEvent() { assert (!ioError); // If write buffer is empty, try to read new data from the encoder. if (outsize == 0) { // Even when we stop polling as soon as there is no // data to send, the poller may invoke outEvent one // more time due to 'speculative write' optimization. if (encoder == null) { assert (handshaking); return; } outpos.set(null); outsize = encoder.encode(outpos, 0); while (outsize < Config.OUT_BATCH_SIZE.getValue()) { Msg msg = nextMsg.get(); if (msg == null) { break; } encoder.loadMsg(msg); int n = encoder.encode(outpos, Config.OUT_BATCH_SIZE.getValue() - outsize); assert (n > 0); outsize += n; } // If there is no data to send, stop polling for output. if (outsize == 0) { outputStopped = true; ioObject.resetPollOut(handle); return; } // slight difference with libzmq: // encoder is notified of the end of the loading encoder.encoded(); } // If there are any data to write in write buffer, write as much as // possible to the socket. Note that amount of data to write can be // arbitrarily large. However, we assume that underlying TCP layer has // limited transmission buffer and thus the actual number of bytes // written should be reasonably modest. int nbytes = write(outpos.get()); // IO error has occurred. We stop waiting for output events. // The engine is not terminated until we detect input error; // this is necessary to prevent losing incoming messages. if (nbytes == -1) { ioObject.resetPollOut(handle); return; } outsize -= nbytes; // If we are still handshaking and there are no data // to send, stop polling for output. if (handshaking) { if (outsize == 0) { ioObject.resetPollOut(handle); } } } @Override public void restartOutput() { if (ioError) { return; } if (outputStopped) { ioObject.setPollOut(handle); outputStopped = false; } // Speculative write: The assumption is that at the moment new message // was sent by the user the socket is probably available for writing. // Thus we try to write the data to socket avoiding polling for POLLOUT. // Consequently, the latency should be better in request/reply scenarios. outEvent(); } @Override public void restartInput() { assert (inputStopped); assert (session != null); assert (decoder != null); Msg msg = decoder.msg(); if (!processMsg.apply(msg)) { if (errno.is(ZError.EAGAIN)) { session.flush(); } else { error(ErrorReason.PROTOCOL); } return; } boolean rc = true; while (insize > 0 && rc) { ValueReference<Integer> processed = new ValueReference<>(0); Step.Result result = decoder.decode(inpos, insize, processed); assert (processed.get() <= insize); insize -= processed.get(); if (result == Step.Result.MORE_DATA) { rc = true; break; } if (result == Step.Result.ERROR) { rc = false; break; } msg = decoder.msg(); rc = processMsg.apply(msg); } if (!rc && errno.is(ZError.EAGAIN)) { session.flush(); } else if (ioError) { error(ErrorReason.CONNECTION); } else if (!rc) { error(ErrorReason.PROTOCOL); } else { inputStopped = false; ioObject.setPollIn(handle); session.flush(); // Speculative read. inEvent(); } } // Detects the protocol used by the peer. private boolean handshake() { assert (handshaking); assert (greetingRecv.position() < greetingSize); // Position of the version field in the greeting. final int revisionPos = SIGNATURE_SIZE; // Receive the greeting. while (greetingRecv.position() < greetingSize) { final int n = read(greetingRecv); if (n == 0) { error(ErrorReason.CONNECTION); return false; } if (n == -1) { if (!errno.is(ZError.EAGAIN)) { error(ErrorReason.CONNECTION); } return false; } // We have received at least one byte from the peer. // If the first byte is not 0xff, we know that the // peer is using unversioned protocol. if ((greetingRecv.get(0) & 0xff) != 0xff) { // If this first byte is not %FF, // then the other peer is using ZMTP 1.0. break; } if (greetingRecv.position() < SIGNATURE_SIZE) { continue; } // Inspect the right-most bit of the 10th byte (which coincides // with the 'flags' field if a regular message was sent). // Zero indicates this is a header of identity message // (i.e. the peer is using the unversioned protocol). if ((greetingRecv.get(9) & 0x01) != 0x01) { break; } // If the least significant bit is 1, the peer is using ZMTP 2.0 or later // and has sent us the ZMTP signature. int outpos = greetingSend.position(); // The peer is using versioned protocol. // Send the major version number. if (greetingSend.limit() == SIGNATURE_SIZE) { if (outsize == 0) { ioObject.setPollOut(handle); } greetingSend.limit(SIGNATURE_SIZE + 1); greetingSend.put(revisionPos, Protocol.V3.revision); // Major version number outsize += 1; } if (greetingRecv.position() > SIGNATURE_SIZE) { if (greetingSend.limit() == SIGNATURE_SIZE + 1) { if (outsize == 0) { ioObject.setPollOut(handle); } // We read a further byte, which indicates the ZMTP version. byte protocol = greetingRecv.get(revisionPos); if (protocol == Protocol.V1.revision || protocol == Protocol.V2.revision) { // If this is V1 or V2, we have a ZMTP 2.0 peer. greetingSend.limit(V2_GREETING_SIZE); greetingSend.position(SIGNATURE_SIZE + 1); greetingSend.put((byte) options.type); // Socket type outsize += 1; } else { // If this is 3 or greater, we have a ZMTP 3.0 peer. greetingSend.limit(V3_GREETING_SIZE); greetingSend.position(SIGNATURE_SIZE + 1); greetingSend.put((byte) 0); // Minor version number outsize += 1; greetingSend.mark(); greetingSend.put(new byte[20]); assert (options.mechanism == Mechanisms.NULL || options.mechanism == Mechanisms.PLAIN || options.mechanism == Mechanisms.CURVE || options.mechanism == Mechanisms.GSSAPI); greetingSend.reset(); greetingSend.put(options.mechanism.name().getBytes(ZMQ.CHARSET)); greetingSend.reset(); greetingSend.position(greetingSend.position() + 20); outsize += 20; greetingSend.put(new byte[32]); outsize += 32; greetingSize = V3_GREETING_SIZE; } } } greetingSend.position(outpos); } // Is the peer using the unversioned protocol? // If so, we send and receive rest of identity // messages. if ((greetingRecv.get(0) & 0xff) != 0xff || (greetingRecv.get(9) & 0x01) == 0) { // If this first byte is %FF, then we read nine further bytes, // and inspect the last byte (the 10th in total). // If the least significant bit is 0, then the other peer is using ZMTP 1.0. if (session.zapEnabled()) { // reject ZMTP 1.0 connections if ZAP is enabled error(ErrorReason.PROTOCOL); return false; } zmtpVersion = Protocol.V0; encoder = new V1Encoder(errno, Config.OUT_BATCH_SIZE.getValue()); decoder = new V1Decoder(errno, Config.IN_BATCH_SIZE.getValue(), options.maxMsgSize, options.allocator); // We have already sent the message header. // Since there is no way to tell the encoder to // skip the message header, we simply throw that // header data away. final int headerSize = options.identitySize + 1 >= 255 ? 10 : 2; ByteBuffer tmp = ByteBuffer.allocate(headerSize); // Prepare the identity message and load it into encoder. // Then consume bytes we have already sent to the peer. Msg txMsg = new Msg(options.identitySize); txMsg.put(options.identity, 0, options.identitySize); encoder.loadMsg(txMsg); ValueReference<ByteBuffer> bufferp = new ValueReference<>(tmp); int bufferSize = encoder.encode(bufferp, headerSize); assert (bufferSize == headerSize); // Make sure the decoder sees the data we have already received. decodeDataAfterHandshake(0); // To allow for interoperability with peers that do not forward // their subscriptions, we inject a phantom subscription message // message into the incoming message stream. if (options.type == ZMQ.ZMQ_PUB || options.type == ZMQ.ZMQ_XPUB) { subscriptionRequired = true; } // We are sending our identity now and the next message // will come from the socket. nextMsg = pullMsgFromSession; // We are expecting identity message. processMsg = processIdentity; } else if (greetingRecv.get(revisionPos) == Protocol.V1.revision) { // ZMTP/1.0 framing. zmtpVersion = Protocol.V1; if (session.zapEnabled()) { // reject ZMTP 1.0 connections if ZAP is enabled error(ErrorReason.PROTOCOL); return false; } encoder = new V1Encoder(errno, Config.OUT_BATCH_SIZE.getValue()); decoder = new V1Decoder(errno, Config.IN_BATCH_SIZE.getValue(), options.maxMsgSize, options.allocator); decodeDataAfterHandshake(V2_GREETING_SIZE); } else if (greetingRecv.get(revisionPos) == Protocol.V2.revision) { // ZMTP/2.0 framing. zmtpVersion = Protocol.V2; if (session.zapEnabled()) { // reject ZMTP 2.0 connections if ZAP is enabled error(ErrorReason.PROTOCOL); return false; } encoder = new V2Encoder(errno, Config.OUT_BATCH_SIZE.getValue()); decoder = new V2Decoder(errno, Config.IN_BATCH_SIZE.getValue(), options.maxMsgSize, options.allocator); decodeDataAfterHandshake(V2_GREETING_SIZE); } else { zmtpVersion = Protocol.V3; encoder = new V2Encoder(errno, Config.OUT_BATCH_SIZE.getValue()); decoder = new V2Decoder(errno, Config.IN_BATCH_SIZE.getValue(), options.maxMsgSize, options.allocator); greetingRecv.position(V2_GREETING_SIZE); if (options.mechanism == null) { error(ErrorReason.PROTOCOL); return false; } else { if (options.mechanism.isMechanism(greetingRecv)) { mechanism = options.mechanism.create(session, peerAddress, options); } else { error(ErrorReason.PROTOCOL); return false; } } nextMsg = nextHandshakeCommand; processMsg = processHandshakeCommand; } // Start polling for output if necessary. if (outsize == 0) { ioObject.setPollOut(handle); } // Handshaking was successful. // Switch into the normal message flow. handshaking = false; if (hasHandshakeTimer) { ioObject.cancelTimer(HANDSHAKE_TIMER_ID); hasHandshakeTimer = false; } socket.eventHandshaken(endpoint, zmtpVersion.ordinal()); return true; } private void decodeDataAfterHandshake(int greetingSize) { final int pos = greetingRecv.position(); if (pos > greetingSize) { // data is present after handshake greetingRecv.position(greetingSize).limit(pos); // Make sure the decoder sees this extra data. inpos = greetingRecv; insize = greetingRecv.remaining(); } } private Msg identityMsg() { Msg msg = new Msg(options.identitySize); if (options.identitySize > 0) { msg.put(options.identity, 0, options.identitySize); } nextMsg = pullMsgFromSession; return msg; } private boolean processIdentityMsg(Msg msg) { if (options.recvIdentity) { msg.setFlags(Msg.IDENTITY); boolean rc = session.pushMsg(msg); assert (rc); } if (subscriptionRequired) { // Inject the subscription message, so that also // ZMQ 2.x peers receive published messages. Msg subscription = new Msg(1); subscription.put((byte) 1); boolean rc = session.pushMsg(subscription); assert (rc); } processMsg = pushMsgToSession; return true; } private final Function<Msg, Boolean> processIdentity = this::processIdentityMsg; private final Supplier<Msg> nextIdentity = this::identityMsg; private Msg nextHandshakeCommand() { assert (mechanism != null); if (mechanism.status() == Mechanism.Status.READY) { mechanismReady(); return pullAndEncode.get(); } else if (mechanism.status() == Mechanism.Status.ERROR) { errno.set(ZError.EPROTO); // error(ErrorReason.PROTOCOL); return null; } else { Msg.Builder msg = new Msg.Builder(); int rc = mechanism.nextHandshakeCommand(msg); if (rc == 0) { msg.setFlags(Msg.COMMAND); return msg.build(); } else { errno.set(rc); return null; } } } private boolean processHandshakeCommand(Msg msg) { assert (mechanism != null); int rc = mechanism.processHandshakeCommand(msg); if (rc == 0) { if (mechanism.status() == Mechanism.Status.READY) { mechanismReady(); } else if (mechanism.status() == Mechanism.Status.ERROR) { errno.set(ZError.EPROTO); return false; } if (outputStopped) { restartOutput(); } } else { errno.set(rc); } return rc == 0; } private final Function<Msg, Boolean> processHandshakeCommand = this::processHandshakeCommand; private final Supplier<Msg> nextHandshakeCommand = this::nextHandshakeCommand; @Override public void zapMsgAvailable() { assert (mechanism != null); int rc = mechanism.zapMsgAvailable(); if (rc == -1) { error(ErrorReason.PROTOCOL); return; } if (inputStopped) { restartInput(); } if (outputStopped) { restartOutput(); } } private void mechanismReady() { if (options.heartbeatInterval > 0) { ioObject.addTimer(options.heartbeatInterval, HEARTBEAT_IVL_TIMER_ID); hasHeartbeatTimer = true; } if (options.recvIdentity) { Msg identity = mechanism.peerIdentity(); boolean rc = session.pushMsg(identity); if (!rc && errno.is(ZError.EAGAIN)) { // If the write is failing at this stage with // an EAGAIN the pipe must be being shut down, // so we can just bail out of the identity set. return; } assert (rc); session.flush(); } nextMsg = pullAndEncode; processMsg = writeCredential; // Compile metadata. assert (metadata == null); metadata = new Metadata(); // If we have a peer_address, add it to metadata if (peerAddress != null && !peerAddress.address().isEmpty()) { metadata.set(Metadata.PEER_ADDRESS, peerAddress.address()); } // Add ZAP properties. metadata.set(mechanism.zapProperties); // Add ZMTP properties. metadata.set(mechanism.zmtpProperties); if (metadata.isEmpty()) { metadata = null; } } private Msg pullMsgFromSession() { return session.pullMsg(); } private boolean pushMsgToSession(Msg msg) { return session.pushMsg(msg); } private final Function<Msg, Boolean> pushMsgToSession = this::pushMsgToSession; private final Supplier<Msg> pullMsgFromSession = this::pullMsgFromSession; private boolean pushRawMsgToSession(Msg msg) { if (metadata != null && !metadata.equals(msg.getMetadata())) { msg.setMetadata(metadata); } return pushMsgToSession(msg); } private final Function<Msg, Boolean> pushRawMsgToSession = this::pushRawMsgToSession; private boolean writeCredential(Msg msg) { assert (mechanism != null); assert (session != null); Blob credential = mechanism.getUserId(); if (credential != null && credential.size() > 0) { Msg cred = new Msg(credential.size()); cred.put(credential.data(), 0, credential.size()); cred.setFlags(Msg.CREDENTIAL); boolean rc = session.pushMsg(cred); if (!rc) { return false; } } processMsg = decodeAndPush; return decodeAndPush.apply(msg); } private final Function<Msg, Boolean> writeCredential = this::writeCredential; private Msg pullAndEncode() { assert (mechanism != null); Msg msg = session.pullMsg(); if (msg == null) { return null; } msg = mechanism.encode(msg); return msg; } private final Supplier<Msg> pullAndEncode = this::pullAndEncode; private boolean decodeAndPush(Msg msg) { assert (mechanism != null); msg = mechanism.decode(msg); if (msg == null) { return false; } if (hasTimeoutTimer) { hasTimeoutTimer = false; ioObject.cancelTimer(HEARTBEAT_TIMEOUT_TIMER_ID); } if (hasTtlTimer) { hasTtlTimer = false; ioObject.cancelTimer(HEARTBEAT_TTL_TIMER_ID); } if (msg.isCommand()) { StreamEngine.this.processCommand(msg); } if (metadata != null) { msg.setMetadata(metadata); } boolean rc = session.pushMsg(msg); if (!rc) { if (errno.is(ZError.EAGAIN)) { processMsg = pushOneThenDecodeAndPush; } return false; } return true; } private final Function<Msg, Boolean> decodeAndPush = this::decodeAndPush; private boolean pushOneThenDecodeAndPush(Msg msg) { boolean rc = session.pushMsg(msg); if (rc) { processMsg = decodeAndPush; } return rc; } private final Function<Msg, Boolean> pushOneThenDecodeAndPush = this::pushOneThenDecodeAndPush; private final Supplier<Msg> producePingMessage = this::producePingMessage; // Function to handle network disconnections. private void error(ErrorReason error) { if (options.rawSocket) { // For raw sockets, send a final 0-length message to the application // so that it knows the peer has been disconnected. Msg terminator = new Msg(); processMsg.apply(terminator); } assert (session != null); socket.eventDisconnected(endpoint, fd); session.flush(); session.engineError(error); unplug(); destroy(); } private void setHandshakeTimer() { assert (!hasHandshakeTimer); if (!options.rawSocket && options.handshakeIvl > 0) { ioObject.addTimer(options.handshakeIvl, HANDSHAKE_TIMER_ID); hasHandshakeTimer = true; } } @Override public void timerEvent(int id) { if (id == HANDSHAKE_TIMER_ID) { hasHandshakeTimer = false; // handshake timer expired before handshake completed, so engine fails error(ErrorReason.TIMEOUT); } else if (id == HEARTBEAT_IVL_TIMER_ID) { nextMsg = producePingMessage; outEvent(); ioObject.addTimer(options.heartbeatInterval, HEARTBEAT_IVL_TIMER_ID); } else if (id == HEARTBEAT_TTL_TIMER_ID) { hasTtlTimer = false; error(ErrorReason.TIMEOUT); } else if (id == HEARTBEAT_TIMEOUT_TIMER_ID) { hasTimeoutTimer = false; error(ErrorReason.TIMEOUT); } else { // There are no other valid timer ids! assert (false); } } private Msg producePingMessage() { assert (mechanism != null); Msg msg = new Msg(7 + heartbeatContext.length); msg.setFlags(Msg.COMMAND); Msgs.put(msg, "PING"); Wire.putUInt16(msg, options.heartbeatTtl); msg.put(heartbeatContext); msg = mechanism.encode(msg); nextMsg = pullAndEncode; if (!hasTimeoutTimer && heartbeatTimeout > 0) { ioObject.addTimer(heartbeatTimeout, HEARTBEAT_TIMEOUT_TIMER_ID); hasTimeoutTimer = true; } return msg; } private Msg producePongMessage(byte[] pingContext) { assert (mechanism != null); assert (pingContext != null); Msg msg = new Msg(5 + pingContext.length); msg.setFlags(Msg.COMMAND); Msgs.put(msg, "PONG"); msg.put(pingContext); msg = mechanism.encode(msg); nextMsg = pullAndEncode; return msg; } private boolean processCommand(Msg msg) { if (Msgs.startsWith(msg, "PING", true)) { return processHeartbeatMessage(msg); } return false; } private boolean processHeartbeatMessage(Msg msg) { // Get the remote heartbeat TTL to setup the timer int remoteHeartbeatTtl = msg.getShort(5); // The remote heartbeat is in 10ths of a second // so we multiply it by 100 to get the timer interval in ms. remoteHeartbeatTtl *= 100; if (!hasTtlTimer && remoteHeartbeatTtl > 0) { ioObject.addTimer(remoteHeartbeatTtl, HEARTBEAT_TTL_TIMER_ID); hasTtlTimer = true; } // extract the ping context that will be sent back inside the pong message int remaining = msg.size() - 7; // As per ZMTP 3.1 the PING command might contain an up to 16 bytes // context which needs to be PONGed back, so build the pong message // here and store it. Truncate it if it's too long. // Given the engine goes straight to outEvent(), sequential PINGs will // not be a problem. if (remaining > 16) { remaining = 16; } final byte[] pingContext = new byte[remaining]; msg.getBytes(7, pingContext, 0, remaining); nextMsg = new ProducePongMessage(pingContext); outEvent(); return true; } // Writes data to the socket. Returns the number of bytes actually // written (even zero is to be considered to be a success). In case // of error or orderly shutdown by the other peer -1 is returned. private int write(ByteBuffer outbuf) { int nbytes; try { nbytes = fd.write(outbuf); if (nbytes == 0) { errno.set(ZError.EAGAIN); } } catch (IOException e) { errno.set(ZError.ENOTCONN); nbytes = -1; } return nbytes; } // Reads data from the socket (up to 'size' bytes). // Returns the number of bytes actually read or -1 on error. // Zero indicates the peer has closed the connection. private int read(ByteBuffer buf) { int nbytes; try { nbytes = fd.read(buf); if (nbytes == -1) { errno.set(ZError.ENOTCONN); } else if (nbytes == 0) { if (!fd.isBlocking()) { // If not a single byte can be read from the socket in non-blocking mode // we'll get an error (this may happen during the speculative read). // Several errors are OK. When speculative read is being done we may not // be able to read a single byte from the socket. Also, SIGSTOP issued // by a debugging tool can result in EINTR error. errno.set(ZError.EAGAIN); nbytes = -1; } } } catch (IOException e) { errno.set(ZError.ENOTCONN); nbytes = -1; } return nbytes; } @Override public String toString() { return getClass().getSimpleName() + socket + "-" + zmtpVersion; } }
package zmq.io; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.util.Arrays; import java.util.function.Function; import java.util.function.Supplier; import zmq.Config; import zmq.Msg; import zmq.Options; import zmq.SocketBase; import zmq.ZError; import zmq.ZMQ; import zmq.io.coder.IDecoder; import zmq.io.coder.IDecoder.Step; import zmq.io.coder.IEncoder; import zmq.io.coder.raw.RawDecoder; import zmq.io.coder.raw.RawEncoder; import zmq.io.coder.v1.V1Decoder; import zmq.io.coder.v1.V1Encoder; import zmq.io.coder.v2.V2Decoder; import zmq.io.coder.v2.V2Encoder; import zmq.io.mechanism.Mechanism; import zmq.io.mechanism.Mechanisms; import zmq.io.net.Address; import zmq.poll.IPollEvents; import zmq.poll.Poller; import zmq.util.Blob; import zmq.util.Errno; import zmq.util.Utils; import zmq.util.ValueReference; import zmq.util.Wire; // This engine handles any socket with SOCK_STREAM semantics, // e.g. TCP socket or an UNIX domain socket. public class StreamEngine implements IEngine, IPollEvents { private final class ProducePongMessage implements Supplier<Msg> { private final byte[] pingContext; public ProducePongMessage(byte[] pingContext) { assert (pingContext != null); this.pingContext = pingContext; } @Override public Msg get() { return producePongMessage(pingContext); } } // Protocol revisions private enum Protocol { V0(-1), V1(0), V2(1), V3(3); private final byte revision; Protocol(int revision) { this.revision = (byte) revision; } } public enum ErrorReason { PROTOCOL, CONNECTION, TIMEOUT, } private IOObject ioObject; // Underlying socket. private SocketChannel fd; // True if this is server's engine. // private boolean asServer; // private Msg txMsg; private Poller.Handle handle; private ByteBuffer inpos; private int insize; private IDecoder decoder; private final ValueReference<ByteBuffer> outpos; private int outsize; private IEncoder encoder; private Metadata metadata; // When true, we are still trying to determine whether // the peer is using versioned protocol, and if so, which // version. When false, normal message flow has started. private boolean handshaking; private static final int SIGNATURE_SIZE = 10; // Size of ZMTP/1.0 and ZMTP/2.0 greeting message private static final int V2_GREETING_SIZE = 12; // Size of ZMTP/3.0 greeting message private static final int V3_GREETING_SIZE = 64; // Expected greeting size. private int greetingSize; // Greeting received from, and sent to peer private final ByteBuffer greetingRecv; private final ByteBuffer greetingSend; // handy reminder of the used ZMTP protocol version private Protocol zmtpVersion; // The session this engine is attached to. private SessionBase session; private Options options; // String representation of endpoint private String endpoint; private boolean plugged; private Supplier<Msg> nextMsg; private Function<Msg, Boolean> processMsg; private boolean ioError; // Indicates whether the engine is to inject a phantom // subscription message into the incoming stream. // Needed to support old peers. private boolean subscriptionRequired; private Mechanism mechanism; // True if the engine couldn't consume the last decoded message. private boolean inputStopped; // True if the engine doesn't have any message to encode. private boolean outputStopped; // ID of the handshake timer private static final int HANDSHAKE_TIMER_ID = 0x40; private static final int HEARTBEAT_TTL_TIMER_ID = 0x80; private static final int HEARTBEAT_IVL_TIMER_ID = 0x81; private static final int HEARTBEAT_TIMEOUT_TIMER_ID = 0x82; // True is linger timer is running. private boolean hasHandshakeTimer; private boolean hasTtlTimer; private boolean hasTimeoutTimer; private boolean hasHeartbeatTimer; private final int heartbeatTimeout; private final byte[] heartbeatContext; // Socket private SocketBase socket; private Address peerAddress; private final Errno errno; public StreamEngine(SocketChannel fd, final Options options, final String endpoint) { this.errno = options.errno; this.fd = fd; this.handshaking = true; greetingSize = V2_GREETING_SIZE; this.options = options; this.endpoint = endpoint; nextMsg = nextIdentity; processMsg = processIdentity; outpos = new ValueReference<>(); greetingRecv = ByteBuffer.allocate(V3_GREETING_SIZE); greetingSend = ByteBuffer.allocate(V3_GREETING_SIZE); // Put the socket into non-blocking mode. try { Utils.unblockSocket(this.fd); } catch (IOException e) { throw new ZError.IOException(e); } peerAddress = Utils.getPeerIpAddress(fd); heartbeatTimeout = heartbeatTimeout(); heartbeatContext = Arrays.copyOf(options.heartbeatContext, options.heartbeatContext.length); } private int heartbeatTimeout() { int timeout = 0; if (options.heartbeatInterval > 0) { timeout = options.heartbeatTimeout; if (timeout == -1) { timeout = options.heartbeatInterval; } } return timeout; } public void destroy() { assert (!plugged); if (fd != null) { try { fd.close(); } catch (IOException e) { assert (false); } fd = null; } if (encoder != null) { encoder.destroy(); } if (decoder != null) { decoder.destroy(); } if (mechanism != null) { mechanism.destroy(); } } @Override public void plug(IOThread ioThread, SessionBase session) { assert (!plugged); plugged = true; // Connect to session object. assert (this.session == null); assert (session != null); this.session = session; socket = session.getSocket(); // Connect to I/O threads poller object. ioObject = new IOObject(ioThread, this); ioObject.plug(); handle = ioObject.addFd(fd); ioError = false; if (options.rawSocket) { decoder = (IDecoder) instantiate(options.decoder, Config.IN_BATCH_SIZE.getValue(), options.maxMsgSize); if (decoder == null) { decoder = new RawDecoder(Config.IN_BATCH_SIZE.getValue()); } encoder = (IEncoder) instantiate(options.encoder, Config.OUT_BATCH_SIZE.getValue(), options.maxMsgSize); if (encoder == null) { encoder = new RawEncoder(errno, Config.OUT_BATCH_SIZE.getValue()); } // disable handshaking for raw socket handshaking = false; nextMsg = pullMsgFromSession; processMsg = pushRawMsgToSession; if (peerAddress != null && !peerAddress.address().isEmpty()) { assert (metadata == null); // Compile metadata metadata = new Metadata(); metadata.set(Metadata.PEER_ADDRESS, peerAddress.address()); } // For raw sockets, send an initial 0-length message to the // application so that it knows a peer has connected. Msg connector = new Msg(); pushRawMsgToSession(connector); session.flush(); } else { // start optional timer, to prevent handshake hanging on no input setHandshakeTimer(); // Send the 'length' and 'flags' fields of the identity message. // The 'length' field is encoded in the long format. greetingSend.put((byte) 0xff); Wire.putUInt64(greetingSend, options.identitySize + 1); greetingSend.put((byte) 0x7f); outpos.set(greetingSend); outsize = greetingSend.position(); greetingSend.flip(); } ioObject.setPollIn(handle); ioObject.setPollOut(handle); // Flush all the data that may have been already received downstream. inEvent(); } private Object instantiate(Class<?> decoder, int size, long max) { if (decoder == null) { return null; } try { return decoder.getConstructor(int.class, long.class).newInstance(size, max); } catch (Exception e) { e.printStackTrace(); return null; } } private void unplug() { assert (plugged); plugged = false; // Cancel all timers. if (hasHandshakeTimer) { ioObject.cancelTimer(HANDSHAKE_TIMER_ID); hasHandshakeTimer = false; } if (hasTtlTimer) { ioObject.cancelTimer(HEARTBEAT_TTL_TIMER_ID); hasTtlTimer = false; } if (hasTimeoutTimer) { ioObject.cancelTimer(HEARTBEAT_TIMEOUT_TIMER_ID); hasTimeoutTimer = false; } if (hasHeartbeatTimer) { ioObject.cancelTimer(HEARTBEAT_IVL_TIMER_ID); hasHeartbeatTimer = false; } if (!ioError) { // Cancel all fd subscriptions. ioObject.removeHandle(handle); handle = null; } // Disconnect from I/O threads poller object. ioObject.unplug(); session = null; } @Override public void terminate() { unplug(); destroy(); } @Override public void inEvent() { assert (!ioError); // If still handshaking, receive and process the greeting message. if (handshaking) { if (!handshake()) { return; } } assert (decoder != null); // If there has been an I/O error, stop polling. if (inputStopped) { ioObject.removeHandle(handle); handle = null; ioError = true; return; } // If there's no data to process in the buffer... if (insize == 0) { // Retrieve the buffer and read as much data as possible. // Note that buffer can be arbitrarily large. However, we assume // the underlying TCP layer has fixed buffer size and thus the // number of bytes read will be always limited. inpos = decoder.getBuffer(); int rc = read(inpos); if (rc == 0) { error(ErrorReason.CONNECTION); } if (rc == -1) { if (!errno.is(ZError.EAGAIN)) { error(ErrorReason.CONNECTION); } return; } // Adjust input size inpos.flip(); insize = rc; } boolean rc = false; ValueReference<Integer> processed = new ValueReference<>(0); while (insize > 0) { // Push the data to the decoder. Step.Result result = decoder.decode(inpos, insize, processed); assert (processed.get() <= insize); insize -= processed.get(); if (result == Step.Result.MORE_DATA) { rc = true; break; } if (result == Step.Result.ERROR) { rc = false; break; } Msg msg = decoder.msg(); rc = processMsg.apply(msg); if (!rc) { break; } } // Tear down the connection if we have failed to decode input data // or the session has rejected the message. if (!rc) { if (!errno.is(ZError.EAGAIN)) { error(ErrorReason.PROTOCOL); return; } inputStopped = true; ioObject.resetPollIn(handle); } // Flush all messages the decoder may have produced. session.flush(); } @Override public void outEvent() { assert (!ioError); // If write buffer is empty, try to read new data from the encoder. if (outsize == 0) { // Even when we stop polling as soon as there is no // data to send, the poller may invoke outEvent one // more time due to 'speculative write' optimization. if (encoder == null) { assert (handshaking); return; } outpos.set(null); outsize = encoder.encode(outpos, 0); while (outsize < Config.OUT_BATCH_SIZE.getValue()) { Msg msg = nextMsg.get(); if (msg == null) { break; } encoder.loadMsg(msg); int n = encoder.encode(outpos, Config.OUT_BATCH_SIZE.getValue() - outsize); assert (n > 0); outsize += n; } // If there is no data to send, stop polling for output. if (outsize == 0) { outputStopped = true; ioObject.resetPollOut(handle); return; } // slight difference with libzmq: // encoder is notified of the end of the loading encoder.encoded(); } // If there are any data to write in write buffer, write as much as // possible to the socket. Note that amount of data to write can be // arbitrarily large. However, we assume that underlying TCP layer has // limited transmission buffer and thus the actual number of bytes // written should be reasonably modest. int nbytes = write(outpos.get()); // IO error has occurred. We stop waiting for output events. // The engine is not terminated until we detect input error; // this is necessary to prevent losing incoming messages. if (nbytes == -1) { ioObject.resetPollOut(handle); return; } outsize -= nbytes; // If we are still handshaking and there are no data // to send, stop polling for output. if (handshaking) { if (outsize == 0) { ioObject.resetPollOut(handle); } } } @Override public void restartOutput() { if (ioError) { return; } if (outputStopped) { ioObject.setPollOut(handle); outputStopped = false; } // Speculative write: The assumption is that at the moment new message // was sent by the user the socket is probably available for writing. // Thus we try to write the data to socket avoiding polling for POLLOUT. // Consequently, the latency should be better in request/reply scenarios. outEvent(); } @Override public void restartInput() { assert (inputStopped); assert (session != null); assert (decoder != null); Msg msg = decoder.msg(); if (!processMsg.apply(msg)) { if (errno.is(ZError.EAGAIN)) { session.flush(); } else { error(ErrorReason.PROTOCOL); } return; } boolean rc = decodeInputsGetRC(); if (!rc && errno.is(ZError.EAGAIN)) { session.flush(); } else if (ioError) { error(ErrorReason.CONNECTION); } else if (!rc) { error(ErrorReason.PROTOCOL); } else { inputStopped = false; ioObject.setPollIn(handle); session.flush(); // Speculative read. inEvent(); } } private boolean decodeInputsGetRC() { boolean rc = true; while (insize > 0 && rc) { ValueReference<Integer> processed = new ValueReference<>(0); Step.Result result = decoder.decode(inpos, insize, processed); assert (processed.get() <= insize); insize -= processed.get(); if (result == Step.Result.MORE_DATA) { return true; } if (result == Step.Result.ERROR) { return false; } rc = processMsg.apply(decoder.msg()); } return rc; } // Detects the protocol used by the peer. private boolean handshake() { assert (handshaking); assert (greetingRecv.position() < greetingSize); // Position of the version field in the greeting. final int revisionPos = SIGNATURE_SIZE; // Receive the greeting. while (greetingRecv.position() < greetingSize) { final int n = read(greetingRecv); if (n == 0) { error(ErrorReason.CONNECTION); return false; } if (n == -1) { if (!errno.is(ZError.EAGAIN)) { error(ErrorReason.CONNECTION); } return false; } // We have received at least one byte from the peer. // If the first byte is not 0xff, we know that the // peer is using unversioned protocol. if ((greetingRecv.get(0) & 0xff) != 0xff) { // If this first byte is not %FF, // then the other peer is using ZMTP 1.0. break; } if (greetingRecv.position() < SIGNATURE_SIZE) { continue; } // Inspect the right-most bit of the 10th byte (which coincides // with the 'flags' field if a regular message was sent). // Zero indicates this is a header of identity message // (i.e. the peer is using the unversioned protocol). if ((greetingRecv.get(9) & 0x01) != 0x01) { break; } // If the least significant bit is 1, the peer is using ZMTP 2.0 or later // and has sent us the ZMTP signature. int outpos = greetingSend.position(); // The peer is using versioned protocol. // Send the major version number. if (greetingSend.limit() == SIGNATURE_SIZE) { if (outsize == 0) { ioObject.setPollOut(handle); } greetingSend.limit(SIGNATURE_SIZE + 1); greetingSend.put(revisionPos, Protocol.V3.revision); // Major version number outsize += 1; } if (greetingRecv.position() > SIGNATURE_SIZE) { if (greetingSend.limit() == SIGNATURE_SIZE + 1) { if (outsize == 0) { ioObject.setPollOut(handle); } // We read a further byte, which indicates the ZMTP version. byte protocol = greetingRecv.get(revisionPos); if (protocol == Protocol.V1.revision || protocol == Protocol.V2.revision) { // If this is V1 or V2, we have a ZMTP 2.0 peer. greetingSend.limit(V2_GREETING_SIZE); greetingSend.position(SIGNATURE_SIZE + 1); greetingSend.put((byte) options.type); // Socket type outsize += 1; } else { // If this is 3 or greater, we have a ZMTP 3.0 peer. greetingSend.limit(V3_GREETING_SIZE); greetingSend.position(SIGNATURE_SIZE + 1); greetingSend.put((byte) 0); // Minor version number outsize += 1; greetingSend.mark(); greetingSend.put(new byte[20]); assert (options.mechanism == Mechanisms.NULL || options.mechanism == Mechanisms.PLAIN || options.mechanism == Mechanisms.CURVE || options.mechanism == Mechanisms.GSSAPI); greetingSend.reset(); greetingSend.put(options.mechanism.name().getBytes(ZMQ.CHARSET)); greetingSend.reset(); greetingSend.position(greetingSend.position() + 20); outsize += 20; greetingSend.put(new byte[32]); outsize += 32; greetingSize = V3_GREETING_SIZE; } } } greetingSend.position(outpos); } // Is the peer using the unversioned protocol? // If so, we send and receive rest of identity // messages. if ((greetingRecv.get(0) & 0xff) != 0xff || (greetingRecv.get(9) & 0x01) == 0) { // If this first byte is %FF, then we read nine further bytes, // and inspect the last byte (the 10th in total). // If the least significant bit is 0, then the other peer is using ZMTP 1.0. if (session.zapEnabled()) { // reject ZMTP 1.0 connections if ZAP is enabled error(ErrorReason.PROTOCOL); return false; } zmtpVersion = Protocol.V0; encoder = new V1Encoder(errno, Config.OUT_BATCH_SIZE.getValue()); decoder = new V1Decoder(errno, Config.IN_BATCH_SIZE.getValue(), options.maxMsgSize, options.allocator); // We have already sent the message header. // Since there is no way to tell the encoder to // skip the message header, we simply throw that // header data away. final int headerSize = options.identitySize + 1 >= 255 ? 10 : 2; ByteBuffer tmp = ByteBuffer.allocate(headerSize); // Prepare the identity message and load it into encoder. // Then consume bytes we have already sent to the peer. Msg txMsg = new Msg(options.identitySize); txMsg.put(options.identity, 0, options.identitySize); encoder.loadMsg(txMsg); ValueReference<ByteBuffer> bufferp = new ValueReference<>(tmp); int bufferSize = encoder.encode(bufferp, headerSize); assert (bufferSize == headerSize); // Make sure the decoder sees the data we have already received. decodeDataAfterHandshake(0); // To allow for interoperability with peers that do not forward // their subscriptions, we inject a phantom subscription message // message into the incoming message stream. if (options.type == ZMQ.ZMQ_PUB || options.type == ZMQ.ZMQ_XPUB) { subscriptionRequired = true; } // We are sending our identity now and the next message // will come from the socket. nextMsg = pullMsgFromSession; // We are expecting identity message. processMsg = processIdentity; } else if (greetingRecv.get(revisionPos) == Protocol.V1.revision) { // ZMTP/1.0 framing. zmtpVersion = Protocol.V1; if (session.zapEnabled()) { // reject ZMTP 1.0 connections if ZAP is enabled error(ErrorReason.PROTOCOL); return false; } encoder = new V1Encoder(errno, Config.OUT_BATCH_SIZE.getValue()); decoder = new V1Decoder(errno, Config.IN_BATCH_SIZE.getValue(), options.maxMsgSize, options.allocator); decodeDataAfterHandshake(V2_GREETING_SIZE); } else if (greetingRecv.get(revisionPos) == Protocol.V2.revision) { // ZMTP/2.0 framing. zmtpVersion = Protocol.V2; if (session.zapEnabled()) { // reject ZMTP 2.0 connections if ZAP is enabled error(ErrorReason.PROTOCOL); return false; } encoder = new V2Encoder(errno, Config.OUT_BATCH_SIZE.getValue()); decoder = new V2Decoder(errno, Config.IN_BATCH_SIZE.getValue(), options.maxMsgSize, options.allocator); decodeDataAfterHandshake(V2_GREETING_SIZE); } else { zmtpVersion = Protocol.V3; encoder = new V2Encoder(errno, Config.OUT_BATCH_SIZE.getValue()); decoder = new V2Decoder(errno, Config.IN_BATCH_SIZE.getValue(), options.maxMsgSize, options.allocator); greetingRecv.position(V2_GREETING_SIZE); if (options.mechanism == null) { error(ErrorReason.PROTOCOL); return false; } else { if (options.mechanism.isMechanism(greetingRecv)) { mechanism = options.mechanism.create(session, peerAddress, options); } else { error(ErrorReason.PROTOCOL); return false; } } nextMsg = nextHandshakeCommand; processMsg = processHandshakeCommand; } // Start polling for output if necessary. if (outsize == 0) { ioObject.setPollOut(handle); } // Handshaking was successful. // Switch into the normal message flow. handshaking = false; if (hasHandshakeTimer) { ioObject.cancelTimer(HANDSHAKE_TIMER_ID); hasHandshakeTimer = false; } socket.eventHandshaken(endpoint, zmtpVersion.ordinal()); return true; } private void decodeDataAfterHandshake(int greetingSize) { final int pos = greetingRecv.position(); if (pos > greetingSize) { // data is present after handshake greetingRecv.position(greetingSize).limit(pos); // Make sure the decoder sees this extra data. inpos = greetingRecv; insize = greetingRecv.remaining(); } } private Msg identityMsg() { Msg msg = new Msg(options.identitySize); if (options.identitySize > 0) { msg.put(options.identity, 0, options.identitySize); } nextMsg = pullMsgFromSession; return msg; } private boolean processIdentityMsg(Msg msg) { if (options.recvIdentity) { msg.setFlags(Msg.IDENTITY); boolean rc = session.pushMsg(msg); assert (rc); } if (subscriptionRequired) { // Inject the subscription message, so that also // ZMQ 2.x peers receive published messages. Msg subscription = new Msg(1); subscription.put((byte) 1); boolean rc = session.pushMsg(subscription); assert (rc); } processMsg = pushMsgToSession; return true; } private final Function<Msg, Boolean> processIdentity = this::processIdentityMsg; private final Supplier<Msg> nextIdentity = this::identityMsg; private Msg nextHandshakeCommand() { assert (mechanism != null); if (mechanism.status() == Mechanism.Status.READY) { mechanismReady(); return pullAndEncode.get(); } else if (mechanism.status() == Mechanism.Status.ERROR) { errno.set(ZError.EPROTO); // error(ErrorReason.PROTOCOL); return null; } else { Msg.Builder msg = new Msg.Builder(); int rc = mechanism.nextHandshakeCommand(msg); if (rc == 0) { msg.setFlags(Msg.COMMAND); return msg.build(); } else { errno.set(rc); return null; } } } private boolean processHandshakeCommand(Msg msg) { assert (mechanism != null); int rc = mechanism.processHandshakeCommand(msg); if (rc == 0) { if (mechanism.status() == Mechanism.Status.READY) { mechanismReady(); } else if (mechanism.status() == Mechanism.Status.ERROR) { errno.set(ZError.EPROTO); return false; } if (outputStopped) { restartOutput(); } } else { errno.set(rc); } return rc == 0; } private final Function<Msg, Boolean> processHandshakeCommand = this::processHandshakeCommand; private final Supplier<Msg> nextHandshakeCommand = this::nextHandshakeCommand; @Override public void zapMsgAvailable() { assert (mechanism != null); int rc = mechanism.zapMsgAvailable(); if (rc == -1) { error(ErrorReason.PROTOCOL); return; } if (inputStopped) { restartInput(); } if (outputStopped) { restartOutput(); } } private void mechanismReady() { if (options.heartbeatInterval > 0) { ioObject.addTimer(options.heartbeatInterval, HEARTBEAT_IVL_TIMER_ID); hasHeartbeatTimer = true; } if (options.recvIdentity) { Msg identity = mechanism.peerIdentity(); boolean rc = session.pushMsg(identity); if (!rc && errno.is(ZError.EAGAIN)) { // If the write is failing at this stage with // an EAGAIN the pipe must be being shut down, // so we can just bail out of the identity set. return; } assert (rc); session.flush(); } nextMsg = pullAndEncode; processMsg = writeCredential; // Compile metadata. assert (metadata == null); metadata = new Metadata(); // If we have a peer_address, add it to metadata if (peerAddress != null && !peerAddress.address().isEmpty()) { metadata.set(Metadata.PEER_ADDRESS, peerAddress.address()); } // Add ZAP properties. metadata.set(mechanism.zapProperties); // Add ZMTP properties. metadata.set(mechanism.zmtpProperties); if (metadata.isEmpty()) { metadata = null; } } private Msg pullMsgFromSession() { return session.pullMsg(); } private boolean pushMsgToSession(Msg msg) { return session.pushMsg(msg); } private final Function<Msg, Boolean> pushMsgToSession = this::pushMsgToSession; private final Supplier<Msg> pullMsgFromSession = this::pullMsgFromSession; private boolean pushRawMsgToSession(Msg msg) { if (metadata != null && !metadata.equals(msg.getMetadata())) { msg.setMetadata(metadata); } return pushMsgToSession(msg); } private final Function<Msg, Boolean> pushRawMsgToSession = this::pushRawMsgToSession; private boolean writeCredential(Msg msg) { assert (mechanism != null); assert (session != null); Blob credential = mechanism.getUserId(); if (credential != null && credential.size() > 0) { Msg cred = new Msg(credential.size()); cred.put(credential.data(), 0, credential.size()); cred.setFlags(Msg.CREDENTIAL); boolean rc = session.pushMsg(cred); if (!rc) { return false; } } processMsg = decodeAndPush; return decodeAndPush.apply(msg); } private final Function<Msg, Boolean> writeCredential = this::writeCredential; private Msg pullAndEncode() { assert (mechanism != null); Msg msg = session.pullMsg(); if (msg == null) { return null; } msg = mechanism.encode(msg); return msg; } private final Supplier<Msg> pullAndEncode = this::pullAndEncode; private boolean decodeAndPush(Msg msg) { assert (mechanism != null); msg = mechanism.decode(msg); if (msg == null) { return false; } if (hasTimeoutTimer) { hasTimeoutTimer = false; ioObject.cancelTimer(HEARTBEAT_TIMEOUT_TIMER_ID); } if (hasTtlTimer) { hasTtlTimer = false; ioObject.cancelTimer(HEARTBEAT_TTL_TIMER_ID); } if (msg.isCommand()) { StreamEngine.this.processCommand(msg); } if (metadata != null) { msg.setMetadata(metadata); } boolean rc = session.pushMsg(msg); if (!rc) { if (errno.is(ZError.EAGAIN)) { processMsg = pushOneThenDecodeAndPush; } return false; } return true; } private final Function<Msg, Boolean> decodeAndPush = this::decodeAndPush; private boolean pushOneThenDecodeAndPush(Msg msg) { boolean rc = session.pushMsg(msg); if (rc) { processMsg = decodeAndPush; } return rc; } private final Function<Msg, Boolean> pushOneThenDecodeAndPush = this::pushOneThenDecodeAndPush; private final Supplier<Msg> producePingMessage = this::producePingMessage; // Function to handle network disconnections. private void error(ErrorReason error) { if (options.rawSocket) { // For raw sockets, send a final 0-length message to the application // so that it knows the peer has been disconnected. Msg terminator = new Msg(); processMsg.apply(terminator); } assert (session != null); socket.eventDisconnected(endpoint, fd); session.flush(); session.engineError(error); unplug(); destroy(); } private void setHandshakeTimer() { assert (!hasHandshakeTimer); if (!options.rawSocket && options.handshakeIvl > 0) { ioObject.addTimer(options.handshakeIvl, HANDSHAKE_TIMER_ID); hasHandshakeTimer = true; } } @Override public void timerEvent(int id) { if (id == HANDSHAKE_TIMER_ID) { hasHandshakeTimer = false; // handshake timer expired before handshake completed, so engine fails error(ErrorReason.TIMEOUT); } else if (id == HEARTBEAT_IVL_TIMER_ID) { nextMsg = producePingMessage; outEvent(); ioObject.addTimer(options.heartbeatInterval, HEARTBEAT_IVL_TIMER_ID); } else if (id == HEARTBEAT_TTL_TIMER_ID) { hasTtlTimer = false; error(ErrorReason.TIMEOUT); } else if (id == HEARTBEAT_TIMEOUT_TIMER_ID) { hasTimeoutTimer = false; error(ErrorReason.TIMEOUT); } else { // There are no other valid timer ids! assert (false); } } private Msg producePingMessage() { assert (mechanism != null); Msg msg = new Msg(7 + heartbeatContext.length); msg.setFlags(Msg.COMMAND); Msgs.put(msg, "PING"); Wire.putUInt16(msg, options.heartbeatTtl); msg.put(heartbeatContext); msg = mechanism.encode(msg); nextMsg = pullAndEncode; if (!hasTimeoutTimer && heartbeatTimeout > 0) { ioObject.addTimer(heartbeatTimeout, HEARTBEAT_TIMEOUT_TIMER_ID); hasTimeoutTimer = true; } return msg; } private Msg producePongMessage(byte[] pingContext) { assert (mechanism != null); assert (pingContext != null); Msg msg = new Msg(5 + pingContext.length); msg.setFlags(Msg.COMMAND); Msgs.put(msg, "PONG"); msg.put(pingContext); msg = mechanism.encode(msg); nextMsg = pullAndEncode; return msg; } private boolean processCommand(Msg msg) { if (Msgs.startsWith(msg, "PING", true)) { return processHeartbeatMessage(msg); } return false; } private boolean processHeartbeatMessage(Msg msg) { // Get the remote heartbeat TTL to setup the timer int remoteHeartbeatTtl = msg.getShort(5); // The remote heartbeat is in 10ths of a second // so we multiply it by 100 to get the timer interval in ms. remoteHeartbeatTtl *= 100; if (!hasTtlTimer && remoteHeartbeatTtl > 0) { ioObject.addTimer(remoteHeartbeatTtl, HEARTBEAT_TTL_TIMER_ID); hasTtlTimer = true; } // extract the ping context that will be sent back inside the pong message int remaining = msg.size() - 7; // As per ZMTP 3.1 the PING command might contain an up to 16 bytes // context which needs to be PONGed back, so build the pong message // here and store it. Truncate it if it's too long. // Given the engine goes straight to outEvent(), sequential PINGs will // not be a problem. if (remaining > 16) { remaining = 16; } final byte[] pingContext = new byte[remaining]; msg.getBytes(7, pingContext, 0, remaining); nextMsg = new ProducePongMessage(pingContext); outEvent(); return true; } // Writes data to the socket. Returns the number of bytes actually // written (even zero is to be considered to be a success). In case // of error or orderly shutdown by the other peer -1 is returned. private int write(ByteBuffer outbuf) { int nbytes; try { nbytes = fd.write(outbuf); if (nbytes == 0) { errno.set(ZError.EAGAIN); } } catch (IOException e) { errno.set(ZError.ENOTCONN); nbytes = -1; } return nbytes; } // Reads data from the socket (up to 'size' bytes). // Returns the number of bytes actually read or -1 on error. // Zero indicates the peer has closed the connection. private int read(ByteBuffer buf) { int nbytes; try { nbytes = fd.read(buf); if (nbytes == -1) { errno.set(ZError.ENOTCONN); } else if (nbytes == 0) { if (!fd.isBlocking()) { // If not a single byte can be read from the socket in non-blocking mode // we'll get an error (this may happen during the speculative read). // Several errors are OK. When speculative read is being done we may not // be able to read a single byte from the socket. Also, SIGSTOP issued // by a debugging tool can result in EINTR error. errno.set(ZError.EAGAIN); nbytes = -1; } } } catch (IOException e) { errno.set(ZError.ENOTCONN); nbytes = -1; } return nbytes; } @Override public String toString() { return getClass().getSimpleName() + socket + "-" + zmtpVersion; } }
package org.bimserver.starter; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.io.BufferedInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLDecoder; import java.util.Enumeration; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.Manifest; import javax.imageio.ImageIO; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SpringLayout; import javax.swing.UIManager; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Starter extends JFrame { private static final long serialVersionUID = 5356018168589837130L; private Process exec; private JarSettings jarSettings = JarSettings.readFromFile(); private JTextField addressField; private JTextField portField; private JTextField heapSizeField; private JTextField permSizeField; private JTextField stackSizeField; private JButton browserHomeDir; private JButton browserJvm; private JTextField jvmField; private JTextField homeDirField; public static void main(String[] args) { new Starter().start(); } private void start() { final JTextArea logField = new JTextArea(); final PrintStream systemOut = System.out; PrintStream out = new PrintStream(new OutputStream() { @Override public void write(byte[] bytes, int off, int len) throws IOException { String str = new String(bytes, off, len); systemOut.append(str); logField.append(str); logField.setCaretPosition(logField.getDocument().getLength()); } @Override public void write(int b) throws IOException { String str = new String(new char[] { (char) b }); systemOut.append(str); logField.append(str); logField.setCaretPosition(logField.getDocument().getLength()); } }); System.setOut(out); System.setErr(out); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setTitle("BIMserver Starter"); try { setIconImage(ImageIO.read(getClass().getResource("logo_small.png"))); } catch (IOException e) { e.printStackTrace(); } setSize(640, 500); getContentPane().setLayout(new BorderLayout()); JPanel fields = new JPanel(new SpringLayout()); JLabel jvmLabel = new JLabel("JVM"); fields.add(jvmLabel); jvmField = new JTextField(jarSettings.getJvm()); browserJvm = new JButton("Browse..."); browserJvm.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { File currentFile = new File(jvmField.getText()); JFileChooser chooser = new JFileChooser(currentFile.exists() ? currentFile : new File(".")); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int showOpenDialog = chooser.showOpenDialog(Starter.this); if (showOpenDialog == JFileChooser.APPROVE_OPTION) { jvmField.setText(chooser.getSelectedFile().getAbsolutePath()); } } }); JPanel jvmPanel = new JPanel(); jvmPanel.setLayout(new BorderLayout()); jvmPanel.add(jvmField, BorderLayout.CENTER); jvmPanel.add(browserJvm, BorderLayout.EAST); fields.add(jvmPanel); JLabel homeDirLabel = new JLabel("Home directory"); fields.add(homeDirLabel); homeDirField = new JTextField(jarSettings.getHomedir()); browserHomeDir = new JButton("Browse..."); browserHomeDir.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { File currentFile = new File(homeDirField.getText()); JFileChooser chooser = new JFileChooser(currentFile.exists() ? currentFile : new File(".")); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int showOpenDialog = chooser.showOpenDialog(Starter.this); if (showOpenDialog == JFileChooser.APPROVE_OPTION) { homeDirField.setText(chooser.getSelectedFile().getAbsolutePath()); } } }); JPanel homeDirPanel = new JPanel(); homeDirPanel.setLayout(new BorderLayout()); homeDirPanel.add(homeDirField, BorderLayout.CENTER); homeDirPanel.add(browserHomeDir, BorderLayout.EAST); fields.add(homeDirPanel); JLabel addressLabel = new JLabel("Address"); fields.add(addressLabel); addressField = new JTextField(jarSettings.getAddress()); fields.add(addressField); JLabel portLabel = new JLabel("Port"); fields.add(portLabel); portField = new JTextField(jarSettings.getPort() + ""); fields.add(portField); JLabel heapSizeLabel = new JLabel("Max Heap Size"); fields.add(heapSizeLabel); heapSizeField = new JTextField(jarSettings.getHeapsize()); fields.add(heapSizeField); JLabel permSizeLabel = new JLabel("Max Perm Size"); fields.add(permSizeLabel); permSizeField = new JTextField(jarSettings.getPermsize()); fields.add(permSizeField); JLabel stackSizeLabel = new JLabel("Stack Size"); fields.add(stackSizeLabel); stackSizeField = new JTextField(jarSettings.getStacksize()); fields.add(stackSizeField); SpringUtilities.makeCompactGrid(fields, 7, 2, // rows, cols 6, 6, // initX, initY 6, 6); // xPad, yPad JPanel buttons = new JPanel(new FlowLayout(FlowLayout.TRAILING)); final JButton startStopButton = new JButton("Start"); startStopButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (startStopButton.getText().equals("Start")) { new Thread(new Runnable() { @Override public void run() { if (jvmField.getText().equalsIgnoreCase("default") || new File(jvmField.getText()).exists()) { setComponentsEnabled(false); File file = expand(); startStopButton.setText("Stop"); start(file, addressField.getText(), portField.getText(), heapSizeField.getText(), stackSizeField.getText(), permSizeField.getText(), jvmField.getText(), homeDirField.getText()); } else { JOptionPane.showMessageDialog(Starter.this, "JVM field should contain a valid JVM directory, or 'default' for the default JVM"); } } }).start(); } else if (startStopButton.getText().equals("Stop")) { if (exec != null) { exec.destroy(); System.out.println("Server has been shut down"); exec = null; startStopButton.setText("Start"); setComponentsEnabled(true); } } } }); DocumentListener documentChangeListener = new DocumentListener() { @Override public void removeUpdate(DocumentEvent e) { save(); } @Override public void insertUpdate(DocumentEvent e) { save(); } @Override public void changedUpdate(DocumentEvent e) { save(); } private void save() { try { jarSettings.setAddress(addressField.getText()); jarSettings.setPort(Integer.parseInt(portField.getText())); jarSettings.setJvm(jvmField.getText()); jarSettings.setStacksize(stackSizeField.getText()); jarSettings.setHeapsize(heapSizeField.getText()); jarSettings.setPermsize(permSizeField.getText()); jarSettings.setHomedir(homeDirField.getText()); jarSettings.save(); } catch (Exception e) { // ignore } } }; jvmField.getDocument().addDocumentListener(documentChangeListener); homeDirField.getDocument().addDocumentListener(documentChangeListener); addressField.getDocument().addDocumentListener(documentChangeListener); portField.getDocument().addDocumentListener(documentChangeListener); permSizeField.getDocument().addDocumentListener(documentChangeListener); heapSizeField.getDocument().addDocumentListener(documentChangeListener); stackSizeField.getDocument().addDocumentListener(documentChangeListener); buttons.add(startStopButton); // JButton launchWebBrowser = new JButton("Launch Webbrowser"); // launchWebBrowser.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent e) { // try { // } catch (Exception e) { // LOGGER.error("", e); // buttons.add(launchWebBrowser); logField.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12)); logField.setEditable(true); logField.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { try { exec.getOutputStream().write(e.getKeyChar()); if (e.getKeyCode() == KeyEvent.VK_ENTER) { exec.getOutputStream().flush(); } } catch (IOException e2) { e2.printStackTrace(); } } }); JScrollPane scrollPane = new JScrollPane(logField); getContentPane().add(fields, BorderLayout.NORTH); getContentPane().add(scrollPane, BorderLayout.CENTER); getContentPane().add(buttons, BorderLayout.SOUTH); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { if (exec != null) { exec.destroy(); } } })); setVisible(true); } private void setComponentsEnabled(boolean enabled) { addressField.setEditable(enabled); portField.setEditable(enabled); heapSizeField.setEditable(enabled); stackSizeField.setEditable(enabled); permSizeField.setEditable(enabled); jvmField.setEditable(enabled); homeDirField.setEditable(enabled); browserHomeDir.setEnabled(enabled); browserJvm.setEnabled(enabled); } private void start(File destDir, String address, String port, String heapsize, String stacksize, String permsize, String jvmPath, String homedir) { try { String command = ""; if (jvmPath.equalsIgnoreCase("default")) { command = "java"; } else { File jvm = new File(jvmPath); if (jvm.exists()) { File jre = new File(jvm, "jre"); if (!jre.exists()) { jre = jvm; } command = new File(jre, "bin" + File.separator + "java").getAbsolutePath(); File jreLib = new File(jre, "lib"); command += " -Xbootclasspath:\""; for (File file : jreLib.listFiles()) { if (file.getName().endsWith(".jar")) { command += file.getAbsolutePath() + File.pathSeparator; } } if (jre != jvm) { command += new File(jvm, "lib" + File.separator + "tools.jar"); } command += "\""; } } command += " -Xmx" + heapsize; command += " -Xss" + stacksize; command += " -XX:MaxPermSize=" + permsize; // boolean debug = true; // if (debug ) { // command += " -Xdebug -Xrunjdwp:transport=dt_socket,address=8998,server=y"; command += " -classpath"; command += " lib" + File.pathSeparator; File dir = new File(destDir + File.separator + "lib"); for (File lib : dir.listFiles()) { if (lib.isFile()) { command += "lib" + File.separator + lib.getName() + File.pathSeparator; } } if (command.endsWith(File.pathSeparator)) { command = command.substring(0, command.length()-1); } Enumeration<URL> resources = getClass().getClassLoader().getResources("META-INF/MANIFEST.MF"); String realMainClass = ""; while (resources.hasMoreElements()) { URL url = resources.nextElement(); Manifest manifest = new Manifest(url.openStream()); Attributes mainAttributes = manifest.getMainAttributes(); for (Object key : mainAttributes.keySet()) { if (key.toString().equals("Real-Main-Class")) { realMainClass = mainAttributes.get(key).toString(); break; } } } System.out.println("Main class: " + realMainClass); command += " " + realMainClass; command += " address=" + address; command += " port=" + port; command += " homedir=\"" + homedir + "\""; System.out.println("Running: " + command); exec = Runtime.getRuntime().exec(command, null, destDir); new Thread(new Runnable(){ @Override public void run() { BufferedInputStream inputStream = new BufferedInputStream(exec.getInputStream()); byte[] buffer = new byte[1024]; int red; try { red = inputStream.read(buffer); while (red != -1) { String s = new String(buffer, 0, red); System.out.print(s); red = inputStream.read(buffer); } } catch (IOException e) { } }}).start(); new Thread(new Runnable(){ @Override public void run() { BufferedInputStream errorStream = new BufferedInputStream(exec.getErrorStream()); byte[] buffer = new byte[1024]; int red; try { red = errorStream.read(buffer); while (red != -1) { String s = new String(buffer, 0, red); System.out.print(s); red = errorStream.read(buffer); } } catch (IOException e) { } }}).start(); } catch (IOException e) { e.printStackTrace(); } } private File expand() { JarFile jar = null; String jarFileName = getJarFileNameNew(); File destDir = new File(jarFileName.substring(0, jarFileName.indexOf(".jar"))); if (!destDir.isDirectory()) { System.out.println("Expanding " + jarFileName); try { jar = new java.util.jar.JarFile(jarFileName); Enumeration<JarEntry> enumr = jar.entries(); while (enumr.hasMoreElements()) { JarEntry file = (JarEntry) enumr.nextElement(); System.out.println(file.getName()); File f = new File(destDir, file.getName()); if (file.isDirectory()) { if (!f.getParentFile().exists()) { f.getParentFile().mkdir(); } f.mkdir(); continue; } InputStream is = jar.getInputStream(file); FileOutputStream fos = new FileOutputStream(f); byte[] buffer = new byte[1024]; int red = is.read(buffer); while (red != -1) { fos.write(buffer, 0, red); red = is.read(buffer); } fos.close(); is.close(); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (jar != null) { jar.close(); } } catch (IOException e) { e.printStackTrace(); } } } else { System.out.println("No expanding necessary"); } return destDir; } private String getJarFileNameNew() { String name = this.getClass().getName().replace(".", "/") + ".class"; URL urlJar = getClass().getClassLoader().getResource(name); String urlString = urlJar.getFile(); urlString = urlString.substring(urlString.indexOf(":") + 1, urlString.indexOf("!")); try { return URLDecoder.decode(urlString, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } }
import java.util.Arrays; public class SieveOfEratosthenes { private boolean[] sieve; /** * Creates a sieve that can be queried for numbers up to maxNumber. * * @param maxNumber */ public SieveOfEratosthenes(final int maxNumber) { initSieve(maxNumber); crossMultiplesOfKnownPrimes(); } private void initSieve(int maxNumber) { this.sieve = new boolean[maxNumber + 1]; Arrays.fill(sieve, true); cross(0); cross(1); } /** * Iterates the sieve and when it finds a prime in it, it'll cross its multiples, since by definition those numbers are not prime. */ private void crossMultiplesOfKnownPrimes() { for (int n = 2; n * n < sieve.length; ++n) { if (isPrime(n)) { crossMultiplesOf(n); } } } /** * Given prime, crosses all multiples of prime in the sieve * * @param prime */ private void crossMultiplesOf(final int prime) { for (int n = prime * prime; n < sieve.length; n += prime) { cross(n); } } /** * Marks n as a non-prime in the sieve. * * @param n */ private void cross(final int n) { sieve[n] = false; } /** * Returns true if n is a prime number, false otherwise. * * @param n * @return */ public boolean isPrime(final int n) { return sieve[n]; } public static void main(String[] args) { int max = 100; SieveOfEratosthenes sieve = new SieveOfEratosthenes(max); for (int n = 0; n < 100; ++n) { if (sieve.isPrime(n)) { System.out.println(n); } } } }
package org.dynmap; import org.dynmap.MapType.ImageFormat; import org.dynmap.common.DynmapListenerManager.EventType; import org.dynmap.common.DynmapListenerManager.PlayerEventListener; import org.dynmap.common.DynmapPlayer; import org.dynmap.debug.Debug; import org.dynmap.storage.MapStorage; import org.dynmap.utils.BufferOutputStream; import org.dynmap.utils.DynmapBufferedImage; import org.dynmap.utils.ImageIOManager; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLEncoder; import java.util.UUID; /** * Listen for player logins, and process player faces by fetching skins * */ public class PlayerFaces { private boolean fetchskins; private boolean refreshskins; private String skinurl; public MapStorage storage; public enum FaceType { FACE_8X8("8x8", 0), FACE_16X16("16x16", 1), FACE_32X32("32x32", 2), BODY_32X32("body", 3); public final String id; public final int typeID; FaceType(String id, int typeid) { this.id = id; this.typeID = typeid; } public static FaceType byID(String i_d) { for (FaceType ft : values()) { if (ft.id.equals(i_d)) { return ft; } } return null; } public static FaceType byTypeID(int tid) { for (FaceType ft : values()) { if (ft.typeID == tid) { return ft; } } return null; } } private void copyLayersToTarget(BufferedImage srcimg, int layer1x, int layer1y, int layer2x, int layer2y, int w, int h, int[] dest, int destoff, int destscansize) { int[] l1 = new int[w * h]; int[] l2 = new int[w * h]; int imgh = srcimg.getHeight(); // Read layer 1 if (imgh >= (layer1y+h)) srcimg.getRGB(layer1x, layer1y, w, h, l1, 0, w); // Read layer 2 if (imgh >= (layer2y+h)) srcimg.getRGB(layer2x, layer2y, w, h, l2, 0, w); // Apply layer1 to layer 1 boolean transp = false; int v = l2[0]; for (int i = 0; i < (w*h); i++) { if ((l2[i] & 0xFF000000) == 0) { transp = true; break; } /* If any different values, render face too */ else if (l2[i] != v) { transp = true; break; } } if(transp) { for (int i = 0; i < (w*h); i++) { if ((l2[i] & 0xFF000000) != 0) l1[i] = l2[i]; } } // Write to dest for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { dest[destoff + (y*destscansize + x)] = l1[(y*w)+x]; } } } private void copyLayersToTarget(BufferedImage srcimg, int layer1x, int layer1y, int layer2x, int layer2y, int w, int h, BufferedImage dest, int destoff, int destscansize) { int[] tmp = new int[w*h]; copyLayersToTarget(srcimg,layer1x,layer1y,layer2x,layer2y,w,h,tmp,0,w); dest.setRGB(0,0,w,h,tmp,destoff,destscansize); } private class LoadPlayerImages implements Runnable { private SkinUrlProvider mSkinUrlProvider; public final String playername; public final String playerskinurl; public LoadPlayerImages(String playername, String playerskinurl, UUID playeruuid, SkinUrlProvider skinUrlProvider) { this.playername = playername; this.playerskinurl = playerskinurl; mSkinUrlProvider = skinUrlProvider; } public void run() { boolean has_8x8 = storage.hasPlayerFaceImage(playername, FaceType.FACE_8X8); boolean has_16x16 = storage.hasPlayerFaceImage(playername, FaceType.FACE_16X16); boolean has_32x32 = storage.hasPlayerFaceImage(playername, FaceType.FACE_32X32); boolean has_body = storage.hasPlayerFaceImage(playername, FaceType.BODY_32X32); boolean missing_any = !(has_8x8 && has_16x16 && has_32x32 && has_body); boolean is_64x32_skin = false; BufferedImage img = null; try { if(fetchskins && (refreshskins || missing_any)) { URL url = null; if (mSkinUrlProvider == null) { if (!skinurl.equals("")) { url = new URL(skinurl.replace("%player%", URLEncoder.encode(playername, "UTF-8"))); } else if (playerskinurl != null) { url = new URL(playerskinurl); } } else { url = mSkinUrlProvider.getSkinUrl(playername); } if (url != null) img = ImageIO.read(url); /* Load skin for player */ } } catch (IOException iox) { Debug.debug("Error loading skin for '" + playername + "' - " + iox); } if(img == null) { try { InputStream in = getClass().getResourceAsStream("/char.png"); img = ImageIO.read(in); /* Load generic skin for player */ in.close(); } catch (IOException iox) { Debug.debug("Error loading default skin for '" + playername + "' - " + iox); } } if(img == null) { /* No image to process? Quit */ return; } if((img.getWidth() < 64) || (img.getHeight() < 32)) { img.flush(); return; } else if( (img.getWidth() / img.getHeight()) == 2 ) { /* Is single layer skin? */ is_64x32_skin = true; } /* Get buffered image for face at original size */ int scale = img.getWidth()/8 /8; BufferedImage faceOriginal = new BufferedImage(8*scale, 8*scale, BufferedImage.TYPE_INT_ARGB); // Copy face and overlay to icon copyLayersToTarget(img, 8*scale, 8*scale, 40*scale, 8*scale, 8*scale, 8*scale, faceOriginal, 0, 8*scale); int[] faceaccessory = new int[64]; /* 8x8 of face accessory */ /* Get buffered image for face at 8x8 */ DynmapBufferedImage face8x8 = DynmapBufferedImage.allocateBufferedImage(8, 8); Image face8x8_image = faceOriginal.getScaledInstance(8,8,BufferedImage.SCALE_SMOOTH); BufferedImage face8x8_buff = new BufferedImage(8, 8, BufferedImage.TYPE_INT_ARGB); face8x8_buff.getGraphics().drawImage(face8x8_image,0,0,null); face8x8_buff.getRGB(0,0,8,8,face8x8.argb_buf,0,8); /* Write 8x8 file */ if(refreshskins || (!has_8x8)) { BufferOutputStream bos = ImageIOManager.imageIOEncode(face8x8.buf_img, ImageFormat.FORMAT_PNG); if (bos != null) { storage.setPlayerFaceImage(playername, FaceType.FACE_8X8, bos); } } /* Write 16x16 file */ if(refreshskins || (!has_16x16)) { /* Make 16x16 version */ DynmapBufferedImage face16x16 = DynmapBufferedImage.allocateBufferedImage(16, 16); Image face16x16_image = faceOriginal.getScaledInstance(16,16,BufferedImage.SCALE_SMOOTH); BufferedImage face16x16_buff = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB); face16x16_buff.getGraphics().drawImage(face16x16_image,0,0,null); face16x16_buff.getRGB(0,0,16,16,face16x16.argb_buf,0,16); BufferOutputStream bos = ImageIOManager.imageIOEncode(face16x16.buf_img, ImageFormat.FORMAT_PNG); if (bos != null) { storage.setPlayerFaceImage(playername, FaceType.FACE_16X16, bos); } DynmapBufferedImage.freeBufferedImage(face16x16); face16x16_buff.flush(); } /* Write 32x32 file */ if(refreshskins || (!has_32x32)) { /* Make 32x32 version */ DynmapBufferedImage face32x32 = DynmapBufferedImage.allocateBufferedImage(32, 32); Image face32x32_image = faceOriginal.getScaledInstance(32,32,BufferedImage.SCALE_SMOOTH); BufferedImage face32x32_buff = new BufferedImage(32, 32, BufferedImage.TYPE_INT_ARGB); face32x32_buff.getGraphics().drawImage(face32x32_image,0,0,null); face32x32_buff.getRGB(0,0,32,32,face32x32.argb_buf,0,32); BufferOutputStream bos = ImageIOManager.imageIOEncode(face32x32.buf_img, ImageFormat.FORMAT_PNG); if (bos != null) { storage.setPlayerFaceImage(playername, FaceType.FACE_32X32, bos); } DynmapBufferedImage.freeBufferedImage(face32x32); face32x32_buff.flush(); } /* Write body file */ if(refreshskins || (!has_body)) { Image skin_image = null; BufferedImage skin_buff = null; if (is_64x32_skin){ skin_image = img.getScaledInstance(64,32,BufferedImage.SCALE_SMOOTH); skin_buff = new BufferedImage(64, 32, BufferedImage.TYPE_INT_ARGB); skin_buff.getGraphics().drawImage(skin_image,0,0,null); } else { skin_image = img.getScaledInstance(64,64,BufferedImage.SCALE_SMOOTH); skin_buff = new BufferedImage(64, 64, BufferedImage.TYPE_INT_ARGB); skin_buff.getGraphics().drawImage(skin_image,0,0,null); } /* Make 32x32 version */ DynmapBufferedImage body32x32 = DynmapBufferedImage.allocateBufferedImage(32, 32); /* Copy face at 12,0 to 20,8 (already handled accessory) */ for(int i = 0; i < 8; i++) { for(int j = 0; j < 8; j++) { body32x32.argb_buf[i*32+j+12] = face8x8.argb_buf[i*8 + j]; } } /* Copy body at 20,20 and chest at 20,36 to 8,12 */ copyLayersToTarget(skin_buff, 20, 20, 20, 36, 8, 12, body32x32.argb_buf, 8*32+12, 32); /* Copy right leg at 4,20 and 4,36 to 20,12 */ copyLayersToTarget(skin_buff, 4, 20, 4, 36, 4, 12, body32x32.argb_buf, 20*32+12, 32); /* Copy left leg at 4,20 if old format or 20,52 and 4,53 to 20,16 */ if(is_64x32_skin) { skin_buff.getRGB(4, 20, 4, 12, body32x32.argb_buf, 20*32+16, 32); } else { copyLayersToTarget(skin_buff, 20, 52, 4, 52, 4, 12, body32x32.argb_buf, 20 * 32 + 16, 32); } /* Copy right arm at 44,20 and 44,36 to 8,8 */ copyLayersToTarget(skin_buff, 44, 20, 44, 36, 4, 12, body32x32.argb_buf, 8*32+8, 32); /* Copy left arm at 44,20 if old format or 36,52 and 52,52 to 8,20 */ if(is_64x32_skin) { skin_buff.getRGB(44, 20, 4, 12, body32x32.argb_buf, 8*32+20, 32); } else { copyLayersToTarget(skin_buff, 36, 52, 52, 52, 4, 12, body32x32.argb_buf, 8 * 32 + 20, 32); } BufferOutputStream bos = ImageIOManager.imageIOEncode(body32x32.buf_img, ImageFormat.FORMAT_PNG); if (bos != null) { storage.setPlayerFaceImage(playername, FaceType.BODY_32X32, bos); } DynmapBufferedImage.freeBufferedImage(body32x32); skin_buff.flush(); } DynmapBufferedImage.freeBufferedImage(face8x8); face8x8_buff.flush(); faceOriginal.flush(); img.flush(); } } public PlayerFaces(DynmapCore core) { fetchskins = core.configuration.getBoolean("fetchskins", true); /* Control whether to fetch skins */ refreshskins = core.configuration.getBoolean("refreshskins", true); /* Control whether to update existing fetched skins or faces */ skinurl = core.configuration.getString("skin-url", ""); // These don't work anymore - Mojang retired them if (skinurl.equals("http://s3.amazonaws.com/MinecraftSkins/%player%.png") || skinurl.equals("http://skins.minecraft.net/MinecraftSkins/%player%.png")) { skinurl = ""; } core.listenerManager.addListener(EventType.PLAYER_JOIN, new PlayerEventListener() { @Override public void playerEvent(DynmapPlayer p) { Runnable job = new LoadPlayerImages(p.getName(), p.getSkinURL(), p.getUUID(), core.skinUrlProvider); MapManager.scheduleDelayedJob(job, 0); } }); storage = core.getDefaultMapStorage(); } }
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; 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); this.person.setFullName("Guest"); } // 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); } /* * 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 String getStructureStylesheet() { return (UtilitiesBean.fixURI(this.getStructureStylesheetDescription().getStylesheetURI())); } /* * Returns theme stylesheet defined by the user profile */ public String getThemeStylesheet() { return (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 uLayoutXML.getElementById (elementID); } public Node getRoot () { return uLayoutXML; } // 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=uLayoutXML.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 = uLayoutXML.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.spout.renderer.api.gl; import java.nio.ByteBuffer; import org.spout.renderer.api.Creatable; import org.spout.renderer.api.GLVersioned; import org.spout.renderer.api.data.Color; import org.spout.renderer.api.data.VertexAttribute.DataType; /** * Represents a texture for OpenGL. Image data can be set with one of the <code>setImageData(...)</code> methods before creation, but this is not obligatory. This results in an empty texture, with an * undefined content. This is mostly used for frame buffers. */ public abstract class Texture extends Creatable implements GLVersioned { protected int id = 0; // The format protected Format format = Format.RGB; protected InternalFormat internalFormat = null; protected DataType type = DataType.UNSIGNED_BYTE; // Wrapping modes for s and t protected WrapMode wrapT = WrapMode.REPEAT; protected WrapMode wrapS = WrapMode.REPEAT; // Minimisation and magnification modes protected FilterMode minFilter = FilterMode.NEAREST; protected FilterMode magFilter = FilterMode.NEAREST; // Anisotropic filtering protected float anisotropicFiltering = 0; // Compare modes for PCF protected CompareMode compareMode = null; // Border color when sampling outside the textures for certain wrap modes protected Color borderColor = null; // The texture image data protected ByteBuffer imageData; // Texture image dimensions protected int width; protected int height; @Override public void create() { imageData = null; super.create(); } @Override public void destroy() { id = 0; super.destroy(); } /** * Binds the texture to the OpenGL context. * * @param unit The unit to bind the texture to, or -1 to just bind the texture */ public abstract void bind(int unit); /** * Unbinds the texture from the OpenGL context. */ public abstract void unbind(); /** * Gets the ID for this texture as assigned by OpenGL. * * @return The ID */ public int getID() { return id; } /** * Sets the texture's format. * * @param format The format to set */ public void setFormat(Format format) { if (format == null) { throw new IllegalArgumentException("Format cannot be null"); } this.format = format; } /** * Sets the texture's internal format. Set to null to use the un-sized format instead. * * @param internalFormat The internal format to set */ public void setInternalFormat(InternalFormat internalFormat) { this.internalFormat = internalFormat; } /** * Sets the value for anisotropic filtering. A value smaller or equal to zero is considered as no filtering. Note that this is EXT based and might not be supported on all hardware. * * @param value The anisotropic filtering value */ public void setAnisotropicFiltering(float value) { this.anisotropicFiltering = value; } /** * Sets the texture's data type. * * @param type The type to set */ public void setComponentType(DataType type) { if (type == null) { throw new IllegalArgumentException("Type cannot be null"); } this.type = type; } /** * Sets the horizontal texture wrap. * * @param wrapS Horizontal texture wrap */ public void setWrapS(WrapMode wrapS) { if (wrapS == null) { throw new IllegalArgumentException("Wrap cannot be null"); } this.wrapS = wrapS; } /** * Sets the vertical texture wrap. * * @param wrapT Vertical texture wrap */ public void setWrapT(WrapMode wrapT) { if (wrapT == null) { throw new IllegalArgumentException("Wrap cannot be null"); } this.wrapT = wrapT; } /** * Sets the texture's min filter. * * @param minFilter The min filter */ public void setMinFilter(FilterMode minFilter) { if (minFilter == null) { throw new IllegalArgumentException("Filter cannot be null"); } this.minFilter = minFilter; } /** * Sets the texture's mag filter. Filters that require mipmaps generation cannot be used here. * * @param magFilter The mag filter */ public void setMagFilter(FilterMode magFilter) { if (magFilter == null) { throw new IllegalArgumentException("Filter cannot be null"); } if (magFilter.needsMipMaps()) { throw new IllegalArgumentException("Mimpmap filters cannot be used for texture magnification"); } this.magFilter = magFilter; } /** * Sets the compare mode. If null, this feature is deactivated. Use this for PCF with shadow samplers. * * @param compareMode The compare mode */ public void setCompareMode(CompareMode compareMode) { this.compareMode = compareMode; } /** * Sets the border color. If null, the default OpenGL border color is used. * * @param borderColor The border color */ public void setBorderColor(Color borderColor) { this.borderColor = borderColor; } /** * Sets the texture's image data. The image data reading is done according the the set {@link org.spout.renderer.api.gl.Texture.Format}. * * @param imageData The image data * @param width The width of the image * @param height the height of the image */ public void setImageData(ByteBuffer imageData, int width, int height) { this.imageData = imageData; this.width = width; this.height = height; } /** * Returns the image data. After creation is over, it returns null. * * @return The image data */ public ByteBuffer getImageData() { return imageData; } /** * Returns the width of the image. * * @return The image width */ public int getWidth() { return width; } /** * Returns the height of the image. * * @return The image height */ public int getHeight() { return height; } /** * An enum of texture component formats. */ public static enum Format { RED(0x1903, 1, true, false, false, false, false, false), // GL11.GL_RED RGB(0x1907, 3, true, true, true, false, false, false), // GL11.GL_RGB RGBA(0x1908, 4, true, true, true, true, false, false), // GL11.GL_RGBA DEPTH(0x1902, 1, false, false, false, false, true, false), // GL11.GL_DEPTH_COMPONENT RG(0x8227, 2, true, true, false, false, false, false), // GL30.GL_RG DEPTH_STENCIL(0x84F9, 1, false, false, false, false, false, true); // GL30.GL_DEPTH_STENCIL private final int glConstant; private final int components; private final boolean hasRed; private final boolean hasGreen; private final boolean hasBlue; private final boolean hasAlpha; private final boolean hasDepth; private final boolean hasStencil; private Format(int glConstant, int components, boolean hasRed, boolean hasGreen, boolean hasBlue, boolean hasAlpha, boolean hasDepth, boolean hasStencil) { this.glConstant = glConstant; this.components = components; this.hasRed = hasRed; this.hasGreen = hasGreen; this.hasBlue = hasBlue; this.hasAlpha = hasAlpha; this.hasDepth = hasDepth; this.hasStencil = hasStencil; } /** * Gets the OpenGL constant for this format. * * @return The OpenGL Constant */ public int getGLConstant() { return glConstant; } /** * Returns the number of components in the format. * * @return The number of components */ public int getComponentCount() { return components; } /** * Returns true if this format has a red component. * * @return True if a red component is present */ public boolean hasRed() { return hasRed; } /** * Returns true if this format has a green component. * * @return True if a green component is present */ public boolean hasGreen() { return hasGreen; } /** * Returns true if this format has a blue component. * * @return True if a blue component is present */ public boolean hasBlue() { return hasBlue; } /** * Returns true if this format has an alpha component. * * @return True if an alpha component is present */ public boolean hasAlpha() { return hasAlpha; } /** * Returns true if this format has a depth component. * * @return True if a depth component is present */ public boolean hasDepth() { return hasDepth; } /** * Returns true if this format has a stencil component. * * @return True if a stencil component is present */ public boolean hasStencil() { return hasStencil; } } /** * An enum of sized texture component formats. */ public static enum InternalFormat { RGB8(0x8051, 3, 3, true, true, true, false, false, false), // GL11.GL_RGB8 RGBA8(0x8058, 4, 4, true, true, true, true, false, false), // GL11.GL_RGBA8 RGBA16(0x805B, 4, 8, true, true, true, true, false, false), // GL11.GL_RGBA16 DEPTH_COMPONENT16(0x81A5, 1, 2, false, false, false, false, true, false), // GL14.GL_DEPTH_COMPONENT16 DEPTH_COMPONENT24(0x81A6, 1, 3, false, false, false, false, true, false), // GL14.GL_DEPTH_COMPONENT24 DEPTH_COMPONENT32(0x81A7, 1, 4, false, false, false, false, true, false), // GL14.GL_DEPTH_COMPONENT32 R8(0x8229, 1, 1, true, false, false, false, false, false), // GL30.GL_R8 R16(0x822A, 1, 2, true, false, false, false, false, false), // GL30.GL_R16 RG8(0x822B, 2, 2, true, true, false, false, false, false), // GL30.GL_RG8 RG16(0x822C, 2, 4, true, true, false, false, false, false), // GL30.GL_RG16 R16F(0x822D, 1, 2, true, false, false, false, false, true), // GL30.GL_R16F R32F(0x822E, 1, 4, true, false, false, false, false, true), // GL30.GL_R32F RG16F(0x822F, 2, 4, true, true, false, false, false, true), // GL30.GL_RG16F RG32F(0x8230, 2, 8, true, true, false, false, false, true), // GL30.GL_RG32F RGBA32F(0x8814, 4, 16, true, true, true, true, false, true), // GL30.GL_RGBA32F RGB32F(0x8815, 3, 12, true, true, true, false, false, true), // GL30.GL_RGB32F RGBA16F(0x881A, 4, 8, true, true, true, true, false, true), // GL30.GL_RGBA16F RGB16F(0x881B, 3, 6, true, true, true, false, false, true); // GL30.GL_RGB16F private final int glConstant; private final int components; private final int bytes; private final int bytesPerComponent; private final boolean hasRed; private final boolean hasGreen; private final boolean hasBlue; private final boolean hasAlpha; private final boolean hasDepth; private final boolean floatBased; private InternalFormat(int glConstant, int components, int bytes, boolean hasRed, boolean hasGreen, boolean hasBlue, boolean hasAlpha, boolean hasDepth, boolean floatBased) { this.glConstant = glConstant; this.components = components; this.bytes = bytes; bytesPerComponent = bytes / components; this.hasRed = hasRed; this.hasGreen = hasGreen; this.hasBlue = hasBlue; this.hasAlpha = hasAlpha; this.hasDepth = hasDepth; this.floatBased = floatBased; } /** * Gets the OpenGL constant for this internal format. * * @return The OpenGL Constant */ public int getGLConstant() { return glConstant; } /** * Returns the number of components in the format. * * @return The number of components */ public int getComponentCount() { return components; } /** * Returns the number of bytes used by a single pixel in the format. * * @return The number of bytes for a pixel */ public int getBytes() { return bytes; } /** * Returns the number of bytes used by a single pixel component in the format. * * @return The number of bytes for a pixel component */ public int getBytesPerComponent() { return bytesPerComponent; } /** * Returns true if this format has a red component. * * @return True if a red component is present */ public boolean hasRed() { return hasRed; } /** * Returns true if this format has a green component. * * @return True if a green component is present */ public boolean hasGreen() { return hasGreen; } /** * Returns true if this format has a blue component. * * @return True if a blue component is present */ public boolean hasBlue() { return hasBlue; } /** * Returns true if this format has an alpha component. * * @return True if an alpha component is present */ public boolean hasAlpha() { return hasAlpha; } /** * Returns true if this format has a depth component. * * @return True if a depth component is present */ public boolean hasDepth() { return hasDepth; } /** * Returns true if this format has float based components. * * @return True if the components are float based */ public boolean isFloatBased() { return floatBased; } } /** * An enum for the texture wrapping modes. */ public static enum WrapMode { REPEAT(0x2901), // GL11.GL_REPEAT CLAMP_TO_EDGE(0x812F), // GL12.GL_CLAMP_TO_EDGE CLAMP_TO_BORDER(0x812D), // GL13.GL_CLAMP_TO_BORDER MIRRORED_REPEAT(0x8370); // GL14.GL_MIRRORED_REPEAT private final int glConstant; private WrapMode(int glConstant) { this.glConstant = glConstant; } /** * Gets the OpenGL constant for this texture wrap. * * @return The OpenGL Constant */ public int getGLConstant() { return glConstant; } } /** * An enum for the texture filtering modes. */ public static enum FilterMode { LINEAR(0x2601, false), // GL11.GL_LINEAR NEAREST(0x2600, false), // GL11.GL_NEAREST NEAREST_MIPMAP_NEAREST(0x2700, true), // GL11.GL_NEAREST_MIPMAP_NEAREST LINEAR_MIPMAP_NEAREST(0x2701, true), //GL11.GL_LINEAR_MIPMAP_NEAREST NEAREST_MIPMAP_LINEAR(0x2702, true), // GL11.GL_NEAREST_MIPMAP_LINEAR LINEAR_MIPMAP_LINEAR(0x2703, true); // GL11.GL_LINEAR_MIPMAP_LINEAR private final int glConstant; private final boolean mimpaps; private FilterMode(int glConstant, boolean mimpaps) { this.glConstant = glConstant; this.mimpaps = mimpaps; } /** * Gets the OpenGL constant for this texture filter. * * @return The OpenGL Constant */ public int getGLConstant() { return glConstant; } /** * Returns true if the filtering mode required generation of mipmaps. * * @return Whether or not mipmaps are required */ public boolean needsMipMaps() { return mimpaps; } } public static enum CompareMode { LEQUAL(0x203), // GL11.GL_LEQUAL GEQUAL(0x206), // GL11.GL_GEQUAL LESS(0x201), // GL11.GL_LESS GREATER(0x204), // GL11.GL_GREATER EQUAL(0x202), // GL11.GL_EQUAL NOTEQUAL(0x205), // GL11.GL_NOTEQUAL ALWAYS(0x206), // GL11.GL_ALWAYS NEVER(0x200); // GL11.GL_NEVER private final int glConstant; private CompareMode(int glConstant) { this.glConstant = glConstant; } /** * Gets the OpenGL constant for this texture filter. * * @return The OpenGL Constant */ public int getGLConstant() { return glConstant; } } }
package VASSAL.tools.image; import java.awt.Dimension; import java.awt.color.CMMException; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Collections; import java.util.Iterator; import java.util.Set; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.MemoryCacheImageInputStream; import VASSAL.tools.io.IOUtils; import VASSAL.tools.io.RereadableInputStream; import VASSAL.tools.lang.Reference; /** * An image loader which wraps {@link ImageIO}. * * This class handles the assorted problems with various versions of * {@link ImageIO}, ensuring that we can reliably load image files to * {@link BufferedImages} with a predictable type. * * @since 3.1.0 * @author Joel Uckelman */ public class ImageIOImageLoader implements ImageLoader { protected final ImageTypeConverter tconv; /** * Create an image loader. * * @param tconv the <code>ImageTypeConverter</code> to use for type * conversions */ public ImageIOImageLoader(ImageTypeConverter tconv) { this.tconv = tconv; } // Used to indicate whether this version of Java has the PNG iTXt bug. // This can be removed once we no longer support Java 1.5. protected static final boolean iTXtBug; static { final String jvmver = System.getProperty("java.version"); iTXtBug = jvmver == null || jvmver.startsWith("1.5"); } protected static final Set<Integer> skip_iTXt = Collections.singleton(PNGDecoder.iTXt); /** * Loads an image. * * @param name the image name * @param in the input stream * @param typeIfOpaque the requested image type for opaque images * @param typeIfTransparent the requested image type for transparent images * @param managed <code>true</code> if a managed image should be returned * @return the image * * @throws BrokenImageException if the image is faulty * @throws UnrecognizedImageTypeException if the image type is not recognized * @throws ImageIOException if reading the image goes wrong */ public BufferedImage load( String name, InputStream in, int typeIfOpaque, int typeIfTransparent, boolean managed ) throws ImageIOException { // ImageIO fails on the following types of images: // Sun Bug 6788458: 8-bit/channel color type 2 (RGB) PNGs with tRNS chunks // Sun Bug 6541476: PNGs with iTXt chunks on Java 1.5 // Sun Bug 6444360: JPEGs with corrupt color profiles // Sun Bug 6404011: JPEGs with corrupt color profiles on Java 1.5 // Someday, when both ImageIO is fixed and everyone's JRE contains // that fix, we can do this the simple way. boolean fix_tRNS = false; int tRNS = 0x00000000; BufferedImage img = null; RereadableInputStream rin = null; try { rin = new RereadableInputStream(in); rin.mark(512); DataInputStream din = new DataInputStream(rin); PNGDecoder.Chunk ch; // Is this a PNG? if (PNGDecoder.decodeSignature(din)) { // The PNG chunks refered to here are defined in the PNG ch = PNGDecoder.decodeChunk(din); // Sanity check: This is not a PNG if IHDR is not the first chunk. if (ch.type == PNGDecoder.IHDR) { // At present, ImageIO does not honor the tRNS chunk in 8-bit color // type 2 (RGB) PNGs. This is not a bug per se, as the PNG standard // the does not require compliant decoders to use ancillary chunks. // However, every other PNG decoder we can find *does* honor the // tRNS chunk for this type of image, and so the appearance for // users is that VASSAL is broken when their 8-bit RGB PNGs don't // show the correct transparency. // We check for type-2 8-bit PNGs with tRNS chunks. if (ch.data[8] == 8 && ch.data[9] == 2) { // This is an 8-bit-per-channel Truecolor image; we must check // whether there is a tRNS chunk, and if so, record the color // so that we can manually set transparency later. // IHDR is required to be first, and tRNS is required to appear // before the first IDAT chunk; therefore, if we find an IDAT // we're done. DONE: for (;;) { ch = PNGDecoder.decodeChunk(din); switch (ch.type) { case PNGDecoder.tRNS: fix_tRNS = true; break DONE; case PNGDecoder.IDAT: fix_tRNS = false; break DONE; default: } } if (fix_tRNS) { if (ch.data.length != 6) { // There is at least one piece of software (SplitImage) which // writes tRNS chunks for type 2 images which are only 3 bytes // long, and because this kind of thing is used by module // designers for slicing up scans of countersheets, we can // expect to see such crap from time to time. throw new BrokenImageException(name, "bad tRNS chunk length"); } // tRNS chunk: PNG Standard, 11.3.2.1 // tRNS data is stored as three 2-byte samples, but the high // byte of each sample is empty because we are dealing with // 8-bit-per-channel images. tRNS = 0xff000000 | ((ch.data[1] & 0xff) << 16) | ((ch.data[3] & 0xff) << 8) | (ch.data[5] & 0xff); } } if (iTXtBug) { // Filter out iTXt chunks on JVMs with the iTXt bug. rin.reset(); rin = new RereadableInputStream( new PNGChunkSkipInputStream(skip_iTXt, rin)); rin.mark(1); } } } // Load the image rin.reset(); img = wrapImageIO(name, rin, readImage); rin.close(); } catch (ImageIOException e) { // Don't wrap ImageIOExceptions. throw e; } catch (IOException e) { throw new ImageIOException(name, e); } finally { IOUtils.closeQuietly(rin); } final int type = img.getTransparency() == BufferedImage.OPAQUE && !fix_tRNS ? typeIfOpaque : typeIfTransparent; final Reference<BufferedImage> ref = new Reference<BufferedImage>(img); // Fix up transparency in type 2 Truecolor images. if (fix_tRNS) { img = null; img = fix_tRNS(ref, tRNS, type); ref.obj = img; } // We convert the image in two cases: // 1) the image is not yet the requested type, or // 2) a managed image was requested, but the image // was unmanaged by the transparency fix. if (img.getType() != type || (fix_tRNS && managed)) { img = null; img = tconv.convert(ref, type); } return img; } protected static interface Wrapper<T> { T run(String name, InputStream in) throws IOException; } protected <T> T wrapImageIO(String name, InputStream in, Wrapper<T> w) throws ImageIOException { try { return w.run(name, in); } catch (ArrayIndexOutOfBoundsException e) { // Note: ImageIO can throw an ArrayIndexOutOfBoundsException for // some corrupt JPEGs. This problem is noted in Sun Bug 6351707, throw new BrokenImageException(name, e); } catch (CMMException e) { // Note: ImageIO can throw a CMMException for JPEGs which have // broken color profiles. This problem is noted in Sun Bugs 6444360 // and 6839133. throw new BrokenImageException(name, e); } catch (IllegalArgumentException e) { // kinds of broken images, e.g., JPEGs which are in the RGB color // space but have non-RGB color profiles (see Bug 2673589 for an // example of this). This problem is noted in Sun Bug 6404011, throw new BrokenImageException(name, e); } catch (ImageIOException e) { // Don't wrap ImageIOExceptions. throw e; } catch (IOException e) { throw new ImageIOException(name, e); } } /** A functor for reading images. */ protected static Wrapper<BufferedImage> readImage = new Wrapper<BufferedImage>() { /** * Loads an image. * * @param name the image name * @param in the input stream * @return the image * * @throws UnrecognizedImageTypeException if the image type is unknown * @throws IOException if reading the image goes wrong */ public BufferedImage run(String name, InputStream in) throws IOException { final BufferedImage img = ImageIO.read(new MemoryCacheImageInputStream(in)); if (img == null) throw new UnrecognizedImageTypeException(name); return img; } }; /** A functor for reading image dimensions. */ protected static Wrapper<Dimension> readSize = new Wrapper<Dimension>() { /** * Gets the size of an image. * * @param name the image name * @param in the input stream * @return the size of the image * * @throws BrokenImageException if the image is faulty * @throws UnrecognizedImageTypeException if the image type is unknown * @throws IOException if reading the image goes wrong */ public Dimension run(String name, InputStream in) throws IOException { final ImageInputStream stream = new MemoryCacheImageInputStream(in); final Iterator<ImageReader> i = ImageIO.getImageReaders(stream); if (!i.hasNext()) throw new UnrecognizedImageTypeException(name); final ImageReader reader = i.next(); try { reader.setInput(stream); return new Dimension(reader.getWidth(0), reader.getHeight(0)); } finally { reader.dispose(); } } }; protected BufferedImage fix_tRNS(Reference<BufferedImage> ref, int tRNS, int type) throws ImageIOException { BufferedImage img = ref.obj; // Ensure that we are working with integer ARGB data. Whether it's // premultiplied doesn't matter, since fully transparent black pixels // are the same in both. if (img.getType() != BufferedImage.TYPE_INT_ARGB && img.getType() != BufferedImage.TYPE_INT_ARGB_PRE) { // If the requested type is not an ARGB one, then we convert to ARGB // for applying this fix. if (type != BufferedImage.TYPE_INT_ARGB && type != BufferedImage.TYPE_INT_ARGB_PRE) { type = BufferedImage.TYPE_INT_ARGB; } img = null; img = tconv.convert(ref, type); } // NB: This unmanages the image. final DataBufferInt db = (DataBufferInt) img.getRaster().getDataBuffer(); final int[] data = db.getData(); // Set all pixels of the transparent color to have alpha 0. for (int i = 0; i < data.length; ++i) { if (data[i] == tRNS) data[i] = 0x00000000; } return img; } /** * Gets the size of an image. * * @param name the image name * @param in the input stream * @return the size of the image * * @throws BrokenImageException if the image is faulty * @throws UnrecognizedImageTypeException if the image type is not recognized * @throws ImageIOException if reading the image goes wrong */ public Dimension size(String name, InputStream in) throws ImageIOException { return wrapImageIO(name, in, readSize); } }
package ch.frontg8.view; import android.app.Activity; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.method.ScrollingMovementMethod; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.security.InvalidKeyException; import java.util.ArrayList; import java.util.UUID; import ch.frontg8.R; import ch.frontg8.bl.Contact; import ch.frontg8.bl.Message; import ch.frontg8.lib.connection.TlsTest; import ch.frontg8.lib.crypto.KeystoreHandler; import ch.frontg8.lib.crypto.LibCrypto; import ch.frontg8.lib.dbstore.ContactsDataSource; public class DeveloperActivity extends AppCompatActivity { private Activity thisActivity; private ContactsDataSource datasource = new ContactsDataSource(this); private TextView textViewLog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_developer); thisActivity = this; Button buttonKeyGen = (Button) findViewById(R.id.buttonKeyGen); Button buttonClearDB = (Button) findViewById(R.id.buttonClearDB); Button buttonLoadTestData = (Button) findViewById(R.id.buttonLoadTestData); Button buttonTlsTest = (Button) findViewById(R.id.buttonTlsTest); Button buttonShowDB = (Button) findViewById(R.id.buttonShowDB); datasource.open(); buttonKeyGen.setOnClickListener(new AdapterView.OnClickListener() { public void onClick(View view) { try { LibCrypto.generateNewKeys(new KeystoreHandler(thisActivity), thisActivity); Toast toast = Toast.makeText(thisActivity, "Keys generated", Toast.LENGTH_SHORT); toast.show(); } catch (Exception e) { e.printStackTrace(); } } }); buttonClearDB.setOnClickListener(new AdapterView.OnClickListener() { public void onClick(View view) { datasource.deleteAllContacts(); datasource.deleteAllMessages(); Toast toast = Toast.makeText(thisActivity, "all data deleted", Toast.LENGTH_SHORT); toast.show(); } }); buttonLoadTestData.setOnClickListener(new AdapterView.OnClickListener() { public void onClick(View view) { String keyA = "MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQBf72KrjMTpU60csP6cVefgJocZpj+OOTF8sNueIPU8krHCycTozNoycoguqLkI6jU66pTXtnx/nxgXprVqg6bEyMBB5oCXoPNQSrb8GBkL5p764is9dn27q57cJ/Mw1zp1W/cNKJj2uWtuyFxXcwEhjVh8Vja47BaJCbFg7drjrzTxZM="; String keyB = "MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQBGp6vB5n7L2+6QdKY5ETFnY0QhIFIUqtVW0QaSDEUYJoLceBjKLyiLiQhiYo8tANXsBlrB+F/wQPARoYbaaFKX/cBUTYioTcVWpa4r2lupMyBwZ7x3v8cznfY4aSRWcQKIOtQxpHm7sDQWnViAVmKI4Xgw50ZE0ONxgIjNBioosO3K6I="; String keyC = "MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQBRg1Zd0pBm6ST8dULpAuwWxq+llhdguXfRkuf5stzPVYOgwgjO4j3qDe6z5tgK/iS9wMSAjqYuzvr6UkQAJtAXHABEoheuPgoKp2PI3Nozn8E+zsH0RQWhKHV+XiUp4tv6TAPuyTelHVsNJYOCjS5IkzCGROQqEVzMonlyRN2HNXvaIs="; Contact a = datasource.createContact(new Contact(UUID.fromString("11111111-1111-1111-1111-111111111111"), "The", "Other", keyA, 2, false)); Contact b = datasource.createContact(new Contact(UUID.fromString("22222222-2222-2222-2222-222222222222"), "Tobias", "Stauber", keyB, 1, false)); Contact c = datasource.createContact(new Contact(UUID.fromString("33333333-3333-3333-3333-333333333333"), "Ueli", "Bosshard", keyC, 1, false)); Contact d = datasource.createContact(new Contact(UUID.fromString("44444444-4444-4444-4444-444444444444"), "Flix", "", "", 0, false)); Contact e = datasource.createContact(new Contact(UUID.fromString("55555555-5555-5555-5555-555555555555"), "Benny", "", "", 0, false)); datasource.insertMessage(a, new Message("bla")); datasource.insertMessage(b, new Message("blb")); datasource.insertMessage(c, new Message("blc")); datasource.insertMessage(d, new Message("bld")); datasource.insertMessage(d, new Message("bld")); try { LibCrypto.negotiateSessionKeys(a.getContactId(), a.getPublicKeyString().getBytes(), new KeystoreHandler(thisActivity), thisActivity); LibCrypto.negotiateSessionKeys(b.getContactId(), b.getPublicKeyString().getBytes(), new KeystoreHandler(thisActivity), thisActivity); LibCrypto.negotiateSessionKeys(c.getContactId(), c.getPublicKeyString().getBytes(), new KeystoreHandler(thisActivity), thisActivity); a.setValidPubkey(true); b.setValidPubkey(true); c.setValidPubkey(true); a.incrementUnreadMessageCounter(); datasource.updateContact(a); datasource.updateContact(b); datasource.updateContact(c); } catch (InvalidKeyException f) { f.printStackTrace(); } Toast toast = Toast.makeText(thisActivity, "demo data inserted", Toast.LENGTH_SHORT); toast.show(); } }); buttonTlsTest.setOnClickListener(new AdapterView.OnClickListener() { public void onClick(View view) { textViewLog = (TextView) findViewById(R.id.textViewLog); textViewLog.setText(""); textViewLog.setMovementMethod(new ScrollingMovementMethod()); new Thread(new Runnable() { @Override public void run() { TlsTest tlstest = new TlsTest(thisActivity); tlstest.RunTlsTest(); } }).start(); } }); buttonShowDB.setOnClickListener(new AdapterView.OnClickListener() { public void onClick(View view) { textViewLog = (TextView) findViewById(R.id.textViewLog); textViewLog.setText(""); datasource.open(); ArrayList<Contact> contacts = datasource.getAllContacts(); for (Contact c: contacts) { textViewLog.append("Contact: " + c.getName() + " " + c.getSurname() + " " + c.hasValidPubKey() + "\n" ); for (Message m: c.getMessages()) { textViewLog.append("- Message: " + m.getMessage() + "\n"); } } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_developer, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override protected void onPause() { super.onPause(); datasource.close(); } }
package com.meituan.sample; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.meituan.robust.patch.annotaion.Add; import com.meituan.robust.patch.annotaion.Modify; import java.lang.reflect.Field; public class SecondActivity extends AppCompatActivity implements View.OnClickListener { protected static String name = "SecondActivity"; private ListView listView; private String[] multiArr = {"1", "2", "3", "4"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); listView = (ListView) findViewById(R.id.listview); TextView textView = (TextView) findViewById(R.id.secondtext); textView.setOnClickListener(v -> { // RobustModify.modify(); Log.d("robust", " onclick in Listener"); } ); //change text on the SecondActivity textView.setText(getTextInfo()); //test array BaseAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_expandable_list_item_1, multiArr); listView.setAdapter(adapter); printLog("robust", new String[][]{new String[]{"1", "2", "3"}, new String[]{"4", "5", "6"}}); } // @Modify public String getTextInfo() { getArray(); return "error occur " ; // return "error fixed"; } @Add public String[] getArray() { return new String[]{"hello","world"}; } @Override public View onCreateView(String name, Context context, AttributeSet attrs) { return super.onCreateView(name, context, attrs); } @Override public void onClick(View v) { Toast.makeText(SecondActivity.this, "from implements onclick ", Toast.LENGTH_SHORT).show(); } public static Field getReflectField(String name, Object instance) throws NoSuchFieldException { for (Class<?> clazz = instance.getClass(); clazz != null; clazz = clazz.getSuperclass()) { try { Field field = clazz.getDeclaredField(name); if (!field.isAccessible()) { field.setAccessible(true); } return field; } catch (NoSuchFieldException e) { // ignore and search next } } throw new NoSuchFieldException("Field " + name + " not found in " + instance.getClass()); } public static Object getFieldValue(String name, Object instance) { try { return getReflectField(name, instance).get(instance); } catch (Exception e) { Log.d("robust", "getField error " + name + " target " + instance); e.printStackTrace(); } return null; } private void printLog(@NonNull String tag, @NonNull String[][] args) { int i = 0; int j = 0; for (String[] array : args) { for (String arg : array) { Log.d(tag, "args[" + i + "][" + j + "] is: " + arg); j++; } i++; } } }
package com.pherux.skyquest.utils; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.location.Location; import android.location.LocationManager; import android.os.BatteryManager; import android.os.Environment; import android.os.StrictMode; import android.telephony.SmsManager; import android.util.Log; import android.widget.Toast; import com.pherux.skyquest.App; import com.pherux.skyquest.Constants; import com.pherux.skyquest.managers.Persistence; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; public class Tracker { private static final String TAG = Tracker.class.getName(); public static int alarmId = 314; public static String photoPrefixKey = "PhotoPrefix"; public static String photoCountKey = "PhotoCount"; public static String photoRunningKey = "PhotoRunning"; public static String errorCountKey = "ErrorCount"; public static String trackerNameKey = "TrackerName"; public static String pingSMSKey = "PhoneNumber"; public static String trackerUrlKey = "TrackerUrl"; public static String smsStatusKey = "SMSStatus"; public static String gpsStatusKey = "GPSStatus"; public static String trackerStatusKey = "TrackerStatus"; public static String photoStatusKey = "PhotoStatus"; public static String errorLogFile = "skyquest.error.log"; public static String nmeaLogFile = "skyquest.nmea.log"; public static String configFile = "skyquest.config"; public static Integer incrementIntVal(String key) { Integer val = Persistence.getIntVal(key, 0); val = val + 1; Persistence.putIntVal(key, val); return val; } public static String getStorageRoot() { return Environment.getExternalStorageDirectory() + "/skyquest"; } public static void logException(Throwable ex) { try { PrintWriter pw = new PrintWriter( new FileWriter(Tracker.getStorageRoot() + "/" + Tracker.errorLogFile, true)); ex.printStackTrace(pw); pw.flush(); pw.close(); } catch (Throwable e) { Log.e("Exception", "File write failed: " + e.toString()); } } public static void appendToFile(String filename, String data) { try { PrintWriter pw = new PrintWriter( new FileWriter(Tracker.getStorageRoot() + "/" + filename, true)); pw.print(data); pw.flush(); pw.close(); } catch (Throwable e) { Log.e("Exception", "File write failed: " + e.toString()); } } public static void reboot() { try { Log.d(TAG, "Tracker attempting to reboot via su"); java.lang.Process proc = Runtime.getRuntime().exec( new String[]{"su", "-c", "reboot"}); proc.waitFor(); } catch (Throwable ex) { Toast.makeText(App.getContext(), "Device not rooted", Toast.LENGTH_LONG).show(); Log.d(TAG, "Error attempting to reboot via su"); } } public static void pingSuccess() { Persistence.putIntVal(Tracker.errorCountKey, 0); } public static void pingError() { Integer errorCount = incrementIntVal(Tracker.errorCountKey); if (errorCount > 5) { Persistence.putIntVal(Tracker.errorCountKey, 0); reboot(); } } public static String getLocationString(Location location) { String timestamp = new SimpleDateFormat("HH:mm:ss", Locale.US).format(new Date(location.getTime())); DecimalFormat df = new DecimalFormat(" String latitude = df.format(location.getLatitude()); String longitude = df.format(location.getLongitude()); df = new DecimalFormat(" String altitude = df.format(location.getAltitude()); df = new DecimalFormat(" String accuracy = df.format(location.getAccuracy()); return timestamp + " http://maps.google.com/?q=" + latitude + "," + longitude + " Alt:" + altitude + " Acc:" + accuracy; } public static Location getLocation() { LocationManager locationManager = (LocationManager) App.getContext() .getSystemService(Context.LOCATION_SERVICE); try { Location location = locationManager .getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location == null) { location = new Location("reverseGeocoded"); location.setAltitude(0); location.setLatitude(0); location.setLongitude(0); } return location; } catch (SecurityException e) { Log.d(TAG, "Error getting location: " + e.getMessage()); return new Location("reverseGeocoded"); } } public static void sendLocationSMS() { Log.d(TAG, "Tracker attempting to send location SMS"); String phoneNumber = Persistence.getStringVal(Tracker.pingSMSKey, ""); String trackerName = Persistence.getStringVal(Tracker.trackerNameKey, ""); try { Location location = getLocation(); SmsManager sm = SmsManager.getDefault(); String locationString = Tracker.getLocationString(location); String battString = Tracker.getBatteryString(); String smsBody = trackerName + ": " + locationString + " " + battString; sm.sendTextMessage(phoneNumber, null, smsBody, null, null); Log.d(TAG, "Tracker location SMS sent to " + phoneNumber + " : " + smsBody); String smsStatus = "SMS " + new SimpleDateFormat("HH:mm:ss", Locale.US).format(new Date()) + " sent to " + phoneNumber; Persistence.putStringVal(Tracker.smsStatusKey, smsStatus); } catch (Throwable ex) { try { SmsManager sm = SmsManager.getDefault(); String locationString = "Unknown location"; String battString = Tracker.getBatteryString(); String smsBody = trackerName + ": " + locationString + " " + battString; sm.sendTextMessage(phoneNumber, null, smsBody, null, null); } catch (Throwable ignored) { } Log.d(TAG, "Tracker error sending location SMS"); } } public static void sendTrackerPing() { Log.d(TAG, "Tracker attempting to send tracker ping"); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); try { Location location = getLocation(); DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss", Locale.US); // dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); String time = dateFormat.format(Calendar.getInstance().getTime()); String batteryData = getBatteryString(); Log.d(TAG, "Tracker data:\nBattery: " + batteryData + "\nTime: " + time + "\nLatitude:" + location.getLatitude() + "\nLongitude: " + location.getLongitude() + "\nAltitude: " + location.getAltitude() + "\nDevice Name: " + Utils.getDeviceName()); App.getNetwork().getService().log( Constants.MOBILE_SERVICE_PRIVATE_KEY, batteryData, time, "" + location.getLatitude(), "" + location.getLongitude(), "" + location.getAltitude(), "", Utils.getDeviceName(), new Callback<Response>() { @Override public void success(Response response, Response response2) { pingSuccess(); Log.d(TAG, "Data uploaded!"); } @Override public void failure(RetrofitError error) { Log.e(TAG, "Error sending data to server:" + error.getMessage()); pingError(); } } ); } catch (Throwable ex) { Log.d(TAG, "Tracker error sending tracker ping"); } } public static String getBatteryString() { Intent batteryIntent = App.getContext().registerReceiver(null, new IntentFilter( Intent.ACTION_BATTERY_CHANGED)); int level; if (batteryIntent != null) { level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1); double pct = 0.0; if (level > 0 && scale > 0) { pct = ((double) level / (double) scale) * 100.0d; } double volts = 0.0; int mv = batteryIntent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0); if (mv > 0) { volts = (double) mv / 1000.0d; } DecimalFormat df = new DecimalFormat(" String spct = df.format(pct); df = new DecimalFormat(" String svolts = df.format(volts); return "BVlt: " + svolts + " BPct:" + spct; } else { return ""; } } public static void loadConfig() { //// TODO: 8/18/15 create config file try { String configFileName = Tracker.getStorageRoot() + "/" + Tracker.configFile; BufferedReader reader = new BufferedReader(new FileReader(configFileName)); String input; if ((input = reader.readLine()) != null) { Persistence.putStringVal(Tracker.trackerNameKey, input); } if ((input = reader.readLine()) != null) { Persistence.putStringVal(Tracker.pingSMSKey, input); } if ((input = reader.readLine()) != null) { Persistence.putStringVal(Tracker.trackerUrlKey, input); } reader.close(); } catch (Throwable ignored) { } } }
package im.tny.segvault.disturbances; import android.annotation.TargetApi; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; import android.support.v4.content.ContextCompat; import android.support.v4.graphics.drawable.DrawableCompat; import android.support.v7.widget.Toolbar; import android.text.Html; import android.text.Spanned; import android.text.TextUtils; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import com.google.android.gms.maps.model.BitmapDescriptor; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Locale; import java.util.Optional; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executor; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import im.tny.segvault.subway.Line; import im.tny.segvault.subway.Network; import static android.content.Context.MODE_PRIVATE; public class Util { @SuppressWarnings("deprecation") public static Spanned fromHtml(String html) { Spanned result; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) { result = Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY); } else { result = Html.fromHtml(html); } return result; } public static int getDrawableResourceIdForLine(Line line) { return getDrawableResourceIdForLineId(line.getId()); } public static final int[] lobbyColors = new int[]{ Color.parseColor("#C040CE"), Color.parseColor("#4CAF50"), Color.parseColor("#142382"), Color.parseColor("#E0A63A"), Color.parseColor("#F15D2A")}; public static int getDrawableResourceIdForLineId(String id) { switch (id) { case "pt-ml-amarela": return R.drawable.line_pt_ml_amarela; case "pt-ml-azul": return R.drawable.line_pt_ml_azul; case "pt-ml-verde": return R.drawable.line_pt_ml_verde; case "pt-ml-vermelha": return R.drawable.line_pt_ml_vermelha; default: return R.drawable.ic_menu_directions_subway; } } public static int getDrawableResourceIdForPOIType(String type) { switch (type) { case "dinning": return R.drawable.ic_silverware_black_24dp; case "police": return R.drawable.ic_police_black_24dp; case "fire-station": return R.drawable.ic_fireman_black_24dp; case "sports": return R.drawable.ic_sports_black_24dp; case "school": case "university": return R.drawable.ic_school_black_24dp; case "library": return R.drawable.ic_local_library_black_24dp; case "airport": return R.drawable.ic_local_airport_black_24dp; case "embassy": return R.drawable.ic_flag_black_24dp; case "church": return R.drawable.ic_human_handsup_black_24dp; case "business": return R.drawable.ic_store_mall_directory_black_24dp; case "zoo": return R.drawable.ic_elephant_black_24dp; case "court": return R.drawable.ic_gavel_black_24dp; case "park": return R.drawable.ic_local_florist_black_24dp; case "hospital": return R.drawable.ic_local_hospital_black_24dp; case "monument": return R.drawable.ic_chess_rook_black_24dp; case "museum": return R.drawable.ic_account_balance_black_24dp; case "shopping-center": return R.drawable.ic_shopping_basket_black_24dp; case "health-center": return R.drawable.ic_medical_bag_black_24dp; case "bank": return R.drawable.ic_money_bag_black_24dp; case "viewpoint": return R.drawable.ic_binoculars_black_24dp; case "casino": return R.drawable.ic_casino_black_24dp; case "theater": return R.drawable.ic_guy_fawkes_mask_black_24dp; case "show-room": return R.drawable.ic_spotlight_beam_black_24dp; case "organization": return R.drawable.ic_group_black_24dp; case "transportation-hub": return R.drawable.ic_device_hub_black_24dp; case "public-space": return R.drawable.ic_location_city_black_24dp; case "government": return R.drawable.ic_portuguese_flag_black_24dp; case "market": return R.drawable.ic_food_apple_black_24dp; case "public-service": return R.drawable.ic_room_service_black_24dp; case "institute": return R.drawable.ic_certificate_black_24dp; case "post-office": return R.drawable.ic_mail_black_24dp; case "cemetery": return R.drawable.ic_coffin_black_24dp; case "hotel": return R.drawable.ic_hotel_black_24dp; default: return R.drawable.ic_place_black_24dp; } } public static int getStringResourceIdForPOIType(String type) { switch (type) { case "dinning": return R.string.poi_type_dinning; case "police": return R.string.poi_type_police; case "fire-station": return R.string.poi_type_fire_station; case "sports": return R.string.poi_type_sports; case "school": return R.string.poi_type_school; case "university": return R.string.poi_type_university; case "library": return R.string.poi_type_library; case "airport": return R.string.poi_type_airport; case "embassy": return R.string.poi_type_embassy; case "church": return R.string.poi_type_church; case "business": return R.string.poi_type_business; case "zoo": return R.string.poi_type_zoo; case "court": return R.string.poi_type_court; case "park": return R.string.poi_type_park; case "hospital": return R.string.poi_type_hospital; case "monument": return R.string.poi_type_monument; case "museum": return R.string.poi_type_museum; case "shopping-center": return R.string.poi_type_shopping_center; case "health-center": return R.string.poi_type_health_center; case "bank": return R.string.poi_type_bank; case "viewpoint": return R.string.poi_type_viewpoint; case "casino": return R.string.poi_type_casino; case "theater": return R.string.poi_type_theater; case "show-room": return R.string.poi_type_show_room; case "organization": return R.string.poi_type_organization; case "transportation-hub": return R.string.poi_type_transportation_hub; case "public-space": return R.string.poi_type_public_space; case "government": return R.string.poi_type_government; case "market": return R.string.poi_type_market; case "public-service": return R.string.poi_type_public_service; case "institute": return R.string.poi_type_institute; case "post-office": return R.string.poi_type_post_office; case "cemetery": return R.string.poi_type_cemetery; case "hotel": return R.string.poi_type_hotel; default: return R.string.search_poi_subtitle; } } public static int getColorForPOIType(String type, Context context) { switch (type) { case "police": case "fire-station": case "health-center": case "hospital": case "cemetery": return Color.parseColor("#3E6990"); case "school": case "university": case "library": case "institute": case "hotel": return Color.parseColor("#D66F37"); case "airport": case "transportation-hub": return Color.parseColor("#381D2A"); case "museum": case "viewpoint": case "monument": case "sports": case "park": case "zoo": return Color.parseColor("#008C70"); case "dinning": case "casino": case "theater": case "show-room": return Color.parseColor("#D14E45"); case "shopping-center": case "market": case "bank": case "organization": case "church": case "business": return Color.parseColor("#5A6199"); case "embassy": case "court": case "public-space": case "government": case "public-service": case "post-office": return Color.parseColor("#AD9000"); default: return ContextCompat.getColor(context, R.color.colorPrimary); } } public static int getDrawableResourceIdForExitType(String type, boolean closed) { if (closed) { return R.drawable.ic_no_entry_black_24dp; } switch (type) { case "stairs": return R.drawable.ic_stairs_black_24dp; case "escalator": return R.drawable.ic_escalator_black_24dp; case "ramp": return R.drawable.ic_ramp_black_24dp; case "lift": return R.drawable.ic_elevator; default: // TODO return R.drawable.ic_place_black_24dp; } } public static int getDrawableResourceIdForStationTag(String tag) { switch (tag) { case "a_store": return R.drawable.ic_gift_black_24dp; case "a_wc": return R.drawable.ic_wc_black_24dp; case "a_wifi": return R.drawable.ic_wifi_black_24dp; case "c_airport": return R.drawable.ic_local_airport_black_24dp; case "c_bike": return R.drawable.ic_directions_bike_black_24dp; case "c_boat": return R.drawable.ic_directions_boat_black_24dp; case "c_bus": return R.drawable.ic_directions_bus_black_24dp; case "c_parking": return R.drawable.ic_local_parking_black_24dp; case "c_taxi": return R.drawable.ic_local_taxi_black_24dp; case "c_train": return R.drawable.ic_train_black_24dp; case "m_escalator_platform": case "m_escalator_surface": return R.drawable.ic_escalator_black_24dp; case "m_lift_platform": case "m_lift_surface": return R.drawable.ic_elevator; case "m_platform": case "m_stepfree": return R.drawable.ic_wheelchair_black_24dp; case "s_lostfound": return R.drawable.ic_account_balance_wallet_black_24dp; case "s_ticket1": case "s_ticket2": case "s_ticket3": case "s_urgent_pass": return R.drawable.ic_cards_black_24dp; default: return 0; } } public static BitmapDescriptor getBitmapDescriptorFromVector(Context context, @DrawableRes int vectorResId, int tintColor) { Drawable vectorDrawable = ContextCompat.getDrawable(context, vectorResId); vectorDrawable.setBounds(0, 0, vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight()); Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); Drawable wrapDrawable = DrawableCompat.wrap(vectorDrawable); DrawableCompat.setTint(wrapDrawable, tintColor); wrapDrawable.draw(canvas); return BitmapDescriptorFactory.fromBitmap(bitmap); } public static BitmapDescriptor getBitmapDescriptorFromVector(Context context, @DrawableRes int vectorResId) { Drawable vectorDrawable = ContextCompat.getDrawable(context, vectorResId); vectorDrawable.setBounds(0, 0, vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight()); Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); vectorDrawable.draw(canvas); return BitmapDescriptorFactory.fromBitmap(bitmap); } public static BitmapDescriptor createMapMarker(Context context, @DrawableRes int vectorResId, int markerColor) { Drawable background_background = ContextCompat.getDrawable(context, R.drawable.map_marker_background_background); background_background.setBounds(0, 0, background_background.getIntrinsicWidth(), background_background.getIntrinsicHeight()); Drawable background = ContextCompat.getDrawable(context, R.drawable.map_marker_background); background.setBounds(0, 0, background.getIntrinsicWidth(), background.getIntrinsicHeight()); Drawable backgroundWrap = DrawableCompat.wrap(background); DrawableCompat.setTint(backgroundWrap, markerColor); Drawable vectorDrawable = ContextCompat.getDrawable(context, vectorResId); int one = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, context.getResources().getDisplayMetrics()); int twentyfour = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 23, context.getResources().getDisplayMetrics()); vectorDrawable.setBounds(one, one, twentyfour, twentyfour); Drawable foregroundWrap = DrawableCompat.wrap(vectorDrawable); DrawableCompat.setTint(foregroundWrap, markerColor); Bitmap bitmap = Bitmap.createBitmap(backgroundWrap.getIntrinsicWidth(), backgroundWrap.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); background_background.draw(canvas); backgroundWrap.draw(canvas); foregroundWrap.draw(canvas); return BitmapDescriptorFactory.fromBitmap(bitmap); } public static int manipulateColor(int color, float factor) { int a = Color.alpha(color); int r = Math.round(Color.red(color) * factor); int g = Math.round(Color.green(color) * factor); int b = Math.round(Color.blue(color) * factor); return Color.argb(a, Math.min(r, 255), Math.min(g, 255), Math.min(b, 255)); } @TargetApi(Build.VERSION_CODES.N) public static Locale getCurrentLocale(Context context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { return context.getResources().getConfiguration().getLocales().get(0); } else { //noinspection deprecation return context.getResources().getConfiguration().locale; } } public static String getCurrentLanguage(Context context) { return getCurrentLocale(context).getLanguage(); } public static String[] getLineNames(Context context, Line line) { SharedPreferences sharedPref = context.getSharedPreferences("settings", MODE_PRIVATE); boolean preferMainNames = sharedPref.getBoolean(PreferenceNames.PreferMainNames, true); String[] names = line.getNames(getCurrentLanguage(context)); if (!preferMainNames && names.length > 1) { return new String[]{names[1], names[0]}; } return names; } public static String[] getNetworkNames(Context context, Network network) { SharedPreferences sharedPref = context.getSharedPreferences("settings", MODE_PRIVATE); boolean preferMainNames = sharedPref.getBoolean(PreferenceNames.PreferMainNames, true); String[] names = network.getNames(getCurrentLanguage(context)); if (!preferMainNames && names.length > 1) { return new String[]{names[1], names[0]}; } return names; } public static String encodeRFC3339(Date date) { return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US).format(date) .replaceAll("(\\d\\d)(\\d\\d)$", "$1:$2"); } public static View getToolbarNavigationIcon(Toolbar toolbar) { //check if contentDescription previously was set boolean hadContentDescription = TextUtils.isEmpty(toolbar.getNavigationContentDescription()); String contentDescription = !hadContentDescription ? toolbar.getNavigationContentDescription().toString() : "navigationIcon"; toolbar.setNavigationContentDescription(contentDescription); ArrayList<View> potentialViews = new ArrayList<View>(); //find the view based on it's content description, set programatically or with android:contentDescription toolbar.findViewsWithText(potentialViews, contentDescription, View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION); //Nav icon is always instantiated at this point because calling setNavigationContentDescription ensures its existence View navIcon = null; if (potentialViews.size() > 0) { navIcon = potentialViews.get(0); //navigation icon is ImageButton } //Clear content description if not previously present if (hadContentDescription) toolbar.setNavigationContentDescription(null); return navIcon; } public static void setViewAndChildrenEnabled(View view, boolean enabled) { view.setEnabled(enabled); if (view instanceof ViewGroup) { ViewGroup viewGroup = (ViewGroup) view; for (int i = 0; i < viewGroup.getChildCount(); i++) { View child = viewGroup.getChildAt(i); setViewAndChildrenEnabled(child, enabled); } } } public static int tryParseInteger(String string, int defaultValue) { try { return Integer.valueOf(string); } catch (NumberFormatException e) { return defaultValue; } } // large stack thread pool executor private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors(); private static final int CORE_POOL_SIZE = CPU_COUNT + 1; private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1; private static final int KEEP_ALIVE = 1; private static final ThreadFactory yourFactory = new ThreadFactory() { private final AtomicInteger mCount = new AtomicInteger(1); public Thread newThread(@NonNull Runnable r) { ThreadGroup group = new ThreadGroup("threadGroup"); return new Thread(group, r, "LargeCallStackThread", 50000); } }; private static final BlockingQueue<Runnable> sPoolWorkQueue = new LinkedBlockingQueue<Runnable>(128); public static final Executor LARGE_STACK_THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sPoolWorkQueue, yourFactory); // end of large stack thread pool executor }
package bramble.node.controller; import java.util.ArrayList; import java.util.Collection; import bramble.networking.JobMetadata; public class JobList { private ArrayList<JobMetadata> unstartedJobs; private ArrayList<JobMetadata> startedJobs; private ArrayList<JobMetadata> completedJobs; /** * Initializes an empty job list. */ public JobList(){ this.unstartedJobs = new ArrayList<>(); this.startedJobs = new ArrayList<>(); this.completedJobs = new ArrayList<>(); } /** * Sets all the jobs to be contained in this list. * @param allJobNumbers all of the job numbers */ public synchronized void setUnstartedJobs(Collection<Integer> allJobNumbers) { for(Integer jobNumber : allJobNumbers){ JobMetadata job = new JobMetadata(jobNumber); if(!isJobInAnyList(job)){ unstartedJobs.add(job); } } } private boolean isJobInAnyList(final JobMetadata job){ if(unstartedJobs.contains(job)){ return true; } if(startedJobs.contains(job)){ return true; } if(completedJobs.contains(job)){ return true; } return false; } /** * Gets all the jobs that this controller node has. * @return all the jobs that this controller node has */ public int getTotalNumberOfJobs(){ return unstartedJobs.size() + startedJobs.size() + completedJobs.size(); } /** * Gets all the jobs that have been completed. * @return all the jobs that have been completed */ public int getNumberOfCompletedJobs(){ return completedJobs.size(); } /** * Gets all the jobs which have been started, including completed ones. * @return all the jobs which have been started, including completed ones */ public int getNumberOfJobsInProgress(){ return startedJobs.size(); } /** * Gets whether all the jobs have been completed. * @return true if all jobs are complete, false otherwise */ public boolean areAllJobsFinished(){ if(unstartedJobs.size() == 0 && startedJobs.size() == 0){ return true; } return false; } /** * Gets the job identifier of the next job that should be run. * @return the job identifier of the next job that should be run * or null if there are no suitable jobs */ public synchronized JobMetadata getNextJob(){ try{ return unstartedJobs.get(0); } catch (IndexOutOfBoundsException ex){ return null; } } /** * Cancels a job. * @param job the job to cancel */ public synchronized void cancelJob(final JobMetadata job) { startedJobs.remove(job); unstartedJobs.add(job); } /** * Marks a job as completed. * @param job the job that is complete */ public synchronized void jobCompleted(final JobMetadata job) { startedJobs.remove(job); completedJobs.add(job); } /** * Marks a job as started. * @param job the job that has been started */ public synchronized void jobStarted(final JobMetadata job) { unstartedJobs.remove(job); startedJobs.add(job); } }
package DatabaseModel; import java.sql.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Properties; import java.lang.reflect.*; import DatabaseModel.SQLExpressions.SQLExpression; public class DatabaseConnection { public Connection connection; public DatabaseConnection() throws SQLException { System.out.println("====CONNECTING TO DATABASE======"); System.out.println("................................"); connection = null; // Connection information. Properties connectionInfo = new Properties(); connectionInfo.put("user", "SERVER1"); connectionInfo.put("password", "P@ssw0rd"); DriverManager.registerDriver(new com.mysql.jdbc.Driver()); connection = DriverManager.getConnection("jdbc:mysql://localhost/Test", connectionInfo); connection.setAutoCommit(false); if (connection.isClosed()) System.out.println("Closed???"); } public void closeConnection() throws SQLException { if (connection != null) connection.close(); System.out.println("Connection closed."); } public static int getResultSize(ResultSet resultSet) throws SQLException { resultSet.last(); int max = resultSet.getRow(); resultSet.beforeFirst(); return max; } public <T extends DatabaseObject> ArrayList<T> select(Class<T> T) throws SQLException { ArrayList<T> items = new ArrayList<T>(); Statement statement = this.connection.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT * FROM " + T.getSimpleName()); int max = getResultSize(resultSet); ResultSetMetaData metaData = resultSet.getMetaData(); int columns = metaData.getColumnCount(); String[] columnNames = new String[columns]; HashMap<String, Object[]> values = new HashMap<String, Object[]>(); for (int i = 1; i <= columns; i++) { values.put(metaData.getColumnName(i), new Object[max]); columnNames[i - 1] = metaData.getColumnName(i); } int i = 1, columnIndex = 1; while (resultSet.next()) { columnIndex = 1; try { items.add(T.newInstance()); } catch (IllegalAccessException exception) { System.out.println("Target class with inaccessible protection level. - " + exception); return null; } catch (InstantiationException exception) { System.out.println("Target class with inaccessible protection level. - " + exception); return null; } for (String columnName : columnNames) { Object[] objects = values.get(columnName); Object obj = resultSet.getObject(columnIndex); objects[i - 1] = obj; values.replace(columnName, objects); columnIndex++; } T item = items.get(i - 1); Field[] fields = item.getClass().getFields(); for (Field field : fields) { if (values.containsKey(field.getName())) { try { field.set(item, field.getType().cast(values.get(field.getName())[i - 1])); } catch (IllegalAccessException exception) { System.out.println("Field with inaccessible protection level. - " + exception); return null; } } } i++; } return items; } public <T extends DatabaseObject> List<T> select(SQLExpression<T> expression) throws SQLException { List<T> items = new ArrayList<T>(); ResultSet results = connection.prepareStatement(expression.toString()).executeQuery(); ResultSetMetaData metaData = results.getMetaData(); int columns = metaData.getColumnCount(), max = DatabaseConnection.getResultSize(results); String[] columnNames = new String[columns]; HashMap<String, Object[]> values = new HashMap<String, Object[]>(); for (int i = 1; i <= columns; i++) { values.put(metaData.getColumnName(i), new Object[max]); columnNames[i - 1] = metaData.getColumnName(i); } int i = 1, columnIndex = 1; while (results.next()) { columnIndex = 1; try { items.add((T) expression.model.newInstance()); } catch (IllegalAccessException exception) { System.out.println("Target class with inaccessible protection level. - " + exception); return null; } catch (InstantiationException exception) { System.out.println("Target class with inaccessible protection level. - " + exception); return null; } for (String columnName : columnNames) { Object[] objects = values.get(columnName); Object obj = results.getObject(columnIndex); objects[i - 1] = obj; values.replace(columnName, objects); columnIndex++; } T item = items.get(i - 1); Field[] fields = item.getClass().getFields(); for (Field field : fields) { if (values.containsKey(field.getName())) { try { field.set(item, field.getType().cast(values.get(field.getName())[i - 1])); } catch (IllegalAccessException exception) { System.out.println("Field with inaccessible protection level. - " + exception); return null; } } } i++; } return items; } public <T extends Table> void insert(T instance) throws SQLException { Field[] fields = instance.getClass().asSubclass(instance.getClass()).getDeclaredFields(); String fieldValuesString = ""; String fieldsString = ""; int iterations = fields.length; for (Field field : fields) { fieldsString += field.getName(); try { if (field.get(instance) != null) { fieldValuesString += wrapValue(instance, field); } else fieldValuesString += "NULL"; } catch (IllegalAccessException ex) { System.out.println(ex); return; } iterations fieldsString += (iterations != 0 ? "," : ""); fieldValuesString += (iterations != 0 ? "," : ""); } String sql = "INSERT INTO " + instance.getClass().getSimpleName() + "(" + fieldsString + ") VALUES(" + fieldValuesString + ")"; //System.out.println(sql); PreparedStatement statement = connection.prepareStatement(sql); statement.executeUpdate(); connection.commit(); } private static <T extends DatabaseObject> String wrapValue(T T, Field field) throws IllegalArgumentException, IllegalAccessException { Class<?> type = field.getType(); String value = ""; try { value = field.get(T).toString(); } catch (Exception e) { System.out.println(e); return value; } if (type == String.class) { return "\"" + value + "\""; } else if (type == Date.class) { return "\"" + value + "\""; } else if (type == java.util.Date.class) { return "\"" + new java.sql.Date(((java.util.Date)field.get(T)).getTime()).toString() + "\""; } else if (type == Timestamp.class) { return "\"" + value + "\""; } return value; } public <T extends DatabaseObject> void delete(Class<T> T, HashMap<Field, Object> conditions) throws SQLException { String sqlWhereCondition = ""; if (conditions.size() != 0) { sqlWhereCondition = " WHERE"; int iterations = conditions.size(); for (Field field : conditions.keySet()) { boolean isString = field.getType().isAssignableFrom(String.class); sqlWhereCondition += " " + field.getName() + " = " + (isString ? "\"" : "") + conditions.get(field) + (isString ? "\"" : ""); iterations sqlWhereCondition += (iterations != 0 ? " AND " : ""); } } //System.out.println("DELETE FROM " + T.getSimpleName() + sqlWhereCondition); PreparedStatement statement = this.connection .prepareStatement("DELETE FROM " + T.getSimpleName() + sqlWhereCondition); statement.executeUpdate(); connection.commit(); } public <T extends DatabaseObject> void delete(SQLExpression<T> expression) throws SQLException { // System.out.println("DELETE FROM " + expression.model.getSimpleName() + " " // + (expression.hasWhereCondition ? expression.whereExpression : "")); PreparedStatement statement = this.connection.prepareStatement("DELETE FROM " + expression.wrapClass() + " " + (expression.hasWhereCondition ? expression.whereExpression : "")); statement.executeUpdate(); connection.commit(); } public <T extends DatabaseObject> void update(T instance, SQLExpression<T> expression) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException { String sql = "UPDATE " + expression.wrapClass() + " SET "; int iterations = expression.selectFields.size(); for (Field field : expression.selectFields) { sql += SQLExpression.wrapField(field) + " = " + SQLExpression.wrapValue(instance, field); if (--iterations != 0) { sql += ", "; } } sql += " " + expression.whereExpression; //System.out.println(sql); connection.prepareStatement(sql).executeUpdate(); connection.commit(); } public <T extends DatabaseObject> void update(Class<T> T, HashMap<Field, Object> fieldsToUpdate, HashMap<Field, Object> conditions) throws SQLException, IllegalArgumentException, IllegalAccessException { String sqlSetFields = ""; int iterations = fieldsToUpdate.size(); for (Field field : fieldsToUpdate.keySet()) { boolean isString = field.getType().isAssignableFrom(String.class); sqlSetFields += field.getName() + " = " + (isString ? "\"" : "") + fieldsToUpdate.get(field) + (isString ? "\"" : ""); iterations sqlSetFields += (iterations != 0 ? "," : ""); } //System.out.println(sqlSetFields); String sqlWhereExpression = ""; if (conditions.size() != 0) { sqlWhereExpression = " WHERE"; iterations = conditions.size(); for (Field field : conditions.keySet()) { boolean isString = field.getType().isAssignableFrom(String.class); sqlWhereExpression += " " + field.getName() + " = " + (isString ? "\"" : "") + conditions.get(field) + (isString ? "\"" : ""); iterations sqlWhereExpression += (iterations != 0 ? " AND " : ""); } } //System.out.println("UPDATE " + T.getSimpleName() + " SET " + sqlSetFields + sqlWhereExpression); PreparedStatement statement = this.connection .prepareStatement("UPDATE " + T.getSimpleName() + " SET " + sqlSetFields + sqlWhereExpression); statement.executeUpdate(); connection.commit(); } public <T extends DatabaseObject> boolean exists(SQLExpression<T> expression) throws SQLException { ResultSet results = connection.createStatement().executeQuery("SELECT 1 as `BooleanColumn` FROM " + expression.wrapClass() + " " + expression.whereExpression); results.next(); if (results.getMetaData().getColumnCount() > 0 && results.getInt(1) == 1) return true; return false; } }
package org.splevo.ui.jobs; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.splevo.extraction.DefaultExtractionService; import org.splevo.project.SPLevoProject; import com.google.common.collect.Lists; /** * Utility class for common tasks performed by jobs. */ public final class JobUtil { /** Disabled constructor to use utility class in a static manner. */ private JobUtil() { } /** * Initialize the resource set including preparation by the source model * extractors for specific source models. * * @param splevoProject * The {@link SPLevoProject} to get required configurations from. * * @return The initialized resource set. */ public static ResourceSetImpl initResourceSet(SPLevoProject splevoProject) { ResourceSetImpl resourceSet = new ResourceSetImpl(); List<String> sourceModelPaths = Lists.newArrayList(); sourceModelPaths.add(splevoProject.getSourceModelPathLeading()); sourceModelPaths.add(splevoProject.getSourceModelPathIntegration()); DefaultExtractionService extractionService = new DefaultExtractionService(); extractionService.prepareResourceSet(resourceSet, sourceModelPaths); return resourceSet; } /** * Get the current human readable timestamp. For example, to be used in * logging. * * @return The string representation of the timestamp. */ public static String getTimestamp() { /** The date format to use in job logging etc. */ DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd hh:mm:ss:S"); return (dateFormat.format(new Date())); } }
package io.spine.base.entity; import com.google.errorprone.annotations.Immutable; import io.spine.annotation.FirstGenericParameter; import io.spine.annotation.GeneratedMixin; import io.spine.base.KnownMessage; /** * A common interface for entity state messages. * * <p>Any message that defines an {@code (entity)} option with a valid {@code kind} is marked with * this interface by the Model Compiler. * * <p>The first field of the entity state message is treated as its identifier. It is a convention * that has two goals: * * <ol> * <li>The definition of an entity state always starts with its ID with no extra Protobuf * options. This way it's feels easy and more natural to read the code. * <li>Developers don't forget to specify which of the fields declared in Protobuf corresponds * to the entity ID. * </ol> * * <p>At codegen-time, the Model Compiler substitutes the generic parameter {@code <I>} with * an actual type of the first field of the entity state message. * * @param <I> * the type of entity identifiers * @see io.spine.code.proto.EntityStateOption */ //TODO:2020-06-10:alex.tymchenko: kill this warning? //@SuppressWarnings("InterfaceNeverImplemented") // Implemented in the dependent repos. @SuppressWarnings("unused") // <I> is used in scope of the code generated by the Model Compiler. @Immutable @GeneratedMixin @FirstGenericParameter(is = FirstMessageField.class) public interface EntityState<I> extends KnownMessage { }
package org.intermine.bio.util; import java.util.HashSet; import java.util.Set; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreException; import org.intermine.objectstore.intermine.ObjectStoreInterMineImpl; import org.intermine.objectstore.query.ConstraintOp; import org.intermine.objectstore.query.ConstraintSet; import org.intermine.objectstore.query.ContainsConstraint; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.QueryClass; import org.intermine.objectstore.query.QueryField; import org.intermine.objectstore.query.QueryNode; import org.intermine.objectstore.query.QueryObjectReference; import org.intermine.objectstore.query.Results; import org.intermine.objectstore.query.SimpleConstraint; /** * Bio utility methods for queries. * @author Kim Rutherford */ public abstract class BioQueries { private BioQueries() { //disable external instantiation } /** * Query ObjectStore for all Location object between given object (eg. Chromosome) and * subject (eg. Gene) classes. Return an iterator over the results ordered by subject if * orderBySubject is true, otherwise order by object. * @param os the ObjectStore to find the Locations in * @param objectCls object type of the Location * @param subjectCls subject type of the Location * @param orderBySubject if true order the results using the subjectCls, otherwise order by * objectCls * @param hasLength if true, only query locations where the objectCls object has a non-zero * length, e.g. a chromosome's length should be greater than zero * @param batchSize the batch size for the results object * @param hasChromosomeLocation if true, only query where the subject has a chromosome location * @return a Results object: object.id, location, subject * @throws ObjectStoreException if problem reading ObjectStore */ public static Results findLocationAndObjects(ObjectStore os, Class<?> objectCls, Class<?> subjectCls, boolean orderBySubject, boolean hasLength, boolean hasChromosomeLocation, int batchSize) throws ObjectStoreException { // TODO check objectCls and subjectCls assignable to BioEntity Query q = new Query(); q.setDistinct(false); QueryClass qcObj = new QueryClass(objectCls); QueryField qfObj = new QueryField(qcObj, "id"); q.addFrom(qcObj); q.addToSelect(qfObj); if (!orderBySubject) { q.addToOrderBy(qfObj); } QueryClass qcSub = new QueryClass(subjectCls); q.addFrom(qcSub); q.addToSelect(qcSub); if (orderBySubject) { q.addToOrderBy(qcSub); } Class<?> locationCls; try { locationCls = Class.forName("org.intermine.model.bio.Location"); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } QueryClass qcLoc = new QueryClass(locationCls); q.addFrom(qcLoc); q.addToSelect(qcLoc); ConstraintSet cs = new ConstraintSet(ConstraintOp.AND); QueryObjectReference ref1 = new QueryObjectReference(qcLoc, "locatedOn"); ContainsConstraint cc1 = new ContainsConstraint(ref1, ConstraintOp.CONTAINS, qcObj); cs.addConstraint(cc1); QueryObjectReference ref2 = new QueryObjectReference(qcLoc, "feature"); ContainsConstraint cc2 = new ContainsConstraint(ref2, ConstraintOp.CONTAINS, qcSub); cs.addConstraint(cc2); if (hasLength) { QueryField qfObjLength = new QueryField(qcObj, "length"); SimpleConstraint lengthNotNull = new SimpleConstraint(qfObjLength, ConstraintOp.IS_NOT_NULL); cs.addConstraint(lengthNotNull); } if (hasChromosomeLocation) { QueryObjectReference chrLocationRef = new QueryObjectReference(qcSub, "chromosomeLocation"); ContainsConstraint chrLocRefNotNull = new ContainsConstraint(chrLocationRef, ConstraintOp.IS_NOT_NULL); cs.addConstraint(chrLocRefNotNull); } q.setConstraint(cs); Set<QueryNode> indexesToCreate = new HashSet<QueryNode>(); indexesToCreate.add(qfObj); indexesToCreate.add(qcLoc); indexesToCreate.add(qcSub); ((ObjectStoreInterMineImpl) os).precompute(q, indexesToCreate, Constants.PRECOMPUTE_CATEGORY); /** * Query in a semi-SQL form: * * SELECT a1_.id AS a2_, a3_, a4_ FROM * org.intermine.model.bio.Chromosome AS a1_, * org.intermine.model.bio.SequenceFeature AS a3_, * org.intermine.model.bio.Location AS a4_ WHERE (a4_.locatedOn CONTAINS * a1_ AND a4_.feature CONTAINS a3_ AND a1_.length IS NOT NULL) ORDER BY * a1_.id with indexes [a2_, a3_id, a4_id, a2_, a3_id] * *or equivalently as: * * SELECT a1_.id AS a2_, a3_.id AS a3_id, a4_.id AS a4_id FROM * Chromosome AS a1_, SequenceFeature AS a3_, Location AS a4_ WHERE * a4_.locatedOnId = a1_.id AND a4_.featureId = a3_.id AND a1_.length IS * NOT NULL ORDER BY a1_.id, a3_.id, a4_.id */ Results res = os.execute(q, batchSize, true, true, true); return res; } }
package nova.sample.block; import nova.core.block.Block; import nova.core.block.Stateful; import nova.core.component.Category; import nova.core.component.Component; import nova.core.component.Passthrough; import nova.core.component.misc.Collider; import nova.core.component.renderer.ItemRenderer; import nova.core.component.renderer.StaticRenderer; import nova.core.network.NetworkTarget; import nova.core.network.Packet; import nova.core.network.Syncable; import nova.core.network.Sync; import nova.core.render.model.Model; import nova.core.retention.Storable; import nova.core.retention.Store; import nova.core.util.math.RotationUtil; import org.apache.commons.math3.geometry.euclidean.threed.Rotation; /** * This is a test block that has state. * @author Calclavia */ public class BlockStateful extends Block implements Storable, Stateful, Syncable { /** * Angle to rotate around */ @Store @Sync private double angle = 0; public BlockStateful() { add(new Collider().isOpaqueCube(false)); add(new StaticRenderer(this) .setOnRender(model -> { Model grinderModel = NovaBlock.grinderModel.getModel(); grinderModel .combineChildren("crank", "crank1", "crank2", "crank3") .matrix.rotate(new Rotation(RotationUtil.DEFAULT_ORDER,0, 0, angle)); model.children.add(grinderModel); model.bindAll(NovaBlock.grinderTexture); } ) ); add(new ItemRenderer(this)); add(new Category("buildingBlocks")); //add(new TestComponent()); rightClickEvent.add(this::onRightClick); } public boolean onRightClick(RightClickEvent evt) { if (NetworkTarget.Side.get().isServer()) { angle = (angle + Math.PI / 12) % (Math.PI * 2); NovaBlock.networkManager.sync(this); } //world().addEntity(NovaTest.movableSimpleTestFactory).transform().setPosition(evt.entity.position()); return true; } @Override public void read(Packet packet) { Syncable.super.read(packet); world().markStaticRender(position()); } @Override public String getID() { return "stateful"; } public static interface TestInterface { public void test(); } @Passthrough("nova.sample.block.BlockStateful$TestInterface") public static class TestComponent extends Component implements TestInterface { @Override public void test() { System.out.println("I do nothing"); } } }
package be.ibridge.kettle.trans.step; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Hashtable; import java.util.List; import java.util.Map; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.KettleVariables; import be.ibridge.kettle.core.LocalVariables; import be.ibridge.kettle.core.LogWriter; import be.ibridge.kettle.core.ResultFile; import be.ibridge.kettle.core.Row; import be.ibridge.kettle.core.RowSet; import be.ibridge.kettle.core.exception.KettleException; import be.ibridge.kettle.core.exception.KettleStepException; import be.ibridge.kettle.core.exception.KettleStepLoaderException; import be.ibridge.kettle.core.value.Value; import be.ibridge.kettle.trans.StepLoader; import be.ibridge.kettle.trans.StepPlugin; import be.ibridge.kettle.trans.StepPluginMeta; import be.ibridge.kettle.trans.Trans; import be.ibridge.kettle.trans.TransMeta; import be.ibridge.kettle.trans.step.accessoutput.AccessOutputMeta; import be.ibridge.kettle.trans.step.addsequence.AddSequenceMeta; import be.ibridge.kettle.trans.step.addxml.AddXMLMeta; import be.ibridge.kettle.trans.step.aggregaterows.AggregateRowsMeta; import be.ibridge.kettle.trans.step.blockingstep.BlockingStepMeta; import be.ibridge.kettle.trans.step.calculator.CalculatorMeta; import be.ibridge.kettle.trans.step.combinationlookup.CombinationLookupMeta; import be.ibridge.kettle.trans.step.constant.ConstantMeta; import be.ibridge.kettle.trans.step.cubeinput.CubeInputMeta; import be.ibridge.kettle.trans.step.cubeoutput.CubeOutputMeta; import be.ibridge.kettle.trans.step.databasejoin.DatabaseJoinMeta; import be.ibridge.kettle.trans.step.databaselookup.DatabaseLookupMeta; import be.ibridge.kettle.trans.step.dbproc.DBProcMeta; import be.ibridge.kettle.trans.step.delete.DeleteMeta; import be.ibridge.kettle.trans.step.denormaliser.DenormaliserMeta; import be.ibridge.kettle.trans.step.dimensionlookup.DimensionLookupMeta; import be.ibridge.kettle.trans.step.dummytrans.DummyTransMeta; import be.ibridge.kettle.trans.step.excelinput.ExcelInputMeta; import be.ibridge.kettle.trans.step.exceloutput.ExcelOutputMeta; import be.ibridge.kettle.trans.step.fieldsplitter.FieldSplitterMeta; import be.ibridge.kettle.trans.step.filesfromresult.FilesFromResultMeta; import be.ibridge.kettle.trans.step.filestoresult.FilesToResultMeta; import be.ibridge.kettle.trans.step.filterrows.FilterRowsMeta; import be.ibridge.kettle.trans.step.flattener.FlattenerMeta; import be.ibridge.kettle.trans.step.getfilenames.GetFileNamesMeta; import be.ibridge.kettle.trans.step.getvariable.GetVariableMeta; import be.ibridge.kettle.trans.step.groupby.GroupByMeta; import be.ibridge.kettle.trans.step.http.HTTPMeta; import be.ibridge.kettle.trans.step.injector.InjectorMeta; import be.ibridge.kettle.trans.step.insertupdate.InsertUpdateMeta; import be.ibridge.kettle.trans.step.joinrows.JoinRowsMeta; import be.ibridge.kettle.trans.step.mapping.MappingMeta; import be.ibridge.kettle.trans.step.mappinginput.MappingInputMeta; import be.ibridge.kettle.trans.step.mappingoutput.MappingOutputMeta; import be.ibridge.kettle.trans.step.mergejoin.MergeJoinMeta; import be.ibridge.kettle.trans.step.mergerows.MergeRowsMeta; import be.ibridge.kettle.trans.step.normaliser.NormaliserMeta; import be.ibridge.kettle.trans.step.nullif.NullIfMeta; import be.ibridge.kettle.trans.step.rowgenerator.RowGeneratorMeta; import be.ibridge.kettle.trans.step.rowsfromresult.RowsFromResultMeta; import be.ibridge.kettle.trans.step.rowstoresult.RowsToResultMeta; import be.ibridge.kettle.trans.step.scriptvalues.ScriptValuesMeta; import be.ibridge.kettle.trans.step.scriptvalues_mod.ScriptValuesMetaMod; import be.ibridge.kettle.trans.step.selectvalues.SelectValuesMeta; import be.ibridge.kettle.trans.step.setvariable.SetVariableMeta; import be.ibridge.kettle.trans.step.socketreader.SocketReaderMeta; import be.ibridge.kettle.trans.step.socketwriter.SocketWriterMeta; import be.ibridge.kettle.trans.step.sortedmerge.SortedMergeMeta; import be.ibridge.kettle.trans.step.sortrows.SortRowsMeta; import be.ibridge.kettle.trans.step.sql.ExecSQLMeta; import be.ibridge.kettle.trans.step.streamlookup.StreamLookupMeta; import be.ibridge.kettle.trans.step.systemdata.SystemDataMeta; import be.ibridge.kettle.trans.step.tableinput.TableInputMeta; import be.ibridge.kettle.trans.step.tableoutput.TableOutputMeta; import be.ibridge.kettle.trans.step.textfileinput.TextFileInputMeta; import be.ibridge.kettle.trans.step.textfileoutput.TextFileOutputMeta; import be.ibridge.kettle.trans.step.uniquerows.UniqueRowsMeta; import be.ibridge.kettle.trans.step.update.UpdateMeta; import be.ibridge.kettle.trans.step.valuemapper.ValueMapperMeta; import be.ibridge.kettle.trans.step.xbaseinput.XBaseInputMeta; import be.ibridge.kettle.trans.step.xmlinput.XMLInputMeta; import be.ibridge.kettle.trans.step.xmloutput.XMLOutputMeta; public class BaseStep extends Thread { public static final String CATEGORY_INPUT = Messages.getString("BaseStep.Category.Input"); public static final String CATEGORY_OUTPUT = Messages.getString("BaseStep.Category.Output"); public static final String CATEGORY_TRANSFORM = Messages.getString("BaseStep.Category.Transform"); public static final String CATEGORY_SCRIPTING = Messages.getString("BaseStep.Category.Scripting"); public static final String CATEGORY_LOOKUP = Messages.getString("BaseStep.Category.Lookup"); public static final String CATEGORY_JOINS = Messages.getString("BaseStep.Category.Joins"); public static final String CATEGORY_DATA_WAREHOUSE = Messages.getString("BaseStep.Category.DataWarehouse"); public static final String CATEGORY_JOB = Messages.getString("BaseStep.Category.Job"); public static final String CATEGORY_MAPPING = Messages.getString("BaseStep.Category.Mapping"); public static final String CATEGORY_INLINE = Messages.getString("BaseStep.Category.Inline"); public static final String CATEGORY_EXPERIMENTAL = Messages.getString("BaseStep.Category.Experimental"); public static final String CATEGORY_DEPRECATED = Messages.getString("BaseStep.Category.Deprecated"); protected static LocalVariables localVariables = LocalVariables.getInstance(); public static final StepPluginMeta[] steps = { new StepPluginMeta(TextFileInputMeta.class, "TextFileInput", Messages.getString("BaseStep.TypeLongDesc.TextFileInput"), Messages .getString("BaseStep.TypeTooltipDesc.TextInputFile", Const.CR), "TFI.png", CATEGORY_INPUT), new StepPluginMeta(TextFileOutputMeta.class, "TextFileOutput", Messages.getString("BaseStep.TypeLongDesc.TextFileOutput"), Messages .getString("BaseStep.TypeTooltipDesc.TextOutputFile"), "TFO.png", CATEGORY_OUTPUT), new StepPluginMeta(TableInputMeta.class, "TableInput", Messages.getString("BaseStep.TypeLongDesc.TableInput"), Messages .getString("BaseStep.TypeTooltipDesc.TableInput"), "TIP.png", CATEGORY_INPUT), new StepPluginMeta(TableOutputMeta.class, "TableOutput", Messages.getString("BaseStep.TypeLongDesc.Output"), Messages .getString("BaseStep.TypeTooltipDesc.TableOutput"), "TOP.png", CATEGORY_OUTPUT), new StepPluginMeta(SelectValuesMeta.class, "SelectValues", Messages.getString("BaseStep.TypeLongDesc.SelectValues"), Messages.getString( "BaseStep.TypeTooltipDesc.SelectValues", Const.CR), "SEL.png", CATEGORY_TRANSFORM), new StepPluginMeta(FilterRowsMeta.class, "FilterRows", Messages.getString("BaseStep.TypeLongDesc.FilterRows"), Messages .getString("BaseStep.TypeTooltipDesc.FilterRows"), "FLT.png", CATEGORY_TRANSFORM), new StepPluginMeta(DatabaseLookupMeta.class, "DBLookup", Messages.getString("BaseStep.TypeLongDesc.DatabaseLookup"), Messages .getString("BaseStep.TypeTooltipDesc.Databaselookup"), "DLU.png", CATEGORY_LOOKUP), new StepPluginMeta(SortRowsMeta.class, "SortRows", Messages.getString("BaseStep.TypeLongDesc.SortRows"), Messages .getString("BaseStep.TypeTooltipDesc.Sortrows"), "SRT.png", CATEGORY_TRANSFORM), new StepPluginMeta(StreamLookupMeta.class, "StreamLookup", Messages.getString("BaseStep.TypeLongDesc.StreamLookup"), Messages .getString("BaseStep.TypeTooltipDesc.Streamlookup"), "SLU.png", CATEGORY_LOOKUP), new StepPluginMeta(AddSequenceMeta.class, "Sequence", Messages.getString("BaseStep.TypeLongDesc.AddSequence"), Messages .getString("BaseStep.TypeTooltipDesc.Addsequence"), "SEQ.png", CATEGORY_TRANSFORM), new StepPluginMeta(DimensionLookupMeta.class, "DimensionLookup", Messages.getString("BaseStep.TypeLongDesc.DimensionUpdate"), Messages .getString("BaseStep.TypeTooltipDesc.Dimensionupdate", Const.CR), "DIM.png", CATEGORY_DATA_WAREHOUSE), new StepPluginMeta(CombinationLookupMeta.class, "CombinationLookup", Messages.getString("BaseStep.TypeLongDesc.CombinationUpdate"), Messages.getString("BaseStep.TypeTooltipDesc.CombinationUpdate", Const.CR, Const.CR), "CMB.png", CATEGORY_DATA_WAREHOUSE), new StepPluginMeta(DummyTransMeta.class, "Dummy", Messages.getString("BaseStep.TypeLongDesc.Dummy"), Messages.getString( "BaseStep.TypeTooltipDesc.Dummy", Const.CR), "DUM.png", CATEGORY_TRANSFORM), new StepPluginMeta(JoinRowsMeta.class, "JoinRows", Messages.getString("BaseStep.TypeLongDesc.JoinRows"), Messages.getString( "BaseStep.TypeTooltipDesc.JoinRows", Const.CR), "JRW.png", CATEGORY_JOINS), new StepPluginMeta(AggregateRowsMeta.class, "AggregateRows", Messages.getString("BaseStep.TypeLongDesc.AggregateRows"), Messages .getString("BaseStep.TypeTooltipDesc.AggregateRows", Const.CR), "AGG.png", CATEGORY_DEPRECATED), new StepPluginMeta(SystemDataMeta.class, "SystemInfo", Messages.getString("BaseStep.TypeLongDesc.GetSystemInfo"), Messages .getString("BaseStep.TypeTooltipDesc.GetSystemInfo"), "SYS.png", CATEGORY_INPUT), new StepPluginMeta(RowGeneratorMeta.class, "RowGenerator", Messages.getString("BaseStep.TypeLongDesc.GenerateRows"), Messages .getString("BaseStep.TypeTooltipDesc.GenerateRows"), "GEN.png", CATEGORY_INPUT), new StepPluginMeta(ScriptValuesMeta.class, "ScriptValue", Messages.getString("BaseStep.TypeLongDesc.JavaScript"), Messages .getString("BaseStep.TypeTooltipDesc.JavaScriptValue"), "SCR.png", CATEGORY_SCRIPTING), new StepPluginMeta(ScriptValuesMetaMod.class, "ScriptValueMod", Messages.getString("BaseStep.TypeLongDesc.JavaScriptMod"), Messages .getString("BaseStep.TypeTooltipDesc.JavaScriptValueMod"), "SCR_mod.png", CATEGORY_SCRIPTING), new StepPluginMeta(DBProcMeta.class, "DBProc", Messages.getString("BaseStep.TypeLongDesc.CallDBProcedure"), Messages .getString("BaseStep.TypeTooltipDesc.CallDBProcedure"), "PRC.png", CATEGORY_LOOKUP), new StepPluginMeta(InsertUpdateMeta.class, "InsertUpdate", Messages.getString("BaseStep.TypeLongDesc.InsertOrUpdate"), Messages .getString("BaseStep.TypeTooltipDesc.InsertOrUpdate"), "INU.png", CATEGORY_OUTPUT), new StepPluginMeta(UpdateMeta.class, "Update", Messages.getString("BaseStep.TypeLongDesc.Update"), Messages .getString("BaseStep.TypeTooltipDesc.Update"), "UPD.png", CATEGORY_OUTPUT), new StepPluginMeta(DeleteMeta.class, "Delete", Messages.getString("BaseStep.TypeLongDesc.Delete"), Messages .getString("BaseStep.TypeTooltipDesc.Delete"), "Delete.png", CATEGORY_OUTPUT), new StepPluginMeta(NormaliserMeta.class, "Normaliser", Messages.getString("BaseStep.TypeLongDesc.RowNormaliser"), Messages .getString("BaseStep.TypeTooltipDesc.RowNormaliser"), "NRM.png", CATEGORY_TRANSFORM), new StepPluginMeta(FieldSplitterMeta.class, "FieldSplitter", Messages.getString("BaseStep.TypeLongDesc.SplitFields"), Messages .getString("BaseStep.TypeTooltipDesc.SplitFields"), "SPL.png", CATEGORY_TRANSFORM), new StepPluginMeta(UniqueRowsMeta.class, "Unique", Messages.getString("BaseStep.TypeLongDesc.UniqueRows"), Messages.getString( "BaseStep.TypeTooltipDesc.Uniquerows", Const.CR, Const.CR), "UNQ.png", CATEGORY_TRANSFORM), new StepPluginMeta(GroupByMeta.class, "GroupBy", Messages.getString("BaseStep.TypeLongDesc.GroupBy"), Messages.getString( "BaseStep.TypeTooltipDesc.Groupby", Const.CR, Const.CR), "GRP.png", CATEGORY_TRANSFORM), new StepPluginMeta(RowsFromResultMeta.class, "RowsFromResult", Messages.getString("BaseStep.TypeLongDesc.GetRows"), Messages .getString("BaseStep.TypeTooltipDesc.GetRowsFromResult"), "FCH.png", CATEGORY_JOB), new StepPluginMeta(RowsToResultMeta.class, "RowsToResult", Messages.getString("BaseStep.TypeLongDesc.CopyRows"), Messages.getString( "BaseStep.TypeTooltipDesc.CopyRowsToResult", Const.CR), "TCH.png", CATEGORY_JOB), new StepPluginMeta(CubeInputMeta.class, "CubeInput", Messages.getString("BaseStep.TypeLongDesc.CubeInput"), Messages .getString("BaseStep.TypeTooltipDesc.Cubeinput"), "CIP.png", CATEGORY_INPUT), new StepPluginMeta(CubeOutputMeta.class, "CubeOutput", Messages.getString("BaseStep.TypeLongDesc.CubeOutput"), Messages .getString("BaseStep.TypeTooltipDesc.Cubeoutput"), "COP.png", CATEGORY_OUTPUT), new StepPluginMeta(DatabaseJoinMeta.class, "DBJoin", Messages.getString("BaseStep.TypeLongDesc.DatabaseJoin"), Messages .getString("BaseStep.TypeTooltipDesc.Databasejoin"), "DBJ.png", CATEGORY_JOINS), new StepPluginMeta(XBaseInputMeta.class, "XBaseInput", Messages.getString("BaseStep.TypeLongDesc.XBaseInput"), Messages .getString("BaseStep.TypeTooltipDesc.XBaseinput"), "XBI.png", CATEGORY_INPUT), new StepPluginMeta(ExcelInputMeta.class, "ExcelInput", Messages.getString("BaseStep.TypeLongDesc.ExcelInput"), Messages .getString("BaseStep.TypeTooltipDesc.ExcelInput"), "XLI.png", CATEGORY_INPUT), new StepPluginMeta(NullIfMeta.class, "NullIf", Messages.getString("BaseStep.TypeLongDesc.NullIf"), Messages .getString("BaseStep.TypeTooltipDesc.Nullif"), "NUI.png", CATEGORY_TRANSFORM), new StepPluginMeta(CalculatorMeta.class, "Calculator", Messages.getString("BaseStep.TypeLongDesc.Caculator"), Messages .getString("BaseStep.TypeTooltipDesc.Calculator"), "CLC.png", CATEGORY_TRANSFORM), new StepPluginMeta(ExecSQLMeta.class, "ExecSQL", Messages.getString("BaseStep.TypeLongDesc.ExcuteSQL"), Messages .getString("BaseStep.TypeTooltipDesc.ExecuteSQL"), "SQL.png", CATEGORY_SCRIPTING), new StepPluginMeta(MappingMeta.class, "Mapping", Messages.getString("BaseStep.TypeLongDesc.MappingSubTransformation"), Messages .getString("BaseStep.TypeTooltipDesc.MappingSubTransformation"), "MAP.png", CATEGORY_MAPPING), new StepPluginMeta(MappingInputMeta.class, "MappingInput", Messages.getString("BaseStep.TypeLongDesc.MappingInput"), Messages .getString("BaseStep.TypeTooltipDesc.MappingInputSpecification"), "MPI.png", CATEGORY_MAPPING), new StepPluginMeta(MappingOutputMeta.class, "MappingOutput", Messages.getString("BaseStep.TypeLongDesc.MappingOutput"), Messages .getString("BaseStep.TypeTooltipDesc.MappingOutputSpecification"), "MPO.png", CATEGORY_MAPPING), new StepPluginMeta(XMLInputMeta.class, "XMLInput", Messages.getString("BaseStep.TypeLongDesc.XMLInput"), Messages .getString("BaseStep.TypeTooltipDesc.XMLInput"), "XIN.png", CATEGORY_INPUT), new StepPluginMeta(XMLOutputMeta.class, "XMLOutput", Messages.getString("BaseStep.TypeLongDesc.XMLOutput"), Messages .getString("BaseStep.TypeTooltipDesc.XMLOutput"), "XOU.png", CATEGORY_OUTPUT), new StepPluginMeta(AddXMLMeta.class, "AddXML", Messages.getString("BaseStep.TypeLongDesc.AddXML"), Messages .getString("BaseStep.TypeTooltipDesc.AddXML"), "XIN.png", CATEGORY_TRANSFORM), new StepPluginMeta(MergeRowsMeta.class, "MergeRows", Messages.getString("BaseStep.TypeLongDesc.MergeRows"), Messages .getString("BaseStep.TypeTooltipDesc.MergeRows"), "MRG.png", CATEGORY_JOINS), new StepPluginMeta(ConstantMeta.class, "Constant", Messages.getString("BaseStep.TypeLongDesc.AddConstants"), Messages .getString("BaseStep.TypeTooltipDesc.Addconstants"), "CST.png", CATEGORY_TRANSFORM), new StepPluginMeta(DenormaliserMeta.class, "Denormaliser", Messages.getString("BaseStep.TypeLongDesc.RowDenormaliser"), Messages .getString("BaseStep.TypeTooltipDesc.RowsDenormalises", Const.CR), "UNP.png", CATEGORY_TRANSFORM), new StepPluginMeta(FlattenerMeta.class, new String[] { "Flattener", "Flatterner" }, Messages .getString("BaseStep.TypeLongDesc.RowFalttener"), Messages.getString("BaseStep.TypeTooltipDesc.Rowflattener"), "FLA.png", CATEGORY_TRANSFORM), new StepPluginMeta(ValueMapperMeta.class, "ValueMapper", Messages.getString("BaseStep.TypeLongDesc.ValueMapper"), Messages .getString("BaseStep.TypeTooltipDesc.MapValues"), "VMP.png", CATEGORY_TRANSFORM), new StepPluginMeta(SetVariableMeta.class, "SetVariable", Messages.getString("BaseStep.TypeLongDesc.SetVariable"), Messages .getString("BaseStep.TypeTooltipDesc.SetVariable"), "SVA.png", CATEGORY_JOB), new StepPluginMeta(GetVariableMeta.class, "GetVariable", Messages.getString("BaseStep.TypeLongDesc.GetVariable"), Messages .getString("BaseStep.TypeTooltipDesc.GetVariable"), "GVA.png", CATEGORY_JOB), new StepPluginMeta(GetFileNamesMeta.class, "GetFileNames", Messages.getString("BaseStep.TypeLongDesc.GetFileNames"), Messages .getString("BaseStep.TypeTooltipDesc.GetFileNames"), "GFN.png", CATEGORY_INPUT), new StepPluginMeta(FilesFromResultMeta.class, "FilesFromResult", Messages.getString("BaseStep.TypeLongDesc.FilesFromResult"), Messages .getString("BaseStep.TypeTooltipDesc.FilesFromResult"), "FFR.png", CATEGORY_JOB), new StepPluginMeta(FilesToResultMeta.class, "FilesToResult", Messages.getString("BaseStep.TypeLongDesc.FilesToResult"), Messages .getString("BaseStep.TypeTooltipDesc.FilesToResult"), "FTR.png", CATEGORY_JOB), new StepPluginMeta(BlockingStepMeta.class, "BlockingStep", Messages.getString("BaseStep.TypeLongDesc.BlockingStep"), Messages .getString("BaseStep.TypeTooltipDesc.BlockingStep"), "BLK.png", CATEGORY_TRANSFORM), new StepPluginMeta(InjectorMeta.class, "Injector", Messages.getString("BaseStep.TypeLongDesc.Injector"), Messages .getString("BaseStep.TypeTooltipDesc.Injector"), "INJ.png", CATEGORY_INLINE), new StepPluginMeta(ExcelOutputMeta.class, "ExcelOutput", Messages.getString("BaseStep.TypeLongDesc.ExcelOutput"), Messages .getString("BaseStep.TypeTooltipDesc.ExcelOutput"), "XLO.png", CATEGORY_OUTPUT), new StepPluginMeta(AccessOutputMeta.class, "AccessOutput", Messages.getString("BaseStep.TypeLongDesc.AccessOutput"), Messages .getString("BaseStep.TypeTooltipDesc.AccessOutput"), "ACO.png", CATEGORY_OUTPUT), new StepPluginMeta(SortedMergeMeta.class, "SortedMerge", Messages.getString("BaseStep.TypeLongDesc.SortedMerge"), Messages .getString("BaseStep.TypeTooltipDesc.SortedMerge"), "SMG.png", CATEGORY_JOINS), new StepPluginMeta(MergeJoinMeta.class, "MergeJoin", Messages.getString("BaseStep.TypeLongDesc.MergeJoin"), Messages .getString("BaseStep.TypeTooltipDesc.MergeJoin"), "MJOIN.png", CATEGORY_JOINS), new StepPluginMeta(SocketReaderMeta.class, "SocketReader", Messages.getString("BaseStep.TypeLongDesc.SocketReader"), Messages .getString("BaseStep.TypeTooltipDesc.SocketReader"), "SKR.png", CATEGORY_INLINE), new StepPluginMeta(SocketWriterMeta.class, "SocketWriter", Messages.getString("BaseStep.TypeLongDesc.SocketWriter"), Messages .getString("BaseStep.TypeTooltipDesc.SocketWriter"), "SKW.png", CATEGORY_INLINE), new StepPluginMeta(HTTPMeta.class, "HTTP", Messages.getString("BaseStep.TypeLongDesc.HTTP"), Messages .getString("BaseStep.TypeTooltipDesc.HTTP"), "WEB.png", CATEGORY_LOOKUP), }; public static final String category_order[] = { CATEGORY_INPUT, CATEGORY_OUTPUT, CATEGORY_LOOKUP, CATEGORY_TRANSFORM, CATEGORY_JOINS, CATEGORY_SCRIPTING, CATEGORY_DATA_WAREHOUSE, CATEGORY_MAPPING, CATEGORY_JOB, CATEGORY_INLINE, CATEGORY_EXPERIMENTAL, CATEGORY_DEPRECATED, }; private static final int MIN_PRIORITY = 1; private static final int LOW_PRIORITY = 3; private static final int NORMAL_PRIORITY = 5; private static final int HIGH_PRIORITY = 7; private static final int MAX_PRIORITY = 10; public static final String[] statusDesc = { Messages.getString("BaseStep.status.Empty"), Messages.getString("BaseStep.status.Init"), Messages.getString("BaseStep.status.Running"), Messages.getString("BaseStep.status.Idle"), Messages.getString("BaseStep.status.Finished"), Messages.getString("BaseStep.status.Stopped"), Messages.getString("BaseStep.status.Disposed"), Messages.getString("BaseStep.status.Halted"), }; private TransMeta transMeta; private StepMeta stepMeta; private String stepname; protected LogWriter log; private Trans trans; public ArrayList previewBuffer; public int previewSize; public long linesRead; // // lines // read // from // previous // step(s) public long linesWritten; // // lines // written // next // step(s) public long linesInput; // // lines // read // from // file // database public long linesOutput; // // lines // written // file // database public long linesUpdated; // // lines // updated // database // (dimension) public long linesSkipped; // // lines // passed // without // alteration // (dimension) private long nrGetSleeps; // // total // get // sleep // time // nano-seconds private long nrPutSleeps; // // total // put // sleep // time // nano-seconds private boolean distributed; private long errors; private StepMeta nextSteps[]; private StepMeta prevSteps[]; private int in_handling, out_handling; public ArrayList thr; public ArrayList inputRowSets; public ArrayList outputRowSets; public boolean stopped; public boolean waiting; public boolean init; private int stepcopy; // The // copy // number // THIS // thread. private int output_rowset_nr; // for // fixed // input // channel: // StreamLookup private Date start_time, stop_time; public boolean first; public boolean terminator; public ArrayList terminator_rows; private StepMetaInterface stepMetaInterface; private StepDataInterface stepDataInterface; private List rowListeners; // List // RowListener // interfaces /** * List of files that are generated or used by this step. After execution, these can be added to result. */ private List resultFiles; /** * Set this to true if you want to have extra checking enabled on the rows that are entering this step. All too * often people send in bugs when it is really the mixing of different types of rows that is causing the problem. */ private boolean safeModeEnabled; /** * This contains the first row received and will be the reference row. We used it to perform extra checking: see if * we don't get rows with "mixed" contents. */ private Row referenceRow; /** * This field tells the putRow() method that we are in partitioned mode */ private boolean partitioned; /** * The partition ID at which this step copy runs, or null if this step is not running partitioned. */ private String partitionID; /** * This field tells the putRow() method to re-partition the incoming data */ private boolean repartitioning; /** * True if the step needs to perform a sorted merge on the incoming partitioned data */ private boolean partitionMerging; /** * The index of the column to partition or -1 if not known yet (before first row) */ private int partitionColumnIndex; /** * The partitionID to rowset mapping */ private Map partitionTargets; /** * Cache for the partition IDs */ private static String[] partitionIDs; /** * step partitioning information of the NEXT step */ private static StepPartitioningMeta nextStepPartitioningMeta; /** * This is the base step that forms that basis for all steps. You can derive from this class to implement your own * steps. * * @param stepMeta The StepMeta object to run. * @param stepDataInterface the data object to store temporary data, database connections, caches, result sets, * hashtables etc. * @param copyNr The copynumber for this step. * @param transMeta The TransInfo of which the step stepMeta is part of. * @param trans The (running) transformation to obtain information shared among the steps. */ public BaseStep(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { log = LogWriter.getInstance(); this.stepMeta = stepMeta; this.stepDataInterface = stepDataInterface; this.stepcopy += copyNr; this.transMeta = transMeta; this.trans = trans; this.stepname = stepMeta.getName(); // Set the name of the thread if (stepMeta.getName() != null) { setName(toString() + " (" + super.getName() + ")"); } else { throw new RuntimeException("A step in transformation [" + transMeta.toString() + "] doesn't have a name. A step should always have a name to identify it by."); } first = true; stopped = false; init = false; linesRead = 0L; // Keep some statistics! linesWritten = 0L; linesUpdated = 0L; linesSkipped = 0L; nrGetSleeps = 0L; nrPutSleeps = 0L; inputRowSets = null; outputRowSets = null; nextSteps = null; terminator = stepMeta.hasTerminator(); if (terminator) { terminator_rows = new ArrayList(); } else { terminator_rows = null; } // debug="-"; //$NON-NLS-1$ output_rowset_nr = -1; start_time = null; stop_time = null; distributed = stepMeta.isDistributes(); if (distributed) if (log.isDetailed()) logDetailed(Messages.getString("BaseStep.Log.DistributionActivated")); //$NON-NLS-1$ else if (log.isDetailed()) logDetailed(Messages.getString("BaseStep.Log.DistributionDeactivated")); //$NON-NLS-1$ rowListeners = new ArrayList(); resultFiles = new ArrayList(); repartitioning = false; partitionColumnIndex = -1; partitionTargets = new Hashtable(); dispatch(); } public boolean init(StepMetaInterface smi, StepDataInterface sdi) { sdi.setStatus(StepDataInterface.STATUS_INIT); return true; } public void dispose(StepMetaInterface smi, StepDataInterface sdi) { sdi.setStatus(StepDataInterface.STATUS_DISPOSED); } public long getProcessed() { return linesRead; } public void setCopy(int cop) { stepcopy = cop; } /** * @return The steps copy number (default 0) */ public int getCopy() { return stepcopy; } public long getErrors() { return errors; } public void setErrors(long e) { errors = e; } /** * @return Returns the linesInput. */ public long getLinesInput() { return linesInput; } /** * @return Returns the linesOutput. */ public long getLinesOutput() { return linesOutput; } /** * @return Returns the linesRead. */ public long getLinesRead() { return linesRead; } /** * @return Returns the linesWritten. */ public long getLinesWritten() { return linesWritten; } /** * @return Returns the linesUpdated. */ public long getLinesUpdated() { return linesUpdated; } public String getStepname() { return stepname; } public void setStepname(String stepname) { this.stepname = stepname; } public Trans getDispatcher() { return trans; } public String getStatusDescription() { return statusDesc[getStatus()]; } /** * @return Returns the stepMetaInterface. */ public StepMetaInterface getStepMetaInterface() { return stepMetaInterface; } /** * @param stepMetaInterface The stepMetaInterface to set. */ public void setStepMetaInterface(StepMetaInterface stepMetaInterface) { this.stepMetaInterface = stepMetaInterface; } /** * @return Returns the stepDataInterface. */ public StepDataInterface getStepDataInterface() { return stepDataInterface; } /** * @param stepDataInterface The stepDataInterface to set. */ public void setStepDataInterface(StepDataInterface stepDataInterface) { this.stepDataInterface = stepDataInterface; } /** * @return Returns the stepMeta. */ public StepMeta getStepMeta() { return stepMeta; } /** * @param stepMeta The stepMeta to set. */ public void setStepMeta(StepMeta stepMeta) { this.stepMeta = stepMeta; } /** * @return Returns the transMeta. */ public TransMeta getTransMeta() { return transMeta; } /** * @param transMeta The transMeta to set. */ public void setTransMeta(TransMeta transMeta) { this.transMeta = transMeta; } /** * @return Returns the trans. */ public Trans getTrans() { return trans; } /** * putRow is used to copy a row, to the alternate rowset(s) This should get priority over everything else! * (synchronized) If distribute is true, a row is copied only once to the output rowsets, otherwise copies are sent * to each rowset! * * @param row The row to put to the destination rowset(s). * @throws KettleStepException */ public synchronized void putRow(Row row) throws KettleStepException { synchronized(outputRowSets) { if (previewSize > 0 && previewBuffer.size() < previewSize) { previewBuffer.add(new Row(row)); } // call all rowlisteners... for (int i = 0; i < rowListeners.size(); i++) { RowListener rowListener = (RowListener) rowListeners.get(i); rowListener.rowWrittenEvent(row); } // Keep adding to terminator_rows buffer... if (terminator && terminator_rows != null) { terminator_rows.add(new Row(row)); } if (outputRowSets.size() == 0) { // No more output rowsets! return; // we're done here! } // Before we copy this row to output, wait for room... for (int i = 0; i < outputRowSets.size(); i++) // Wait for all rowsets: keep synchronised! { int sleeptime = transMeta.getSleepTimeFull(); RowSet rs = (RowSet) outputRowSets.get(i); // Set the priority every 128k rows only if (transMeta.isUsingThreadPriorityManagment()) { if (linesWritten>0 && (linesWritten & 0xFF) == 0) { rs.setPriorityFrom(calcPutPriority(rs)); } } while (rs.isFull() && !stopped) { try { if (sleeptime > 0) { sleep(0, sleeptime); } else { super.notifyAll(); } } catch (Exception e) { logError(Messages.getString("BaseStep.Log.ErrorInThreadSleeping") + e.toString()); //$NON-NLS-1$ setErrors(1); stopAll(); return; } nrPutSleeps += sleeptime; if (sleeptime < 100) sleeptime = ((int) (sleeptime * 1.2)) + 1; else sleeptime = 100; } } if (stopped) { if (log.isDebug()) logDebug(Messages.getString("BaseStep.Log.StopPuttingARow")); //$NON-NLS-1$ stopAll(); return; } // Repartitioning happens when the current step is not partitioned, but the next one is. // That means we need to look up the partitioning information in the next step.. // If there are multiple steps, we need to look at the first (they should be all the same) // TODO: make something smart later to allow splits etc. if (repartitioning) { // Do some pre-processing on the first row... // This is only done once and should cost very little in terms of processing time. if (partitionColumnIndex < 0) { StepMeta nextSteps[] = transMeta.getNextSteps(stepMeta); if (nextSteps == null || nextSteps.length == 0) { throw new KettleStepException( "Re-partitioning is enabled but no next steps could be found: developer error!"); } // Take the partitioning logic from one of the next steps nextStepPartitioningMeta = nextSteps[0].getStepPartitioningMeta(); // What's the column index of the partitioning fieldname? partitionColumnIndex = row.searchValueIndex(nextStepPartitioningMeta.getFieldName()); if (partitionColumnIndex < 0) { throw new KettleStepException("Unable to find partitioning field name [" + nextStepPartitioningMeta.getFieldName() + "] in the output row : " + row); } // Cache the partition IDs as well... partitionIDs = nextSteps[0].getStepPartitioningMeta().getPartitionSchema().getPartitionIDs(); // OK, we also want to cache the target rowset // We know that we have to partition in N pieces // We should also have N rowsets to the next step // This is always the case, wheter the target is partitioned or not. // So what we do is now count the number of rowsets // And we take the steps copy nr to map. // It's simple for the time being. // P1 : MOD(field,N)==0 // P2 : MOD(field,N)==1 // PN : MOD(field,N)==N-1 for (int r = 0; r < outputRowSets.size(); r++) { RowSet rowSet = (RowSet) outputRowSets.get(r); if (rowSet.getOriginStepName().equalsIgnoreCase(getStepname()) && rowSet.getOriginStepCopy() == getCopy()) { // Find the target step metadata StepMeta targetStep = transMeta.findStep(rowSet.getDestinationStepName()); // What are the target partition ID's String targetPartitions[] = targetStep.getStepPartitioningMeta().getPartitionSchema().getPartitionIDs(); // The target partitionID: String targetPartitionID = targetPartitions[rowSet.getDestinationStepCopy()]; // Save the mapping: if we want to know to which rowset belongs to a partition this is the place // to be. partitionTargets.put(targetPartitionID, rowSet); } } } // End of the one-time init code. // Here we go with the regular show int partitionNr = nextStepPartitioningMeta.getPartitionNr(row.getValue(partitionColumnIndex), partitionIDs.length); String targetPartition = partitionIDs[partitionNr]; // Put the row forward to the next step according to the partition rule. RowSet rs = (RowSet) partitionTargets.get(targetPartition); rs.putRow(row); linesWritten++; } else { if (distributed) { // Copy the row to the "next" output rowset. // We keep the next one in out_handling RowSet rs = (RowSet) outputRowSets.get(out_handling); rs.putRow(row); linesWritten++; // Now determine the next output rowset! // Only if we have more then one output... if (outputRowSets.size() > 1) { out_handling++; if (out_handling >= outputRowSets.size()) out_handling = 0; } } else // Copy the row to all output rowsets! { // Copy to the row in the other output rowsets... for (int i = 1; i < outputRowSets.size(); i++) // start at 1 { RowSet rs = (RowSet) outputRowSets.get(i); rs.putRow(new Row(row)); } // set row in first output rowset RowSet rs = (RowSet) outputRowSets.get(0); rs.putRow(row); linesWritten++; } } } } /** * This version of getRow() only takes data from certain rowsets We select these rowsets that have name = step * Otherwise it's the same as the other one. * * @param row the row to send to the destination step * @param to the name of the step to send the row to */ public synchronized void putRowTo(Row row, String to) throws KettleStepException { output_rowset_nr = findOutputRowSetNumber(stepname, getCopy(), to, 0); if (output_rowset_nr < 0) { // No rowset found: normally it can't happen: // we deleted the rowset because it was // finished throw new KettleStepException(Messages.getString("BaseStep.Exception.UnableToFindRowset", to)); //$NON-NLS-1$ //$NON-NLS-2$ } putRowTo(row, output_rowset_nr); } /** * putRow is used to copy a row, to the alternate rowset(s) This should get priority over everything else! * (synchronized) If distribute is true, a a row is copied only once to a single output rowset! * * @param row The row to put to the destination rowsets. * @param output_rowset_nr the number of the rowset to put the row to. */ public synchronized void putRowTo(Row row, int output_rowset_nr) { int sleeptime; if (previewSize > 0 && previewBuffer.size() < previewSize) { previewBuffer.add(new Row(row)); } // call all rowlisteners... for (int i = 0; i < rowListeners.size(); i++) { RowListener rowListener = (RowListener) rowListeners.get(i); rowListener.rowWrittenEvent(row); } // Keep adding to terminator_rows buffer... if (terminator && terminator_rows != null) { terminator_rows.add(new Row(row)); } if (outputRowSets.size() == 0) return; // nothing to do here! RowSet rs = (RowSet) outputRowSets.get(output_rowset_nr); sleeptime = transMeta.getSleepTimeFull(); while (rs.isFull() && !stopped) { try { if (sleeptime > 0) { sleep(0, sleeptime); } else { super.notifyAll(); } } catch (Exception e) { logError(Messages.getString("BaseStep.Log.ErrorInThreadSleeping") + e.toString()); //$NON-NLS-1$ setErrors(1); stopAll(); return; } nrPutSleeps += sleeptime; if (sleeptime < 100) sleeptime = ((int) (sleeptime * 1.2)) + 1; else sleeptime = 100; } if (stopped) { if (log.isDebug()) logDebug(Messages.getString("BaseStep.Log.StopPuttingARow")); //$NON-NLS-1$ stopAll(); return; } // Don't distribute or anything, only go to this rowset! rs.putRow(row); linesWritten++; } private synchronized RowSet currentInputStream() { return (RowSet) inputRowSets.get(in_handling); } /** * Find the next not-finished input-stream... in_handling says which one... */ private synchronized void nextInputStream() { int streams = inputRowSets.size(); // No more streams left: exit! if (streams == 0) return; // If we have some left: take the next! in_handling++; if (in_handling >= inputRowSets.size()) in_handling = 0; // logDebug("nextInputStream advanced to in_handling="+in_handling); } /** * In case of getRow, we receive data from previous steps through the input rowset. In case we split the stream, we * have to copy the data to the alternate splits: rowsets 1 through n. */ public synchronized Row getRow() throws KettleException { int sleeptime; int switches; // If everything is finished, we can stop immediately! synchronized (inputRowSets) { if (inputRowSets.size() == 0) { return null; } // What's the current input stream? RowSet in = currentInputStream(); switches = 0; sleeptime = transMeta.getSleepTimeEmpty(); while (in.isEmpty() && !stopped) { // in : empty if (in.isEmpty() && in.isDone()) // nothing more here: remove it from input { inputRowSets.remove(in_handling); if (inputRowSets.size() == 0) // nothing more to be found! { return null; } } nextInputStream(); in = currentInputStream(); switches++; if (switches >= inputRowSets.size()) // every n looks, wait a bit! Don't use too much CPU! { switches = 0; try { if (sleeptime > 0) { sleep(0, sleeptime); } else { super.notifyAll(); } } catch (Exception e) { logError(Messages.getString("BaseStep.Log.SleepInterupted") + e.toString()); //$NON-NLS-1$ setErrors(1); stopAll(); return null; } if (sleeptime < 100) sleeptime = ((int) (sleeptime * 1.2)) + 1; else sleeptime = 100; nrGetSleeps += sleeptime; } } if (stopped) { if (log.isDebug()) logDebug(Messages.getString("BaseStep.Log.StopLookingForMoreRows")); //$NON-NLS-1$ stopAll(); return null; } // Set the appropriate priority depending on the amount of data in the rowset: // Only do this every 4096 rows... // Mmm, the less we do it, the faster the tests run, let's leave this out for now ;-) if (transMeta.isUsingThreadPriorityManagment()) { if (linesRead>0 && (linesRead & 0xFF) == 0) { in.setPriorityTo(calcGetPriority(in)); } } // Get this row! Row row = in.getRow(); linesRead++; // Notify all rowlisteners... for (int i = 0; i < rowListeners.size(); i++) { RowListener rowListener = (RowListener) rowListeners.get(i); rowListener.rowReadEvent(row); } nextInputStream(); // Look for the next input stream to get row from. // OK, before we return the row, let's see if we need to check on mixing row compositions... if (safeModeEnabled) { safeModeChecking(row); } // Extra checking return row; } } protected synchronized void safeModeChecking(Row row) { // String saveDebug=debug; // debug="Safe mode checking"; if (referenceRow == null) { referenceRow = new Row(row); // copy it! } else { // See if the row we got has the same layout as the reference row. // First check the number of fields if (referenceRow.size() != row.size()) { throw new RuntimeException("We detected rows with varying number of fields, this is not allowed in a transformation. " + "Check your settings. (first row contained " + referenceRow.size() + " elements, this one contains " + row.size() + " : " + row); } else { // Check field by field for the position of the names... for (int i = 0; i < referenceRow.size(); i++) { Value referenceValue = referenceRow.getValue(i); Value compareValue = row.getValue(i); if (!referenceValue.getName().equalsIgnoreCase(compareValue.getName())) { throw new RuntimeException("The name of field #" + i + " is not the same as in the first row received: you're mixing rows with different layout! (" + referenceValue.toStringMeta() + "!=" + compareValue.toStringMeta() + ")"); } if (referenceValue.getType()!=compareValue.getType()) { throw new RuntimeException("The data type of field #" + i + " is not the same as the first row received: you're mixing rows with different layout! (" + referenceValue.toStringMeta() + "!=" + compareValue.toStringMeta() + ")"); } } } } // debug=saveDebug; } /** * This version of getRow() only takes data from certain rowsets We select these rowsets that have name = step * Otherwise it's the same as the other one. */ public synchronized Row getRowFrom(String from) { output_rowset_nr = findInputRowSetNumber(from, 0, stepname, 0); if (output_rowset_nr < 0) // No rowset found: normally it can't happen: we deleted the rowset because it was // finished { return null; } return getRowFrom(output_rowset_nr); } public synchronized Row getRowFrom(int input_rowset_nr) { // Read from one specific rowset int sleeptime = transMeta.getSleepTimeEmpty(); RowSet in = (RowSet) inputRowSets.get(input_rowset_nr); while (in.isEmpty() && !in.isDone() && !stopped) { try { if (sleeptime > 0) { sleep(0, sleeptime); } else { super.notifyAll(); } } catch (Exception e) { logError(Messages.getString("BaseStep.Log.SleepInterupted2", in.getOriginStepName()) + e.toString()); //$NON-NLS-1$ //$NON-NLS-2$ setErrors(1); stopAll(); return null; } nrGetSleeps += sleeptime; } if (stopped) { logError(Messages.getString("BaseStep.Log.SleepInterupted3", in.getOriginStepName())); //$NON-NLS-1$ //$NON-NLS-2$ stopAll(); return null; } if (in.isEmpty() && in.isDone()) { inputRowSets.remove(input_rowset_nr); return null; } Row row = in.getRow(); // Get this row! linesRead++; // call all rowlisteners... for (int i = 0; i < rowListeners.size(); i++) { RowListener rowListener = (RowListener) rowListeners.get(i); rowListener.rowWrittenEvent(row); } return row; } private synchronized int findInputRowSetNumber(String from, int fromcopy, String to, int tocopy) { int i; for (i = 0; i < inputRowSets.size(); i++) { RowSet rs = (RowSet) inputRowSets.get(i); if (rs.getOriginStepName().equalsIgnoreCase(from) && rs.getDestinationStepName().equalsIgnoreCase(to) && rs.getOriginStepCopy() == fromcopy && rs.getDestinationStepCopy() == tocopy) return i; } return -1; } private synchronized int findOutputRowSetNumber(String from, int fromcopy, String to, int tocopy) { int i; for (i = 0; i < outputRowSets.size(); i++) { RowSet rs = (RowSet) outputRowSets.get(i); if (rs.getOriginStepName().equalsIgnoreCase(from) && rs.getDestinationStepName().equalsIgnoreCase(to) && rs.getOriginStepCopy() == fromcopy && rs.getDestinationStepCopy() == tocopy) return i; } return -1; } // We have to tell the next step we're finished with // writing to output rowset(s)! public synchronized void setOutputDone() { if (log.isDebug()) logDebug(Messages.getString("BaseStep.Log.OutputDone", String.valueOf(outputRowSets.size()))); //$NON-NLS-1$ //$NON-NLS-2$ for (int i = 0; i < outputRowSets.size(); i++) { RowSet rs = (RowSet) outputRowSets.get(i); rs.setDone(); } } /** * This method finds the surrounding steps and rowsets for this base step. This steps keeps it's own list of rowsets * (etc.) to prevent it from having to search every time. */ public void dispatch() { if (transMeta == null) // for preview reasons, no dispatching is done! { return; } StepMeta stepMeta = transMeta.findStep(stepname); if (log.isDetailed()) logDetailed(Messages.getString("BaseStep.Log.StartingBuffersAllocation")); //$NON-NLS-1$ // How many next steps are there? 0, 1 or more?? // How many steps do we send output to? int nrInput = transMeta.findNrPrevSteps(stepMeta, true); int nrOutput = transMeta.findNrNextSteps(stepMeta); inputRowSets = new ArrayList(); // new RowSet[nrinput]; outputRowSets = new ArrayList(); // new RowSet[nroutput+out_copies]; prevSteps = new StepMeta[nrInput]; nextSteps = new StepMeta[nrOutput]; in_handling = 0; // we start with input[0]; logDetailed(Messages.getString("BaseStep.Log.StepInfo", String.valueOf(nrInput), String.valueOf(nrOutput))); //$NON-NLS-1$ //$NON-NLS-2$ for (int i = 0; i < nrInput; i++) { prevSteps[i] = transMeta.findPrevStep(stepMeta, i, true); // sir.getHopFromWithTo(stepname, i); logDetailed(Messages.getString("BaseStep.Log.GotPreviousStep", stepname, String.valueOf(i), prevSteps[i].getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // Looking at the previous step, you can have either 1 rowset to look at or more then one. int prevCopies = prevSteps[i].getCopies(); int nextCopies = stepMeta.getCopies(); logDetailed(Messages.getString("BaseStep.Log.InputRowInfo", String.valueOf(prevCopies), String.valueOf(nextCopies))); //$NON-NLS-1$ //$NON-NLS-2$ int nrCopies; int dispatchType; if (prevCopies == 1 && nextCopies == 1) { dispatchType = Trans.TYPE_DISP_1_1; nrCopies = 1; } else if (prevCopies == 1 && nextCopies > 1) { dispatchType = Trans.TYPE_DISP_1_N; nrCopies = 1; } else if (prevCopies > 1 && nextCopies == 1) { dispatchType = Trans.TYPE_DISP_N_1; nrCopies = prevCopies; } else if (prevCopies == nextCopies) { dispatchType = Trans.TYPE_DISP_N_N; nrCopies = 1; } else { dispatchType = Trans.TYPE_DISP_N_M; nrCopies = prevCopies; } for (int c = 0; c < nrCopies; c++) { RowSet rowSet = null; switch (dispatchType) { case Trans.TYPE_DISP_1_1: rowSet = trans.findRowSet(prevSteps[i].getName(), 0, stepname, 0); break; case Trans.TYPE_DISP_1_N: rowSet = trans.findRowSet(prevSteps[i].getName(), 0, stepname, getCopy()); break; case Trans.TYPE_DISP_N_1: rowSet = trans.findRowSet(prevSteps[i].getName(), c, stepname, 0); break; case Trans.TYPE_DISP_N_N: rowSet = trans.findRowSet(prevSteps[i].getName(), getCopy(), stepname, getCopy()); break; case Trans.TYPE_DISP_N_M: rowSet = trans.findRowSet(prevSteps[i].getName(), c, stepname, getCopy()); break; } if (rowSet != null) { inputRowSets.add(rowSet); logDetailed(Messages.getString("BaseStep.Log.FoundInputRowset", rowSet.getName())); //$NON-NLS-1$ //$NON-NLS-2$ } else { logError(Messages.getString("BaseStep.Log.UnableToFindInputRowset")); //$NON-NLS-1$ setErrors(1); stopAll(); return; } } } // And now the output part! for (int i = 0; i < nrOutput; i++) { nextSteps[i] = transMeta.findNextStep(stepMeta, i); int prevCopies = stepMeta.getCopies(); int nextCopies = nextSteps[i].getCopies(); logDetailed(Messages.getString("BaseStep.Log.OutputRowInfo", String.valueOf(prevCopies), String.valueOf(nextCopies))); //$NON-NLS-1$ //$NON-NLS-2$ int nrCopies; int dispatchType; if (prevCopies == 1 && nextCopies == 1) { dispatchType = Trans.TYPE_DISP_1_1; nrCopies = 1; } else if (prevCopies == 1 && nextCopies > 1) { dispatchType = Trans.TYPE_DISP_1_N; nrCopies = nextCopies; } else if (prevCopies > 1 && nextCopies == 1) { dispatchType = Trans.TYPE_DISP_N_1; nrCopies = 1; } else if (prevCopies == nextCopies) { dispatchType = Trans.TYPE_DISP_N_N; nrCopies = 1; } else { dispatchType = Trans.TYPE_DISP_N_M; nrCopies = nextCopies; } for (int c = 0; c < nrCopies; c++) { RowSet rowSet = null; switch (dispatchType) { case Trans.TYPE_DISP_1_1: rowSet = trans.findRowSet(stepname, 0, nextSteps[i].getName(), 0); break; case Trans.TYPE_DISP_1_N: rowSet = trans.findRowSet(stepname, 0, nextSteps[i].getName(), c); break; case Trans.TYPE_DISP_N_1: rowSet = trans.findRowSet(stepname, getCopy(), nextSteps[i].getName(), 0); break; case Trans.TYPE_DISP_N_N: rowSet = trans.findRowSet(stepname, getCopy(), nextSteps[i].getName(), getCopy()); break; case Trans.TYPE_DISP_N_M: rowSet = trans.findRowSet(stepname, getCopy(), nextSteps[i].getName(), c); break; } if (rowSet != null) { outputRowSets.add(rowSet); logDetailed(Messages.getString("BaseStep.Log.FoundOutputRowset", rowSet.getName())); //$NON-NLS-1$ //$NON-NLS-2$ } else { logError(Messages.getString("BaseStep.Log.UnableToFindOutputRowset")); //$NON-NLS-1$ setErrors(1); stopAll(); return; } } } logDetailed(Messages.getString("BaseStep.Log.FinishedDispatching")); //$NON-NLS-1$ } public void logMinimal(String s) { log.println(LogWriter.LOG_LEVEL_MINIMAL, stepname + "." + stepcopy, s); //$NON-NLS-1$ } public void logBasic(String s) { log.println(LogWriter.LOG_LEVEL_BASIC, stepname + "." + stepcopy, s); //$NON-NLS-1$ } public void logError(String s) { log.println(LogWriter.LOG_LEVEL_ERROR, stepname + "." + stepcopy, s); //$NON-NLS-1$ } public void logDetailed(String s) { log.println(LogWriter.LOG_LEVEL_DETAILED, stepname + "." + stepcopy, s); //$NON-NLS-1$ } public void logDebug(String s) { log.println(LogWriter.LOG_LEVEL_DEBUG, stepname + "." + stepcopy, s); //$NON-NLS-1$ } public void logRowlevel(String s) { log.println(LogWriter.LOG_LEVEL_ROWLEVEL, stepname + "." + stepcopy, s); //$NON-NLS-1$ } public int getNextClassNr() { int ret = trans.class_nr; trans.class_nr++; return ret; } public boolean outputIsDone() { int nrstopped = 0; RowSet rs; int i; for (i = 0; i < outputRowSets.size(); i++) { rs = (RowSet) outputRowSets.get(i); if (rs.isDone()) nrstopped++; } return nrstopped >= outputRowSets.size(); } public void stopAll() { stopped = true; } public boolean isStopped() { return stopped; } public boolean isInitialising() { return init; } public void markStart() { Calendar cal = Calendar.getInstance(); start_time = cal.getTime(); setInternalVariables(); } public void setInternalVariables() { KettleVariables kettleVariables = KettleVariables.getInstance(); kettleVariables.setVariable(Const.INTERNAL_VARIABLE_STEP_NAME, stepname); kettleVariables.setVariable(Const.INTERNAL_VARIABLE_STEP_COPYNR, Integer.toString(getCopy())); // Also set the internal variable for the partition if (!Const.isEmpty(partitionID)) { kettleVariables.setVariable(Const.INTERNAL_VARIABLE_STEP_PARTITION_ID, partitionID); } } public void markStop() { Calendar cal = Calendar.getInstance(); stop_time = cal.getTime(); } public long getRuntime() { long lapsed; if (start_time != null && stop_time == null) { Calendar cal = Calendar.getInstance(); long now = cal.getTimeInMillis(); long st = start_time.getTime(); lapsed = now - st; } else if (start_time != null && stop_time != null) { lapsed = stop_time.getTime() - start_time.getTime(); } else { lapsed = 0; } return lapsed; } public Row buildLog(String sname, int copynr, long lines_read, long lines_written, long lines_updated, long lines_skipped, long errors, Value start_date, Value end_date) { Row r = new Row(); r.addValue(new Value(Messages.getString("BaseStep.ColumnName.Stepname"), sname)); //$NON-NLS-1$ r.addValue(new Value(Messages.getString("BaseStep.ColumnName.Copy"), (double) copynr)); //$NON-NLS-1$ r.addValue(new Value(Messages.getString("BaseStep.ColumnName.LinesReaded"), (double) lines_read)); //$NON-NLS-1$ r.addValue(new Value(Messages.getString("BaseStep.ColumnName.LinesWritten"), (double) lines_written)); //$NON-NLS-1$ r.addValue(new Value(Messages.getString("BaseStep.ColumnName.LinesUpdated"), (double) lines_updated)); //$NON-NLS-1$ r.addValue(new Value(Messages.getString("BaseStep.ColumnName.LinesSkipped"), (double) lines_skipped)); //$NON-NLS-1$ r.addValue(new Value(Messages.getString("BaseStep.ColumnName.Errors"), (double) errors)); //$NON-NLS-1$ r.addValue(start_date); r.addValue(end_date); return r; } public static final Row getLogFields(String comm) { Row r = new Row(); int i; Value sname = new Value(Messages.getString("BaseStep.ColumnName.Stepname"), ""); //$NON-NLS-1$ //$NON-NLS-2$ sname.setLength(256); r.addValue(sname); r.addValue(new Value(Messages.getString("BaseStep.ColumnName.Copy"), 0.0)); //$NON-NLS-1$ r.addValue(new Value(Messages.getString("BaseStep.ColumnName.LinesReaded"), 0.0)); //$NON-NLS-1$ r.addValue(new Value(Messages.getString("BaseStep.ColumnName.LinesWritten"), 0.0)); //$NON-NLS-1$ r.addValue(new Value(Messages.getString("BaseStep.ColumnName.LinesUpdated"), 0.0)); //$NON-NLS-1$ r.addValue(new Value(Messages.getString("BaseStep.ColumnName.LinesSkipped"), 0.0)); //$NON-NLS-1$ r.addValue(new Value(Messages.getString("BaseStep.ColumnName.Errors"), 0.0)); //$NON-NLS-1$ r.addValue(new Value(Messages.getString("BaseStep.ColumnName.StartDate"), Const.MIN_DATE)); //$NON-NLS-1$ r.addValue(new Value(Messages.getString("BaseStep.ColumnName.EndDate"), Const.MAX_DATE)); //$NON-NLS-1$ for (i = 0; i < r.size(); i++) { r.getValue(i).setOrigin(comm); } return r; } public String toString() { return stepname + "." + getCopy(); //$NON-NLS-1$ } public Thread getThread() { return this; } private int calcPutPriority(RowSet rs) { if (rs.size() > transMeta.getSizeRowset() * 0.95) return MIN_PRIORITY; if (rs.size() > transMeta.getSizeRowset() * 0.75) return LOW_PRIORITY; if (rs.size() > transMeta.getSizeRowset() * 0.50) return NORMAL_PRIORITY; if (rs.size() > transMeta.getSizeRowset() * 0.25) return HIGH_PRIORITY; return MAX_PRIORITY; } private int calcGetPriority(RowSet rs) { if (rs.size() > transMeta.getSizeRowset() * 0.95) return MAX_PRIORITY; if (rs.size() > transMeta.getSizeRowset() * 0.75) return HIGH_PRIORITY; if (rs.size() > transMeta.getSizeRowset() * 0.50) return NORMAL_PRIORITY; if (rs.size() > transMeta.getSizeRowset() * 0.25) return LOW_PRIORITY; return MIN_PRIORITY; } public int rowsetOutputSize() { int size = 0; int i; for (i = 0; i < outputRowSets.size(); i++) { size += ((RowSet) outputRowSets.get(i)).size(); } return size; } public int rowsetInputSize() { int size = 0; int i; for (i = 0; i < inputRowSets.size(); i++) { size += ((RowSet) inputRowSets.get(i)).size(); } return size; } /** * Create a new empty StepMeta class from the steploader * * @param stepplugin The step/plugin to use * @param steploader The StepLoader to load from * @return The requested class. */ public static final StepMetaInterface getStepInfo(StepPlugin stepplugin, StepLoader steploader) throws KettleStepLoaderException { return steploader.getStepClass(stepplugin); } public static final String getIconFilename(int steptype) { return steps[steptype].getImageFileName(); } /** * Perform actions to stop a running step. This can be stopping running SQL queries (cancel), etc. Default it * doesn't do anything. * * @param stepDataInterface The interface to the step data containing the connections, resultsets, open files, etc. * @throws KettleException in case something goes wrong * */ public void stopRunning(StepMetaInterface stepMetaInterface, StepDataInterface stepDataInterface) throws KettleException { } /** * Stops running operations This method is deprecated, please use the method specifying the metadata and data * interfaces. * * @deprecated */ public void stopRunning() { } public void logSummary() { logBasic(Messages .getString( "BaseStep.Log.SummaryInfo", String.valueOf(linesInput), String.valueOf(linesOutput), String.valueOf(linesRead), String.valueOf(linesWritten), String.valueOf(linesUpdated), String.valueOf(getErrors()))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ } public String getStepID() { if (stepMeta != null) return stepMeta.getStepID(); return null; } /** * @return Returns the inputRowSets. */ public List getInputRowSets() { return inputRowSets; } /** * @param inputRowSets The inputRowSets to set. */ public void setInputRowSets(ArrayList inputRowSets) { this.inputRowSets = inputRowSets; } /** * @return Returns the outputRowSets. */ public List getOutputRowSets() { return outputRowSets; } /** * @param outputRowSets The outputRowSets to set. */ public void setOutputRowSets(ArrayList outputRowSets) { this.outputRowSets = outputRowSets; } /** * @return Returns the distributed. */ public boolean isDistributed() { return distributed; } /** * @param distributed The distributed to set. */ public void setDistributed(boolean distributed) { this.distributed = distributed; } public void addRowListener(RowListener rowListener) { rowListeners.add(rowListener); } public void removeRowListener(RowListener rowListener) { rowListeners.remove(rowListener); } public List getRowListeners() { return rowListeners; } public void addResultFile(ResultFile resultFile) { resultFiles.add(resultFile); } public List getResultFiles() { return resultFiles; } /** * @return Returns the total sleep time in ns in case nothing was found in an input buffer for this step. */ public long getNrGetSleeps() { return nrGetSleeps; } /** * @param nrGetSleeps the total sleep time in ns in case nothing was found in an input buffer for this step. */ public void setNrGetSleeps(long nrGetSleeps) { this.nrGetSleeps = nrGetSleeps; } /** * @return Returns the total sleep time in ns in case the output buffer was full for this step. */ public long getNrPutSleeps() { return nrPutSleeps; } /** * @param nrPutSleeps the total sleep time in ns in case the output buffer was full for this step. */ public void setNrPutSleeps(long nrPutSleeps) { this.nrPutSleeps = nrPutSleeps; } /** * @return Returns true is this step is running in safe mode, with extra checking enabled... */ public boolean isSafeModeEnabled() { return safeModeEnabled; } /** * @param safeModeEnabled set to true is this step has to be running in safe mode, with extra checking enabled... */ public void setSafeModeEnabled(boolean safeModeEnabled) { this.safeModeEnabled = safeModeEnabled; } public int getStatus() { if (isAlive()) return StepDataInterface.STATUS_RUNNING; if (isStopped()) return StepDataInterface.STATUS_STOPPED; // Get the rest in StepDataInterface object: StepDataInterface sdi = trans.getStepDataInterface(stepname, stepcopy); if (sdi != null) { if (sdi.getStatus() == StepDataInterface.STATUS_DISPOSED && !isAlive()) return StepDataInterface.STATUS_FINISHED; return sdi.getStatus(); } return StepDataInterface.STATUS_EMPTY; } /** * @return the partitionID */ public String getPartitionID() { return partitionID; } /** * @param partitionID the partitionID to set */ public void setPartitionID(String partitionID) { this.partitionID = partitionID; } /** * @return the partitionTargets */ public Map getPartitionTargets() { return partitionTargets; } /** * @param partitionTargets the partitionTargets to set */ public void setPartitionTargets(Map partitionTargets) { this.partitionTargets = partitionTargets; } /** * @return the partitionColumnIndex */ public int getPartitionColumnIndex() { return partitionColumnIndex; } /** * @param partitionColumnIndex the partitionColumnIndex to set */ public void setPartitionColumnIndex(int partitionColumnIndex) { this.partitionColumnIndex = partitionColumnIndex; } /** * @return the repartitioning */ public boolean isRepartitioning() { return repartitioning; } /** * @param repartitioning the repartitioning to set */ public void setRepartitioning(boolean repartitioning) { this.repartitioning = repartitioning; } /** * @return the partitioned */ public boolean isPartitioned() { return partitioned; } /** * @param partitioned the partitioned to set */ public void setPartitioned(boolean partitioned) { this.partitioned = partitioned; } /** * @return the partitionMerging */ public boolean isPartitionMerging() { return partitionMerging; } /** * @param partitionMerging the partitionMerging to set */ public void setPartitionMerging(boolean partitionMerging) { this.partitionMerging = partitionMerging; } protected boolean checkFeedback(long lines) { return getTransMeta().isFeedbackShown() && (lines > 0) && (getTransMeta().getFeedbackSize() > 0) && (lines % getTransMeta().getFeedbackSize()) == 0; } }
/* WARNING: THIS FILE IS AUTO-GENERATED DO NOT MODIFY THIS SOURCE ALL CHANGES MUST BE MADE IN THE CATALOG GENERATOR */ package org.voltdb.catalog; import java.util.List; import java.util.Set; import org.apache.hadoop_voltpatches.util.PureJavaCrc32; import org.voltdb.common.Constants; import org.voltdb.compiler.deploymentfile.DrRoleType; import org.voltdb.dr2.DRProtocol; import org.voltdb.utils.CatalogUtil; import org.voltdb.utils.Encoder; import com.google_voltpatches.common.collect.ImmutableSet; /** * Specialized CatalogDiffEngine that checks the following conditions: * - The localCatalog contains all DR tables contained in the remote catalog * - All shared DR tables contain the same columns in the same order * - All shared DR tables have the same partition column * - All shared DR tables have the same unique indexes/primary keys */ public class DRCatalogDiffEngine extends CatalogDiffEngine { /* White list of fields that we care about for DR for table children classes. This is used only in serialize commands for DR method. There are duplicates added to the set because it lists all the fields per type */ private static final Set<String> s_whiteListFields = ImmutableSet.of( /* Table */ "isreplicated", "partitioncolumn", "materializer", "signature", "isDRed", /* ColumnRef */ "index", "column", /* Column */ "index", "type", "size", "nullable", "name", "inbytes", /* Index */ "unique", "assumeUnique", "countable", "type", "expressionsjson", "predicatejson", /* Constraint */ "type", "oncommit", "index", "foreignkeytable" ); private static final Set<Class<? extends CatalogType>> s_whiteListChildren = ImmutableSet.of(Column.class, Index.class, Constraint.class, ColumnRef.class); private byte m_remoteClusterId; public DRCatalogDiffEngine(Catalog localCatalog, Catalog remoteCatalog, byte remoteClusterId) { super(localCatalog, remoteCatalog); m_remoteClusterId = remoteClusterId; } public static DRCatalogCommands serializeCatalogCommandsForDr(Catalog catalog, int protocolVersion) { Cluster cluster = CatalogUtil.getCluster(catalog); CatalogSerializer serializer = new CatalogSerializer(s_whiteListFields, s_whiteListChildren); assert (protocolVersion == -1 || protocolVersion >= DRProtocol.MULTICLUSTER_PROTOCOL_VERSION); serializer.writeCommandForField(cluster, "drRole", true); Database db = CatalogUtil.getDatabase(catalog); for (Table t : db.getTables()) { if (t.getIsdred() && t.getMaterializer() == null && ! CatalogUtil.isStream(db, t)) { t.accept(serializer); } } String catalogCommands = serializer.getResult(); PureJavaCrc32 crc = new PureJavaCrc32(); crc.update(catalogCommands.getBytes(Constants.UTF8ENCODING)); // DR catalog exchange still uses the old gzip scheme for now, next time DR protocol version is bumped // the logic can be updated to choose compression/decompression scheme based on agreed protocol version return new DRCatalogCommands(protocolVersion, crc.getValue(), Encoder.compressAndBase64Encode(catalogCommands)); } public static Catalog deserializeCatalogCommandsForDr(String encodedCatalogCommands) { String catalogCommands = Encoder.decodeBase64AndDecompress(encodedCatalogCommands); Catalog deserializedMasterCatalog = new Catalog(); Cluster c = deserializedMasterCatalog.getClusters().add("cluster"); Database db = c.getDatabases().add("database"); deserializedMasterCatalog.execute(catalogCommands); if (db.getIsactiveactivedred()) { // The catalog came from an old version, set DR role here // appropriately so that the diff engine can just look at the role. c.setDrrole(DrRoleType.XDCR.value()); } return deserializedMasterCatalog; } @Override protected String checkAddDropWhitelist(final CatalogType suspect, final ChangeType changeType) { // Only on remote if (ChangeType.ADDITION == changeType && suspect instanceof Table) { assert ((Boolean)suspect.getField("isDRed")); return "Missing DR table " + suspect.getTypeName() + " on local cluster"; } if (suspect instanceof Column || isUniqueIndex(suspect) || isUniqueIndexColumn(suspect)) { return "Missing " + suspect + " from " + suspect.getParent() + " on " + (ChangeType.ADDITION == changeType ? "local cluster" : "remote cluster " + m_remoteClusterId); } return null; } @Override protected String checkModifyWhitelist(final CatalogType remoteType, final CatalogType localType, final String field) { if (remoteType instanceof Cluster || remoteType instanceof PlanFragment || remoteType instanceof MaterializedViewInfo) { if ("drRole".equalsIgnoreCase(field)) { if (((String) localType.getField(field)).equalsIgnoreCase(DrRoleType.XDCR.value()) ^ ((String) remoteType.getField(field)).equalsIgnoreCase(DrRoleType.XDCR.value())) { m_replicableTables.clear(); return "Incompatible DR modes between two clusters"; } } return null; } else if (remoteType instanceof Table) { if ("estimatedtuplecount".equals(field) || "tuplelimit".equals(field) || "tableType".equals(field)) { return null; } } else if (remoteType instanceof Database) { if ("schema".equalsIgnoreCase(field) || "securityprovider".equalsIgnoreCase(field) || "isActiveActiveDRed".equalsIgnoreCase(field)) { return null; } } else if (remoteType instanceof Column) { if ("defaultvalue".equals(field) || "defaulttype".equals(field) || "matview".equals(field) || "aggregatetype".equals(field) || "matviewsource".equals(field)) { return null; } } else if (isTableLimitDeleteStmt(remoteType)) { return null; } else if ((remoteType instanceof Index && isUniqueIndex(remoteType) == isUniqueIndex(localType)) || (remoteType instanceof ColumnRef && !isUniqueIndexColumn(remoteType))) { return null; } return "Incompatible schema between remote cluster " + m_remoteClusterId + " and local cluster: field " + field + " in schema object " + remoteType; } private boolean isUniqueIndexColumn(CatalogType suspect) { return suspect instanceof ColumnRef && isUniqueIndex(suspect.getParent()); } private boolean isUniqueIndex(CatalogType suspect) { return suspect instanceof Index && (Boolean)suspect.getField("unique"); } @Override protected TablePopulationRequirements checkAddDropIfTableIsEmptyWhitelist(final CatalogType suspect, final ChangeType changeType) { return null; } @Override public List<TablePopulationRequirements> checkModifyIfTableIsEmptyWhitelist(CatalogType suspect, CatalogType prevType, String field) { return null; } }
package ch.idsia.benchmark.tasks; import ch.idsia.tools.EvaluationInfo; import ch.idsia.tools.MarioAIOptions; import java.text.DecimalFormat; public class GamePlayTask extends BasicTask implements Task { private static final DecimalFormat df = new DecimalFormat(" private EvaluationInfo localEvaluationInfo; private int difqualifications = 0; public GamePlayTask(MarioAIOptions marioAIOptions) { super(marioAIOptions); localEvaluationInfo = new EvaluationInfo(); localEvaluationInfo.setTaskName("GamePlayTask"); localEvaluationInfo.distancePassedCells = 0; localEvaluationInfo.distancePassedPhys = 0; localEvaluationInfo.flowersDevoured = 0; localEvaluationInfo.killsTotal = 0; localEvaluationInfo.killsByFire = 0; localEvaluationInfo.killsByShell = 0; localEvaluationInfo.killsByStomp = 0; localEvaluationInfo.marioMode = 0; localEvaluationInfo.marioStatus = 0; localEvaluationInfo.mushroomsDevoured = 0; localEvaluationInfo.coinsGained = 0; localEvaluationInfo.timeLeft = 0; localEvaluationInfo.timeSpent = 0; localEvaluationInfo.hiddenBlocksFound = 0; localEvaluationInfo.totalNumberOfCoins = 0; localEvaluationInfo.totalNumberOfCreatures = 0; localEvaluationInfo.totalNumberOfFlowers = 0; localEvaluationInfo.totalNumberOfMushrooms = 0; localEvaluationInfo.totalNumberOfHiddenBlocks = 0; localEvaluationInfo.collisionsWithCreatures = 0; localEvaluationInfo.levelLength = 0; } private void updateEvaluationInfo(EvaluationInfo evInfo) { localEvaluationInfo.distancePassedCells += evInfo.distancePassedCells; localEvaluationInfo.distancePassedPhys += evInfo.distancePassedPhys; localEvaluationInfo.flowersDevoured += evInfo.flowersDevoured; localEvaluationInfo.killsTotal += evInfo.killsTotal; localEvaluationInfo.killsByFire += evInfo.killsByFire; localEvaluationInfo.killsByShell += evInfo.killsByShell; localEvaluationInfo.killsByStomp += evInfo.killsByStomp; localEvaluationInfo.marioMode += evInfo.marioMode; localEvaluationInfo.marioStatus += evInfo.marioStatus; localEvaluationInfo.mushroomsDevoured += evInfo.mushroomsDevoured; localEvaluationInfo.coinsGained += evInfo.coinsGained; localEvaluationInfo.timeLeft += evInfo.timeLeft; localEvaluationInfo.timeSpent += evInfo.timeSpent; localEvaluationInfo.hiddenBlocksFound += evInfo.hiddenBlocksFound; localEvaluationInfo.totalNumberOfCoins += evInfo.totalNumberOfCoins; localEvaluationInfo.totalNumberOfCreatures += evInfo.totalNumberOfCreatures; localEvaluationInfo.totalNumberOfFlowers += evInfo.totalNumberOfFlowers; localEvaluationInfo.totalNumberOfMushrooms += evInfo.totalNumberOfMushrooms; localEvaluationInfo.totalNumberOfHiddenBlocks += evInfo.totalNumberOfHiddenBlocks; localEvaluationInfo.collisionsWithCreatures += evInfo.collisionsWithCreatures; localEvaluationInfo.levelLength += evInfo.levelLength; } public void doEpisodes(final int amount, final boolean verbose, final int repetitionsOfSingleEpisode) { for (int i = 0; i < amount; ++i) { options.setLevelLength((200 + (i * 12) + (options.getLevelRandSeed() % (i + 1))) % 512); options.setLevelType(i % 3); options.setLevelRandSeed(options.getLevelRandSeed() + i); options.setLevelDifficulty(i / 20); options.setGapsCount(i % 3 == 0); options.setCannonsCount(i % 3 != 0); options.setCoinsCount(i % 5 != 0); options.setBlocksCount(i % 4 != 0); options.setHiddenBlocksCount(i % 6 != 0); options.setDeadEndsCount(i % 10 == 0); options.setLevelLadder(i % 10 == 2); options.setFrozenCreatures(i % 3 == 1); options.setEnemies(i % 4 == 1 ? "off" : ""); this.reset(); if (!this.runSingleEpisode(repetitionsOfSingleEpisode)) difqualifications++; updateEvaluationInfo(environment.getEvaluationInfo()); if (verbose) System.out.println(environment.getEvaluationInfoAsString()); } } public EvaluationInfo getEvaluationInfo() { return localEvaluationInfo; } public void printStatistics() { System.out.println("\n[MarioAI] ~ Evaluation Results for Task: " + localEvaluationInfo.getTaskName() + "\n Weighted Fitness : " + df.format(localEvaluationInfo.computeWeightedFitness()) + "\n Mario Status : " + localEvaluationInfo.marioStatus + "\n Mario Mode : " + localEvaluationInfo.marioMode + "\nCollisions with creatures : " + localEvaluationInfo.collisionsWithCreatures + "\n Passed (Cells, Phys) : " + localEvaluationInfo.distancePassedCells + " of " + localEvaluationInfo.levelLength + ", " + df.format(localEvaluationInfo.distancePassedPhys) + " of " + df.format(localEvaluationInfo.levelLength * 16) + " (" + localEvaluationInfo.distancePassedCells * 100 / localEvaluationInfo.levelLength + "% passed)" + "\n Time Spent(marioseconds) : " + localEvaluationInfo.timeSpent + "\n Time Left(marioseconds) : " + localEvaluationInfo.timeLeft + "\n Coins Gained : " + localEvaluationInfo.coinsGained + " of " + localEvaluationInfo.totalNumberOfCoins + " (" + localEvaluationInfo.coinsGained * 100 / (localEvaluationInfo.totalNumberOfCoins == 0 ? 1 : localEvaluationInfo.totalNumberOfCoins) + "% collected)" + "\n Hidden Blocks Found : " + localEvaluationInfo.hiddenBlocksFound + " of " + localEvaluationInfo.totalNumberOfHiddenBlocks + " (" + localEvaluationInfo.hiddenBlocksFound * 100 / (localEvaluationInfo.totalNumberOfHiddenBlocks == 0 ? 1 : localEvaluationInfo.totalNumberOfHiddenBlocks) + "% found)" + "\n Mushrooms Devoured : " + localEvaluationInfo.mushroomsDevoured + " of " + localEvaluationInfo.totalNumberOfMushrooms + " found (" + localEvaluationInfo.mushroomsDevoured * 100 / (localEvaluationInfo.totalNumberOfMushrooms == 0 ? 1 : localEvaluationInfo.totalNumberOfMushrooms) + "% collected)" + "\n Flowers Devoured : " + localEvaluationInfo.flowersDevoured + " of " + localEvaluationInfo.totalNumberOfFlowers + " found (" + localEvaluationInfo.flowersDevoured * 100 / (localEvaluationInfo.totalNumberOfFlowers == 0 ? 1 : localEvaluationInfo.totalNumberOfFlowers) + "% collected)" + "\n kills Total : " + localEvaluationInfo.killsTotal + " of " + localEvaluationInfo.totalNumberOfCreatures + " found (" + localEvaluationInfo.killsTotal * 100 / (localEvaluationInfo.totalNumberOfCreatures == 0 ? 1 : localEvaluationInfo.totalNumberOfCreatures) + "%)" + "\n kills By Fire : " + localEvaluationInfo.killsByFire + "\n kills By Shell : " + localEvaluationInfo.killsByShell + "\n kills By Stomp : " + localEvaluationInfo.killsByStomp); // System.out.println(localEvaluationInfo.toString()); // System.out.println("Mario status sum: " + localEvaluationInfo.marioStatus); // System.out.println("Mario mode sum: " + localEvaluationInfo.marioMode); } }
package capsule; import java.io.PrintStream; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.maven.repository.internal.MavenRepositorySystemUtils; import org.apache.maven.settings.Server; import org.apache.maven.settings.Settings; import org.apache.maven.settings.building.DefaultSettingsBuilderFactory; import org.apache.maven.settings.building.DefaultSettingsBuildingRequest; import org.apache.maven.settings.building.SettingsBuildingException; import org.apache.maven.settings.crypto.DefaultSettingsDecrypter; import org.apache.maven.settings.crypto.DefaultSettingsDecryptionRequest; import org.apache.maven.settings.crypto.SettingsDecryptionResult; import org.eclipse.aether.ConfigurationProperties; import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.RepositoryException; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.artifact.DefaultArtifact; import org.eclipse.aether.collection.CollectRequest; import org.eclipse.aether.collection.CollectResult; import org.eclipse.aether.collection.DependencyCollectionException; import org.eclipse.aether.graph.Dependency; import org.eclipse.aether.graph.Exclusion; import org.eclipse.aether.impl.DefaultServiceLocator; import org.eclipse.aether.repository.AuthenticationSelector; import org.eclipse.aether.repository.LocalRepository; import org.eclipse.aether.repository.MirrorSelector; import org.eclipse.aether.repository.ProxySelector; import org.eclipse.aether.repository.RemoteRepository; import org.eclipse.aether.repository.RepositoryPolicy; import org.eclipse.aether.resolution.ArtifactResult; import org.eclipse.aether.resolution.DependencyRequest; import org.eclipse.aether.resolution.DependencyResolutionException; import org.eclipse.aether.resolution.VersionRangeRequest; import org.eclipse.aether.resolution.VersionRangeResult; import org.eclipse.aether.resolution.VersionRequest; import org.eclipse.aether.resolution.VersionResult; import org.eclipse.aether.util.artifact.JavaScopes; import org.eclipse.aether.util.graph.transformer.ConflictResolver; import org.eclipse.aether.util.repository.AuthenticationBuilder; import org.eclipse.aether.util.repository.ConservativeAuthenticationSelector; import org.eclipse.aether.util.repository.DefaultAuthenticationSelector; import org.eclipse.aether.util.repository.DefaultMirrorSelector; import org.eclipse.aether.util.repository.DefaultProxySelector; import org.eclipse.aether.version.Version; import org.sonatype.plexus.components.cipher.DefaultPlexusCipher; import org.sonatype.plexus.components.cipher.PlexusCipherException; import org.sonatype.plexus.components.sec.dispatcher.DefaultSecDispatcher; /** * Uses Aether as the Maven dependency manager. */ public class DependencyManagerImpl implements DependencyManager { //<editor-fold desc="Constants"> /////////// Constants /////////////////////////////////// private static final String PROP_OFFLINE = "capsule.offline"; private static final String PROP_CONNECT_TIMEOUT = "capsule.connect.timeout"; private static final String PROP_REQUEST_TIMEOUT = "capsule.request.timeout"; private static final String PROP_MAVEN_HOME = "maven.home"; private static final String PROP_USER_HOME = "user.home"; private static final String PROP_OS_NAME = "os.name"; private static final String ENV_MAVEN_HOME = "M2_HOME"; private static final String ENV_CONNECT_TIMEOUT = "CAPSULE_CONNECT_TIMEOUT"; private static final String ENV_REQUEST_TIMEOUT = "CAPSULE_REQUEST_TIMEOUT"; private static final String LATEST_VERSION = "[0,)"; private static final String SETTINGS_XML = "settings.xml"; private static final Path MAVEN_HOME = getMavenHome(); private static final Path DEFAULT_LOCAL_MAVEN = Paths.get(System.getProperty(PROP_USER_HOME), ".m2"); private static final Map<String, String> WELL_KNOWN_REPOS = stringMap( "central", "central(https://repo1.maven.org/maven2/)", "central-http", "central(http://repo1.maven.org/maven2/)", "jcenter", "jcenter(https://jcenter.bintray.com/)", "jcenter-http", "jcenter(http://jcenter.bintray.com/)", "local", "local(file:" + DEFAULT_LOCAL_MAVEN.resolve("repository") + ")" ); private static final int LOG_NONE = 0; private static final int LOG_QUIET = 1; private static final int LOG_VERBOSE = 2; private static final int LOG_DEBUG = 3; private static final String LOG_PREFIX = "CAPSULE: "; //</editor-fold> private final boolean forceRefresh; private final boolean offline; private final boolean allowSnapshots; private final RepositorySystem system; private final RepositorySystemSession session; private final List<RemoteRepository> repos; private final int logLevel; private final Settings settings; //<editor-fold desc="Construction and Setup"> /////////// Construction and Setup /////////////////////////////////// public DependencyManagerImpl(Path localRepoPath, List<String> repos, boolean forceRefresh, boolean allowSnapshots, int logLevel) { this.logLevel = logLevel; this.allowSnapshots = allowSnapshots; this.forceRefresh = forceRefresh; this.offline = isPropertySet(PROP_OFFLINE, false); log(LOG_DEBUG, "Offline: " + offline); if (localRepoPath == null) localRepoPath = DEFAULT_LOCAL_MAVEN.resolve("repository"); final LocalRepository localRepo = new LocalRepository(localRepoPath.toFile()); this.settings = getSettings(); this.system = newRepositorySystem(); this.session = newRepositorySession(system, localRepo); if (repos == null) repos = Arrays.asList("central"); this.repos = new ArrayList<RemoteRepository>(); for (String r : repos) this.repos.add(createRepo(r, allowSnapshots)); log(LOG_VERBOSE, "Dependency manager initialized with repositories: " + this.repos); } private static Settings getSettings() { final DefaultSettingsBuildingRequest request = new DefaultSettingsBuildingRequest(); request.setUserSettingsFile(DEFAULT_LOCAL_MAVEN.resolve(SETTINGS_XML).toFile()); request.setGlobalSettingsFile(MAVEN_HOME != null ? MAVEN_HOME.resolve("conf").resolve(SETTINGS_XML).toFile() : null); request.setSystemProperties(getSystemProperties()); try { final Settings settings = new DefaultSettingsBuilderFactory().newInstance().build(request).getEffectiveSettings(); final SettingsDecryptionResult result = newDefaultSettingsDecrypter().decrypt(new DefaultSettingsDecryptionRequest(settings)); settings.setServers(result.getServers()); settings.setProxies(result.getProxies()); return settings; } catch (SettingsBuildingException e) { throw new RuntimeException(e); } } private static RepositorySystem newRepositorySystem() { /* * We're using DefaultServiceLocator rather than Guice/Sisu because it's more lightweight. * This method pulls together the necessary Aether components and plugins. */ final DefaultServiceLocator locator = MavenRepositorySystemUtils.newServiceLocator(); locator.setErrorHandler(new DefaultServiceLocator.ErrorHandler() { @Override public void serviceCreationFailed(Class<?> type, Class<?> impl, Throwable ex) { throw new RuntimeException("Service creation failed for type " + type.getName() + " with impl " + impl, ex); } }); locator.addService(org.eclipse.aether.spi.connector.RepositoryConnectorFactory.class, org.eclipse.aether.connector.basic.BasicRepositoryConnectorFactory.class); locator.addService(org.eclipse.aether.spi.connector.transport.TransporterFactory.class, org.eclipse.aether.transport.http.HttpTransporterFactory.class); locator.addService(org.eclipse.aether.spi.connector.transport.TransporterFactory.class, org.eclipse.aether.transport.file.FileTransporterFactory.class); // Takari (support concurrent downloads) locator.setService(org.eclipse.aether.impl.SyncContextFactory.class, LockingSyncContextFactory.class); locator.setService(org.eclipse.aether.spi.io.FileProcessor.class, LockingFileProcessor.class); return locator.getService(RepositorySystem.class); } private RepositorySystemSession newRepositorySession(RepositorySystem system, LocalRepository localRepo) { final DefaultRepositorySystemSession s = MavenRepositorySystemUtils.newSession(); s.setConfigProperty(ConfigurationProperties.CONNECT_TIMEOUT, propertyOrEnv(PROP_CONNECT_TIMEOUT, ENV_CONNECT_TIMEOUT)); s.setConfigProperty(ConfigurationProperties.REQUEST_TIMEOUT, propertyOrEnv(PROP_REQUEST_TIMEOUT, ENV_REQUEST_TIMEOUT)); s.setConfigProperty(ConflictResolver.CONFIG_PROP_VERBOSE, true); s.setOffline(offline); s.setUpdatePolicy(forceRefresh ? RepositoryPolicy.UPDATE_POLICY_ALWAYS : RepositoryPolicy.UPDATE_POLICY_NEVER); s.setLocalRepositoryManager(system.newLocalRepositoryManager(s, localRepo)); s.setProxySelector(getProxySelector(settings)); s.setMirrorSelector(getMirrorSelector(settings)); s.setAuthenticationSelector(getAuthSelector(settings)); if (logLevel > LOG_NONE) { final PrintStream out = prefixStream(System.err, LOG_PREFIX); s.setTransferListener(new ConsoleTransferListener(isLogging(LOG_VERBOSE), out)); s.setRepositoryListener(new ConsoleRepositoryListener(isLogging(LOG_VERBOSE), out)); } return s; } //</editor-fold> //<editor-fold desc="Operations"> /////////// Operations /////////////////////////////////// private CollectRequest collect() { return new CollectRequest().setRepositories(repos); } @Override public void printDependencyTree(List<String> coords, String type, PrintStream out) { printDependencyTree(collect().setDependencies(toDependencies(coords, type)), out); } @Override public void printDependencyTree(String coords, String type, PrintStream out) { printDependencyTree(collect().setRoot(toDependency(coords, type)), out); } private void printDependencyTree(CollectRequest collectRequest, PrintStream out) { try { CollectResult collectResult = system.collectDependencies(session, collectRequest); collectResult.getRoot().accept(new ConsoleDependencyGraphDumper(out)); } catch (DependencyCollectionException e) { throw new RuntimeException(e); } } @Override public List<Path> resolveDependencies(List<String> coords, String type) { return resolve(collect().setDependencies(toDependencies(coords, type))); } @Override public List<Path> resolveDependency(String coords, String type) { return resolve(collect().setRoot(toDependency(coords, type))); // resolveDependencies(Collections.singletonList(coords), type); } private List<Path> resolve(CollectRequest collectRequest) { try { final DependencyRequest dependencyRequest = new DependencyRequest(collectRequest, null); final List<ArtifactResult> artifactResults = system.resolveDependencies(session, dependencyRequest).getArtifactResults(); final List<Path> jars = new ArrayList<Path>(); for (ArtifactResult artifactResult : artifactResults) jars.add(artifactResult.getArtifact().getFile().toPath().toAbsolutePath()); return jars; } catch (DependencyResolutionException e) { throw new RuntimeException("Error resolving dependencies.", e); } } @Override public String getLatestVersion(String coords, String type) { return artifactToCoords(getLatestVersion0(coords, type)); } private Artifact getLatestVersion0(String coords, String type) { try { final Artifact artifact = coordsToArtifact(coords, type); final String version; if (isVersionRange(artifact.getVersion())) { final VersionRangeRequest request = new VersionRangeRequest().setRepositories(repos).setArtifact(artifact); final VersionRangeResult result = system.resolveVersionRange(session, request); final Version highestVersion = result.getHighestVersion(); version = highestVersion != null ? highestVersion.toString() : null; } else { final VersionRequest request = new VersionRequest().setRepositories(repos).setArtifact(artifact); final VersionResult result = system.resolveVersion(session, request); version = result.getVersion(); } if (version == null) throw new RuntimeException("Could not find any version of artifact " + coords + " (looking for: " + artifact + ")"); return artifact.setVersion(version); } catch (RepositoryException e) { throw new RuntimeException(e); } } private static boolean isVersionRange(String version) { return version.startsWith("(") || version.startsWith("["); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Parsing"> /////////// Parsing /////////////////////////////////// // visible for testing static Dependency toDependency(String coords, String type) { return new Dependency(coordsToArtifact(coords, type), JavaScopes.RUNTIME, false, getExclusions(coords)); } private static Dependency toDependency(Artifact artifact) { return new Dependency(artifact, JavaScopes.RUNTIME, false, null); } private static List<Dependency> toDependencies(List<String> coords, String type) { final List<Dependency> deps = new ArrayList<Dependency>(coords.size()); for (String c : coords) deps.add(toDependency(c, type)); return deps; } private static String artifactToCoords(Artifact artifact) { if (artifact == null) return null; return artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getVersion() + ((artifact.getClassifier() != null && !artifact.getClassifier().isEmpty()) ? (":" + artifact.getClassifier()) : ""); } private static final Pattern PAT_DEPENDENCY = Pattern.compile("(?<groupId>[^:\\(]+):(?<artifactId>[^:\\(]+)(:(?<version>\\(?[^:\\(]*))?(:(?<classifier>[^:\\(]+))?(\\((?<exclusions>[^\\(\\)]*)\\))?"); private static Artifact coordsToArtifact(final String depString, String type) { final Matcher m = PAT_DEPENDENCY.matcher(depString); if (!m.matches()) throw new IllegalArgumentException("Could not parse dependency: " + depString); final String groupId = m.group("groupId"); final String artifactId = m.group("artifactId"); String version = m.group("version"); if (version == null || version.isEmpty()) version = LATEST_VERSION; final String classifier = m.group("classifier"); return new DefaultArtifact(groupId, artifactId, classifier, type, version); } private static Collection<Exclusion> getExclusions(String depString) { final Matcher m = PAT_DEPENDENCY.matcher(depString); if (!m.matches()) throw new IllegalArgumentException("Could not parse dependency: " + depString); if (m.group("exclusions") == null || m.group("exclusions").isEmpty()) return null; final List<String> exclusionPatterns = Arrays.asList(m.group("exclusions").split(",")); final List<Exclusion> exclusions = new ArrayList<Exclusion>(); for (String ex : exclusionPatterns) { String[] coords = ex.trim().split(":"); if (coords.length != 2) throw new IllegalArgumentException("Illegal exclusion dependency coordinates: " + depString + " (in exclusion " + ex + ")"); exclusions.add(new Exclusion(coords[0], coords[1], "*", "*")); } return exclusions; } private static final Pattern PAT_REPO = Pattern.compile("(?<id>[^(]+)(\\((?<url>[^\\)]+)\\))?"); // visible for testing static RemoteRepository createRepo(String repo, boolean allowSnapshots) { final Matcher m = PAT_REPO.matcher(repo); if (!m.matches()) throw new IllegalArgumentException("Could not parse repository: " + repo); String id = m.group("id"); String url = m.group("url"); if (url == null && WELL_KNOWN_REPOS.containsKey(id)) return createRepo(WELL_KNOWN_REPOS.get(id), allowSnapshots); if (url == null) url = id; RepositoryPolicy releasePolicy = new RepositoryPolicy(true, RepositoryPolicy.UPDATE_POLICY_NEVER, RepositoryPolicy.CHECKSUM_POLICY_WARN); RepositoryPolicy snapshotPolicy = allowSnapshots ? releasePolicy : new RepositoryPolicy(false, null, null); if (url.startsWith("file:")) { releasePolicy = new RepositoryPolicy(releasePolicy.isEnabled(), releasePolicy.getUpdatePolicy(), RepositoryPolicy.CHECKSUM_POLICY_IGNORE); snapshotPolicy = releasePolicy; } return new RemoteRepository.Builder(id, "default", url).setReleasePolicy(releasePolicy).setSnapshotPolicy(snapshotPolicy).build(); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Setup Helpers"> /////////// Setup Helpers /////////////////////////////////// private static Path getMavenHome() { String mhome = emptyToNull(System.getenv(ENV_MAVEN_HOME)); if (mhome == null) mhome = System.getProperty(PROP_MAVEN_HOME); return mhome != null ? Paths.get(mhome) : null; } private static Properties getSystemProperties() { Properties props = new Properties(); getEnvProperties(props); props.putAll(System.getProperties()); return props; } private static Properties getEnvProperties(Properties props) { if (props == null) props = new Properties(); boolean envCaseInsensitive = isWindows(); for (Map.Entry<String, String> entry : System.getenv().entrySet()) { String key = entry.getKey(); if (envCaseInsensitive) key = key.toUpperCase(Locale.ENGLISH); key = "env." + key; props.put(key, entry.getValue()); } return props; } private static ProxySelector getProxySelector(Settings settings) { final DefaultProxySelector selector = new DefaultProxySelector(); for (org.apache.maven.settings.Proxy proxy : settings.getProxies()) { AuthenticationBuilder auth = new AuthenticationBuilder(); auth.addUsername(proxy.getUsername()).addPassword(proxy.getPassword()); selector.add(new org.eclipse.aether.repository.Proxy(proxy.getProtocol(), proxy.getHost(), proxy.getPort(), auth.build()), proxy.getNonProxyHosts()); } return selector; } private static MirrorSelector getMirrorSelector(Settings settings) { final DefaultMirrorSelector selector = new DefaultMirrorSelector(); for (org.apache.maven.settings.Mirror mirror : settings.getMirrors()) selector.add(String.valueOf(mirror.getId()), mirror.getUrl(), mirror.getLayout(), false, mirror.getMirrorOf(), mirror.getMirrorOfLayouts()); return selector; } private static AuthenticationSelector getAuthSelector(Settings settings) { final DefaultAuthenticationSelector selector = new DefaultAuthenticationSelector(); for (Server server : settings.getServers()) { AuthenticationBuilder auth = new AuthenticationBuilder(); auth.addUsername(server.getUsername()).addPassword(server.getPassword()); auth.addPrivateKey(server.getPrivateKey(), server.getPassphrase()); selector.add(server.getId(), auth.build()); } return new ConservativeAuthenticationSelector(selector); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="General Utils"> /////////// General Utils /////////////////////////////////// private static PrintStream prefixStream(PrintStream out, final String prefix) { return new PrintStream(out) { @Override public void println(String x) { super.println(prefix + x); } }; } private static String propertyOrEnv(String propName, String envVar) { String val = System.getProperty(propName); if (val == null) val = emptyToNull(System.getenv(envVar)); return val; } private static Boolean isPropertySet(String property, boolean defaultValue) { final String val = System.getProperty(property); if (val == null) return defaultValue; return "".equals(val) | Boolean.parseBoolean(val); } private static String emptyToNull(String s) { if (s == null) return null; s = s.trim(); return s.isEmpty() ? null : s; } private static Map<String, String> stringMap(String... ss) { final Map<String, String> m = new HashMap<>(); for (int i = 0; i < ss.length / 2; i++) m.put(ss[i * 2], ss[i * 2 + 1]); return Collections.unmodifiableMap(m); } private static boolean isWindows() { return System.getProperty(PROP_OS_NAME).toLowerCase().startsWith("windows"); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Logging"> /////////// Logging /////////////////////////////////// private boolean isLogging(int level) { return level <= logLevel; } private void log(int level, String str) { if (isLogging(level)) System.err.println(LOG_PREFIX + str); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="DI Workarounds"> /////////// DI Workarounds /////////////////////////////////// private static DefaultSettingsDecrypter newDefaultSettingsDecrypter() { DefaultSecDispatcher secDispatcher = new DefaultSecDispatcher() { { _configurationFile = "~/.m2/settings-security.xml"; try { _cipher = new DefaultPlexusCipher(); } catch (PlexusCipherException e) { throw new RuntimeException(e); } } }; final DefaultSettingsDecrypter decrypter = new DefaultSettingsDecrypter(); try { java.lang.reflect.Field field = decrypter.getClass().getDeclaredField("securityDispatcher"); field.setAccessible(true); field.set(decrypter, secDispatcher); } catch (ReflectiveOperationException e) { throw new AssertionError(e); } return decrypter; } // necessary if we want to forgo Guice/Sisu injection and use DefaultServiceLocator instead private static final io.takari.filemanager.FileManager takariFileManager = new io.takari.filemanager.internal.DefaultFileManager(); public static class LockingFileProcessor extends io.takari.aether.concurrency.LockingFileProcessor { public LockingFileProcessor() { super(takariFileManager); } } public static class LockingSyncContextFactory extends io.takari.aether.concurrency.LockingSyncContextFactory { public LockingSyncContextFactory() { super(takariFileManager); } } //</editor-fold> }
package ucar.nc2.dt.radial; import ucar.nc2.dt.*; import ucar.nc2.dataset.*; import ucar.nc2.dataset.conv._Coordinate; import ucar.nc2.units.DateUnit; import ucar.nc2.units.SimpleUnit; import ucar.nc2.VariableSimpleIF; import ucar.nc2.Variable; import ucar.nc2.Attribute; import ucar.nc2.Dimension; import ucar.ma2.*; import java.io.IOException; import java.util.List; import java.util.Iterator; import java.util.Date; import java.util.ArrayList; public class Netcdf2Dataset extends RadialDatasetSweepAdapter implements TypedDatasetFactoryIF { private NetcdfDataset ds; private boolean isVolume; private double latv, lonv, elev; // TypedDatasetFactoryIF public boolean isMine(NetcdfDataset ds) { String format = ds.findAttValueIgnoreCase(null, "format", null); if(format != null) { if(format.startsWith("nssl/netcdf")) return true; } Dimension az = ds.findDimension("Azimuth"); Dimension gt = ds.findDimension("Gate"); if ((null != az) && (null != gt)) { return true; } return false; } public TypedDataset open(NetcdfDataset ncd, ucar.nc2.util.CancelTask task, StringBuffer errlog) throws IOException { return new Netcdf2Dataset(ncd); } public thredds.catalog.DataType getScientificDataType() { return thredds.catalog.DataType.RADIAL; } public Netcdf2Dataset() {} /** * Constructor. * * @param ds must be from netcdf IOSP */ public Netcdf2Dataset(NetcdfDataset ds) { super(ds); this.ds = ds; desc = "Netcdf/NCML 2 radar dataset"; setEarthLocation(); setTimeUnits(); setStartDate(); setEndDate(); setBoundingBox(); try { addCoordSystem(ds); } catch ( IOException e ) { e.printStackTrace(); } } private void addCoordSystem(NetcdfDataset ds) throws IOException { // int time = ds.findGlobalAttributeIgnoreCase("Time").getNumericValue().intValue(); double ele = 0; Attribute attr = ds.findGlobalAttributeIgnoreCase("Elevation"); if( attr != null ) ele = attr.getNumericValue().doubleValue(); // ncml agg add this sweep variable as agg dimension Variable sp = ds.findVariable("sweep"); if(sp == null) { // add Elevation ds.addDimension( null, new Dimension("Elevation", 1 , true)); String lName = "elevation angle in degres: 0 = parallel to pedestal base, 90 = perpendicular"; CoordinateAxis v = new CoordinateAxis1D(ds, null, "Elevation", DataType.DOUBLE, "Elevation", "degrees", lName); ds.setValues(v, 1, ele, 0); v.addAttribute(new Attribute(_Coordinate.AxisType, AxisType.RadialElevation.toString())); ds.addVariable(null, v); } else { Array spdata = sp.read(); float [] spd = (float [])spdata.get1DJavaArray(float.class); int spsize = spd.length; // add Elevation ds.addDimension( null, new Dimension("Elevation", spsize , true)); String lName = "elevation angle in degres: 0 = parallel to pedestal base, 90 = perpendicular"; CoordinateAxis v = new CoordinateAxis1D(ds, null, "Elevation", DataType.DOUBLE, "Elevation", "degrees", lName); //ds.setValues(v, (ArrayList)spdata); v.addAttribute(new Attribute(_Coordinate.AxisType, AxisType.RadialElevation.toString())); ds.addVariable(null, v); } ds.addAttribute( null, new Attribute("IsRadial", new Integer(1))); attr = ds.findGlobalAttributeIgnoreCase("vcp-value"); String vcp; if(attr == null) vcp = "11"; else vcp = attr.getStringValue(); ds.addAttribute( null, new Attribute("VolumeCoveragePatternName", vcp)); ds.finish(); } public ucar.nc2.dt.EarthLocation getCommonOrigin() { return origin; } public String getRadarID() { Attribute ga = ds.findGlobalAttribute("radarName-value"); if(ga != null) return ga.getStringValue(); else return "XXXX"; } public boolean isStationary() { return true; } public String getRadarName() { return ds.findGlobalAttribute("ProductStationName").getStringValue(); } public String getDataFormat() { return RadialDatasetSweep.LevelII; } public void setIsVolume(NetcdfDataset nds) { String format = nds.findAttValueIgnoreCase(null, "volume", null); if( format == null) { isVolume = false; return; } if (format.equals("true")) isVolume = true; else isVolume = false; } public boolean isVolume() { return isVolume; } protected void setEarthLocation() { Attribute ga = ds.findGlobalAttribute("Latitude"); if(ga != null ) latv = ga.getNumericValue().doubleValue(); else latv = 0.0; ga = ds.findGlobalAttribute("Longitude"); if(ga != null) lonv = ga.getNumericValue().doubleValue(); else lonv = 0.0; ga = ds.findGlobalAttribute("Height"); if(ga != null) elev = ga.getNumericValue().doubleValue(); else elev = 0.0; origin = new EarthLocationImpl(latv, lonv, elev); } protected void setTimeUnits() { List axes = ds.getCoordinateAxes(); for (int i = 0; i < axes.size(); i++) { CoordinateAxis axis = (CoordinateAxis) axes.get(i); if (axis.getAxisType() == AxisType.Time) { String units = axis.getUnitsString(); dateUnits = (DateUnit) SimpleUnit.factory(units); return; } } parseInfo.append("*** Time Units not Found\n"); } protected void setStartDate() { String start_datetime = ds.findAttValueIgnoreCase(null, "time_coverage_start", null); if (start_datetime != null) startDate = DateUnit.getStandardOrISO(start_datetime); else parseInfo.append("*** start_datetime not Found\n"); } protected void setEndDate() { String end_datetime = ds.findAttValueIgnoreCase(null, "time_coverage_end", null); if (end_datetime != null) endDate = DateUnit.getStandardOrISO(end_datetime); else parseInfo.append("*** end_datetime not Found\n"); } protected void addRadialVariable(NetcdfDataset nds, Variable var) { RadialVariable rsvar = null; String vName = var.getShortName() ; int rnk = var.getRank(); setIsVolume(nds); if(isVolume && rnk == 3) { VariableSimpleIF v = new MyRadialVariableAdapter(vName, var.getAttributes()); rsvar = makeRadialVariable(nds, v, var); } else if(!isVolume && rnk == 2) { VariableSimpleIF v = new MyRadialVariableAdapter(vName, var.getAttributes()); rsvar = makeRadialVariable(nds, v, var); } if(rsvar != null) dataVariables.add(rsvar); } protected RadialVariable makeRadialVariable(NetcdfDataset nds, VariableSimpleIF v, Variable v0) { return new Netcdf2Variable(nds, v, v0); } public void clearDatasetMemory() { List rvars = getDataVariables(); Iterator iter = rvars.iterator(); while (iter.hasNext()) { RadialVariable radVar = (RadialVariable)iter.next(); radVar.clearVariableMemory(); } } public String getInfo() { StringBuffer sbuff = new StringBuffer(); sbuff.append("Netcdfs2Dataset\n"); sbuff.append(super.getDetailInfo()); sbuff.append("\n\n"); sbuff.append(parseInfo.toString()); return sbuff.toString(); } private class Netcdf2Variable extends MyRadialVariableAdapter implements RadialDatasetSweep.RadialVariable { ArrayList sweeps; int nsweeps; String name; private Netcdf2Variable(NetcdfDataset nds, VariableSimpleIF v, Variable v0) { super(v.getName(), v0.getAttributes()); sweeps = new ArrayList(); nsweeps = 0; name = v.getName(); int[] shape = v0.getShape(); int count = v0.getRank() - 1; int ngates = shape[count]; count int nrays = shape[count]; count if(shape.length == 3) nsweeps = shape[count]; else nsweeps = 1; for(int i = 0; i< nsweeps; i++) sweeps.add( new Netcdf2Sweep(v0, i, nrays, ngates)) ; } public String toString() { return name; } public float[] readAllData() throws IOException { Array allData; Sweep spn = (Sweep)sweeps.get(0); Variable v = spn.getsweepVar(); try { allData = v.read(); } catch (IOException e) { throw new IOException(e.getMessage()); } return (float []) allData.get1DJavaArray(float.class); } public int getNumSweeps() { return nsweeps; } public Sweep getSweep(int sweepNo) { return (Sweep) sweeps.get(sweepNo); } public void clearVariableMemory() { // doing nothing } private class Netcdf2Sweep implements RadialDatasetSweep.Sweep { double meanElevation = Double.NaN; double meanAzimuth = Double.NaN; int sweepno, nrays, ngates; Variable sweepVar; Netcdf2Sweep(Variable v, int sweepno, int rays, int gates) { this.sweepno = sweepno; this.nrays = rays; this.ngates = gates; this.sweepVar = v; //setMeanElevation(); //setMeanAzimuth(); } public Variable getsweepVar(){ return sweepVar; } public float[] readData() throws java.io.IOException { Array allData; int [] shape = sweepVar.getShape(); int [] origind = new int[ sweepVar.getRank()]; if(isVolume) { origind[0] = sweepno; origind[1] = 0; shape[0] = 1; } try { allData = sweepVar.read(origind, shape); } catch (InvalidRangeException e) { throw new IOException(e.getMessage()); } int nradials = shape[0]; int ngates = shape[1]; IndexIterator dataIter = allData.getIndexIterator(); for (int j = 0; j < nradials; j++) { for(int i = 0; i < ngates; i++) { float tp = dataIter.getFloatNext(); if(tp == -32768.0f || tp == -99900.0f) { dataIter.setFloatCurrent(Float.NaN); } } } return (float []) allData.get1DJavaArray(float.class); } // private Object MUTEX =new Object(); /* read 1d data ngates */ public float[] readData(int ray) throws java.io.IOException { Array rayData; int [] shape = sweepVar.getShape(); int [] origind = new int[ sweepVar.getRank()]; if(isVolume) { origind[0] = sweepno; origind[1] = ray; shape[0] = 1; shape[1] = 1; } else { shape[0] = 1; origind[0] = ray; } try { rayData = sweepVar.read(origind, shape); } catch (ucar.ma2.InvalidRangeException e) { throw new IOException(e.getMessage()); } int ngates = shape[1]; IndexIterator dataIter = rayData.getIndexIterator(); for(int i = 0; i < ngates; i++) { float tp = dataIter.getFloatNext(); if(tp == -32768.0f || tp == -99900.0f) { dataIter.setFloatCurrent(Float.NaN); } } return (float []) rayData.get1DJavaArray(float.class); } private void setMeanElevation() { if(isVolume) { try{ Variable sp = ds.findVariable("sweep"); Array spData = sp.read(); float [] spArray = (float [])spData.get1DJavaArray(float.class); meanElevation = spArray[sweepno]; } catch (IOException e) { e.printStackTrace(); meanElevation = 0.0; } } else { Attribute data = ds.findGlobalAttribute("Elevation"); meanElevation = data.getNumericValue().doubleValue(); } } public float getMeanElevation() { if( Double.isNaN(meanElevation) ) setMeanElevation(); return (float) meanElevation ; } public double meanDouble(Array a) { double sum = 0; int size = 0; IndexIterator iterA = a.getIndexIterator(); while (iterA.hasNext()) { double s = iterA.getDoubleNext(); if (! Double.isNaN(s)) { sum += s; size ++; } } return sum / size; } public int getGateNumber() { return ngates; } public int getRadialNumber() { return nrays; } public RadialDatasetSweep.Type getType() { return null; } public ucar.nc2.dt.EarthLocation getOrigin(int ray) { return origin; } public Date getStartingTime() { return startDate; } public Date getEndingTime() { return endDate; } public int getSweepIndex() { return sweepno; } // public int getNumGates() { // return ngates; private void setMeanAzimuth() { meanAzimuth = 0.0; } public float getMeanAzimuth() { if(Double.isNaN(meanAzimuth)) setMeanAzimuth(); return (float) meanAzimuth; } public boolean isConic() { return true; } public float getElevation(int ray) throws IOException { return (float)meanElevation; } public float[] getElevation() throws IOException { float [] dataValue = new float[nrays]; for (int i = 0; i < nrays; i++) { dataValue[i] = (float)meanElevation; } return dataValue; } public float[] getAzimuth() throws IOException { Array aziData = null; try{ Variable azi = ds.findVariable("Azimuth"); aziData = azi.read(); } catch (IOException e) { e.printStackTrace(); meanElevation = 0.0; } return (float [])aziData.get1DJavaArray(float.class); } public float getAzimuth( int ray) throws IOException { String aziName = "Azimuth"; Array aziData = null; if(aziData == null) { try { Array aziTmp = ds.findVariable(aziName).read(); if(isVolume) { int [] aziOrigin = new int[2]; aziOrigin[0] = sweepno; aziOrigin[1] = 0; int [] aziShape = {1, getRadialNumber()}; aziData = aziTmp.section(aziOrigin, aziShape); } else { aziData = aziTmp; } } catch (IOException e) { e.printStackTrace(); } catch (ucar.ma2.InvalidRangeException e) { e.printStackTrace(); } } Index index = aziData.getIndex(); return aziData.getFloat(index.set(ray)); } public float getRadialDistance(int gate) throws IOException { float gateStart = getRangeToFirstGate(); Variable gateSize = ds.findVariable("GateWidth"); float [] data = (float [])gateSize.read().get1DJavaArray(float.class); float dist = (float)(gateStart + gate*data[0]); return dist; } public float getTime(int ray) throws IOException { return startDate.getTime(); } public float getBeamWidth() { return 0.95f; // degrees, info from Chris Burkhart } public float getNyquistFrequency() { return 0; // LOOK this may be radial specific } public float getRangeToFirstGate() { Attribute firstGate = ds.findGlobalAttributeIgnoreCase("RangeToFirstGate"); double gateStart = firstGate.getNumericValue().doubleValue(); return (float)gateStart; } public float getGateSize() { try { return getRadialDistance(1) - getRadialDistance(0); } catch (IOException e) { e.printStackTrace(); return 0.0f; } } public boolean isGateSizeConstant() { return true; } public void clearSweepMemory() { } } // Netcdf2Sweep class } // Netcdf2Variable private static void testRadialVariable(RadialDatasetSweep.RadialVariable rv) throws IOException { int nsweep = rv.getNumSweeps(); Sweep sw; float mele; float [] az; for (int i = 0; i < nsweep; i++) { //ucar.unidata.util.Trace.call1("LevelII2Dataset:testRadialVariable getSweep " + i); sw = rv.getSweep(i); mele = sw.getMeanElevation(); //ucar.unidata.util.Trace.call2("LevelII2Dataset:testRadialVariable getSweep " + i); float me = sw.getMeanElevation(); System.out.println("*** radar Sweep mean elevation of sweep " + i + " is: " + me); int nrays = sw.getRadialNumber(); az = new float[nrays]; for (int j = 0; j < nrays; j++) { float azi = sw.getAzimuth(j); az[j] = azi; } } sw = rv.getSweep(0); //ucar.unidata.util.Trace.call1("LevelII2Dataset:testRadialVariable readData"); float [] ddd = sw.readData(); float [] da = sw.getAzimuth(); float [] de = sw.getElevation(); //ucar.unidata.util.Trace.call2("LevelII2Dataset:testRadialVariable readData"); assert(null != ddd); int nrays = sw.getRadialNumber(); az = new float[nrays]; for (int i = 0; i < nrays; i++) { int ngates = sw.getGateNumber(); assert(ngates > 0); float [] d = sw.readData(i); assert(null != d); // float [] e = sw.readDataNew(i); // assert(null != e); float azi = sw.getAzimuth(i); assert(azi > 0); az[i] = azi; float ele = sw.getElevation(i); assert(ele > 0); float la = (float) sw.getOrigin(i).getLatitude(); assert(la > 0); float lo = (float) sw.getOrigin(i).getLongitude(); assert(lo > 0); float al = (float) sw.getOrigin(i).getAltitude(); assert(al > 0); } assert(0 != nrays); } public static void main(String args[]) throws Exception, IOException, InstantiationException, IllegalAccessException { //String fileIn = "/home/yuanho/NIDS/Reflectivity_0.50_20070329-204156.netcdf"; String fileIn ="/home/yuanho/nssl/netcdf.ncml"; RadialDatasetSweep rds = (RadialDatasetSweep) TypedDatasetFactory.open( thredds.catalog.DataType.RADIAL, fileIn, null, new StringBuffer()); //String st = rds.getStartDate().toString(); //String et = rds.getEndDate().toString(); //String id = rds.getRadarID(); //String name = rds.getRadarName(); rds.getRadarID(); List rvars = rds.getDataVariables(); RadialDatasetSweep.RadialVariable rf = (RadialDatasetSweep.RadialVariable) rds.getDataVariable("Reflectivity"); rf.getSweep(0); testRadialVariable(rf); } }
package ru.job4j.pro.generic; /** * This abstract class have teo abstract methods getId and setId. * * @author Kucykh Vasily (mailto:basil135@mail.ru) * @version $Id$ * @version 22.05.2017 */ public abstract class Base { /** * abstract method getId return id as A String. * * @return String Id */ abstract String getId(); /** * abstract method setId is setting id. * * @param id is identification string */ abstract void setId(String id); }
package org.spine3.base; import com.google.protobuf.BoolValue; import com.google.protobuf.DoubleValue; import com.google.protobuf.FloatValue; import com.google.protobuf.Int32Value; import com.google.protobuf.Int64Value; import org.junit.Test; import com.google.protobuf.StringValue; import static org.junit.Assert.*; import static org.spine3.protobuf.Messages.fromAny; import static org.spine3.protobuf.Values.newStringValue; import static org.spine3.test.Tests.hasPrivateUtilityConstructor; /** * @author Andrey Lavrov */ public class MismatchShould { private static final String REQUESTED = "requested"; private static final String EXPECTED = "expected"; private static final String ACTUAL = "ACTUAL"; private static final int VERSION = 0; private static final String DEFAULT_VALUE = ""; public static final double DELTA = 0.01; @Test public void has_private_constructor() { assertTrue(hasPrivateUtilityConstructor(Mismatch.class)); } @Test public void set_default_expected_value_if_it_was_passed_as_null() { final ValueMismatch mismatch = Mismatch.of(null, ACTUAL, REQUESTED, VERSION); final String expected = mismatch.getExpected() .toString(); assertEquals(DEFAULT_VALUE, expected); } @Test public void set_default_actual_value_if_it_was_passed_as_null() { final ValueMismatch mismatch = Mismatch.of(EXPECTED, null, REQUESTED, VERSION); final String actual = mismatch.getActual() .toString(); assertEquals(DEFAULT_VALUE, actual); } @Test public void return_mismatch_object_with_string_values() { final ValueMismatch mismatch = Mismatch.of(EXPECTED, ACTUAL, REQUESTED, VERSION); final StringValue expected = fromAny(mismatch.getExpected()); final StringValue actual = fromAny(mismatch.getActual()); final StringValue requested = fromAny(mismatch.getRequested()); assertEquals(EXPECTED, expected.getValue()); assertEquals(ACTUAL, actual.getValue()); assertEquals(REQUESTED, requested.getValue()); } @Test public void return_mismatch_object_with_int32_values() { final int expected = 0; final int actual = 1; final int requested = 2; final ValueMismatch mismatch = Mismatch.of(expected, actual, requested, VERSION); final Int32Value expectedWrapper = fromAny(mismatch.getExpected()); final Int32Value actualWrapper = fromAny(mismatch.getActual()); final Int32Value requestedWrapper = fromAny(mismatch.getRequested()); assertEquals(expected, expectedWrapper.getValue()); assertEquals(actual, actualWrapper.getValue()); assertEquals(requested, requestedWrapper.getValue()); } @Test public void return_mismatch_object_with_int64_values() { final long expected = 0L; final long actual = 1L; final long requested = 2L; final ValueMismatch mismatch = Mismatch.of(expected, actual, requested, VERSION); final Int64Value expectedWrapped = fromAny(mismatch.getExpected()); final Int64Value actualWrapped = fromAny(mismatch.getActual()); final Int64Value requestedWrapped = fromAny(mismatch.getRequested()); assertEquals(expected, expectedWrapped.getValue()); assertEquals(actual, actualWrapped.getValue()); assertEquals(requested, requestedWrapped.getValue()); } @Test public void return_mismatch_object_with_float_values() { final float expected = 0.0F; final float actual = 1.0F; final float requested = 2.0F; final ValueMismatch mismatch = Mismatch.of(expected, actual, requested, VERSION); final FloatValue expectedWrapped = fromAny(mismatch.getExpected()); final FloatValue actualWrapped = fromAny(mismatch.getActual()); final FloatValue requestedWrapped = fromAny(mismatch.getRequested()); assertEquals(expected, expectedWrapped.getValue(), DELTA); assertEquals(actual, actualWrapped.getValue(), DELTA); assertEquals(requested, requestedWrapped.getValue(), DELTA); } @Test public void return_mismatch_object_with_double_values() { final double expected = 0.1; final double actual = 0.2; final double requested = 0.3; final ValueMismatch mismatch = Mismatch.of(expected, actual, requested, VERSION); final DoubleValue expectedWrapped = fromAny(mismatch.getExpected()); final DoubleValue actualWrapped = fromAny(mismatch.getActual()); final DoubleValue requestedWrapped = fromAny(mismatch.getRequested()); assertEquals(expected, expectedWrapped.getValue(), DELTA); assertEquals(actual, actualWrapped.getValue(), DELTA); assertEquals(requested, requestedWrapped.getValue(), DELTA); } @Test public void return_mismatch_object_with_boolean_values() { final boolean expected = true; final boolean actual = false; final boolean requested = true; final ValueMismatch mismatch = Mismatch.of(expected, actual, requested, VERSION); final BoolValue expectedWrapped = fromAny(mismatch.getExpected()); final BoolValue actualWrapped = fromAny(mismatch.getActual()); final BoolValue requestedWrapped = fromAny(mismatch.getRequested()); assertEquals(expected, expectedWrapped.getValue()); assertEquals(actual, actualWrapped.getValue()); assertEquals(requested, requestedWrapped.getValue()); } @Test public void set_default_expected_value_if_it_was_passed_as_null_message_overload() { final ValueMismatch mismatch = Mismatch.of(null, newStringValue(ACTUAL), newStringValue(REQUESTED), VERSION); final String expected = mismatch.getExpected() .toString(); assertEquals(DEFAULT_VALUE, expected); } @Test public void set_default_actual_value_if_it_was_passed_as_null_message_overload() { final ValueMismatch mismatch = Mismatch.of(newStringValue(EXPECTED), null, newStringValue(REQUESTED), VERSION); final String actual = mismatch.getActual() .toString(); assertEquals(DEFAULT_VALUE, actual); } @Test public void return_mismatch_object_with_message_values() { final ValueMismatch mismatch = Mismatch.of(newStringValue(EXPECTED), newStringValue(ACTUAL), newStringValue(REQUESTED), VERSION); final StringValue expected = fromAny(mismatch.getExpected()); final StringValue actual = fromAny(mismatch.getActual()); final StringValue requested = fromAny(mismatch.getRequested()); assertEquals(EXPECTED, expected.getValue()); assertEquals(ACTUAL, actual.getValue()); assertEquals(REQUESTED, requested.getValue()); } }
package replicant; import arez.Arez; import arez.Disposable; import org.realityforge.guiceyloops.shared.ValueUtil; import org.testng.annotations.Test; import static org.testng.Assert.*; public class ReplicantContextTest extends AbstractReplicantTest { @Test public void areasOfInterest() { // Pause scheduler so Autoruns don't auto-converge Arez.context().pauseScheduler(); final ReplicantContext context = Replicant.context(); final ChannelAddress address = new ChannelAddress( G.G1 ); final String filter = ValueUtil.randomString(); final String filter2 = ValueUtil.randomString(); Arez.context().safeAction( () -> { assertEquals( context.getAreasOfInterest().size(), 0 ); assertEquals( context.findAreaOfInterestByAddress( address ), null ); final AreaOfInterest areaOfInterest = context.createOrUpdateAreaOfInterest( address, filter ); assertEquals( areaOfInterest.getChannel().getFilter(), filter ); assertEquals( context.getAreasOfInterest().size(), 1 ); assertEquals( context.findAreaOfInterestByAddress( address ), areaOfInterest ); final AreaOfInterest areaOfInterest2 = context.createOrUpdateAreaOfInterest( address, filter2 ); assertEquals( areaOfInterest2, areaOfInterest ); assertEquals( areaOfInterest2.getChannel().getFilter(), filter2 ); assertEquals( context.getAreasOfInterest().size(), 1 ); assertEquals( context.findAreaOfInterestByAddress( address ), areaOfInterest2 ); assertEquals( context.findAreaOfInterestByAddress( address ), areaOfInterest2 ); } ); } @Test public void entities() { final ReplicantContext context = Replicant.context(); Arez.context().safeAction( () -> { assertEquals( context.findAllEntityTypes().size(), 0 ); assertEquals( context.findAllEntitiesByType( A.class ).size(), 0 ); assertEquals( context.findAllEntitiesByType( B.class ).size(), 0 ); assertEquals( context.findEntityByTypeAndId( A.class, 1 ), null ); assertEquals( context.findEntityByTypeAndId( A.class, 2 ), null ); assertEquals( context.findEntityByTypeAndId( B.class, 47 ), null ); final Entity entity1 = context.findOrCreateEntity( A.class, 1 ); assertEquals( entity1.getName(), "A/1" ); assertEquals( context.findAllEntityTypes().size(), 1 ); assertEquals( context.findAllEntitiesByType( A.class ).size(), 1 ); assertEquals( context.findAllEntitiesByType( B.class ).size(), 0 ); assertEquals( context.findEntityByTypeAndId( A.class, 1 ), entity1 ); assertEquals( context.findEntityByTypeAndId( A.class, 2 ), null ); assertEquals( context.findEntityByTypeAndId( B.class, 47 ), null ); final Entity entity2 = context.findOrCreateEntity( "Super-dee-duper", A.class, 2 ); assertEquals( entity2.getName(), "Super-dee-duper" ); assertEquals( context.findAllEntityTypes().size(), 1 ); assertEquals( context.findAllEntitiesByType( A.class ).size(), 2 ); assertEquals( context.findAllEntitiesByType( B.class ).size(), 0 ); assertEquals( context.findEntityByTypeAndId( A.class, 1 ), entity1 ); assertEquals( context.findEntityByTypeAndId( A.class, 2 ), entity2 ); assertEquals( context.findEntityByTypeAndId( B.class, 47 ), null ); final Entity entity3 = context.findOrCreateEntity( B.class, 47 ); assertEquals( context.findAllEntityTypes().size(), 2 ); assertEquals( context.findAllEntitiesByType( A.class ).size(), 2 ); assertEquals( context.findAllEntitiesByType( B.class ).size(), 1 ); assertEquals( context.findEntityByTypeAndId( A.class, 1 ), entity1 ); assertEquals( context.findEntityByTypeAndId( A.class, 2 ), entity2 ); assertEquals( context.findEntityByTypeAndId( B.class, 47 ), entity3 ); Disposable.dispose( entity1 ); assertEquals( context.findAllEntityTypes().size(), 2 ); assertEquals( context.findAllEntitiesByType( A.class ).size(), 1 ); assertEquals( context.findAllEntitiesByType( B.class ).size(), 1 ); assertEquals( context.findEntityByTypeAndId( A.class, 1 ), null ); assertEquals( context.findEntityByTypeAndId( A.class, 2 ), entity2 ); assertEquals( context.findEntityByTypeAndId( B.class, 47 ), entity3 ); Disposable.dispose( entity2 ); assertEquals( context.findAllEntityTypes().size(), 1 ); assertEquals( context.findAllEntitiesByType( A.class ).size(), 0 ); assertEquals( context.findAllEntitiesByType( B.class ).size(), 1 ); assertEquals( context.findEntityByTypeAndId( A.class, 1 ), null ); assertEquals( context.findEntityByTypeAndId( A.class, 2 ), null ); assertEquals( context.findEntityByTypeAndId( B.class, 47 ), entity3 ); Disposable.dispose( entity3 ); assertEquals( context.findAllEntityTypes().size(), 0 ); assertEquals( context.findAllEntitiesByType( A.class ).size(), 0 ); assertEquals( context.findAllEntitiesByType( B.class ).size(), 0 ); assertEquals( context.findEntityByTypeAndId( A.class, 1 ), null ); assertEquals( context.findEntityByTypeAndId( A.class, 2 ), null ); assertEquals( context.findEntityByTypeAndId( B.class, 47 ), null ); } ); } @Test public void subscriptions() { // Pause scheduler so Autoruns don't auto-converge Arez.context().pauseScheduler(); final ReplicantContext context = Replicant.context(); final ChannelAddress address1 = new ChannelAddress( G.G1 ); final ChannelAddress address2 = new ChannelAddress( G.G2, 1 ); final ChannelAddress address3 = new ChannelAddress( G.G2, 2 ); final String filter1 = null; final String filter2 = ValueUtil.randomString(); final String filter3 = ValueUtil.randomString(); final boolean explicitSubscription1 = true; final boolean explicitSubscription2 = true; final boolean explicitSubscription3 = false; Arez.context().safeAction( () -> { assertEquals( context.getTypeSubscriptions().size(), 0 ); assertEquals( context.getInstanceSubscriptions().size(), 0 ); assertEquals( context.getInstanceSubscriptionIds( G.G2 ).size(), 0 ); assertEquals( context.findSubscription( address1 ), null ); assertEquals( context.findSubscription( address2 ), null ); assertEquals( context.findSubscription( address3 ), null ); final Subscription subscription1 = context.createSubscription( address1, filter1, explicitSubscription1 ); assertEquals( subscription1.getChannel().getAddress(), address1 ); assertEquals( subscription1.getChannel().getFilter(), filter1 ); assertEquals( subscription1.isExplicitSubscription(), explicitSubscription1 ); assertEquals( context.getTypeSubscriptions().size(), 1 ); assertEquals( context.getInstanceSubscriptions().size(), 0 ); assertEquals( context.getInstanceSubscriptionIds( G.G2 ).size(), 0 ); assertEquals( context.findSubscription( address1 ), subscription1 ); assertEquals( context.findSubscription( address2 ), null ); assertEquals( context.findSubscription( address3 ), null ); final Subscription subscription2 = context.createSubscription( address2, filter2, explicitSubscription2 ); assertEquals( subscription2.getChannel().getAddress(), address2 ); assertEquals( subscription2.getChannel().getFilter(), filter2 ); assertEquals( subscription2.isExplicitSubscription(), explicitSubscription2 ); assertEquals( context.getTypeSubscriptions().size(), 1 ); assertEquals( context.getInstanceSubscriptions().size(), 1 ); assertEquals( context.getInstanceSubscriptionIds( G.G2 ).size(), 1 ); assertEquals( context.findSubscription( address1 ), subscription1 ); assertEquals( context.findSubscription( address2 ), subscription2 ); assertEquals( context.findSubscription( address3 ), null ); final Subscription subscription3 = context.createSubscription( address3, filter3, explicitSubscription3 ); assertEquals( subscription3.getChannel().getAddress(), address3 ); assertEquals( subscription3.getChannel().getFilter(), filter3 ); assertEquals( subscription3.isExplicitSubscription(), explicitSubscription3 ); assertEquals( context.getTypeSubscriptions().size(), 1 ); assertEquals( context.getInstanceSubscriptions().size(), 2 ); assertEquals( context.getInstanceSubscriptionIds( G.G2 ).size(), 2 ); assertEquals( context.findSubscription( address1 ), subscription1 ); assertEquals( context.findSubscription( address2 ), subscription2 ); assertEquals( context.findSubscription( address3 ), subscription3 ); Disposable.dispose( subscription2 ); Disposable.dispose( subscription3 ); assertEquals( context.getTypeSubscriptions().size(), 1 ); assertEquals( context.getInstanceSubscriptions().size(), 0 ); assertEquals( context.getInstanceSubscriptionIds( G.G2 ).size(), 0 ); assertEquals( context.findSubscription( address1 ), subscription1 ); assertEquals( context.findSubscription( address2 ), null ); assertEquals( context.findSubscription( address3 ), null ); } ); } @Test public void getSpy_whenSpiesDisabled() throws Exception { ReplicantTestUtil.disableSpies(); final ReplicantContext context = new ReplicantContext(); assertEquals( expectThrows( IllegalStateException.class, context::getSpy ).getMessage(), "Replicant-0021: Attempting to get Spy but spies are not enabled." ); } @Test public void getSpy() throws Exception { final ReplicantContext context = new ReplicantContext(); assertFalse( context.willPropagateSpyEvents() ); final Spy spy = context.getSpy(); spy.addSpyEventHandler( new TestSpyEventHandler() ); assertTrue( spy.willPropagateSpyEvents() ); assertTrue( context.willPropagateSpyEvents() ); ReplicantTestUtil.disableSpies(); assertFalse( spy.willPropagateSpyEvents() ); assertFalse( context.willPropagateSpyEvents() ); } enum G { G1, G2 } static class A { } static class B { } }
package org.jetel.graph; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.annotation.XmlAnyAttribute; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlType; import javax.xml.namespace.QName; import org.jetel.component.ComponentDescription.Attribute; import org.jetel.exception.JetelRuntimeException; import org.jetel.graph.parameter.GraphParameterAttributeNode; import org.jetel.graph.parameter.GraphParameterDynamicValueProvider; import org.jetel.graph.runtime.IAuthorityProxy; import org.jetel.util.SubgraphUtils; import org.jetel.util.property.PropertyRefResolver; import org.jetel.util.property.RefResFlag; import org.jetel.util.string.StringUtils; @XmlRootElement(name = "GraphParameter") @XmlType(propOrder = { "name", "value", "secure", "componentReference", "attrs", "singleType" }) public class GraphParameter { public static final String HIDDEN_SECURE_PARAMETER = "*****"; private static final SingleType DEFAULT_SINGLE_TYPE = new SingleType("string"); private String name; private String value; private GraphParameterDynamicValueProvider dynamicValue; private String label; private boolean secure = false; private boolean isPublic = false; private boolean isRequired = false; private String description; private String category; private String defaultHint; private SingleType singleType; private ComponentReference componentReference; @XmlTransient private GraphParameters parentGraphParameters; public GraphParameter() { } public GraphParameter(String name, String value) { this.name = name; this.value = value; } GraphParameter(String name, String value, GraphParameters parentGraphParameters) { this.name = name; this.value = value; this.parentGraphParameters = parentGraphParameters; } void setParentGraphParameters(GraphParameters parentGraphParameters) { this.parentGraphParameters = parentGraphParameters; } @XmlTransient public TransformationGraph getParentGraph() { return parentGraphParameters != null ? parentGraphParameters.getParentGraph() : null; } public void setName(String name) { this.name = name; } /** * @return name of this graph parameter, this is key of parameter * which is used to reference this parameter using ${PARAM_NAME} pattern */ @XmlAttribute(name="name") public String getName() { return name; } public void setValue(String value) { this.value = (value != null) ? value : ""; if (value != null) { this.dynamicValue = null; } } /** * @return true if value of this graph parameter is defined by CTL code */ public boolean hasDynamicValue() { return dynamicValue != null; } /** * @param flag * @return resolved value of this graph parameter * @see PropertyRefResolver */ public String getValueResolved(RefResFlag flag) { if (!hasDynamicValue()) { return getParentGraph().getPropertyRefResolver().getResolvedPropertyValue(name, flag); } else { return dynamicValue.getValue(); } } /** * @return value of this parameter; can contain a parameter reference recursively */ @XmlAttribute(name="value") public String getValue() { if (!hasDynamicValue()) { return value != null ? value : ""; } else { return dynamicValue.getValue(); } } public GraphParameterAttributeNode[] getAttrs() { List<GraphParameterAttributeNode> ret = new ArrayList<>(); if (dynamicValue != null) { GraphParameterAttributeNode attrNode = new GraphParameterAttributeNode(); attrNode.setName("dynamicValue"); attrNode.setValue(dynamicValue.getTransformCode()); ret.add(attrNode); } if (description != null) { GraphParameterAttributeNode attrNode = new GraphParameterAttributeNode(); attrNode.setName("description"); attrNode.setValue(description); ret.add(attrNode); } return ret.toArray(new GraphParameterAttributeNode[ret.size()]); } @XmlElement(name="attr") public void setAttrs(GraphParameterAttributeNode[] attrs) { for (GraphParameterAttributeNode a : attrs) { if ("dynamicValue".equals(a.getName())) { setDynamicValue(a.getValue()); } if ("description".equals(a.getName())) { setDescription(a.getValue()); } } } public void setDynamicValue(String dynamicValue) { if (dynamicValue != null && !dynamicValue.isEmpty()) { this.dynamicValue = GraphParameterDynamicValueProvider.create(this, dynamicValue); } else { this.dynamicValue = null; } } @XmlTransient public String getDynamicValue() { if (this.dynamicValue != null) { return dynamicValue.getTransformCode(); } else { return null; } } /** * Human-readable name of the parameter. Used for public subgraph parameters. * @return the label */ @XmlAttribute(name="label") public String getLabel() { return label; } /** * @return label or name if label is empty */ public String getLabelOrName() { if (!StringUtils.isEmpty(label)) { return label; } else { return name; } } /** * @param label the label to set */ public void setLabel(String label) { this.label = label; } /** * @return true if this parameter is considered as secured; * special value resolution is used for secure parameters, * see {@link IAuthorityProxy#getSecureParamater(String, String)} */ @XmlAttribute(name="secure") public boolean isSecure() { return secure; } /** * Marks this parameter as secure parameter. * @param secure */ public void setSecure(boolean secure) { this.secure = secure; } /** * @return true if this parameter is public. */ @XmlAttribute(name="public") public boolean isPublic() { return isPublic; } /** * Marks this parameter as public parameter. * @param isPublic the isPublic to set */ public void setPublic(boolean isPublic) { this.isPublic = isPublic; } /** * @return true if this parameter is required. */ @XmlAttribute(name="required") public boolean isRequired() { return isRequired; } /** * Marks this parameter as required parameter. * @param isRequired the isRequired to set */ public void setRequired(boolean isRequired) { this.isRequired = isRequired; } /** * @return description of this graph parameter * @note this attribute is not de-serialize from xml now by TransformationGraphXMLReaderWriter */ @XmlTransient public String getDescription() { return description; } /** * Sets description of this graph parameter * @param description new description of this graph parameter */ public void setDescription(String description) { this.description = description; } @XmlAttribute(name="category") public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } @XmlAttribute(name="defaultHint") public String getDefaultHint() { return defaultHint; } public void setDefaultHint(String defaultHint) { this.defaultHint = defaultHint; } @XmlElement(name="SingleType") public SingleType getSingleType() { return singleType; } /** * Returns single type of this graph parameter. Reference type definition is recursively resolved. * If no single type is defined, 'string' type is returned as default. */ public SingleType getSingleTypeRecursive() { if (singleType != null) { //single type defined return singleType; } else if (componentReference != null) { //type is defined by component reference if (getParentGraph() != null) { //graph is available Node component = getParentGraph().getNodes().get(componentReference.getComponentId()); if (component != null) { //referenced component is available if (!SubgraphUtils.isSubJobComponent(component.getType())) { //referenced component is regular component Attribute attribute = component.getDescriptor().getDescription().getAttributes().getAttribute(componentReference.getAttributeName()); if (attribute != null) { //referenced attribute found if (attribute.getSingleType() != null) { //referenced attribute is single type - let's return this single type return new SingleType(attribute.getSingleType().getName()); } else { throw new JetelRuntimeException("Graph parameter '" + getName() + "' references non-single type attribute '" + componentReference + "'."); } } else { throw new JetelRuntimeException("Graph parameter '" + getName() + "' references unknown attribute '" + componentReference + "'."); } } else { //referenced component is Subgraph component SubgraphComponent subgraphComponent = (SubgraphComponent) component; TransformationGraph subgraph = subgraphComponent.getSubgraphNoMetadataPropagation(true); String graphParameterName = SubgraphUtils.getPublicGraphParameterName(componentReference.getAttributeName()); if (subgraph.getGraphParameters().hasGraphParameter(graphParameterName)) { //referenced public subgraph parameter found GraphParameter subgraphGraphParameter = subgraph.getGraphParameters().getGraphParameter(graphParameterName); try { //recursive search of single type return subgraphGraphParameter.getSingleTypeRecursive(); } catch (Exception e) { throw new JetelRuntimeException("Graph parameter '" + getName() + "' reference resolution failed (" + componentReference + ")."); } } else { throw new JetelRuntimeException("Graph parameter '" + getName() + "' references unknown attribute '" + componentReference + "'."); } } } else { throw new JetelRuntimeException("Graph parameter '" + getName() + "' references unknown component '" + componentReference.getComponentId() + "'."); } } else { throw new JetelRuntimeException("Graph parameter '" + getName() + "' cannot provide referenced type. Unknown parent graph."); } } else { return DEFAULT_SINGLE_TYPE; } } public void setSingleType(SingleType singleType) { this.singleType = singleType; } public void setSingleType(String singleTypeName) { this.singleType = new SingleType(singleTypeName); } @XmlElement(name="ComponentReference") public ComponentReference getComponentReference() { return componentReference; } public void setComponentReference(ComponentReference componentReference) { this.componentReference = componentReference; } public void setComponentReference(String referencedComponentId, String referencedAttributeName) { this.componentReference = new ComponentReference(referencedComponentId, referencedAttributeName); } @XmlType public static class SingleType { private String name; @XmlAnyAttribute private Map<QName, String> attributes; public SingleType() { } public SingleType(String name) { this.name = name; } @XmlAttribute(name="name") public String getName() { return name; } public void setName(String name) { this.name = name; } public Map<String, String> getParameters() { Map<String, String> params = new HashMap<>(); for (Map.Entry<QName, String> attribute : attributes.entrySet()) { params.put(attribute.getKey().getLocalPart(), attribute.getValue()); } return params; } } @XmlType(propOrder = { "componentId", "attributeName" }) public static class ComponentReference { private String componentId; private String attributeName; public ComponentReference() { } public ComponentReference(String componentId, String attributeName) { this.componentId = componentId; this.attributeName = attributeName; } @XmlAttribute(name="referencedComponent") public String getComponentId() { return componentId; } public void setComponentId(String componentId) { this.componentId = componentId; } @XmlAttribute(name="referencedProperty") public String getAttributeName() { return attributeName; } public void setAttributeName(String attributeName) { this.attributeName = attributeName; } @Override public String toString() { return componentId + "." + attributeName; } } }
package org.jetel.util; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import org.jetel.data.Defaults; public class ByteBufferUtils { /** * This method flushes the buffer to the Channel and prepares it for next * reading * * @param buffer * @param writer * @return The number of bytes written, possibly zero * @throws IOException */ public static int flush(ByteBuffer buffer, WritableByteChannel writer) throws IOException { int write; if (buffer.position() != 0) { buffer.flip(); } write = writer.write(buffer); buffer.clear(); return write; } /** * This method reads new data to the buffer * * @param buffer * @param reader * @return The number of bytes written, possibly zero * @throws IOException */ public static int reload(ByteBuffer buffer, ReadableByteChannel reader) throws IOException{ int read; if (buffer.position() != 0) { buffer.compact(); } read = reader.read(buffer); buffer.flip(); return read; } /** * This method rewrites bytes from input stream to output stream * * @param in * @param out * @throws IOException */ public static void rewrite(InputStream in, OutputStream out)throws IOException{ ByteBuffer buffer = ByteBuffer.allocateDirect(Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE); ReadableByteChannel reader = Channels.newChannel(in); WritableByteChannel writer = Channels.newChannel(out); while (reload(buffer,reader) > 0){ flush(buffer, writer); } } /** * This method rewrites maximum "bytes" bytes from input stream to output stream * * @param in * @param out * @param bytes number of bytes to rewrite * @throws IOException */ public static void rewrite(InputStream in, OutputStream out, long bytes)throws IOException{ if (Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE == 0){ Defaults.init(); } ByteBuffer buffer = ByteBuffer.allocateDirect(Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE); ReadableByteChannel reader = Channels.newChannel(in); WritableByteChannel writer = Channels.newChannel(out); long b = 0; int r; while ( (r = reload(buffer,reader)) > 0 && b < bytes){ b += r; if (r == buffer.capacity()) { flush(buffer, writer); }else{ buffer.limit((int) (bytes % buffer.capacity())); flush(buffer, writer); } } } }
package dbcache.test; import dbcache.utils.NamedThreadFactory; import dbcache.utils.executors.LinkingExecutable; import dbcache.utils.executors.LinkingRunnable; import dbcache.utils.executors.OrderedThreadPoolExecutor; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicReference; public class TestOrderedExecutor { public static void main(String[] args) { ThreadGroup threadGroup = new ThreadGroup("TestOrderedExecutor"); NamedThreadFactory threadFactory = new NamedThreadFactory(threadGroup, "TestOrderedExecutor"); final IntegerRefrence i = new IntegerRefrence(0); final ExecutorService executorService = OrderedThreadPoolExecutor.newFixedThreadPool(4, threadFactory); final ExecutorService executorService1 = Executors.newFixedThreadPool(4, threadFactory); final AtomicReference<LinkingExecutable> last = new AtomicReference<LinkingExecutable>(); final int TEST_LOOP = 1000000; final CountDownLatch ct = new CountDownLatch(1); final CountDownLatch ct1 = new CountDownLatch(TEST_LOOP * 4); for (int j = 0; j < 4;j++) { new Thread() { @Override public void run() { try { ct.await(); } catch (InterruptedException e) { e.printStackTrace(); } for (int k = 0;k < TEST_LOOP;k++) { executorService.submit(new LinkingRunnable() { @Override public AtomicReference<LinkingExecutable> getLastLinkingRunnable() { return last; } @Override public void run() { int j = i.getVal(); j+=1; i.setVal(j); ct1.countDown(); } }); } } }.start(); } try { ct.countDown(); ct1.await(); System.out.println(i.getVal()); executorService.shutdownNow(); } catch (InterruptedException e) { e.printStackTrace(); } } static class IntegerRefrence { int val; public int getVal() { return val; } public void setVal(int val) { this.val = val; } public IntegerRefrence(int val) { this.val = val; } } }
package com.cloud.network.resource; import iControl.CommonEnabledState; import iControl.CommonIPPortDefinition; import iControl.CommonStatistic; import iControl.CommonStatisticType; import iControl.CommonVirtualServerDefinition; import iControl.Interfaces; import iControl.LocalLBLBMethod; import iControl.LocalLBNodeAddressBindingStub; import iControl.LocalLBPoolBindingStub; import iControl.LocalLBProfileContextType; import iControl.LocalLBVirtualServerBindingStub; import iControl.LocalLBVirtualServerVirtualServerPersistence; import iControl.LocalLBVirtualServerVirtualServerProfile; import iControl.LocalLBVirtualServerVirtualServerResource; import iControl.LocalLBVirtualServerVirtualServerStatisticEntry; import iControl.LocalLBVirtualServerVirtualServerStatistics; import iControl.LocalLBVirtualServerVirtualServerType; import iControl.NetworkingMemberTagType; import iControl.NetworkingMemberType; import iControl.NetworkingRouteDomainBindingStub; import iControl.NetworkingSelfIPBindingStub; import iControl.NetworkingVLANBindingStub; import iControl.NetworkingVLANMemberEntry; import iControl.SystemConfigSyncBindingStub; import iControl.SystemConfigSyncSaveMode; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.naming.ConfigurationException; import org.apache.log4j.Logger; import com.cloud.agent.IAgentControl; import com.cloud.agent.api.Answer; import com.cloud.agent.api.Command; import com.cloud.agent.api.ExternalNetworkResourceUsageAnswer; import com.cloud.agent.api.ExternalNetworkResourceUsageCommand; import com.cloud.agent.api.MaintainAnswer; import com.cloud.agent.api.MaintainCommand; import com.cloud.agent.api.PingCommand; import com.cloud.agent.api.ReadyAnswer; import com.cloud.agent.api.ReadyCommand; import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupExternalLoadBalancerCommand; import com.cloud.agent.api.routing.IpAssocCommand; import com.cloud.agent.api.routing.IpAssocAnswer; import com.cloud.agent.api.routing.LoadBalancerConfigCommand; import com.cloud.agent.api.routing.NetworkElementCommand; import com.cloud.agent.api.to.IpAddressTO; import com.cloud.agent.api.to.LoadBalancerTO; import com.cloud.agent.api.to.LoadBalancerTO.DestinationTO; import com.cloud.host.Host; import com.cloud.resource.ServerResource; import com.cloud.utils.NumbersUtil; import com.cloud.utils.exception.ExecutionException; import com.cloud.utils.net.NetUtils; public class F5BigIpResource implements ServerResource { private enum LbAlgorithm { RoundRobin(null, LocalLBLBMethod.LB_METHOD_ROUND_ROBIN), LeastConn(null, LocalLBLBMethod.LB_METHOD_LEAST_CONNECTION_MEMBER); String persistenceProfileName; LocalLBLBMethod method; LbAlgorithm(String persistenceProfileName, LocalLBLBMethod method) { this.persistenceProfileName = persistenceProfileName; this.method = method; } public String getPersistenceProfileName() { return persistenceProfileName; } public LocalLBLBMethod getMethod() { return method; } } private enum LbProtocol { tcp, udp; } private String _name; private String _zoneId; private String _ip; private String _username; private String _password; private String _publicInterface; private String _privateInterface; private Integer _numRetries; private String _guid; private boolean _inline; private Interfaces _interfaces; private LocalLBVirtualServerBindingStub _virtualServerApi; private LocalLBPoolBindingStub _loadbalancerApi; private LocalLBNodeAddressBindingStub _nodeApi; private NetworkingVLANBindingStub _vlanApi; private NetworkingSelfIPBindingStub _selfIpApi; private NetworkingRouteDomainBindingStub _routeDomainApi; private SystemConfigSyncBindingStub _configSyncApi; private String _objectNamePathSep = "-"; private String _routeDomainIdentifier = "%"; private static final Logger s_logger = Logger.getLogger(F5BigIpResource.class); @Override public boolean configure(String name, Map<String, Object> params) throws ConfigurationException { try { XTrustProvider.install(); _name = (String) params.get("name"); if (_name == null) { throw new ConfigurationException("Unable to find name"); } _zoneId = (String) params.get("zoneId"); if (_zoneId == null) { throw new ConfigurationException("Unable to find zone"); } _ip = (String) params.get("ip"); if (_ip == null) { throw new ConfigurationException("Unable to find IP"); } _username = (String) params.get("username"); if (_username == null) { throw new ConfigurationException("Unable to find username"); } _password = (String) params.get("password"); if (_password == null) { throw new ConfigurationException("Unable to find password"); } _publicInterface = (String) params.get("publicInterface"); if (_publicInterface == null) { throw new ConfigurationException("Unable to find public interface"); } _privateInterface = (String) params.get("privateInterface"); if (_privateInterface == null) { throw new ConfigurationException("Unable to find private interface"); } _numRetries = NumbersUtil.parseInt((String) params.get("numRetries"), 1); _guid = (String)params.get("guid"); if (_guid == null) { throw new ConfigurationException("Unable to find the guid"); } _inline = Boolean.parseBoolean((String) params.get("inline")); if (!login()) { throw new ExecutionException("Failed to login to the F5 BigIp."); } return true; } catch (Exception e) { throw new ConfigurationException(e.getMessage()); } } @Override public StartupCommand[] initialize() { StartupExternalLoadBalancerCommand cmd = new StartupExternalLoadBalancerCommand(); cmd.setName(_name); cmd.setDataCenter(_zoneId); cmd.setPod(""); cmd.setPrivateIpAddress(_ip); cmd.setStorageIpAddress(""); cmd.setVersion(""); cmd.setGuid(_guid); return new StartupCommand[]{cmd}; } @Override public Host.Type getType() { return Host.Type.ExternalLoadBalancer; } @Override public String getName() { return _name; } @Override public PingCommand getCurrentStatus(final long id) { return new PingCommand(Host.Type.ExternalLoadBalancer, id); } @Override public boolean start() { return true; } @Override public boolean stop() { return true; } @Override public void disconnected() { return; } @Override public IAgentControl getAgentControl() { return null; } @Override public void setAgentControl(IAgentControl agentControl) { return; } @Override public Answer executeRequest(Command cmd) { return executeRequest(cmd, _numRetries); } private Answer executeRequest(Command cmd, int numRetries) { if (cmd instanceof ReadyCommand) { return execute((ReadyCommand) cmd); } else if (cmd instanceof MaintainCommand) { return execute((MaintainCommand) cmd); } else if (cmd instanceof IpAssocCommand) { return execute((IpAssocCommand) cmd, numRetries); } else if (cmd instanceof LoadBalancerConfigCommand) { return execute((LoadBalancerConfigCommand) cmd, numRetries); } else if (cmd instanceof ExternalNetworkResourceUsageCommand) { return execute((ExternalNetworkResourceUsageCommand) cmd); } else { return Answer.createUnsupportedCommandAnswer(cmd); } } private Answer retry(Command cmd, int numRetries) { int numRetriesRemaining = numRetries - 1; s_logger.error("Retrying " + cmd.getClass().getSimpleName() + ". Number of retries remaining: " + numRetriesRemaining); return executeRequest(cmd, numRetriesRemaining); } private boolean shouldRetry(int numRetries) { return (numRetries > 0 && login()); } private Answer execute(ReadyCommand cmd) { return new ReadyAnswer(cmd); } private Answer execute(MaintainCommand cmd) { return new MaintainAnswer(cmd); } private synchronized Answer execute(IpAssocCommand cmd, int numRetries) { String[] results = new String[cmd.getIpAddresses().length]; int i = 0; try { IpAddressTO[] ips = cmd.getIpAddresses(); for (IpAddressTO ip : ips) { long guestVlanTag = Long.valueOf(ip.getVlanId()); String vlanSelfIp = _inline ? tagAddressWithRouteDomain(ip.getVlanGateway(), guestVlanTag) : ip.getVlanGateway(); String vlanNetmask = ip.getVlanNetmask(); // Delete any existing guest VLAN with this tag, self IP, and netmask deleteGuestVlan(guestVlanTag, vlanSelfIp, vlanNetmask); if (ip.isAdd()) { // Add a new guest VLAN addGuestVlan(guestVlanTag, vlanSelfIp, vlanNetmask); } saveConfiguration(); results[i++] = ip.getPublicIp() + " - success"; } } catch (ExecutionException e) { s_logger.error("Failed to execute IPAssocCommand due to " + e); if (shouldRetry(numRetries)) { return retry(cmd, numRetries); } else { results[i++] = IpAssocAnswer.errorResult; } } return new IpAssocAnswer(cmd, results); } private synchronized Answer execute(LoadBalancerConfigCommand cmd, int numRetries) { try { long guestVlanTag = Long.parseLong(cmd.getAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG)); LoadBalancerTO[] loadBalancers = cmd.getLoadBalancers(); for (LoadBalancerTO loadBalancer : loadBalancers) { LbProtocol lbProtocol; try { if (loadBalancer.getProtocol() == null) { lbProtocol = LbProtocol.tcp; } else { lbProtocol = LbProtocol.valueOf(loadBalancer.getProtocol()); } } catch (IllegalArgumentException e) { throw new ExecutionException("Got invalid protocol: " + loadBalancer.getProtocol()); } LbAlgorithm lbAlgorithm; if (loadBalancer.getAlgorithm().equals("roundrobin")) { lbAlgorithm = LbAlgorithm.RoundRobin; } else if (loadBalancer.getAlgorithm().equals("leastconn")) { lbAlgorithm = LbAlgorithm.LeastConn; } else { throw new ExecutionException("Got invalid algorithm: " + loadBalancer.getAlgorithm()); } String srcIp = _inline ? tagAddressWithRouteDomain(loadBalancer.getSrcIp(), guestVlanTag) : loadBalancer.getSrcIp(); int srcPort = loadBalancer.getSrcPort(); String virtualServerName = genVirtualServerName(lbProtocol, srcIp, srcPort); boolean destinationsToAdd = false; for (DestinationTO destination : loadBalancer.getDestinations()) { if (!destination.isRevoked()) { destinationsToAdd = true; break; } } if (!loadBalancer.isRevoked() && destinationsToAdd) { // Add the pool addPool(virtualServerName, lbAlgorithm); // Add pool members List<String> activePoolMembers = new ArrayList<String>(); for (DestinationTO destination : loadBalancer.getDestinations()) { if (!destination.isRevoked()) { String destIp = _inline ? tagAddressWithRouteDomain(destination.getDestIp(), guestVlanTag) : destination.getDestIp(); addPoolMember(virtualServerName, destIp, destination.getDestPort()); activePoolMembers.add(destIp + "-" + destination.getDestPort()); } } // Delete any pool members that aren't in the current list of destinations deleteInactivePoolMembers(virtualServerName, activePoolMembers); // Add the virtual server addVirtualServer(virtualServerName, lbProtocol, srcIp, srcPort); } else { // Delete the virtual server with this protocol, source IP, and source port, along with its default pool and all pool members deleteVirtualServerAndDefaultPool(virtualServerName); } } saveConfiguration(); return new Answer(cmd); } catch (ExecutionException e) { s_logger.error("Failed to execute LoadBalancerConfigCommand due to " + e); if (shouldRetry(numRetries)) { return retry(cmd, numRetries); } else { return new Answer(cmd, e); } } } private synchronized ExternalNetworkResourceUsageAnswer execute(ExternalNetworkResourceUsageCommand cmd) { try { return getIpBytesSentAndReceived(cmd); } catch (ExecutionException e) { return new ExternalNetworkResourceUsageAnswer(cmd, e); } } private void saveConfiguration() throws ExecutionException { try { _configSyncApi.save_configuration("", SystemConfigSyncSaveMode.SAVE_BASE_LEVEL_CONFIG); _configSyncApi.save_configuration("", SystemConfigSyncSaveMode.SAVE_HIGH_LEVEL_CONFIG); s_logger.debug("Successfully saved F5 BigIp configuration."); } catch (RemoteException e) { s_logger.error("Failed to save F5 BigIp configuration due to: " + e); throw new ExecutionException(e.getMessage()); } } private void addGuestVlan(long vlanTag, String vlanSelfIp, String vlanNetmask) throws ExecutionException { try { String vlanName = genVlanName(vlanTag); List<String> allVlans = getVlans(); if (!allVlans.contains(vlanName)) { String[] vlanNames = genStringArray(vlanName); long[] vlanTags = genLongArray(vlanTag); CommonEnabledState[] commonEnabledState = {CommonEnabledState.STATE_DISABLED}; // Create the interface name NetworkingVLANMemberEntry[][] vlanMemberEntries = {{new NetworkingVLANMemberEntry()}}; vlanMemberEntries[0][0].setMember_type(NetworkingMemberType.MEMBER_INTERFACE); vlanMemberEntries[0][0].setTag_state(NetworkingMemberTagType.MEMBER_TAGGED); vlanMemberEntries[0][0].setMember_name(_privateInterface); s_logger.debug("Creating a guest VLAN with tag " + vlanTag); _vlanApi.create(vlanNames, vlanTags, vlanMemberEntries, commonEnabledState, new long[]{10L}, new String[]{"00:00:00:00:00:00"}); if (!getVlans().contains(vlanName)) { throw new ExecutionException("Failed to create vlan with tag " + vlanTag); } } if (_inline) { List<Long> allRouteDomains = getRouteDomains(); if (!allRouteDomains.contains(vlanTag)) { long[] routeDomainIds = genLongArray(vlanTag); String[][] vlanNames = new String[][]{genStringArray(genVlanName(vlanTag))}; s_logger.debug("Creating route domain " + vlanTag); _routeDomainApi.create(routeDomainIds, vlanNames); if (!getRouteDomains().contains(vlanTag)) { throw new ExecutionException("Failed to create route domain " + vlanTag); } } } List<String> allSelfIps = getSelfIps(); if (!allSelfIps.contains(vlanSelfIp)) { String[] selfIpsToCreate = genStringArray(vlanSelfIp); String[] vlans = genStringArray(vlanName); String[] netmasks = genStringArray(vlanNetmask); long[] unitIds = genLongArray(0L); CommonEnabledState[] enabledStates = new CommonEnabledState[]{CommonEnabledState.STATE_DISABLED}; s_logger.debug("Creating self IP " + vlanSelfIp); _selfIpApi.create(selfIpsToCreate, vlans, netmasks, unitIds, enabledStates); if (!getSelfIps().contains(vlanSelfIp)) { throw new ExecutionException("Failed to create self IP " + vlanSelfIp); } } } catch (RemoteException e) { s_logger.error(e); throw new ExecutionException(e.getMessage()); } } private void deleteGuestVlan(long vlanTag, String vlanSelfIp, String vlanNetmask) throws ExecutionException { try { // Delete all virtual servers and pools that use this guest VLAN deleteVirtualServersInGuestVlan(vlanSelfIp, vlanNetmask); List<String> allSelfIps = getSelfIps(); if (allSelfIps.contains(vlanSelfIp)) { s_logger.debug("Deleting self IP " + vlanSelfIp); _selfIpApi.delete_self_ip(genStringArray(vlanSelfIp)); if (getSelfIps().contains(vlanSelfIp)) { throw new ExecutionException("Failed to delete self IP " + vlanSelfIp); } } if (_inline) { List<Long> allRouteDomains = getRouteDomains(); if (allRouteDomains.contains(vlanTag)) { s_logger.debug("Deleting route domain " + vlanTag); _routeDomainApi.delete_route_domain(genLongArray(vlanTag)); if (getRouteDomains().contains(vlanTag)) { throw new ExecutionException("Failed to delete route domain " + vlanTag); } } } String vlanName = genVlanName(vlanTag); List<String> allVlans = getVlans(); if (allVlans.contains(vlanName)) { _vlanApi.delete_vlan(genStringArray(vlanName)); if (getVlans().contains(vlanName)) { throw new ExecutionException("Failed to delete VLAN with tag: " + vlanTag); } } } catch (RemoteException e) { throw new ExecutionException(e.getMessage()); } } private void deleteVirtualServersInGuestVlan(String vlanSelfIp, String vlanNetmask) throws ExecutionException { vlanSelfIp = stripRouteDomainFromAddress(vlanSelfIp); List<String> virtualServersToDelete = new ArrayList<String>(); List<String> allVirtualServers = getVirtualServers(); for (String virtualServerName : allVirtualServers) { // Check if the virtual server's default pool has members in this guest VLAN List<String> poolMembers = getMembers(virtualServerName); for (String poolMemberName : poolMembers) { String poolMemberIp = stripRouteDomainFromAddress(getIpAndPort(poolMemberName)[0]); if (NetUtils.sameSubnet(vlanSelfIp, poolMemberIp, vlanNetmask)) { virtualServersToDelete.add(virtualServerName); break; } } } for (String virtualServerName : virtualServersToDelete) { s_logger.debug("Found a virtual server (" + virtualServerName + ") for guest network with self IP " + vlanSelfIp + " that is active when the guest network is being destroyed."); deleteVirtualServerAndDefaultPool(virtualServerName); } } private String genVlanName(long vlanTag) { return "vlan-" + String.valueOf(vlanTag); } private List<Long> getRouteDomains() throws ExecutionException { try { List<Long> routeDomains = new ArrayList<Long>(); long[] routeDomainsArray = _routeDomainApi.get_list(); for (long routeDomainName : routeDomainsArray) { routeDomains.add(routeDomainName); } return routeDomains; } catch (RemoteException e) { throw new ExecutionException(e.getMessage()); } } private List<String> getSelfIps() throws ExecutionException { try { List<String> selfIps = new ArrayList<String>(); String[] selfIpsArray = _selfIpApi.get_list(); for (String selfIp : selfIpsArray) { selfIps.add(selfIp); } return selfIps; } catch (RemoteException e) { throw new ExecutionException(e.getMessage()); } } private List<String> getVlans() throws ExecutionException { try { List<String> vlans = new ArrayList<String>(); String[] vlansArray = _vlanApi.get_list(); for (String vlan : vlansArray) { vlans.add(vlan); } return vlans; } catch (RemoteException e) { throw new ExecutionException(e.getMessage()); } } // Login private boolean login() { try { _interfaces = new Interfaces(); if (!_interfaces.initialize(_ip, _username, _password)) { throw new ExecutionException("Failed to log in to BigIp appliance"); } _virtualServerApi = _interfaces.getLocalLBVirtualServer(); _loadbalancerApi = _interfaces.getLocalLBPool(); _nodeApi = _interfaces.getLocalLBNodeAddress(); _vlanApi = _interfaces.getNetworkingVLAN(); _selfIpApi = _interfaces.getNetworkingSelfIP(); _routeDomainApi = _interfaces.getNetworkingRouteDomain(); _configSyncApi = _interfaces.getSystemConfigSync(); return true; } catch (Exception e) { return false; } } // Virtual server methods private void addVirtualServer(String virtualServerName, LbProtocol protocol, String srcIp, int srcPort) throws ExecutionException { try { if (!virtualServerExists(virtualServerName)) { s_logger.debug("Adding virtual server " + virtualServerName); _virtualServerApi.create(genVirtualServerDefinition(virtualServerName, protocol, srcIp, srcPort), new String[]{"255.255.255.255"}, genVirtualServerResource(virtualServerName), genVirtualServerProfile(protocol)); _virtualServerApi.set_snat_automap(genStringArray(virtualServerName)); if (!virtualServerExists(virtualServerName)) { throw new ExecutionException("Failed to add virtual server " + virtualServerName); } } } catch (RemoteException e) { throw new ExecutionException(e.getMessage()); } } private void deleteVirtualServerAndDefaultPool(String virtualServerName) throws ExecutionException { try { if (virtualServerExists(virtualServerName)) { // Delete the default pool's members List<String> poolMembers = getMembers(virtualServerName); for (String poolMember : poolMembers) { String[] destIpAndPort = getIpAndPort(poolMember); deletePoolMember(virtualServerName, destIpAndPort[0], Integer.valueOf(destIpAndPort[1])); } // Delete the virtual server s_logger.debug("Deleting virtual server " + virtualServerName); _virtualServerApi.delete_virtual_server(genStringArray(virtualServerName)); if (getVirtualServers().contains(virtualServerName)) { throw new ExecutionException("Failed to delete virtual server " + virtualServerName); } // Delete the default pool deletePool(virtualServerName); } } catch (RemoteException e) { throw new ExecutionException(e.getMessage()); } } private String genVirtualServerName(LbProtocol protocol, String srcIp, long srcPort) { srcIp = stripRouteDomainFromAddress(srcIp); return genObjectName("vs", protocol, srcIp, srcPort); } private boolean virtualServerExists(String virtualServerName) throws ExecutionException { return getVirtualServers().contains(virtualServerName); } private List<String> getVirtualServers() throws ExecutionException { try { List<String> virtualServers = new ArrayList<String>(); String[] virtualServersArray = _virtualServerApi.get_list(); for (String virtualServer : virtualServersArray) { virtualServers.add(virtualServer); } return virtualServers; } catch (RemoteException e) { throw new ExecutionException(e.getMessage()); } } private iControl.CommonVirtualServerDefinition[] genVirtualServerDefinition(String name, LbProtocol protocol, String srcIp, long srcPort) { CommonVirtualServerDefinition vsDefs[] = {new CommonVirtualServerDefinition()}; vsDefs[0].setName(name); vsDefs[0].setAddress(srcIp); vsDefs[0].setPort(srcPort); if (protocol.equals(LbProtocol.tcp)) { vsDefs[0].setProtocol(iControl.CommonProtocolType.PROTOCOL_TCP); } else if (protocol.equals(LbProtocol.udp)) { vsDefs[0].setProtocol(iControl.CommonProtocolType.PROTOCOL_UDP); } return vsDefs; } private iControl.LocalLBVirtualServerVirtualServerResource[] genVirtualServerResource(String poolName) { LocalLBVirtualServerVirtualServerResource vsRes[] = {new LocalLBVirtualServerVirtualServerResource()}; vsRes[0].setType(LocalLBVirtualServerVirtualServerType.RESOURCE_TYPE_POOL); vsRes[0].setDefault_pool_name(poolName); return vsRes; } private LocalLBVirtualServerVirtualServerProfile[][] genVirtualServerProfile(LbProtocol protocol) { LocalLBVirtualServerVirtualServerProfile vsProfs[][] = {{new LocalLBVirtualServerVirtualServerProfile()}}; vsProfs[0][0].setProfile_context(LocalLBProfileContextType.PROFILE_CONTEXT_TYPE_ALL); if (protocol.equals(LbProtocol.tcp)) { vsProfs[0][0].setProfile_name("http"); } else if (protocol.equals(LbProtocol.udp)) { vsProfs[0][0].setProfile_name("udp"); } return vsProfs; } private LocalLBVirtualServerVirtualServerPersistence[][] genPersistenceProfile(String persistenceProfileName) { LocalLBVirtualServerVirtualServerPersistence[][] persistenceProfs = {{new LocalLBVirtualServerVirtualServerPersistence()}}; persistenceProfs[0][0].setDefault_profile(true); persistenceProfs[0][0].setProfile_name(persistenceProfileName); return persistenceProfs; } // Load balancing pool methods private void addPool(String virtualServerName, LbAlgorithm algorithm) throws ExecutionException { try { if (!poolExists(virtualServerName)) { if (algorithm.getPersistenceProfileName() != null) { algorithm = LbAlgorithm.RoundRobin; } s_logger.debug("Adding pool for virtual server " + virtualServerName + " with algorithm " + algorithm); _loadbalancerApi.create(genStringArray(virtualServerName), genLbMethod(algorithm), genEmptyMembersArray()); if (!poolExists(virtualServerName)) { throw new ExecutionException("Failed to create new pool for virtual server " + virtualServerName); } } } catch (RemoteException e) { throw new ExecutionException(e.getMessage()); } } private void deletePool(String virtualServerName) throws ExecutionException { try { if (poolExists(virtualServerName) && getMembers(virtualServerName).size() == 0) { s_logger.debug("Deleting pool for virtual server " + virtualServerName); _loadbalancerApi.delete_pool(genStringArray(virtualServerName)); if (poolExists(virtualServerName)) { throw new ExecutionException("Failed to delete pool for virtual server " + virtualServerName); } } } catch (RemoteException e) { throw new ExecutionException(e.getMessage()); } } private void addPoolMember(String virtualServerName, String destIp, int destPort) throws ExecutionException { try { String memberIdentifier = destIp + "-" + destPort; if (poolExists(virtualServerName) && !memberExists(virtualServerName, memberIdentifier)) { s_logger.debug("Adding member " + memberIdentifier + " into pool for virtual server " + virtualServerName); _loadbalancerApi.add_member(genStringArray(virtualServerName), genMembers(destIp, destPort)); if (!memberExists(virtualServerName, memberIdentifier)) { throw new ExecutionException("Failed to add new member " + memberIdentifier + " into pool for virtual server " + virtualServerName); } } } catch (RemoteException e) { throw new ExecutionException(e.getMessage()); } } private void deleteInactivePoolMembers(String virtualServerName, List<String> activePoolMembers) throws ExecutionException { List<String> allPoolMembers = getMembers(virtualServerName); for (String member : allPoolMembers) { if (!activePoolMembers.contains(member)) { String[] ipAndPort = member.split("-"); deletePoolMember(virtualServerName, ipAndPort[0], Integer.valueOf(ipAndPort[1])); } } } private void deletePoolMember(String virtualServerName, String destIp, int destPort) throws ExecutionException { try { String memberIdentifier = destIp + "-" + destPort; List<String> lbPools = getAllLbPools(); if (lbPools.contains(virtualServerName) && memberExists(virtualServerName, memberIdentifier)) { s_logger.debug("Deleting member " + memberIdentifier + " from pool for virtual server " + virtualServerName); _loadbalancerApi.remove_member(genStringArray(virtualServerName), genMembers(destIp, destPort)); if (memberExists(virtualServerName, memberIdentifier)) { throw new ExecutionException("Failed to delete member " + memberIdentifier + " from pool for virtual server " + virtualServerName); } if (nodeExists(destIp)) { boolean nodeNeeded = false; done: for (String poolToCheck : lbPools) { for (String memberInPool : getMembers(poolToCheck)) { if (getIpAndPort(memberInPool)[0].equals(destIp)) { nodeNeeded = true; break done; } } } if (!nodeNeeded) { s_logger.debug("Deleting node " + destIp); _nodeApi.delete_node_address(genStringArray(destIp)); if (nodeExists(destIp)) { throw new ExecutionException("Failed to delete node " + destIp); } } } } } catch (RemoteException e) { throw new ExecutionException(e.getMessage()); } } private boolean poolExists(String poolName) throws ExecutionException { return getAllLbPools().contains(poolName); } private boolean memberExists(String poolName, String memberIdentifier) throws ExecutionException { return getMembers(poolName).contains(memberIdentifier); } private boolean nodeExists(String destIp) throws RemoteException { return getNodes().contains(destIp); } private String[] getIpAndPort(String memberIdentifier) { return memberIdentifier.split("-"); } public List<String> getAllLbPools() throws ExecutionException { try { List<String> lbPools = new ArrayList<String>(); String[] pools = _loadbalancerApi.get_list(); for (String pool : pools) { lbPools.add(pool); } return lbPools; } catch (RemoteException e) { throw new ExecutionException(e.getMessage()); } } private List<String> getMembers(String virtualServerName) throws ExecutionException { try { List<String> members = new ArrayList<String>(); String[] virtualServerNames = genStringArray(virtualServerName); CommonIPPortDefinition[] membersArray = _loadbalancerApi.get_member(virtualServerNames)[0]; for (CommonIPPortDefinition member : membersArray) { members.add(member.getAddress() + "-" + member.getPort()); } return members; } catch (RemoteException e) { throw new ExecutionException(e.getMessage()); } } private List<String> getNodes() throws RemoteException { List<String> nodes = new ArrayList<String>(); String[] nodesArray = _nodeApi.get_list(); for (String node : nodesArray) { nodes.add(node); } return nodes; } private iControl.CommonIPPortDefinition[][] genMembers(String destIp, long destPort) { iControl.CommonIPPortDefinition[] membersInnerArray = new iControl.CommonIPPortDefinition[1]; membersInnerArray[0] = new iControl.CommonIPPortDefinition(destIp, destPort); return new iControl.CommonIPPortDefinition[][]{membersInnerArray}; } private iControl.CommonIPPortDefinition[][] genEmptyMembersArray() { iControl.CommonIPPortDefinition[] membersInnerArray = new iControl.CommonIPPortDefinition[0]; return new iControl.CommonIPPortDefinition[][]{membersInnerArray}; } private LocalLBLBMethod[] genLbMethod(LbAlgorithm algorithm) { if (algorithm.getMethod() != null) { return new LocalLBLBMethod[]{algorithm.getMethod()}; } else { return new LocalLBLBMethod[]{LbAlgorithm.RoundRobin.getMethod()}; } } // Stats methods private ExternalNetworkResourceUsageAnswer getIpBytesSentAndReceived(ExternalNetworkResourceUsageCommand cmd) throws ExecutionException { ExternalNetworkResourceUsageAnswer answer = new ExternalNetworkResourceUsageAnswer(cmd); try { LocalLBVirtualServerVirtualServerStatistics stats = _virtualServerApi.get_all_statistics(); for (LocalLBVirtualServerVirtualServerStatisticEntry entry : stats.getStatistics()) { String virtualServerIp = entry.getVirtual_server().getAddress(); if (_inline) { virtualServerIp = stripRouteDomainFromAddress(virtualServerIp); } long[] bytesSentAndReceived = answer.ipBytes.get(virtualServerIp); if (bytesSentAndReceived == null) { bytesSentAndReceived = new long[]{0, 0}; } for (CommonStatistic stat : entry.getStatistics()) { int index; if (stat.getType().equals(CommonStatisticType.STATISTIC_CLIENT_SIDE_BYTES_OUT)) { // Add to the outgoing bytes index = 0; } else if (stat.getType().equals(CommonStatisticType.STATISTIC_CLIENT_SIDE_BYTES_IN)) { // Add to the incoming bytes index = 1; } else { continue; } long high = stat.getValue().getHigh() & 0x0000ffff; long low = stat.getValue().getLow() & 0x0000ffff; long full = (high << 32) | low; bytesSentAndReceived[index] += full; } if (bytesSentAndReceived[0] >= 0 && bytesSentAndReceived[1] >= 0) { answer.ipBytes.put(virtualServerIp, bytesSentAndReceived); } } } catch (Exception e) { s_logger.error(e); throw new ExecutionException(e.getMessage()); } return answer; } // Misc methods private String tagAddressWithRouteDomain(String address, long vlanTag) { return address + _routeDomainIdentifier + vlanTag; } private String stripRouteDomainFromAddress(String address) { int i = address.indexOf(_routeDomainIdentifier); if (i > 0) { address = address.substring(0, i); } return address; } private String genObjectName(Object... args) { String objectName = ""; for (int i = 0; i < args.length; i++) { objectName += args[i]; if (i != args.length -1) { objectName += _objectNamePathSep; } } return objectName; } private long[] genLongArray(long l) { return new long[]{l}; } private static String[] genStringArray(String s) { return new String[]{s}; } }
package de.longri.cachebox3.gui.stages; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.g2d.GlyphLayout; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.actions.Actions; import com.badlogic.gdx.scenes.scene2d.ui.Button; import com.badlogic.gdx.scenes.scene2d.utils.Drawable; import com.badlogic.gdx.utils.Align; import com.kotcrab.vis.ui.widget.VisLabel; import de.longri.cachebox3.CB; import de.longri.cachebox3.CacheboxMain; import de.longri.cachebox3.gui.actions.*; import de.longri.cachebox3.gui.actions.show_vies.*; import de.longri.cachebox3.gui.events.SelectedCacheEvent; import de.longri.cachebox3.gui.events.SelectedCacheEventList; import de.longri.cachebox3.gui.views.AboutView; import de.longri.cachebox3.gui.views.AbstractView; import de.longri.cachebox3.gui.views.Slider; import de.longri.cachebox3.gui.widgets.ActionButton; import de.longri.cachebox3.gui.widgets.ActionButton.GestureDirection; import de.longri.cachebox3.gui.widgets.ButtonBar; import de.longri.cachebox3.gui.widgets.GestureButton; import de.longri.cachebox3.types.Cache; import de.longri.cachebox3.types.CacheSizes; import de.longri.cachebox3.types.CacheTypes; import de.longri.cachebox3.types.Waypoint; import org.slf4j.LoggerFactory; import static com.badlogic.gdx.scenes.scene2d.actions.Actions.sequence; public class ViewManager extends NamedStage implements SelectedCacheEvent { final static org.slf4j.Logger log = LoggerFactory.getLogger(ViewManager.class); private AbstractView actView; private final float width, height; private final ButtonBar mainButtonBar; private GestureButton db_button, cache_button, navButton, tool_button, misc_button; private VisLabel toastLabel; private Slider slider; public ViewManager(CacheboxMain main) { super("ViewManager"); Gdx.app.log("ScaleFactor", Float.toString(CB.getScaledFloat(1))); Gdx.app.log("Width", Float.toString(Gdx.graphics.getWidth())); Gdx.app.log("Height", Float.toString(Gdx.graphics.getHeight())); Gdx.app.log("PPI", Float.toString(Gdx.graphics.getPpiX())); //set this to static CB for global access CB.viewmanager = this; width = Gdx.graphics.getWidth(); height = Gdx.graphics.getHeight(); slider = new Slider(); slider.setBounds(0, 0, width, height); this.addActor(slider); db_button = new GestureButton("db"); cache_button = new GestureButton("cache"); navButton = new GestureButton("nav"); tool_button = new GestureButton("tool"); misc_button = new GestureButton("misc"); mainButtonBar = new ButtonBar(CB.getSkin().get("main_button_bar", ButtonBar.ButtonBarStyle.class), ButtonBar.Type.DISTRIBUTED); mainButtonBar.addButton(db_button); mainButtonBar.addButton(cache_button); mainButtonBar.addButton(navButton); mainButtonBar.addButton(tool_button); mainButtonBar.addButton(misc_button); mainButtonBar.setBounds(0, 0, width, mainButtonBar.getPrefHeight()); this.addActor(mainButtonBar); mainButtonBar.layout(); initialActionButtons(); showView(new AboutView()); //register SelectedCacheChangedEvent SelectedCacheEventList.Add(this); //set selected Cache to slider selectedCacheChanged(CB.getSelectedCache(), CB.getSelectedWaypoint()); // set position of MapScaleBar main.setMapScaleBarOffset(CB.scaledSizes.MARGIN, mainButtonBar.getHeight()); } @Override public void selectedCacheChanged(Cache selectedCache, Waypoint waypoint) { // set Cache name to Slider CharSequence text = CacheTypes.toShortString(selectedCache) + terrDiffToShortString(selectedCache.getDifficulty()) + "/" + terrDiffToShortString(selectedCache.getTerrain()) + CacheSizes.toShortString(selectedCache) + " " + selectedCache.getName(); slider.setCacheName(text); } private String terrDiffToShortString(float value) { int intValue = (int) value; String retValue; if (value == intValue) { retValue = "" + intValue; } else { retValue = "" + value; } return retValue; } public void showView(AbstractView view) { log.debug("show view:" + view.getName()); if (actView != null) { log.debug("remove and dispose actView" + actView.getName()); this.getRoot().removeActor(actView); actView.onHide(); actView.dispose(); } this.actView = view; this.addActor(view); setActViewBounds(); log.debug("reload view state:" + view.getName()); this.actView.onShow(); //bring ButtonBar to Front mainButtonBar.toFront(); // and over all the slider slider.toFront(); //select main button boolean buttonFound = false; for (Button button : mainButtonBar.getButtons()) { GestureButton gestureButton = (GestureButton) button; gestureButton.setChecked(false); if (!buttonFound) { for (ActionButton actionButton : gestureButton.getButtonActions()) { if (actionButton.getAction() instanceof Abstract_Action_ShowView) { Abstract_Action_ShowView viewAction = (Abstract_Action_ShowView) actionButton.getAction(); if (viewAction.viewTypeEquals(this.actView)) { gestureButton.setChecked(true); gestureButton.setHasContextMenu(viewAction.hasContextMenu()); buttonFound = true; break; } } } } } } private void initialActionButtons() { // assign the actions to the buttons db_button.addAction(new ActionButton(new de.longri.cachebox3.gui.actions.show_vies.Action_Show_CacheList(), true, GestureDirection.Up)); db_button.addAction(new ActionButton(new de.longri.cachebox3.gui.actions.show_vies.Action_Show_TrackableListView(), false, GestureDirection.Right)); db_button.addAction(new ActionButton(new de.longri.cachebox3.gui.actions.show_vies.Action_Show_TrackListView(), false, GestureDirection.Down)); // mDescriptionButtonOnLeftTab.addAction(new CB_ActionButton(actionShowDescriptionView, true, GestureDirection.Up)); // mDescriptionButtonOnLeftTab.addAction(new CB_ActionButton(actionShowWaypointView, false, GestureDirection.Right)); // mDescriptionButtonOnLeftTab.addAction(new CB_ActionButton(actionShowLogView, false, GestureDirection.Down)); // mDescriptionButtonOnLeftTab.addAction(new CB_ActionButton(actionShowHint, false)); // mDescriptionButtonOnLeftTab.addAction(new CB_ActionButton(actionShowDescExt, false)); // mDescriptionButtonOnLeftTab.addAction(new CB_ActionButton(actionShowSpoilerView, false)); // mDescriptionButtonOnLeftTab.addAction(new CB_ActionButton(actionShowNotesView, false)); navButton.addAction(new ActionButton(new Action_Show_MapView(), true, GestureDirection.Up)); navButton.addAction(new ActionButton(new Action_Show_CompassView(), false, GestureDirection.Right)); navButton.addAction(new ActionButton(new Action_NavigateExt(), false, GestureDirection.Down)); navButton.addAction(new ActionButton(new Action_NavigateInt(), false, GestureDirection.Left)); if (CB.isTestVersion()) navButton.addAction(new ActionButton(new Action_Show_TestView(), false)); // mToolsButtonOnLeftTab.addAction(new CB_ActionButton(actionQuickFieldNote, false, GestureDirection.Up)); // mToolsButtonOnLeftTab.addAction(new CB_ActionButton(actionShowFieldNotesView, Config.ShowFieldnotesAsDefaultView.getValue())); // mToolsButtonOnLeftTab.addAction(new CB_ActionButton(actionRecTrack, false)); // mToolsButtonOnLeftTab.addAction(new CB_ActionButton(actionRecVoice, false)); // mToolsButtonOnLeftTab.addAction(new CB_ActionButton(actionRecPicture, false, GestureDirection.Down)); // mToolsButtonOnLeftTab.addAction(new CB_ActionButton(actionRecVideo, false)); // mToolsButtonOnLeftTab.addAction(new CB_ActionButton(actionParking, false)); // mToolsButtonOnLeftTab.addAction(new CB_ActionButton(actionShowSolverView, false, GestureDirection.Left)); // mToolsButtonOnLeftTab.addAction(new CB_ActionButton(actionShowSolverView2, false, GestureDirection.Right)); tool_button.addAction(new ActionButton(new Action_Show_Quit(), true)); misc_button.addAction(new ActionButton(new Action_Show_AboutView(), true, GestureDirection.Up)); misc_button.addAction(new ActionButton(new Action_Show_Credits(), false)); misc_button.addAction(new ActionButton(new de.longri.cachebox3.gui.actions.show_activities.Action_Show_Settings(), false, GestureDirection.Left)); misc_button.addAction(new ActionButton(new Action_Toggle_Day_Night(), false)); misc_button.addAction(new ActionButton(new Action_Show_Help(), false)); misc_button.addAction(new ActionButton(new Action_Show_Quit(), false, GestureDirection.Down)); // actionShowAboutView.execute(); } private void setActViewBounds() { this.actView.setBounds(0, mainButtonBar.getHeight(), width, height - mainButtonBar.getHeight()); } public AbstractView getActView() { return actView; } // Toast pop up public enum ToastLength { SHORT(1.0f), NORMAL(1.5f), LONG(3.5f); public final float value; ToastLength(float value) { this.value = value; } } public void toast(String massage) { toast(massage, ToastLength.NORMAL); } public void toast(String massage, ToastLength length) { if (toastLabel == null) { //initial ToastLabel toastLabel = new VisLabel(massage, "toast"); } toastLabel.setAlignment(Align.center, Align.center); toastLabel.setWrap(true); toastLabel.setText(massage); Drawable labelBackground = toastLabel.getStyle().background; float border = 0; if (labelBackground != null) { border = labelBackground.getLeftWidth() + toastLabel.getStyle().background.getRightWidth() + CB.scaledSizes.MARGINx2; } GlyphLayout bounds = toastLabel.getStyle().font.newFontCache().setText(massage, 0, 0, CB.scaledSizes.WINDOW_WIDTH - border, 0, true); toastLabel.setWidth(bounds.width + border); toastLabel.setHeight(bounds.height + border); toastLabel.setPosition((Gdx.graphics.getWidth() / 2) - (toastLabel.getWidth() / 2), mainButtonBar.getTop() + CB.scaledSizes.MARGINx2); toast(toastLabel, length); } public void toast(final Actor actor, ToastLength length) { StageManager.addToastActor(actor); actor.addAction(sequence(Actions.alpha(0), Actions.fadeIn(CB.WINDOW_FADE_TIME, Interpolation.fade))); new com.badlogic.gdx.utils.Timer().scheduleTask(new com.badlogic.gdx.utils.Timer.Task() { @Override public void run() { actor.addAction(sequence(Actions.fadeOut(CB.WINDOW_FADE_TIME, Interpolation.fade), Actions.removeActor())); } }, length.value); } }
package com.mcxiaoke.next.utils; import android.content.Context; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; import android.util.Log; import com.mcxiaoke.next.Charsets; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Map; public final class LogUtils { /** * LOG * */ public static final int LEVEL_OFF = Integer.MAX_VALUE; public static final String TAG_DEBUG = "DEBUG"; public static final String TAG_TRACE = "TRACE"; private static final String FILE_LOG_DIR = "logs"; private static Map<String, Long> sTraceMap = new HashMap<String, Long>(); private static FileLogger sFileLogger; // logERRORfile log private static int sLoggingLevel = Log.ERROR; private static int sFileLoggingLevel = Log.ASSERT; private LogUtils() { } private static boolean isLoggable(int level) { return level >= sLoggingLevel; } public static void setLevel(int level) { sLoggingLevel = level; } public static void setFileLoggingLevel(Context appContext, int level) { sFileLoggingLevel = level; openFileLogger(appContext); } public static void e(String tag, Throwable e) { if (isLoggable(Log.ERROR)) { Log.e(tag, "", e); } } public static void e(String tag, String message) { if (isLoggable(Log.ERROR)) { Log.e(tag, message); } } public static void w(String tag, String message) { if (isLoggable(Log.WARN)) { Log.w(tag, message); } } public static void i(String tag, String message) { if (isLoggable(Log.INFO)) { Log.i(tag, message); } } public static void d(String tag, String message) { if (isLoggable(Log.DEBUG)) { Log.d(tag, message); } } public static void v(String tag, String message) { if (isLoggable(Log.VERBOSE)) { Log.v(tag, message); } } public static void v(String format, Object... args) { if (isLoggable(Log.VERBOSE)) { Log.v(TAG_DEBUG, buildMessage(format, args)); } } public static void d(String format, Object... args) { if (isLoggable(Log.DEBUG)) { Log.d(TAG_DEBUG, buildMessage(format, args)); } } public static void i(String format, Object... args) { if (isLoggable(Log.INFO)) { Log.i(TAG_DEBUG, buildMessage(format, args)); } } public static void w(String format, Object... args) { if (isLoggable(Log.WARN)) { Log.w(TAG_DEBUG, buildMessage(format, args)); } } public static void e(String format, Object... args) { if (isLoggable(Log.ERROR)) { Log.e(TAG_DEBUG, buildMessage(format, args)); } } public static void e(Throwable tr, String format, Object... args) { if (isLoggable(Log.ERROR)) { Log.e(TAG_DEBUG, buildMessage(format, args), tr); } } /** * log */ public static void fe(String tag, Throwable e) { fe(tag, "", e); } public static void fe(String tag, String message, Throwable e) { if (isLoggable(Log.ERROR)) { Log.e(tag, "", e); } if (isFileLoggable(Log.ERROR)) { if (sFileLogger != null) { sFileLogger.e(tag, message, e); } } } public static void fe(String tag, String message) { if (isLoggable(Log.ERROR)) { Log.e(tag, message); } if (isFileLoggable(Log.ERROR)) { if (sFileLogger != null) { sFileLogger.e(tag, message); } } } public static void fw(String tag, String message) { if (isLoggable(Log.WARN)) { Log.w(tag, message); } if (isFileLoggable(Log.WARN)) { if (sFileLogger != null) { sFileLogger.w(tag, message); } } } public static void fi(String tag, String message) { if (isLoggable(Log.INFO)) { Log.i(tag, message); } if (isFileLoggable(Log.INFO)) { if (sFileLogger != null) { sFileLogger.i(tag, message); } } } public static void fd(String tag, String message) { if (isLoggable(Log.DEBUG)) { Log.d(tag, message); } if (isFileLoggable(Log.DEBUG)) { if (sFileLogger != null) { sFileLogger.d(tag, message); } } } public static void fv(String tag, String message) { if (isLoggable(Log.VERBOSE)) { Log.v(tag, message); } if (isFileLoggable(Log.VERBOSE)) { if (sFileLogger != null) { sFileLogger.v(tag, message); } } } private static boolean isFileLoggable(int level) { return level >= sFileLoggingLevel; } private static void closeFileLogger() { if (sFileLogger != null) { sFileLogger.close(); sFileLogger = null; } } private static void openFileLogger(Context context) { closeFileLogger(); if (sFileLoggingLevel < Log.ASSERT) { sFileLogger = new FileLogger(TAG_DEBUG, createFileLogDirIfNeeded(context)); } } private static File createFileLogDirIfNeeded(Context context) { File dir; if (AndroidUtils.isMediaMounted()) { dir = new File(context.getExternalCacheDir(), FILE_LOG_DIR); } else { dir = new File(context.getCacheDir(), FILE_LOG_DIR); } if (!dir.exists()) { dir.mkdirs(); } return dir; } /** * StackTrace */ private static String buildMessage(String format, Object... args) { String msg = (args == null) ? format : String.format(Locale.US, format, args); StackTraceElement[] trace = new Throwable().fillInStackTrace().getStackTrace(); String caller = "<unknown>"; // Walk up the stack looking for the first caller outside of VolleyLog. // It will be at least two frames up, so start there. for (int i = 2; i < trace.length; i++) { Class<?> clazz = trace[i].getClass(); if (!clazz.equals(LogUtils.class)) { String callingClass = trace[i].getClassName(); callingClass = callingClass.substring(callingClass.lastIndexOf('.') + 1); callingClass = callingClass.substring(callingClass.lastIndexOf('$') + 1); caller = callingClass + "." + trace[i].getMethodName(); break; } } return String.format(Locale.US, "[%d] %s: %s", Thread.currentThread().getId(), caller, msg); } public static void e(Class<?> clz, String message) { e(clz.getSimpleName(), message); } public static void w(Class<?> clz, String message) { w(clz.getSimpleName(), message); } public static void i(Class<?> clz, String message) { i(clz.getSimpleName(), message); } public static void d(Class<?> clz, String message) { d(clz.getSimpleName(), message); } public static void v(Class<?> clz, String message) { v(clz.getSimpleName(), message); } public static void e(Class<?> clz, Throwable t) { e(clz.getSimpleName(), t); } public static void e(String message) { e(TAG_DEBUG, message); } public static void w(String message) { w(TAG_DEBUG, message); } public static void i(String message) { i(TAG_DEBUG, message); } public static void d(String message) { d(TAG_DEBUG, message); } public static void v(String message) { v(TAG_DEBUG, message); } public static void e(Throwable t) { e(TAG_DEBUG, t); } public static void startTrace(String operation) { sTraceMap.put(operation, System.currentTimeMillis()); } public static void stopTrace(String operation) { Long start = sTraceMap.remove(operation); if (start != null) { long end = System.currentTimeMillis(); long interval = end - start; Log.v(TAG_TRACE, operation + " use time: " + interval + "ms"); } } public static void removeTrace(String key) { sTraceMap.remove(key); } public static void clearTrace() { sTraceMap.clear(); Log.v(TAG_TRACE, "trace is cleared."); } public void clearLogFiles(Context context) { File logDir = createFileLogDirIfNeeded(context); IOUtils.delete(logDir.getPath()); } public void clearLogFilesAsync(final Context context) { new Thread() { @Override public void run() { clearLogFiles(context); } }.start(); } private static class LogEntry { private static SimpleDateFormat dateFormat; // must always be used in the same thread private static Date mDate; private final long now; private final char level; private final String tag; private final String threadName; private final String msg; private final Throwable cause; private String date; LogEntry(char lvl, String tag, String threadName, String msg, Throwable tr) { this.now = System.currentTimeMillis(); this.level = lvl; this.tag = tag; this.threadName = threadName; this.msg = msg; this.cause = tr; } private void addCsvHeader(final StringBuilder csv) { if (dateFormat == null) dateFormat = new SimpleDateFormat("MM-dd HH:mm:ss.SSS", Locale.US); if (date == null) { if (null == mDate) mDate = new Date(); mDate.setTime(now); date = dateFormat.format(mDate); } csv.append(date); csv.append(','); csv.append(level); csv.append(','); csv.append(android.os.Process.myPid()); csv.append(','); if (threadName != null) csv.append(threadName); csv.append(','); csv.append(','); if (tag != null) csv.append(tag); csv.append(','); } private void addException(final StringBuilder csv, Throwable tr) { if (tr == null) return; final StringBuilder sb = new StringBuilder(256); sb.append(cause.getClass()); sb.append(": "); sb.append(cause.getMessage()); sb.append('\n'); for (StackTraceElement trace : cause.getStackTrace()) { //addCsvHeader(csv); sb.append(" at "); sb.append(trace.getClassName()); sb.append('.'); sb.append(trace.getMethodName()); sb.append('('); sb.append(trace.getFileName()); sb.append(':'); sb.append(trace.getLineNumber()); sb.append(')'); sb.append('\n'); } addException(sb, tr.getCause()); csv.append(sb.toString().replace(';', '-').replace(',', '-').replace('"', '\'')); } public CharSequence formatCsv() { final StringBuilder csv = new StringBuilder(256); addCsvHeader(csv); csv.append('"'); if (msg != null) csv.append(msg.replace(';', '-').replace(',', '-').replace('"', '\'')); csv.append('"'); csv.append('\n'); if (cause != null) { addCsvHeader(csv); csv.append('"'); addException(csv, cause); csv.append('"'); csv.append('\n'); } return csv.toString(); } } private static class FileLogger implements Handler.Callback { public static final String TAG = FileLogger.class.getSimpleName(); private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd-HH", Locale.US); private static final String UTF_8 = Charsets.ENCODING_UTF_8; private static final int MSG_OPEN = 0; private static final int MSG_WRITE = 1; private static final int MSG_CLEAR = 2; public static long MAX_FILE_SIZE = 1024 * 1024 * 10; private File mLogDir; private File mLogFile; private String mTag; private HandlerThread mHandlerThread; private Handler mAsyncHandler; private Writer mWriter; public FileLogger(String logTag, File logDir) { mTag = logTag; mLogDir = logDir; mHandlerThread = new HandlerThread(TAG, android.os.Process.THREAD_PRIORITY_BACKGROUND); mHandlerThread.start(); mAsyncHandler = new Handler(mHandlerThread.getLooper(), this); sendOpenMessage(); } @Override public boolean handleMessage(Message msg) { switch (msg.what) { case MSG_OPEN: onMessageOpen(msg); break; case MSG_WRITE: onMessageWrite(msg); break; case MSG_CLEAR: onMessageClear(); break; } return true; } public void close() { Handler handler = mAsyncHandler; mAsyncHandler = null; if (handler != null) { handler.removeCallbacksAndMessages(null); } if (mHandlerThread != null) { mHandlerThread.quit(); mHandlerThread = null; } } public void clear() { sendClearMessage(); } private void onMessageOpen(Message msg) { closeWriter(); openWriter(); } private void onMessageWrite(Message msg) { try { LogEntry logMessage = (LogEntry) msg.obj; if (mWriter != null) { mWriter.append(logMessage.formatCsv()); mWriter.flush(); } } catch (IOException e) { Log.e(TAG, e.getClass().getSimpleName() + " : " + e.getMessage()); } verifyFileSize(); } private void onMessageClear() { if (mLogFile != null) { closeWriter(); IOUtils.delete(mLogDir); openWriter(); } } private void sendOpenMessage() { if (mAsyncHandler != null) { mAsyncHandler.sendEmptyMessage(MSG_OPEN); } } private void sendWriteMessage(LogEntry log) { if (mAsyncHandler != null) { Message message = mAsyncHandler.obtainMessage(MSG_WRITE, log); mAsyncHandler.sendMessage(message); } } private void sendClearMessage() { if (mAsyncHandler != null) { mAsyncHandler.sendEmptyMessage(MSG_CLEAR); } } private void createLogFile() { if (mLogDir == null) { return; } if (!mLogDir.exists()) { mLogDir.mkdirs(); } String fileName = String.format("log-%1$s.%2$s", DATE_FORMAT.format(new Date()), "txt"); File file = new File(mLogDir, fileName); try { file.createNewFile(); mLogFile = file; } catch (Exception e) { e.printStackTrace(); Log.e(TAG, "createLogFile ex=" + e); } } private void openWriter() { createLogFile(); if (mLogFile == null) { return; } if (mWriter == null) try { mWriter = new OutputStreamWriter(new FileOutputStream(mLogFile, true), UTF_8); } catch (UnsupportedEncodingException e) { Log.e(TAG, "can't get a writer for " + mLogFile + " : " + e.getMessage()); } catch (FileNotFoundException e) { Log.e(TAG, "can't get a writer for " + mLogFile + " : " + e.getMessage()); } } private void closeWriter() { if (mWriter != null) { try { mWriter.close(); } catch (IOException e) { e.printStackTrace(); } mWriter = null; } } private void verifyFileSize() { if (mLogFile != null) { long size = mLogFile.length(); if (size > MAX_FILE_SIZE) { closeWriter(); mLogFile.delete(); openWriter(); } } } public void d(String tag, String msg) { write('d', tag, msg); } public void d(String msg) { write('d', msg); } public void e(String tag, String msg, Throwable tr) { write('e', tag, msg, tr); } public void e(String tag, String msg) { write('e', tag, msg); } public void e(String msg) { write('e', msg); } public void i(String msg, String tag) { write('i', tag, msg); } public void i(String msg) { write('i', msg); } public void v(String msg, String tag) { write('v', tag, msg); } public void v(String msg) { write('v', msg); } public void w(String tag, String msg, Throwable tr) { write('w', tag, msg, tr); } public void w(String tag, String msg) { write('w', tag, msg); } public void w(String msg) { write('w', msg); } private void write(char lvl, String message) { String tag; if (mTag == null) tag = TAG; else tag = mTag; write(lvl, tag, message); } private void write(char lvl, String tag, String message) { write(lvl, tag, message, null); } private void write(char lvl, String tag, String message, Throwable tr) { if (tag == null) { write(lvl, message); return; } LogEntry log = new LogEntry(lvl, tag, Thread.currentThread().getName(), message, tr); sendWriteMessage(log); } } }
package net.time4j.engine; import java.util.List; import java.util.Map; /** * <p>Represents a set of various calendar systems as members of a family. </p> * * @param <T> generic type compatible to {@link CalendarVariant} * @author Meno Hochschild * @since 3.4/4.3 */ /*[deutsch] * <p>Repr&auml;sentiert eine Familie von miteinander verwandten Kalendersystemen. </p> * * @param <T> generic type compatible to {@link CalendarVariant} * @author Meno Hochschild * @since 3.4/4.3 */ public final class CalendarFamily<T extends CalendarVariant<T>> extends Chronology<T> { private final Map<String, ? extends CalendarSystem<T>> calendars; // must never be exposed private CalendarFamily( Class<T> chronoType, ChronoMerger<T> chronoMerger, Map<ChronoElement<?>, ElementRule<T, ?>> ruleMap, List<ChronoExtension> extensions, Map<String, ? extends CalendarSystem<T>> calendars ) { super(chronoType, chronoMerger, ruleMap, extensions); this.calendars = calendars; } @Override public boolean hasCalendarSystem() { return true; } @Override public CalendarSystem<T> getCalendarSystem() { if (this.calendars.size() == 1) { return this.calendars.values().iterator().next(); } else { throw new ChronoException("Cannot determine calendar system without variant."); } } @Override public CalendarSystem<T> getCalendarSystem(String variant) { CalendarSystem<T> result = this.calendars.get(variant); if (result == null) { return super.getCalendarSystem(variant); } else { return result; } } @Override public boolean isSupported(ChronoElement<?> element) { return super.isSupported(element) || (element instanceof EpochDays); } /*[deutsch] * <p>Erzeugt einen Builder f&uuml;r eine neue Kalenderfamilie und wird ausschlie&szlig;lich beim Laden einer * Klasse zu einer Kalendervariante in einem <i>static initializer</i> benutzt. </p> * * <p>Instanzen dieser Klasse werden &uuml;ber die statische {@code setUp()}-Fabrikmethode erzeugt. </p> * * @param <T> generic type of time context * @author Meno Hochschild * @see #setUp(Class,ChronoMerger,Map) * @since 3.4/4.3 * @doctags.concurrency {mutable} */ public static final class Builder<T extends CalendarVariant<T>> extends Chronology.Builder<T> { private final Map<String, ? extends CalendarSystem<T>> calendars; private Builder( Class<T> chronoType, ChronoMerger<T> merger, Map<String, ? extends CalendarSystem<T>> calendars ) { super(chronoType, merger); if (calendars.isEmpty()) { throw new IllegalArgumentException("Missing calendar variants."); } this.calendars = calendars; } public static <T extends CalendarVariant<T>> Builder<T> setUp( Class<T> chronoType, ChronoMerger<T> merger, Map<String, ? extends CalendarSystem<T>> calendars ) { return new Builder<>(chronoType, merger, calendars); } @Override public <V> Builder<T> appendElement( ChronoElement<V> element, ElementRule<T, V> rule ) { super.appendElement(element, rule); return this; } @Override public Builder<T> appendExtension(ChronoExtension extension) { super.appendExtension(extension); return this; } @Override public CalendarFamily<T> build() { CalendarFamily<T> engine = new CalendarFamily<>( this.chronoType, this.merger, this.ruleMap, this.extensions, this.calendars ); Chronology.register(engine); return engine; } } }
package net.mueller_martin.turirun; import java.io.IOException; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.maps.MapObjects; import com.badlogic.gdx.maps.MapProperties; import com.badlogic.gdx.maps.tiled.TiledMap; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.maps.tiled.TiledMapTileLayer; import com.badlogic.gdx.math.Vector2; import com.esotericsoftware.kryonet.Client; import com.esotericsoftware.kryonet.Connection; import com.esotericsoftware.kryonet.Listener; import com.esotericsoftware.kryonet.Listener.ThreadedListener; import net.mueller_martin.turirun.gameobjects.*; import net.mueller_martin.turirun.network.TurirunNetwork; import net.mueller_martin.turirun.network.TurirunNetwork.Register; import net.mueller_martin.turirun.network.TurirunNetwork.AddCharacter; import net.mueller_martin.turirun.network.TurirunNetwork.UpdateCharacter; import net.mueller_martin.turirun.network.TurirunNetwork.MoveCharacter; import net.mueller_martin.turirun.network.TurirunNetwork.RemoveCharacter; import net.mueller_martin.turirun.network.TurirunNetwork.HitCharacter; import net.mueller_martin.turirun.network.TurirunNetwork.DeadCharacter; import net.mueller_martin.turirun.utils.CollusionDirections; import java.util.ArrayList; import java.util.List; import java.util.Collections; import java.util.Collections.*; public class WorldController { public final static String TAG = WorldController.class.getName(); public int mapPixelWidth = 300; public int mapPixelHeight = 300; Client client; public Turirun game; public ObjectController objs; public Level level; public int checkpointCount = 0; public int checkpointsNeeded = 1; public CharacterController controller; public static List<Object> events; public WorldController(Turirun game) { this.game = game; this.objs = new ObjectController(); this.client = new Client(); // Create Character Input Controller controller = new CharacterController(this.objs, this.client); // Events WorldController.events = Collections.synchronizedList(new ArrayList<Object>()); this.init(); } // Start Game public void init() { //TODO ask server for CharacterObject type CharacterObject playerObj = new CharacterObject(10, 10); this.objs.addObject(playerObj); controller.setPlayerObj(playerObj); // Spawn Checkpoint CheckpointGameObject checkpoint = new CheckpointGameObject(300, 800, 200, 200); this.objs.addObject(checkpoint); //map size level = new Level(); MapProperties prop = level.map.getProperties(); int mapWidth = prop.get("width", Integer.class); int mapHeight = prop.get("height", Integer.class); System.out.println("mapWidth: " + mapWidth + ", " + "mapHeight: " + mapHeight); int tilePixelWidth = prop.get("tilewidth", Integer.class); int tilePixelHeight = prop.get("tileheight", Integer.class); System.out.println("tilePixelWidth: " + tilePixelWidth + ", " + "tilePixelHeight: " + tilePixelHeight); mapPixelWidth = mapWidth * tilePixelWidth; mapPixelHeight = mapHeight * tilePixelHeight; System.out.println("mapPixelWidth: " + mapPixelWidth + ", " + "mapPixelHeight: " + mapPixelHeight); // set bounding boxes for tilemap sprites // stones TiledMapTileLayer layer = (TiledMapTileLayer) level.map.getLayers().get("stones"); System.out.println("Layer: " + layer); for(int x = 0; x < layer.getWidth(); x++) { for(int y = 0; y < layer.getHeight(); y++) { if(layer.getCell(x, y) != null) { // Spawn Walls WallGameObject wall = new WallGameObject(x * tilePixelWidth + 16, y*tilePixelWidth + 64, 218, 97); this.objs.addObject(wall); } } } // bushs layer = (TiledMapTileLayer) level.map.getLayers().get("bushs"); for(int x = 0; x < layer.getWidth(); x++) { for(int y = 0; y < layer.getHeight(); y++) { if(layer.getCell(x, y) != null) { // Spawn Bush BushGameObject bush = new BushGameObject(x * tilePixelWidth + 16, y*tilePixelWidth + 64, 218, 110); this.objs.addObject(bush); } } } this.client.start(); // For consistency, the classes to be sent over the network are registered by the same method for both the client and server TurirunNetwork.register(client); client.addListener(new ThreadedListener(new Listener() { public void connected(Connection connection) { } public void received(Connection connection, Object object) { WorldController.events.add(object); } public void disconnected(Connection connection) { } })); try { // Block for max. 3000ms // 172.18.12.25 client.connect(3000, this.game.host, this.game.port, TurirunNetwork.udpPort); // Server communication after connection can go here, or in Listener#connected() } catch (IOException e) { Gdx.app.error("Could not connect to server", e.getMessage()); } Register register = new Register(); register.nick = this.game.nickname; register.type = 1; client.sendTCP(register); } public void draw(SpriteBatch batch) { level.render(); for (GameObject obj: objs.getObjects()) { obj.draw(batch); } } public void update(float deltaTime) { // Input Update controller.update(deltaTime); // Netzwerk Update this.updateEvents(); if (client != null) { // FIXME: last and current postition are always equal //if (controller.character.currentPosition.x != controller.character.lastPosition.x || controller.character.currentPosition.y != controller.character.lastPosition.y) { MoveCharacter move = new MoveCharacter(); move.x = controller.character.currentPosition.x; move.y = controller.character.currentPosition.y; client.sendTCP(move); } } Camera cam = CameraHelper.instance.camera; // The camera dimensions, halved float cameraHalfWidth = cam.viewportWidth * .5f; float cameraHalfHeight = cam.viewportHeight * .5f; // Move camera after player as normal int pos_x = (int)controller.character.currentPosition.x; if (pos_x % 2 == 0) pos_x++; int pos_y = (int)controller.character.currentPosition.y; if (pos_y % 2 == 0) pos_y++; CameraHelper.instance.camera.position.set(pos_x,pos_y,0); float cameraLeft = cam.position.x - cameraHalfWidth; float cameraRight = cam.position.x + cameraHalfWidth; float cameraBottom = cam.position.y - cameraHalfHeight; float cameraTop = cam.position.y + cameraHalfHeight; // Horizontal axis if(mapPixelWidth < cam.viewportWidth) { cam.position.x = mapPixelWidth / 2; } else if(cameraLeft <= 0) { cam.position.x = 0 + cameraHalfWidth; } else if(cameraRight >= mapPixelWidth) { cam.position.x = mapPixelWidth - cameraHalfWidth; } // Vertical axis if(mapPixelHeight < cam.viewportHeight) { cam.position.y = mapPixelHeight / 2; } else if(cameraBottom <= 0) { cam.position.y = 0 + cameraHalfHeight; } else if(cameraTop >= mapPixelHeight) { cam.position.y = mapPixelHeight - cameraHalfHeight; } // update objects checkpointCount = 0; for (GameObject obj: objs.getObjects()) { obj.update(deltaTime); resetIfOutsideOfMap(obj); checkCheckpoints(obj); } // check for collusion for (GameObject obj: objs.getObjects()) { for (GameObject collusionObj: objs.getObjects()) { if (obj == collusionObj) continue; CollusionDirections.CollusionDirectionsTypes col = obj.bounds.intersection(collusionObj.bounds); if (col != CollusionDirections.CollusionDirectionsTypes.NONE) { System.out.println("Collusion!"); obj.isCollusion(collusionObj, col); } } } } private void resetIfOutsideOfMap(GameObject obj) { if (obj.currentPosition.x < 0) { System.out.println("x: " + obj.currentPosition.x + " " + mapPixelWidth); obj.currentPosition.x = 1; } if (obj.currentPosition.x + obj.size.x > mapPixelWidth) { System.out.println("x: " + obj.currentPosition.x + " " + mapPixelWidth); obj.currentPosition.x = mapPixelWidth - obj.size.x + 1; } if (obj.currentPosition.y < 0) { System.out.println("y: " + obj.currentPosition.y + " " + mapPixelHeight); obj.currentPosition.y = 1; } if (obj.currentPosition.y + obj.size.y> mapPixelHeight) { System.out.println("y: " + obj.currentPosition.y + " " + mapPixelHeight); obj.currentPosition.y = mapPixelHeight - obj.size.y; } } private void checkCheckpoints(GameObject obj) { if (obj instanceof CheckpointGameObject && ((CheckpointGameObject) obj).checked) { checkpointCount++; if (checkpointCount == checkpointsNeeded) { // TODO Tourist won! System.out.println("Tourist won!"); } } } private void updateEvents() { ArrayList<Object> del = new ArrayList<Object>(); synchronized (WorldController.events) { for (Object event : WorldController.events) { // Add Player if (event instanceof AddCharacter) { AddCharacter msg = (AddCharacter)event; CharacterObject newPlayer = new CharacterObject(msg.character.x, msg.character.y); objs.addObject(msg.character.id, newPlayer); del.add(event); continue; } // Update Player if (event instanceof UpdateCharacter) { UpdateCharacter msg = (UpdateCharacter)event; CharacterObject player = (CharacterObject)objs.getObject(msg.id); if (player != null) { player.lastPosition = new Vector2(msg.x, msg.y); player.currentPosition = new Vector2(msg.x, msg.y); } del.add(event); continue; } // Remove Player if (event instanceof RemoveCharacter) { RemoveCharacter msg = (RemoveCharacter)event; CharacterObject player = (CharacterObject)objs.getObject(msg.id); if (player != null) { objs.removeObject(player); } del.add(event); continue; } // HitCharacter if (event instanceof HitCharacter) { HitCharacter msg = (HitCharacter)event; CharacterObject player = (CharacterObject)objs.getObject(msg.id); if (player != null) { System.out.println("Player HIT "+msg.id); } del.add(event); continue; } // Dead Character if (event instanceof DeadCharacter) { DeadCharacter msg = (DeadCharacter)event; CharacterObject player = (CharacterObject)objs.getObject(msg.id); if (player != null && !player.isDead) { player.isDead = true; System.out.println("Dead "+msg.id); } del.add(event); continue; } } } for (Object event : del) { WorldController.events.remove(event); } } }
/* * $Id$ * $URL$ */ package org.subethamail.core.injector; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.annotation.Resource; import javax.annotation.security.PermitAll; import javax.annotation.security.RunAs; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.jws.WebMethod; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import javax.mail.Address; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jboss.annotation.security.SecurityDomain; import org.subethamail.common.MailUtils; import org.subethamail.common.NotFoundException; import org.subethamail.common.SubEthaMessage; import org.subethamail.common.io.LimitExceededException; import org.subethamail.common.io.LimitingInputStream; import org.subethamail.core.admin.i.Encryptor; import org.subethamail.core.admin.i.ExpiredException; import org.subethamail.core.filter.FilterRunner; import org.subethamail.core.injector.i.Injector; import org.subethamail.core.injector.i.InjectorRemote; import org.subethamail.core.plugin.i.HoldException; import org.subethamail.core.plugin.i.IgnoreException; import org.subethamail.core.post.PostOffice; import org.subethamail.core.queue.i.Queuer; import org.subethamail.core.util.EntityManipulatorBean; import org.subethamail.core.util.OwnerAddress; import org.subethamail.core.util.VERPAddress; import org.subethamail.entity.EmailAddress; import org.subethamail.entity.Mail; import org.subethamail.entity.MailingList; import org.subethamail.entity.Person; import org.subethamail.entity.Subscription; import org.subethamail.entity.Mail.HoldType; import org.subethamail.entity.i.Permission; /** * @author Jeff Schnitzer */ @Stateless(name="Injector") @SecurityDomain("subetha") @PermitAll @RunAs("siteAdmin") @WebService(name="Injector", targetNamespace="http://ws.subethamail.org/", serviceName="InjectorService") @SOAPBinding(style=SOAPBinding.Style.RPC) public class InjectorBean extends EntityManipulatorBean implements Injector, InjectorRemote { private static Log log = LogFactory.getLog(InjectorBean.class); /** * We bounce injected messages larger than this amount, in bytes. * Must be hardcoded because JavaMail creates a byte[] representation, * and we don't want huge files taking down our JVM. */ public static final int MAX_MESSAGE_BYTES = 1000 * 1000 * 10; /** * The oldest bounce message we are willing to consider valid. This * is to prevent anyone that finds an old bounce token for a user * from using it to mailiciously unsubscribe that person. */ public static final long MAX_BOUNCE_AGE_MILLIS = 1000 * 60 * 60 * 24 * 7; /** * The maximum bounce count at which we disable mail delivery for a user. * This is not actually a literal number of bounces, it's a number that * tends to go up as bounces occur and tends to go down when bounces do * not occur. */ public static final long MAX_BOUNCE_THRESHOLD = 7; /** * Minimum number of milliseconds between hold notification emails. It might * be longer if a steady stream arrives. The logic actually only sends a * notification if it has been more than this interval since the last message * from the user was held. Currently 24 hours. */ public static final long MIN_HOLD_NOTIFICATION_INTERVAL_MILLIS = 1000 * 60 * 60 * 24; /** * How far back to look for the parent of a message by subject. */ public static final long MAX_SUBJECT_THREAD_PARENT_AGE_MILLIS = 1000L * 60L * 60L * 24L * 30L; @EJB Queuer queuer; @EJB FilterRunner filterRunner; @EJB Encryptor encryptor; @EJB Detacher detacher; @EJB PostOffice postOffice; @Resource(mappedName="java:/Mail") private Session mailSession; /* * (non-Javadoc) * @see org.subethamail.core.injector.i.Injector#accept(java.lang.String) */ @WebMethod public boolean accept(String toAddress) { if (log.isDebugEnabled()) log.debug("Checking if we want address " + toAddress); try { InternetAddress addy = new InternetAddress(toAddress); // Maybe it's a VERP bounce? VERPAddress verp = VERPAddress.getVERPBounce(addy.getAddress()); if (verp != null) addy = new InternetAddress(verp.getEmail()); // check if this is for a list here else { // Maybe it's an owner address? String ownerList = OwnerAddress.getList(addy.getAddress()); if (ownerList != null) addy = new InternetAddress(ownerList); } try { this.em.getMailingList(addy); return true; } catch (NotFoundException ex) { return false; } } catch (MessagingException ex) { throw new RuntimeException(ex); } } /* * (non-Javadoc) * @see org.subethamail.core.injector.i.Injector#inject(java.lang.String, java.lang.String, byte[]) */ public boolean inject(String fromAddress, String toAddress, byte[] mailData) throws LimitExceededException { return this.inject(fromAddress, toAddress, new ByteArrayInputStream(mailData)); } /* * (non-Javadoc) * @see org.subethamail.core.injector.i.Injector#inject(java.lang.String, java.lang.String, byte[]) */ public boolean inject(String envelopeSender, String envelopeRecipient, InputStream mailData) throws LimitExceededException { if (log.isDebugEnabled()) { if (!mailData.markSupported()) mailData = new BufferedInputStream(mailData); mailData.mark(8192); } try { return this.injectImpl(envelopeSender, envelopeRecipient, mailData); } catch (LimitExceededException ex) { throw ex; } catch (Exception ex) { if (log.isDebugEnabled()) { try { mailData.reset(); Reader reader = new InputStreamReader(mailData); StringBuilder builder = new StringBuilder(); while (reader.ready()) builder.append((char)reader.read()); log.debug("Mail body was: " + builder); } catch (IOException e) {} } if (ex instanceof RuntimeException) throw (RuntimeException)ex; else throw new RuntimeException(ex); } } /** * Factors out the exception catching. */ protected boolean injectImpl(String envelopeSender, String envelopeRecipient, InputStream mailData) throws MessagingException, LimitExceededException, IOException { if (log.isDebugEnabled()) log.debug("Injecting message sent to " + envelopeRecipient); InternetAddress recipientAddy = new InternetAddress(envelopeRecipient); // Must check for recipient VERP bounce VERPAddress recipientVerp = VERPAddress.getVERPBounce(recipientAddy.getAddress()); if (recipientVerp != null) { this.handleBounce(recipientVerp); return true; } if (envelopeSender == null || envelopeSender.trim().length() == 0) { log.error("Got non-verp mail with empty sender"); return false; } InternetAddress senderAddy = new InternetAddress(envelopeSender); // Immediately check to see if the envelope sender is a verp address. If it is, // convert it into an -owner address. This magic allows lists to subscribe to lists. VERPAddress senderVerp = VERPAddress.getVERPBounce(senderAddy.getAddress()); if (senderVerp != null) senderAddy = new InternetAddress(OwnerAddress.makeOwner(senderAddy.getAddress())); // Check for -owner mail String listForOwner = OwnerAddress.getList(envelopeRecipient); if (listForOwner != null) recipientAddy = new InternetAddress(listForOwner); // Figure out which list this is for MailingList toList; try { toList = this.em.getMailingList(recipientAddy); } catch (NotFoundException ex) { log.error("Unknown destination: " + recipientAddy); return false; } if (log.isDebugEnabled()) log.debug("Message is for list: " + toList); // Parse up the message mailData = new LimitingInputStream(mailData, MAX_MESSAGE_BYTES); SubEthaMessage msg = new SubEthaMessage(this.mailSession, mailData); // If the message is looping, silently accept and drop it. The // X-Loop header is added by the deliverator. if (msg.hasXLoop(toList.getEmail())) return true; // Now that we have the basic building blocks, see if we // should be forwarding the mail to owners instead if (listForOwner != null) { this.handleOwnerMail(toList, msg); return true; } // Make sure we have a unique message id if (this.isDuplicateMessage(toList, msg)) msg.replaceMessageID(); // If it stays null, no moderation required HoldType hold = null; String holdMsg = null; // Run it through the plugin stack try { this.filterRunner.onInject(msg, toList); } catch (IgnoreException ex) { if (log.isDebugEnabled()) log.debug("Plugin ignoring message", ex); // Maybe we should return false instead? return true; } catch (HoldException ex) { if (log.isDebugEnabled()) log.debug("Plugin holding message", ex); hold = HoldType.HARD; holdMsg = ex.getMessage(); } // Find out if the message should be held for moderation if (hold == null) { // Figure out who sent it, if we know Person author = null; EmailAddress addy = this.em.findEmailAddress(senderAddy.getAddress()); if (addy != null) author = addy.getPerson(); if (log.isDebugEnabled()) log.debug("Message author is: " + author); if (!toList.getPermissionsFor(author).contains(Permission.POST)) hold = HoldType.SOFT; } if (log.isDebugEnabled()) log.debug("Hold? " + hold); Mail mail = new Mail(senderAddy, msg, toList, hold); this.em.persist(mail); // Convert all binary attachments to references and then set the content this.detacher.detach(msg, mail); mail.setContent(msg); if (mail.getHold() != null) { // We don't want to send too many of these notification messages // because they might cause too much backscatter from spam. We // compromise on sending at most one per time period. Date cutoff = new Date(System.currentTimeMillis() - MIN_HOLD_NOTIFICATION_INTERVAL_MILLIS); int recentHolds = this.em.countRecentHeldMail(senderAddy.getAddress(), cutoff); if (recentHolds <= 1) // count includes the current held msg { // Send instructions so that user can self-moderate // Or send a message saying "you must wait for admin approval", use holdMsg if available this.postOffice.sendPosterMailHoldNotice(toList, senderAddy.getAddress(), mail, holdMsg); } if (hold == HoldType.HARD) { for (Subscription sub: toList.getSubscriptions()) { if (sub.getRole().getPermissions().contains(Permission.APPROVE_MESSAGES)) if (sub.getDeliverTo() != null) this.postOffice.sendModeratorMailHoldNotice(sub.getDeliverTo(), toList, mail, msg, holdMsg); } } } else { this.threadMail(mail, msg); this.queuer.queueForDelivery(mail.getId()); } return true; } /* * (non-Javadoc) * @see org.subethamail.core.injector.i.Injector#importMessage(java.lang.Long, java.lang.String, java.io.InputStream, boolean, java.util.Date) */ public Date importMessage(Long listId, String envelopeSender, InputStream mailData, boolean ignoreDuplicate, Date fallbackDate) throws NotFoundException { if (log.isDebugEnabled()) log.debug("Importing message from " + envelopeSender + " into list " + listId); try { InternetAddress senderAddy = new InternetAddress(envelopeSender); // Figure out which list this is for MailingList toList = this.em.get(MailingList.class, listId); // Parse up the message mailData = new LimitingInputStream(mailData, MAX_MESSAGE_BYTES); SubEthaMessage msg = new SubEthaMessage(this.mailSession, mailData); // Check to see if the message is a duplicate. if (this.isDuplicateMessage(toList, msg)) { // Are we dropping duplicates? if (ignoreDuplicate) return msg.getSentDate(); else msg.replaceMessageID(); } // If it stays null, no moderation required HoldType hold = null; // Run it through the plugin stack try { this.filterRunner.onInject(msg, toList); } catch (IgnoreException ex) { if (log.isDebugEnabled()) log.debug("Plugin ignoring message", ex); return msg.getSentDate(); } catch (HoldException ex) { if (log.isDebugEnabled()) log.debug("Plugin holding message", ex); hold = HoldType.HARD; } Date sentDate = msg.getSentDate(); if (sentDate == null) sentDate = fallbackDate; Mail mail = new Mail(senderAddy, msg, toList, hold, sentDate); this.em.persist(mail); // Convert all binary attachments to references and then set the content this.detacher.detach(msg, mail); mail.setContent(msg); if (mail.getHold() == null) this.threadMail(mail, msg); return msg.getSentDate(); } catch (MessagingException ex) { throw new RuntimeException(ex); } catch (IOException ex) { throw new RuntimeException(ex); } } /** * Forwards the message to all owners of the list. The return * address will be VERPed. * * @param list list whose owner(s) should receive the mail * @param msg is the message to forward */ private void handleOwnerMail(MailingList list, SubEthaMessage msg) throws MessagingException { for (Subscription sub: list.getSubscriptions()) { if (sub.getRole().isOwner() && sub.getDeliverTo() != null) { Address destination = new InternetAddress(sub.getDeliverTo().getId()); // Set up the VERP bounce address byte[] token = this.encryptor.encryptString(sub.getDeliverTo().getId()); msg.setEnvelopeFrom(VERPAddress.encodeVERP(list.getEmail(), token)); Transport.send(msg, new Address[] { destination }); sub.getDeliverTo().bounceDecay(); } } } /** * @return true if a message with the id already exists in the list */ protected boolean isDuplicateMessage(MailingList list, SubEthaMessage msg) throws MessagingException { String messageId = msg.getMessageID(); if (messageId != null) { try { this.em.getMailByMessageId(list.getId(), messageId); return true; } catch (NotFoundException ex) { return false; } } return true; } /** * Handle a bounce message. Note we don't really care what the * message data was, just what the VERP address was. */ protected void handleBounce(VERPAddress verp) { if (log.isDebugEnabled()) log.debug("Handling bounce from list " + verp.getEmail()); try { String originalEmail = this.encryptor.decryptString(verp.getToken(), MAX_BOUNCE_AGE_MILLIS); if (log.isDebugEnabled()) log.debug("Bounced from " + originalEmail); EmailAddress found = this.em.getEmailAddress(originalEmail); found.bounceIncrement(); if (found.getBounces() > MAX_BOUNCE_THRESHOLD) { // Unsubscribe the address from any delivery for (Subscription sub: found.getPerson().getSubscriptions().values()) { if (found.equals(sub.getDeliverTo())) { sub.setDeliverTo(null); if (log.isWarnEnabled()) log.warn("Stopping delivery of " + sub.getList().getName() + " to " + found.getId() + " due to excessive bounces"); } } // TODO: somehow notify the person, perhaps at one of their other addresses? // TODO: notify the administrator? } } catch (NotFoundException ex) { // User already unsubscribed the address, great log.debug("Address already removed"); } catch (ExpiredException ex) { // Token is too old, ignore it log.debug("Token is too old"); } catch (GeneralSecurityException ex) { // Problem decoding the token? Someone's messing with us. log.debug("Token is invalid"); } } /** * Places the mail in a thread hierarchy, possibly updating a variety * of other mails which are part of the hierarchy. * * When this completes, the mail may have a parent and children. */ void threadMail(Mail mail, SubEthaMessage msg) throws MessagingException { if (log.isDebugEnabled()) log.debug("Threading mail " + mail); // STEP ONE: Figure who we want to be our parent. List<String> wantedReference = new ArrayList<String>(); // If there is an InReplyTo, that tops the list String inReplyTo = msg.getInReplyTo(); if (inReplyTo != null) wantedReference.add(inReplyTo); // Now add the references field. Careful that the // last reference might be duplicate of inReplyTo String[] references = msg.getReferences(); if (references != null) { // Walk it backwards because recent refs are at the end for (int i=(references.length-1); i>=0; i { if (!wantedReference.contains(references[i])) wantedReference.add(references[i]); } } if (log.isDebugEnabled()) log.debug("Wanted references is " + wantedReference); // STEP TWO: Find an acceptable candidate to be our thread parent, // and eliminate any candidates that are inferior. Mail parent = null; for (int i=0; i<wantedReference.size(); i++) { String candidate = wantedReference.get(i); try { parent = this.em.getMailByMessageId(mail.getList().getId(), candidate); if (log.isDebugEnabled()) log.debug("Found parent at choice " + i + ", max " + (wantedReference.size()-1)); // Got one, eliminate anything from wantedReference that is at this // level or later. Do it from the end to make ArrayList happy. for (int delInd=wantedReference.size()-1; delInd>=i; delInd wantedReference.remove(delInd); break; } catch (NotFoundException ex) {} } // If that didn't help us, try the desperate step of matching on subject if (parent == null) { String subj = mail.getSubject(); subj = MailUtils.cleanRe(subj); Date cutoff = new Date(System.currentTimeMillis() - MAX_SUBJECT_THREAD_PARENT_AGE_MILLIS); // This is a little ugly - grab two because the current mail will show up in the search List<Mail> found = this.em.findRecentMailBySubject(mail.getList().getId(), subj, cutoff, 2); for (Mail foundMail: found) { // The current mail itself should show up in the search if (foundMail == mail) continue; parent = foundMail; if (log.isDebugEnabled()) log.debug("Found parent using subject match"); break; } } if (log.isDebugEnabled()) log.debug("Best thread ancestor found is " + parent); // Intermission - we can now set the mail's parent and wantedReference if (parent != null) { mail.setParent(parent); parent.getReplies().add(mail); } mail.setWantedReference(wantedReference); // STEP THREE: Find anyone looking for us as a parent and insert us in // their thread ancestry. Watch out for loops. List<Mail> descendants = this.em.findMailWantingParent(mail.getList().getId(), mail.getMessageId()); outer: for (Mail descendant: descendants) { if (log.isDebugEnabled()) log.debug("Replacing parent of " + descendant); // Check for a loop Mail checkForLoop = descendant; while (checkForLoop != null) { if (checkForLoop == mail) { if (log.isWarnEnabled()) log.warn("Found a mail loop, parent=" + mail + ", child=" + descendant); // Ignore this link and remove the wanted rerference descendant.getWantedReference().remove(mail.getMessageId()); continue outer; } checkForLoop = checkForLoop.getParent(); } // Remove from the old parent, if exists if (descendant.getParent() != null) { Mail oldParent = descendant.getParent(); oldParent.getReplies().remove(descendant); } // Add the new parent descendant.setParent(mail); mail.getReplies().add(descendant); // Prune the wantedReference collection, possibly to empty List<String> wanted = descendant.getWantedReference(); for (int i=wanted.size()-1; i>=0; i { String removed = wanted.remove(i); if (mail.getMessageId().equals(removed)) break; } } } }
package be.ugent.zeus.resto.client; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; /** * * @author Thomas Meire */ public class Heracles extends Activity { private void link (int id, final Class activity) { findViewById(id).setOnClickListener( new View.OnClickListener() { public void onClick(View view) { startActivity(new Intent(Heracles.this, activity)); } }); } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.heracles); link(R.id.home_btn_news, News.class); link(R.id.home_btn_calendar, Calendar.class); link(R.id.home_btn_info, Info.class); link(R.id.home_btn_menu, RestoMenu.class); link(R.id.home_btn_gsr, GSR.class); link(R.id.home_btn_schamper, SchamperDaily.class); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.heracles, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.settings: Intent intent = new Intent(this, Settings.class); startActivity(intent); return true; default: return super.onOptionsItemSelected(item); } } }
package org.openmrs.module; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.Vector; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.math.NumberUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openmrs.GlobalProperty; import org.openmrs.api.AdministrationService; import org.openmrs.api.context.Context; import org.openmrs.api.context.ServiceContext; import org.openmrs.scheduler.SchedulerUtil; import org.openmrs.util.OpenmrsClassLoader; import org.openmrs.util.OpenmrsConstants; import org.openmrs.util.OpenmrsUtil; import org.springframework.context.support.AbstractRefreshableApplicationContext; /** * Utility methods for working and manipulating modules */ public class ModuleUtil { private static Log log = LogFactory.getLog(ModuleUtil.class); /** * Start up the module system with the given properties. * * @param props Properties (OpenMRS runtime properties) */ public static void startup(Properties props) throws ModuleMustStartException, OpenmrsCoreModuleException { String moduleListString = props.getProperty(ModuleConstants.RUNTIMEPROPERTY_MODULE_LIST_TO_LOAD); if (moduleListString == null || moduleListString.length() == 0) { // Attempt to get all of the modules from the modules folder // and store them in the modules list log.debug("Starting all modules"); ModuleFactory.loadModules(); } else { // use the list of modules and load only those log.debug("Starting all modules in this list: " + moduleListString); String[] moduleArray = moduleListString.split(" "); List<File> modulesToLoad = new Vector<File>(); for (String modulePath : moduleArray) { if (modulePath != null && modulePath.length() > 0) { File file = new File(modulePath); if (file.exists()) { modulesToLoad.add(file); } else { // try to load the file from the classpath InputStream stream = ModuleUtil.class.getClassLoader().getResourceAsStream(modulePath); // expand the classpath-found file to a temporary location if (stream != null) { try { // get and make a temp directory if necessary String tmpDir = System.getProperty("java.io.tmpdir"); File expandedFile = File.createTempFile(file.getName() + "-", ".omod", new File(tmpDir)); // pull the name from the absolute path load attempt FileOutputStream outStream = new FileOutputStream(expandedFile, false); // do the actual file copying OpenmrsUtil.copyFile(stream, outStream); // add the freshly expanded file to the list of modules we're going to start up modulesToLoad.add(expandedFile); expandedFile.deleteOnExit(); } catch (IOException io) { log.error("Unable to expand classpath found module: " + modulePath, io); } } else { log .error("Unable to load module at path: " + modulePath + " because no file exists there and it is not found on the classpath. (absolute path tried: " + file.getAbsolutePath() + ")"); } } } } ModuleFactory.loadModules(modulesToLoad); } // start all of the modules we just loaded ModuleFactory.startModules(); // some debugging info if (log.isDebugEnabled()) { Collection<Module> modules = ModuleFactory.getStartedModules(); if (modules == null || modules.size() == 0) { log.debug("No modules loaded"); } else { log.debug("Found and loaded " + modules.size() + " module(s)"); } } // make sure all openmrs required moduls are loaded and started checkOpenmrsCoreModulesStarted(); // make sure all mandatory modules are loaded and started checkMandatoryModulesStarted(); } /** * Stops the module system by calling stopModule for all modules that are currently started */ public static void shutdown() { List<Module> modules = new Vector<Module>(); modules.addAll(ModuleFactory.getStartedModules()); for (Module mod : modules) { if (log.isDebugEnabled()) { log.debug("stopping module: " + mod.getModuleId()); } if (mod.isStarted()) { ModuleFactory.stopModule(mod, true, true); } } log.debug("done shutting down modules"); // clean up the static variables just in case they weren't done before ModuleFactory.extensionMap = null; ModuleFactory.loadedModules = null; ModuleFactory.moduleClassLoaders = null; ModuleFactory.startedModules = null; } /** * Add the <code>inputStream</code> as a file in the modules repository * * @param inputStream <code>InputStream</code> to load * @return filename String of the file's name of the stream */ public static File insertModuleFile(InputStream inputStream, String filename) { File folder = getModuleRepository(); // check if module filename is already loaded if (OpenmrsUtil.folderContains(folder, filename)) { throw new ModuleException(filename + " is already associated with a loaded module."); } File file = new File(folder.getAbsolutePath(), filename); FileOutputStream outputStream = null; try { outputStream = new FileOutputStream(file); OpenmrsUtil.copyFile(inputStream, outputStream); } catch (FileNotFoundException e) { throw new ModuleException("Can't create module file for " + filename, e); } catch (IOException e) { throw new ModuleException("Can't create module file for " + filename, e); } finally { try { inputStream.close(); } catch (Exception e) { /* pass */} try { outputStream.close(); } catch (Exception e) { /* pass */} } return file; } /** * Checks if the current OpenMRS version is in an array of versions. * <p> * This method calls {@link ModuleUtil#matchRequiredVersions(String, String)} internally. * </p> * * @param versions the openmrs versions to be checked against the current openmrs version * @return true if the current openmrs version is in versions otherwise false * @should return false when versions is null * @should return false when versions is empty * @should return true if current openmrs version matches one element in versions * @should return false if current openmrs version does not match any element in versions */ public static boolean isOpenmrsVersionInVersions(String ...versions) { if (versions == null || versions.length == 0) { return false; } boolean result = false; for (String version : versions) { if (matchRequiredVersions(OpenmrsConstants.OPENMRS_VERSION_SHORT, version)) { result = true; break; } } return result; } /** * This method is an enhancement of {@link #compareVersion(String, String)} and adds support for * wildcard characters and upperbounds. <br> * <br> * This method calls {@link ModuleUtil#checkRequiredVersion(String, String)} internally. <br> * <br> * The require version number in the config file can be in the following format: * <ul> * <li>1.2.3</li> * <li>1.2.*</li> * <li>1.2.2 - 1.2.3</li> * <li>1.2.* - 1.3.*</li> * </ul> * <p> * Again the possible require version number formats with their interpretation: * <ul> * <li>1.2.3 means 1.2.3 and above</li> * <li>1.2.* means any version of the 1.2.x branch. That is 1.2.0, 1.2.1, 1.2.2,... but not 1.3.0, 1.4.0</li> * <li>1.2.2 - 1.2.3 means 1.2.2 and 1.2.3 (inclusive)</li> * <li>1.2.* - 1.3.* means any version of the 1.2.x and 1.3.x branch</li> * </ul> * </p> * * @param version openmrs version number to be compared * @param versionRange value in the config file for required openmrs version * @return true if the <code>version</code> is within the <code>value</code> * @should allow ranged required version * @should allow ranged required version with wild card * @should allow ranged required version with wild card on one end * @should allow single entry for required version * @should allow required version with wild card * @should allow non numeric character required version * @should allow ranged non numeric character required version * @should allow ranged non numeric character with wild card * @should allow ranged non numeric character with wild card on one end * @should return false when openmrs version beyond wild card range * @should return false when required version beyond openmrs version * @should return false when required version with wild card beyond openmrs version * @should return false when required version with wild card on one end beyond openmrs version * @should return false when single entry required version beyond openmrs version * @should allow release type in the version * @should match when revision number is below maximum revision number * @should not match when revision number is above maximum revision number * @should correctly set upper and lower limit for versionRange with qualifiers and wild card * @should match when version has wild card plus qualifier and is within boundary * @should not match when version has wild card plus qualifier and is outside boundary * @should match when version has wild card and is within boundary * @should not match when version has wild card and is outside boundary * @should return true when required version is empty */ public static boolean matchRequiredVersions(String version, String versionRange) { // There is a null check so no risk in keeping the literal on the right side if (StringUtils.isNotEmpty(versionRange)) { String[] ranges = versionRange.split(","); for (String range : ranges) { // need to externalize this string String separator = "-"; if (range.indexOf("*") > 0 || range.indexOf(separator) > 0 && (!isVersionWithQualifier(range))) { // if it contains "*" or "-" then we must separate those two // assume it's always going to be two part // assign the upper and lower bound // if there's no "-" to split lower and upper bound // then assign the same value for the lower and upper String lowerBound = range; String upperBound = range; int indexOfSeparator = range.indexOf(separator); while (indexOfSeparator > 0) { lowerBound = range.substring(0, indexOfSeparator); upperBound = range.substring(indexOfSeparator + 1); if (upperBound.matches("^\\s?\\d+.*")) { break; } indexOfSeparator = range.indexOf(separator, indexOfSeparator + 1); } // only preserve part of the string that match the following format: // - xx.yy.* // - xx.yy.zz* lowerBound = StringUtils.remove(lowerBound, lowerBound.replaceAll("^\\s?\\d+[\\.\\d+\\*?|\\.\\*]+", "")); upperBound = StringUtils.remove(upperBound, upperBound.replaceAll("^\\s?\\d+[\\.\\d+\\*?|\\.\\*]+", "")); // if the lower contains "*" then change it to zero if (lowerBound.indexOf("*") > 0) { lowerBound = lowerBound.replaceAll("\\*", "0"); } // if the upper contains "*" then change it to maxRevisionNumber if (upperBound.indexOf("*") > 0) { upperBound = upperBound.replaceAll("\\*", Integer.toString(Integer.MAX_VALUE)); } int lowerReturn = compareVersion(version, lowerBound); int upperReturn = compareVersion(version, upperBound); if (lowerReturn < 0 || upperReturn > 0) { log.debug("Version " + version + " is not between " + lowerBound + " and " + upperBound); } else { return true; } } else { if (compareVersion(version, range) < 0) { log.debug("Version " + version + " is below " + range); } else { return true; } } } } else { //no version checking if required version is not specified return true; } return false; } /** * This method is an enhancement of {@link #compareVersion(String, String)} and adds support for * wildcard characters and upperbounds. <br> * <br> * <br> * The require version number in the config file can be in the following format: * <ul> * <li>1.2.3</li> * <li>1.2.*</li> * <li>1.2.2 - 1.2.3</li> * <li>1.2.* - 1.3.*</li> * </ul> * <p> * Again the possible require version number formats with their interpretation: * <ul> * <li>1.2.3 means 1.2.3 and above</li> * <li>1.2.* means any version of the 1.2.x branch. That is 1.2.0, 1.2.1, 1.2.2,... but not 1.3.0, 1.4.0</li> * <li>1.2.2 - 1.2.3 means 1.2.2 and 1.2.3 (inclusive)</li> * <li>1.2.* - 1.3.* means any version of the 1.2.x and 1.3.x branch</li> * </ul> * </p> * * @param version openmrs version number to be compared * @param versionRange value in the config file for required openmrs version * @throws ModuleException if the <code>version</code> is not within the <code>value</code> * @should throw ModuleException if openmrs version beyond wild card range * @should throw ModuleException if required version beyond openmrs version * @should throw ModuleException if required version with wild card beyond openmrs version * @should throw ModuleException if required version with wild card on one end beyond openmrs * version * @should throw ModuleException if single entry required version beyond openmrs version * @should throw ModuleException if SNAPSHOT not handled correctly * @should handle SNAPSHOT versions * @should handle ALPHA versions */ public static void checkRequiredVersion(String version, String versionRange) throws ModuleException { if (!matchRequiredVersions(version, versionRange)) { String ms = Context.getMessageSourceService().getMessage("Module.requireVersion.outOfBounds", new String[] { versionRange, version }, Context.getLocale()); throw new ModuleException(ms); } } /** * Compares <code>version</code> to <code>value</code> version and value are strings like * 1.9.2.0 Returns <code>0</code> if either <code>version</code> or <code>value</code> is null. * * @param version String like 1.9.2.0 * @param value String like 1.9.2.0 * @return the value <code>0</code> if <code>version</code> is equal to the argument * <code>value</code>; a value less than <code>0</code> if <code>version</code> is * numerically less than the argument <code>value</code>; and a value greater than * <code>0</code> if <code>version</code> is numerically greater than the argument * <code>value</code> * @should correctly comparing two version numbers * @should treat SNAPSHOT as earliest version */ public static int compareVersion(String version, String value) { try { if (version == null || value == null) { return 0; } List<String> versions = new Vector<String>(); List<String> values = new Vector<String>(); String separator = "-"; // strip off any qualifier e.g. "-SNAPSHOT" int qualifierIndex = version.indexOf(separator); if (qualifierIndex != -1) { version = version.substring(0, qualifierIndex); } qualifierIndex = value.indexOf(separator); if (qualifierIndex != -1) { value = value.substring(0, qualifierIndex); } Collections.addAll(versions, version.split("\\.")); Collections.addAll(values, value.split("\\.")); // match the sizes of the lists while (versions.size() < values.size()) { versions.add("0"); } while (values.size() < versions.size()) { values.add("0"); } for (int x = 0; x < versions.size(); x++) { String verNum = versions.get(x).trim(); String valNum = values.get(x).trim(); Long ver = NumberUtils.toLong(verNum, 0); Long val = NumberUtils.toLong(valNum, 0); int ret = ver.compareTo(val); if (ret != 0) { return ret; } } } catch (NumberFormatException e) { log.error("Error while converting a version/value to an integer: " + version + "/" + value, e); } // default return value if an error occurs or elements are equal return 0; } /** * Checks for qualifier version (i.e "-SNAPSHOT", "-ALPHA" etc. after maven version conventions) * * @param version String like 1.9.2-SNAPSHOT * @return true if version contains qualifier */ public static boolean isVersionWithQualifier(String version) { Matcher matcher = Pattern.compile("(\\d+)\\.(\\d+)(\\.(\\d+))?(\\-([A-Za-z]+))").matcher(version); return matcher.matches(); } /** * Gets the folder where modules are stored. ModuleExceptions are thrown on errors * * @return folder containing modules * @should use the runtime property as the first choice if specified * @should return the correct file if the runtime property is an absolute path */ public static File getModuleRepository() { String folderName = Context.getRuntimeProperties().getProperty(ModuleConstants.REPOSITORY_FOLDER_RUNTIME_PROPERTY); if (StringUtils.isBlank(folderName)) { AdministrationService as = Context.getAdministrationService(); folderName = as.getGlobalProperty(ModuleConstants.REPOSITORY_FOLDER_PROPERTY, ModuleConstants.REPOSITORY_FOLDER_PROPERTY_DEFAULT); } // try to load the repository folder straight away. File folder = new File(folderName); // if the property wasn't a full path already, assume it was intended to be a folder in the // application directory if (!folder.exists()) { folder = new File(OpenmrsUtil.getApplicationDataDirectory(), folderName); } // now create the modules folder if it doesn't exist if (!folder.exists()) { log.warn("Module repository " + folder.getAbsolutePath() + " doesn't exist. Creating directories now."); folder.mkdirs(); } if (!folder.isDirectory()) { throw new ModuleException("Module repository is not a directory at: " + folder.getAbsolutePath()); } return folder; } /** * Utility method to convert a {@link File} object to a local URL. * * @param file a file object * @return absolute URL that points to the given file * @throws MalformedURLException if file can't be represented as URL for some reason */ public static URL file2url(final File file) throws MalformedURLException { if (file == null) { return null; } try { return file.getCanonicalFile().toURI().toURL(); } catch (MalformedURLException mue) { throw mue; } catch (IOException ioe) { throw new MalformedURLException("Cannot convert: " + file.getName() + " to url"); } catch (NoSuchMethodError nsme) { throw new MalformedURLException("Cannot convert: " + file.getName() + " to url"); } } /** * Expand the given <code>fileToExpand</code> jar to the <code>tmpModuleFile</code> directory * * If <code>name</code> is null, the entire jar is expanded. If<code>name</code> is not null, * then only that path/file is expanded. * * @param fileToExpand file pointing at a .jar * @param tmpModuleDir directory in which to place the files * @param name filename inside of the jar to look for and expand * @param keepFullPath if true, will recreate entire directory structure in tmpModuleDir * relating to <code>name</code>. if false will start directory structure at * <code>name</code> */ public static void expandJar(File fileToExpand, File tmpModuleDir, String name, boolean keepFullPath) throws IOException { JarFile jarFile = null; InputStream input = null; String docBase = tmpModuleDir.getAbsolutePath(); try { jarFile = new JarFile(fileToExpand); Enumeration<JarEntry> jarEntries = jarFile.entries(); boolean foundName = (name == null); // loop over all of the elements looking for the match to 'name' while (jarEntries.hasMoreElements()) { JarEntry jarEntry = jarEntries.nextElement(); if (name == null || jarEntry.getName().startsWith(name)) { String entryName = jarEntry.getName(); // trim out the name path from the name of the new file if (!keepFullPath && name != null) { entryName = entryName.replaceFirst(name, ""); } // if it has a slash, it's in a directory int last = entryName.lastIndexOf('/'); if (last >= 0) { File parent = new File(docBase, entryName.substring(0, last)); parent.mkdirs(); log.debug("Creating parent dirs: " + parent.getAbsolutePath()); } // we don't want to "expand" directories or empty names if (entryName.endsWith("/") || "".equals(entryName)) { continue; } input = jarFile.getInputStream(jarEntry); expand(input, docBase, entryName); input.close(); input = null; foundName = true; } } if (!foundName) { log.debug("Unable to find: " + name + " in file " + fileToExpand.getAbsolutePath()); } } catch (IOException e) { log.warn("Unable to delete tmpModuleFile on error", e); throw e; } finally { try { input.close(); } catch (Exception e) { /* pass */} try { jarFile.close(); } catch (Exception e) { /* pass */} } } private static File expand(InputStream input, String fileDir, String name) throws IOException { if (log.isDebugEnabled()) { log.debug("expanding: " + name); } File file = new File(fileDir, name); FileOutputStream outStream = null; try { outStream = new FileOutputStream(file); OpenmrsUtil.copyFile(input, outStream); } finally { try { outStream.close(); } catch (Exception e) { /* pass */} } return file; } /** * Downloads the contents of a URL and copies them to a string (Borrowed from oreilly) * * @param url * @return InputStream of contents * @should return a valid input stream for old module urls */ public static InputStream getURLStream(URL url) { InputStream in = null; try { URLConnection uc = url.openConnection(); uc.setDefaultUseCaches(false); uc.setUseCaches(false); uc.setRequestProperty("Cache-Control", "max-age=0,no-cache"); uc.setRequestProperty("Pragma", "no-cache"); log.debug("Logging an attempt to connect to: " + url); in = openConnectionCheckRedirects(uc); } catch (IOException io) { log.warn("io while reading: " + url, io); } return in; } /** * Convenience method to follow http to https redirects. Will follow a total of 5 redirects, * then fail out due to foolishness on the url's part. * * @param c the {@link URLConnection} to open * @return an {@link InputStream} that is not necessarily at the same url, possibly at a 403 * redirect. * @throws IOException * @see #getURLStream(URL) */ protected static InputStream openConnectionCheckRedirects(URLConnection c) throws IOException { boolean redir; int redirects = 0; InputStream in = null; do { if (c instanceof HttpURLConnection) { ((HttpURLConnection) c).setInstanceFollowRedirects(false); } // We want to open the input stream before getting headers // because getHeaderField() et al swallow IOExceptions. in = c.getInputStream(); redir = false; if (c instanceof HttpURLConnection) { HttpURLConnection http = (HttpURLConnection) c; int stat = http.getResponseCode(); if (stat == 300 || stat == 301 || stat == 302 || stat == 303 || stat == 305 || stat == 307) { URL base = http.getURL(); String loc = http.getHeaderField("Location"); URL target = null; if (loc != null) { target = new URL(base, loc); } http.disconnect(); // Redirection should be allowed only for HTTP and HTTPS // and should be limited to 5 redirections at most. if (target == null || !("http".equals(target.getProtocol()) || "https".equals(target.getProtocol())) || redirects >= 5) { throw new SecurityException("illegal URL redirect"); } redir = true; c = target.openConnection(); redirects++; } } } while (redir); return in; } /** * Downloads the contents of a URL and copies them to a string (Borrowed from oreilly) * * @param url * @return String contents of the URL * @should return an update rdf page for old https dev urls * @should return an update rdf page for old https module urls * @should return an update rdf page for module urls */ public static String getURL(URL url) { InputStream in = null; OutputStream out = null; String output = ""; try { in = getURLStream(url); if (in == null) { // skip this module if updateURL is not defined return ""; } out = new ByteArrayOutputStream(); OpenmrsUtil.copyFile(in, out); output = out.toString(); } catch (IOException io) { log.warn("io while reading: " + url, io); } finally { try { in.close(); } catch (Exception e) { /* pass */} try { out.close(); } catch (Exception e) { /* pass */} } return output; } /** * Iterates over the modules and checks each update.rdf file for an update * * @return True if an update was found for one of the modules, false if none were found * @throws ModuleException */ public static Boolean checkForModuleUpdates() throws ModuleException { Boolean updateFound = false; for (Module mod : ModuleFactory.getLoadedModules()) { String updateURL = mod.getUpdateURL(); if (StringUtils.isNotEmpty(updateURL)) { try { // get the contents pointed to by the url URL url = new URL(updateURL); if (!url.toString().endsWith(ModuleConstants.UPDATE_FILE_NAME)) { log.warn("Illegal url: " + url); continue; } String content = getURL(url); // skip empty or invalid updates if ("".equals(content)) { continue; } // process and parse the contents UpdateFileParser parser = new UpdateFileParser(content); parser.parse(); log.debug("Update for mod: " + mod.getModuleId() + " compareVersion result: " + compareVersion(mod.getVersion(), parser.getCurrentVersion())); // check the udpate.rdf version against the installed version if (compareVersion(mod.getVersion(), parser.getCurrentVersion()) < 0) { if (mod.getModuleId().equals(parser.getModuleId())) { mod.setDownloadURL(parser.getDownloadURL()); mod.setUpdateVersion(parser.getCurrentVersion()); updateFound = true; } else { log.warn("Module id does not match in update.rdf:" + parser.getModuleId()); } } else { mod.setDownloadURL(null); mod.setUpdateVersion(null); } } catch (ModuleException e) { log.warn("Unable to get updates from update.xml", e); } catch (MalformedURLException e) { log.warn("Unable to form a URL object out of: " + updateURL, e); } } } return updateFound; } /** * @return true/false whether the 'allow upload' or 'allow web admin' property has been turned * on */ public static Boolean allowAdmin() { Properties properties = Context.getRuntimeProperties(); String prop = properties.getProperty(ModuleConstants.RUNTIMEPROPERTY_ALLOW_UPLOAD, null); if (prop == null) { prop = properties.getProperty(ModuleConstants.RUNTIMEPROPERTY_ALLOW_ADMIN, "false"); } return "true".equals(prop); } /** * @see ModuleUtil#refreshApplicationContext(AbstractRefreshableApplicationContext, boolean, Module) */ public static AbstractRefreshableApplicationContext refreshApplicationContext(AbstractRefreshableApplicationContext ctx) { return refreshApplicationContext(ctx, false, null); } /** * Refreshes the given application context "properly" in OpenMRS. Will first shut down the * Context and destroy the classloader, then will refresh and set everything back up again. * * @param ctx Spring application context that needs refreshing. * @param isOpenmrsStartup if this refresh is being done at application startup. * @param startedModule the module that was just started and waiting on the context refresh. * @return AbstractRefreshableApplicationContext The newly refreshed application context. */ public static AbstractRefreshableApplicationContext refreshApplicationContext(AbstractRefreshableApplicationContext ctx, boolean isOpenmrsStartup, Module startedModule) { //notify all started modules that we are about to refresh the context Set<Module> startedModules = new LinkedHashSet<Module>(ModuleFactory.getStartedModulesInOrder()); for (Module module : startedModules) { try { if (module.getModuleActivator() != null) { module.getModuleActivator().willRefreshContext(); } } catch (Exception e) { log.warn("Unable to call willRefreshContext() method in the module's activator", e); } } OpenmrsClassLoader.saveState(); SchedulerUtil.shutdown(); ServiceContext.destroyInstance(); try { ctx.stop(); ctx.close(); } catch (Exception e) { log.warn("Exception while stopping and closing context: ", e); // Spring seems to be trying to refresh the context instead of /just/ stopping // pass } OpenmrsClassLoader.destroyInstance(); ctx.setClassLoader(OpenmrsClassLoader.getInstance()); Thread.currentThread().setContextClassLoader(OpenmrsClassLoader.getInstance()); ServiceContext.getInstance().startRefreshingContext(); try { ctx.refresh(); } finally { ServiceContext.getInstance().doneRefreshingContext(); } ctx.setClassLoader(OpenmrsClassLoader.getInstance()); Thread.currentThread().setContextClassLoader(OpenmrsClassLoader.getInstance()); OpenmrsClassLoader.restoreState(); SchedulerUtil.startup(Context.getRuntimeProperties()); OpenmrsClassLoader.setThreadsToNewClassLoader(); // reload the advice points that were lost when refreshing Spring if (log.isDebugEnabled()) { log.debug("Reloading advice for all started modules: " + startedModules.size()); } try { //The call backs in this block may need lazy loading of objects //which will fail because we use an OpenSessionInViewFilter whose opened session //was closed when the application context was refreshed as above. //So we need to open another session now. TRUNK-3739 Context.openSessionWithCurrentUser(); for (Module module : startedModules) { if (!module.isStarted()) { continue; } ModuleFactory.loadAdvice(module); try { ModuleFactory.passDaemonToken(module); if (module.getModuleActivator() != null) { module.getModuleActivator().contextRefreshed(); try { //if it is system start up, call the started method for all started modules if (isOpenmrsStartup) { module.getModuleActivator().started(); } //if refreshing the context after a user started or uploaded a new module else if (!isOpenmrsStartup && module.equals(startedModule)) { module.getModuleActivator().started(); } } catch (Exception e) { log.warn("Unable to invoke started() method on the module's activator", e); ModuleFactory.stopModule(module, true, true); } } } catch (Exception e) { log.warn("Unable to invoke method on the module's activator ", e); } } } finally { Context.closeSessionWithCurrentUser(); } return ctx; } /** * Looks at the &lt;moduleid&gt;.mandatory properties and at the currently started modules to make * sure that all mandatory modules have been started successfully. * * @throws ModuleException if a mandatory module isn't started * @should throw ModuleException if a mandatory module is not started */ protected static void checkMandatoryModulesStarted() throws ModuleException { List<String> mandatoryModuleIds = getMandatoryModules(); Set<String> startedModuleIds = ModuleFactory.getStartedModulesMap().keySet(); mandatoryModuleIds.removeAll(startedModuleIds); // any module ids left in the list are not started if (mandatoryModuleIds.size() > 0) { throw new MandatoryModuleException(mandatoryModuleIds); } } /** * Looks at the list of modules in {@link ModuleConstants#CORE_MODULES} to make sure that all * modules that are core to OpenMRS are started and have at least a minimum version that OpenMRS * needs. * * @throws ModuleException if a module that is core to OpenMRS is not started * @should throw ModuleException if a core module is not started */ protected static void checkOpenmrsCoreModulesStarted() throws OpenmrsCoreModuleException { // if there is a property telling us to ignore required modules, drop out early if (ignoreCoreModules()) { return; } // make a copy of the constant so we can modify the list Map<String, String> coreModules = new HashMap<String, String>(ModuleConstants.CORE_MODULES); Collection<Module> startedModules = ModuleFactory.getStartedModulesMap().values(); // loop through the current modules and test them for (Module mod : startedModules) { String moduleId = mod.getModuleId(); if (coreModules.containsKey(moduleId)) { String coreReqVersion = coreModules.get(moduleId); if (compareVersion(mod.getVersion(), coreReqVersion) >= 0) { coreModules.remove(moduleId); } else { log.debug("Module: " + moduleId + " is a core module and is started, but its version: " + mod.getVersion() + " is not within the required version: " + coreReqVersion); } } } // any module ids left in the list are not started if (coreModules.size() > 0) { throw new OpenmrsCoreModuleException(coreModules); } } /** * Uses the runtime properties to determine if the core modules should be enforced or not. * * @return true if the core modules list can be ignored. */ public static boolean ignoreCoreModules() { String ignoreCoreModules = Context.getRuntimeProperties().getProperty(ModuleConstants.IGNORE_CORE_MODULES_PROPERTY, "false"); return Boolean.parseBoolean(ignoreCoreModules); } /** * Returns all modules that are marked as mandatory. Currently this means there is a * &lt;moduleid&gt;.mandatory=true global property. * * @return list of modules ids for mandatory modules * @should return mandatory module ids */ public static List<String> getMandatoryModules() { List<String> mandatoryModuleIds = new ArrayList<String>(); try { List<GlobalProperty> props = Context.getAdministrationService().getGlobalPropertiesBySuffix(".mandatory"); for (GlobalProperty prop : props) { if ("true".equalsIgnoreCase(prop.getPropertyValue())) { mandatoryModuleIds.add(prop.getProperty().replace(".mandatory", "")); } } } catch (Exception e) { log.warn("Unable to get the mandatory module list", e); } return mandatoryModuleIds; } /** * <pre> * Gets the module that should handle a path. The path you pass in should be a module id (in * path format, i.e. /ui/springmvc, not ui.springmvc) followed by a resource. Something like * the following: * /ui/springmvc/css/ui.css * * The first running module out of the following would be returned: * ui.springmvc.css * ui.springmvc * ui * </pre> * * @param path * @return the running module that matches the most of the given path * @should handle ui springmvc css ui dot css when ui dot springmvc module is running * @should handle ui springmvc css ui dot css when ui module is running * @should return null for ui springmvc css ui dot css when no relevant module is running */ public static Module getModuleForPath(String path) { int ind = path.lastIndexOf('/'); if (ind <= 0) { throw new IllegalArgumentException( "Input must be /moduleId/resource. Input needs a / after the first character: " + path); } String moduleId = path.startsWith("/") ? path.substring(1, ind) : path.substring(0, ind); moduleId = moduleId.replace('/', '.'); // iterate over progressively shorter module ids while (true) { Module mod = ModuleFactory.getStartedModuleById(moduleId); if (mod != null) { return mod; } // try the next shorter module id ind = moduleId.lastIndexOf('.'); if (ind < 0) { break; } moduleId = moduleId.substring(0, ind); } return null; } /** * Takes a global path and returns the local path within the specified module. For example * calling this method with the path "/ui/springmvc/css/ui.css" and the ui.springmvc module, you * would get "/css/ui.css". * * @param module * @param path * @return local path * @should handle ui springmvc css ui dot css example */ public static String getPathForResource(Module module, String path) { if (path.startsWith("/")) { path = path.substring(1); } return path.substring(module.getModuleIdAsPath().length()); } /** * This loops over all FILES in this jar to get the package names. If there is an empty * directory in this jar it is not returned as a providedPackage. * * @param file jar file to look into * @return list of strings of package names in this jar */ public static Collection<String> getPackagesFromFile(File file) { // End early if we're given a non jar file if (!file.getName().endsWith(".jar")) { return Collections.<String> emptySet(); } Set<String> packagesProvided = new HashSet<String>(); JarFile jar = null; try { jar = new JarFile(file); Enumeration<JarEntry> jarEntries = jar.entries(); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = jarEntries.nextElement(); if (jarEntry.isDirectory()) { // skip over directory entries, we only care about files continue; } String name = jarEntry.getName(); // Skip over some folders in the jar/omod if (name.startsWith("lib") || name.startsWith("META-INF") || name.startsWith("web/module")) { continue; } Integer indexOfLastSlash = name.lastIndexOf("/"); if (indexOfLastSlash <= 0) { continue; } String packageName = name.substring(0, indexOfLastSlash); packageName = packageName.replaceAll("/", "."); if (packagesProvided.add(packageName)) { if (log.isTraceEnabled()) { log.trace("Adding module's jarentry with package: " + packageName); } } } jar.close(); } catch (IOException e) { log.error("Error while reading file: " + file.getAbsolutePath(), e); } finally { if (jar != null) { try { jar.close(); } catch (IOException e) { // Ignore quietly } } } return packagesProvided; } /** * Get a resource as from the module's api jar. Api jar should be in the omod's lib folder. * * @param jarFile omod file loaded as jar * @param moduleId id of the module * @param version version of the module * @param resource name of a resource from the api jar * @return resource as an input stream or <code>null</code> if resource cannot be loaded * @should load file from api as input stream * @should return null if api is not found * @should return null if file is not found in api */ public static InputStream getResourceFromApi(JarFile jarFile, String moduleId, String version, String resource) { String apiLocation = "lib/" + moduleId + "-api-" + version + ".jar"; return getResourceFromInnerJar(jarFile, apiLocation, resource); } /** * Load resource from a jar inside a jar. * * @param outerJarFile jar file that contains a jar file * @param innerJarFileLocation inner jar file location relative to the outer jar * @param resource path to a resource relative to the inner jar * @return resource from the inner jar as an input stream or <code>null</code> if resource cannot be loaded */ private static InputStream getResourceFromInnerJar(JarFile outerJarFile, String innerJarFileLocation, String resource) { File tempFile = null; FileOutputStream tempOut = null; JarFile innerJarFile = null; InputStream innerInputStream = null; try { tempFile = File.createTempFile("tempFile", "jar"); tempOut = new FileOutputStream(tempFile); ZipEntry innerJarFileEntry = outerJarFile.getEntry(innerJarFileLocation); if (innerJarFileEntry != null) { IOUtils.copy(outerJarFile.getInputStream(innerJarFileEntry), tempOut); innerJarFile = new JarFile(tempFile); ZipEntry targetEntry = innerJarFile.getEntry(resource); if (targetEntry != null) { // clone InputStream to make it work after the innerJarFile is closed innerInputStream = innerJarFile.getInputStream(targetEntry); byte[] byteArray = IOUtils.toByteArray(innerInputStream); return new ByteArrayInputStream(byteArray); } } } catch (IOException e) { log.error("Unable to get '" + resource + "' from '" + innerJarFileLocation + "' of '" + outerJarFile.getName() + "'", e); } finally { IOUtils.closeQuietly(tempOut); IOUtils.closeQuietly(innerInputStream); // close inner jar file before attempting to delete temporary file try { if (innerJarFile != null) { innerJarFile.close(); } } catch (IOException e) { log.warn("Unable to close inner jarfile: " + innerJarFile, e); } // delete temporary file if (tempFile != null && !tempFile.delete()) { log.warn("Could not delete temporary jarfile: " + tempFile); } } return null; } /** * Gets the root folder of a module's sources during development * * @param moduleId the module id * @return the module's development folder is specified, else null */ public static File getDevelopmentDirectory(String moduleId) { String directory = System.getProperty(moduleId + ".development.directory"); if (StringUtils.isNotBlank(directory)) { return new File(directory); } return null; } }
package bisq.desktop.util; import bisq.desktop.components.AddressTextField; import bisq.desktop.components.AutoTooltipButton; import bisq.desktop.components.AutoTooltipCheckBox; import bisq.desktop.components.AutoTooltipLabel; import bisq.desktop.components.AutoTooltipRadioButton; import bisq.desktop.components.AutoTooltipSlideToggleButton; import bisq.desktop.components.AutocompleteComboBox; import bisq.desktop.components.BalanceTextField; import bisq.desktop.components.BisqTextArea; import bisq.desktop.components.BisqTextField; import bisq.desktop.components.BsqAddressTextField; import bisq.desktop.components.BusyAnimation; import bisq.desktop.components.ExternalHyperlink; import bisq.desktop.components.FundsTextField; import bisq.desktop.components.HyperlinkWithIcon; import bisq.desktop.components.InfoInputTextField; import bisq.desktop.components.InfoTextField; import bisq.desktop.components.InputTextField; import bisq.desktop.components.PasswordTextField; import bisq.desktop.components.TextFieldWithCopyIcon; import bisq.desktop.components.TextFieldWithIcon; import bisq.desktop.components.TitledGroupBg; import bisq.desktop.components.TxIdTextField; import bisq.core.locale.Res; import bisq.common.util.Tuple2; import bisq.common.util.Tuple3; import bisq.common.util.Tuple4; import de.jensd.fx.fontawesome.AwesomeDude; import de.jensd.fx.fontawesome.AwesomeIcon; import de.jensd.fx.glyphs.GlyphIcons; import de.jensd.fx.glyphs.materialdesignicons.utils.MaterialDesignIconFactory; import com.jfoenix.controls.JFXComboBox; import com.jfoenix.controls.JFXDatePicker; import com.jfoenix.controls.JFXTextArea; import com.jfoenix.controls.JFXToggleButton; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.ContentDisplay; import javafx.scene.control.DatePicker; import javafx.scene.control.Label; import javafx.scene.control.ListView; import javafx.scene.control.RadioButton; import javafx.scene.control.TableView; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.control.ToggleButton; import javafx.scene.control.ToggleGroup; import javafx.scene.layout.FlowPane; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.Priority; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.geometry.HPos; import javafx.geometry.Insets; import javafx.geometry.Pos; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import org.jetbrains.annotations.NotNull; import static bisq.desktop.util.GUIUtil.getComboBoxButtonCell; public class FormBuilder { private static final String MATERIAL_DESIGN_ICONS = "'Material Design Icons'"; // TitledGroupBg public static TitledGroupBg addTitledGroupBg(GridPane gridPane, int rowIndex, int rowSpan, String title) { return addTitledGroupBg(gridPane, rowIndex, rowSpan, title, 0); } public static TitledGroupBg addTitledGroupBg(GridPane gridPane, int rowIndex, int columnIndex, int rowSpan, String title) { TitledGroupBg titledGroupBg = addTitledGroupBg(gridPane, rowIndex, rowSpan, title, 0); GridPane.setColumnIndex(titledGroupBg, columnIndex); return titledGroupBg; } public static TitledGroupBg addTitledGroupBg(GridPane gridPane, int rowIndex, int columnIndex, int rowSpan, String title, double top) { TitledGroupBg titledGroupBg = addTitledGroupBg(gridPane, rowIndex, rowSpan, title, top); GridPane.setColumnIndex(titledGroupBg, columnIndex); return titledGroupBg; } public static TitledGroupBg addTitledGroupBg(GridPane gridPane, int rowIndex, int rowSpan, String title, double top) { TitledGroupBg titledGroupBg = new TitledGroupBg(); titledGroupBg.setText(title); titledGroupBg.prefWidthProperty().bind(gridPane.widthProperty()); GridPane.setRowIndex(titledGroupBg, rowIndex); GridPane.setRowSpan(titledGroupBg, rowSpan); GridPane.setMargin(titledGroupBg, new Insets(top + 8, -10, -12, -10)); gridPane.getChildren().add(titledGroupBg); return titledGroupBg; } // Label public static Label addLabel(GridPane gridPane, int rowIndex, String title) { return addLabel(gridPane, rowIndex, title, 0); } public static Label addLabel(GridPane gridPane, int rowIndex, String title, double top) { Label label = new AutoTooltipLabel(title); GridPane.setRowIndex(label, rowIndex); GridPane.setMargin(label, new Insets(top, 0, 0, 0)); gridPane.getChildren().add(label); return label; } // Label + Subtext public static Tuple3<Label, Label, VBox> addLabelWithSubText(GridPane gridPane, int rowIndex, String title, String description) { return addLabelWithSubText(gridPane, rowIndex, title, description, 0); } public static Tuple3<Label, Label, VBox> addLabelWithSubText(GridPane gridPane, int rowIndex, String title, String description, double top) { Label label = new AutoTooltipLabel(title); Label subText = new AutoTooltipLabel(description); VBox vBox = new VBox(); vBox.getChildren().setAll(label, subText); GridPane.setRowIndex(vBox, rowIndex); GridPane.setMargin(vBox, new Insets(top, 0, 0, 0)); gridPane.getChildren().add(vBox); return new Tuple3<>(label, subText, vBox); } // Multiline Label public static Label addMultilineLabel(GridPane gridPane, int rowIndex) { return addMultilineLabel(gridPane, rowIndex, 0); } public static Label addMultilineLabel(GridPane gridPane, int rowIndex, String text) { return addMultilineLabel(gridPane, rowIndex, text, 0); } public static Label addMultilineLabel(GridPane gridPane, int rowIndex, double top) { return addMultilineLabel(gridPane, rowIndex, "", top); } public static Label addMultilineLabel(GridPane gridPane, int rowIndex, String text, double top) { return addMultilineLabel(gridPane, rowIndex, text, top, 600); } public static Label addMultilineLabel(GridPane gridPane, int rowIndex, String text, double top, double maxWidth) { Label label = new AutoTooltipLabel(text); label.setWrapText(true); label.setMaxWidth(maxWidth); GridPane.setHalignment(label, HPos.LEFT); GridPane.setHgrow(label, Priority.ALWAYS); GridPane.setRowIndex(label, rowIndex); GridPane.setMargin(label, new Insets(top + Layout.FLOATING_LABEL_DISTANCE, 0, 0, 0)); gridPane.getChildren().add(label); return label; } // Label + TextField public static Tuple3<Label, TextField, VBox> addTopLabelReadOnlyTextField(GridPane gridPane, int rowIndex, String title) { return addTopLabelTextField(gridPane, rowIndex, title, "", -15); } public static Tuple3<Label, TextField, VBox> addTopLabelReadOnlyTextField(GridPane gridPane, int rowIndex, int columnIndex, String title) { Tuple3<Label, TextField, VBox> tuple = addTopLabelTextField(gridPane, rowIndex, title, "", -15); GridPane.setColumnIndex(tuple.third, columnIndex); return tuple; } public static Tuple3<Label, TextField, VBox> addTopLabelReadOnlyTextField(GridPane gridPane, int rowIndex, String title, double top) { return addTopLabelTextField(gridPane, rowIndex, title, "", top - 15); } public static Tuple3<Label, TextField, VBox> addTopLabelReadOnlyTextField(GridPane gridPane, int rowIndex, String title, String value) { return addTopLabelReadOnlyTextField(gridPane, rowIndex, title, value, 0); } public static Tuple3<Label, TextField, VBox> addTopLabelReadOnlyTextField(GridPane gridPane, int rowIndex, int columnIndex, String title, String value, double top) { Tuple3<Label, TextField, VBox> tuple = addTopLabelTextField(gridPane, rowIndex, title, value, top - 15); GridPane.setColumnIndex(tuple.third, columnIndex); return tuple; } public static Tuple3<Label, TextField, VBox> addTopLabelReadOnlyTextField(GridPane gridPane, int rowIndex, int columnIndex, String title, double top) { Tuple3<Label, TextField, VBox> tuple = addTopLabelTextField(gridPane, rowIndex, title, "", top - 15); GridPane.setColumnIndex(tuple.third, columnIndex); return tuple; } public static Tuple3<Label, TextField, VBox> addTopLabelReadOnlyTextField(GridPane gridPane, int rowIndex, String title, String value, double top) { return addTopLabelTextField(gridPane, rowIndex, title, value, top - 15); } public static Tuple3<Label, TextField, VBox> addTopLabelTextField(GridPane gridPane, int rowIndex, String title) { return addTopLabelTextField(gridPane, rowIndex, title, "", 0); } public static Tuple3<Label, TextField, VBox> addCompactTopLabelTextField(GridPane gridPane, int rowIndex, String title, String value) { return addTopLabelTextField(gridPane, rowIndex, title, value, -Layout.FLOATING_LABEL_DISTANCE); } public static Tuple3<Label, TextField, VBox> addCompactTopLabelTextField(GridPane gridPane, int rowIndex, int colIndex, String title, String value) { final Tuple3<Label, TextField, VBox> labelTextFieldVBoxTuple3 = addTopLabelTextField(gridPane, rowIndex, title, value, -Layout.FLOATING_LABEL_DISTANCE); GridPane.setColumnIndex(labelTextFieldVBoxTuple3.third, colIndex); return labelTextFieldVBoxTuple3; } public static Tuple3<Label, TextField, VBox> addCompactTopLabelTextField(GridPane gridPane, int rowIndex, String title, String value, double top) { return addTopLabelTextField(gridPane, rowIndex, title, value, top - Layout.FLOATING_LABEL_DISTANCE); } public static Tuple3<Label, TextField, VBox> addTopLabelTextField(GridPane gridPane, int rowIndex, String title, String value) { return addTopLabelTextField(gridPane, rowIndex, title, value, 0); } public static Tuple3<Label, TextField, VBox> addTopLabelTextField(GridPane gridPane, int rowIndex, String title, double top) { return addTopLabelTextField(gridPane, rowIndex, title, "", top); } public static Tuple3<Label, TextField, VBox> addTopLabelTextField(GridPane gridPane, int rowIndex, String title, String value, double top) { TextField textField = new BisqTextField(value); textField.setEditable(false); textField.setFocusTraversable(false); final Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, title, textField, top); // TODO not 100% sure if that is a good idea.... //topLabelWithVBox.first.getStyleClass().add("jfx-text-field-top-label"); return new Tuple3<>(topLabelWithVBox.first, textField, topLabelWithVBox.second); } public static Tuple2<TextField, Button> addTextFieldWithEditButton(GridPane gridPane, int rowIndex, String title) { TextField textField = new BisqTextField(); textField.setPromptText(title); textField.setEditable(false); textField.setFocusTraversable(false); textField.setPrefWidth(Layout.INITIAL_WINDOW_WIDTH); Button button = new AutoTooltipButton("..."); button.setStyle("-fx-min-width: 35px; -fx-pref-height: 20; -fx-padding: 3 3 3 3; -fx-border-insets: 5px;"); button.managedProperty().bind(button.visibleProperty()); VBox vBoxButton = new VBox(button); vBoxButton.setAlignment(Pos.CENTER); HBox hBox2 = new HBox(textField, vBoxButton); Label label = getTopLabel(title); VBox textFieldVbox = getTopLabelVBox(0); textFieldVbox.getChildren().addAll(label, hBox2); gridPane.getChildren().add(textFieldVbox); GridPane.setRowIndex(textFieldVbox, rowIndex); GridPane.setMargin(textFieldVbox, new Insets(Layout.FLOATING_LABEL_DISTANCE, 0, 0, 0)); return new Tuple2<>(textField, button); } // Confirmation Fields public static Tuple2<Label, Label> addConfirmationLabelLabel(GridPane gridPane, int rowIndex, String title1, String title2) { return addConfirmationLabelLabel(gridPane, rowIndex, title1, title2, 0); } public static Tuple2<Label, Label> addConfirmationLabelLabel(GridPane gridPane, int rowIndex, String title1, String title2, double top) { Label label1 = addLabel(gridPane, rowIndex, title1); label1.getStyleClass().add("confirmation-label"); Label label2 = addLabel(gridPane, rowIndex, title2); label2.getStyleClass().add("confirmation-value"); GridPane.setColumnIndex(label2, 1); GridPane.setMargin(label1, new Insets(top, 0, 0, 0)); GridPane.setHalignment(label1, HPos.LEFT); GridPane.setMargin(label2, new Insets(top, 0, 0, 0)); return new Tuple2<>(label1, label2); } public static Tuple2<Label, TextArea> addConfirmationLabelTextArea(GridPane gridPane, int rowIndex, String title1, String title2, double top) { Label label = addLabel(gridPane, rowIndex, title1); label.getStyleClass().add("confirmation-label"); TextArea textArea = addTextArea(gridPane, rowIndex, title2); ((JFXTextArea) textArea).setLabelFloat(false); GridPane.setColumnIndex(textArea, 1); GridPane.setMargin(label, new Insets(top, 0, 0, 0)); GridPane.setHalignment(label, HPos.LEFT); GridPane.setMargin(textArea, new Insets(top, 0, 0, 0)); return new Tuple2<>(label, textArea); } // Label + TextFieldWithIcon public static Tuple2<Label, TextFieldWithIcon> addTopLabelTextFieldWithIcon(GridPane gridPane, int rowIndex, String title, double top) { return addTopLabelTextFieldWithIcon(gridPane, rowIndex, 0, title, top); } public static Tuple2<Label, TextFieldWithIcon> addTopLabelTextFieldWithIcon(GridPane gridPane, int rowIndex, int columnIndex, String title, double top) { TextFieldWithIcon textFieldWithIcon = new TextFieldWithIcon(); textFieldWithIcon.setMouseTransparent(true); textFieldWithIcon.setFocusTraversable(false); return new Tuple2<>(addTopLabelWithVBox(gridPane, rowIndex, columnIndex, title, textFieldWithIcon, top).first, textFieldWithIcon); } // HyperlinkWithIcon public static HyperlinkWithIcon addHyperlinkWithIcon(GridPane gridPane, int rowIndex, String title, String url) { return addHyperlinkWithIcon(gridPane, rowIndex, title, url, 0); } public static HyperlinkWithIcon addHyperlinkWithIcon(GridPane gridPane, int rowIndex, String title, String url, double top) { HyperlinkWithIcon hyperlinkWithIcon = new ExternalHyperlink(title); hyperlinkWithIcon.setOnAction(e -> GUIUtil.openWebPage(url)); GridPane.setRowIndex(hyperlinkWithIcon, rowIndex); GridPane.setColumnIndex(hyperlinkWithIcon, 0); GridPane.setMargin(hyperlinkWithIcon, new Insets(top, 0, 0, 0)); GridPane.setHalignment(hyperlinkWithIcon, HPos.LEFT); gridPane.getChildren().add(hyperlinkWithIcon); return hyperlinkWithIcon; } // Label + HyperlinkWithIcon public static Tuple2<Label, HyperlinkWithIcon> addLabelHyperlinkWithIcon(GridPane gridPane, int rowIndex, String labelTitle, String title, String url) { return addLabelHyperlinkWithIcon(gridPane, rowIndex, labelTitle, title, url, 0); } public static Tuple2<Label, HyperlinkWithIcon> addLabelHyperlinkWithIcon(GridPane gridPane, int rowIndex, String labelTitle, String title, String url, double top) { Label label = addLabel(gridPane, rowIndex, labelTitle, top); HyperlinkWithIcon hyperlinkWithIcon = new ExternalHyperlink(title); hyperlinkWithIcon.setOnAction(e -> GUIUtil.openWebPage(url)); GridPane.setRowIndex(hyperlinkWithIcon, rowIndex); GridPane.setMargin(hyperlinkWithIcon, new Insets(top, 0, 0, -4)); gridPane.getChildren().add(hyperlinkWithIcon); return new Tuple2<>(label, hyperlinkWithIcon); } public static Tuple3<Label, HyperlinkWithIcon, VBox> addTopLabelHyperlinkWithIcon(GridPane gridPane, int rowIndex, int columnIndex, String title, String value, String url, double top) { Tuple3<Label, HyperlinkWithIcon, VBox> tuple = addTopLabelHyperlinkWithIcon(gridPane, rowIndex, title, value, url, top); GridPane.setColumnIndex(tuple.third, columnIndex); return tuple; } public static Tuple3<Label, HyperlinkWithIcon, VBox> addTopLabelHyperlinkWithIcon(GridPane gridPane, int rowIndex, String title, String value, String url, double top) { HyperlinkWithIcon hyperlinkWithIcon = new ExternalHyperlink(value); hyperlinkWithIcon.setOnAction(e -> GUIUtil.openWebPage(url)); hyperlinkWithIcon.getStyleClass().add("hyperlink-with-icon"); GridPane.setRowIndex(hyperlinkWithIcon, rowIndex); Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, title, hyperlinkWithIcon, top - 15); return new Tuple3<>(topLabelWithVBox.first, hyperlinkWithIcon, topLabelWithVBox.second); } // TextArea public static TextArea addTextArea(GridPane gridPane, int rowIndex, String prompt) { return addTextArea(gridPane, rowIndex, prompt, 0); } public static TextArea addTextArea(GridPane gridPane, int rowIndex, String prompt, double top) { JFXTextArea textArea = new BisqTextArea(); textArea.setPromptText(prompt); textArea.setLabelFloat(true); textArea.setWrapText(true); GridPane.setRowIndex(textArea, rowIndex); GridPane.setColumnIndex(textArea, 0); GridPane.setMargin(textArea, new Insets(top + Layout.FLOATING_LABEL_DISTANCE, 0, 0, 0)); gridPane.getChildren().add(textArea); return textArea; } // Label + TextArea public static Tuple2<Label, TextArea> addCompactTopLabelTextArea(GridPane gridPane, int rowIndex, String title, String prompt) { return addTopLabelTextArea(gridPane, rowIndex, title, prompt, -Layout.FLOATING_LABEL_DISTANCE); } public static Tuple2<Label, TextArea> addCompactTopLabelTextArea(GridPane gridPane, int rowIndex, int colIndex, String title, String prompt) { return addTopLabelTextArea(gridPane, rowIndex, colIndex, title, prompt, -Layout.FLOATING_LABEL_DISTANCE); } public static Tuple2<Label, TextArea> addTopLabelTextArea(GridPane gridPane, int rowIndex, String title, String prompt) { return addTopLabelTextArea(gridPane, rowIndex, title, prompt, 0); } public static Tuple2<Label, TextArea> addTopLabelTextArea(GridPane gridPane, int rowIndex, int colIndex, String title, String prompt) { return addTopLabelTextArea(gridPane, rowIndex, colIndex, title, prompt, 0); } public static Tuple2<Label, TextArea> addTopLabelTextArea(GridPane gridPane, int rowIndex, String title, String prompt, double top) { return addTopLabelTextArea(gridPane, rowIndex, 0, title, prompt, top); } public static Tuple2<Label, TextArea> addTopLabelTextArea(GridPane gridPane, int rowIndex, int colIndex, String title, String prompt, double top) { TextArea textArea = new BisqTextArea(); textArea.setPromptText(prompt); textArea.setWrapText(true); final Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, title, textArea, top); GridPane.setColumnIndex(topLabelWithVBox.second, colIndex); return new Tuple2<>(topLabelWithVBox.first, textArea); } // Label + DatePicker public static Tuple2<Label, DatePicker> addTopLabelDatePicker(GridPane gridPane, int rowIndex, String title, double top) { DatePicker datePicker = new JFXDatePicker(); final Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, title, datePicker, top); return new Tuple2<>(topLabelWithVBox.first, datePicker); } // Label + TxIdTextField @SuppressWarnings("UnusedReturnValue") public static Tuple2<Label, TxIdTextField> addLabelTxIdTextField(GridPane gridPane, int rowIndex, String title, String value) { return addLabelTxIdTextField(gridPane, rowIndex, title, value, 0); } public static Tuple2<Label, TxIdTextField> addLabelTxIdTextField(GridPane gridPane, int rowIndex, String title, String value, double top) { Label label = addLabel(gridPane, rowIndex, title, top); label.getStyleClass().add("confirmation-label"); GridPane.setHalignment(label, HPos.LEFT); TxIdTextField txTextField = new TxIdTextField(); txTextField.setup(value); GridPane.setRowIndex(txTextField, rowIndex); GridPane.setColumnIndex(txTextField, 1); gridPane.getChildren().add(txTextField); return new Tuple2<>(label, txTextField); } // Label + InputTextField public static InputTextField addInputTextField(GridPane gridPane, int rowIndex, String title) { return addInputTextField(gridPane, rowIndex, title, 0); } public static InputTextField addInputTextField(GridPane gridPane, int rowIndex, String title, double top) { InputTextField inputTextField = new InputTextField(); inputTextField.setLabelFloat(true); inputTextField.setPromptText(title); GridPane.setRowIndex(inputTextField, rowIndex); GridPane.setColumnIndex(inputTextField, 0); GridPane.setMargin(inputTextField, new Insets(top + Layout.FLOATING_LABEL_DISTANCE, 0, 0, 0)); gridPane.getChildren().add(inputTextField); return inputTextField; } // Label + InputTextField public static Tuple2<Label, InputTextField> addTopLabelInputTextField(GridPane gridPane, int rowIndex, String title) { return addTopLabelInputTextField(gridPane, rowIndex, title, 0); } public static Tuple2<Label, InputTextField> addTopLabelInputTextField(GridPane gridPane, int rowIndex, String title, double top) { final Tuple3<Label, InputTextField, VBox> topLabelWithVBox = addTopLabelInputTextFieldWithVBox(gridPane, rowIndex, title, top); return new Tuple2<>(topLabelWithVBox.first, topLabelWithVBox.second); } public static Tuple3<Label, InputTextField, VBox> addTopLabelInputTextFieldWithVBox(GridPane gridPane, int rowIndex, String title, double top) { InputTextField inputTextField = new InputTextField(); final Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, title, inputTextField, top); return new Tuple3<>(topLabelWithVBox.first, inputTextField, topLabelWithVBox.second); } // Label + InfoInputTextField public static Tuple2<Label, InfoInputTextField> addTopLabelInfoInputTextField(GridPane gridPane, int rowIndex, String title) { return addTopLabelInfoInputTextField(gridPane, rowIndex, title, 0); } public static Tuple2<Label, InfoInputTextField> addTopLabelInfoInputTextField(GridPane gridPane, int rowIndex, String title, double top) { InfoInputTextField inputTextField = new InfoInputTextField(); final Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, title, inputTextField, top); return new Tuple2<>(topLabelWithVBox.first, inputTextField); } // PasswordField public static PasswordTextField addPasswordTextField(GridPane gridPane, int rowIndex, String title) { return addPasswordTextField(gridPane, rowIndex, title, 0); } public static PasswordTextField addPasswordTextField(GridPane gridPane, int rowIndex, String title, double top) { PasswordTextField passwordField = new PasswordTextField(); passwordField.setPromptText(title); GridPane.setRowIndex(passwordField, rowIndex); GridPane.setColumnIndex(passwordField, 0); GridPane.setColumnSpan(passwordField, 2); GridPane.setMargin(passwordField, new Insets(top + 10, 0, 20, 0)); gridPane.getChildren().add(passwordField); return passwordField; } // Label + InputTextField + CheckBox public static Tuple3<Label, InputTextField, ToggleButton> addTopLabelInputTextFieldSlideToggleButton(GridPane gridPane, int rowIndex, String title, String toggleButtonTitle) { InputTextField inputTextField = new InputTextField(); ToggleButton toggleButton = new JFXToggleButton(); toggleButton.setText(toggleButtonTitle); VBox.setMargin(toggleButton, new Insets(4, 0, 0, 0)); final Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, title, inputTextField, 0); topLabelWithVBox.second.getChildren().add(toggleButton); return new Tuple3<>(topLabelWithVBox.first, inputTextField, toggleButton); } // Label + InputTextField + Button public static Tuple3<Label, InputTextField, Button> addTopLabelInputTextFieldButton(GridPane gridPane, int rowIndex, String title, String buttonTitle) { InputTextField inputTextField = new InputTextField(); Button button = new AutoTooltipButton(buttonTitle); button.setDefaultButton(true); HBox hBox = new HBox(); hBox.setSpacing(10); hBox.getChildren().addAll(inputTextField, button); HBox.setHgrow(inputTextField, Priority.ALWAYS); final Tuple2<Label, VBox> labelVBoxTuple2 = addTopLabelWithVBox(gridPane, rowIndex, title, hBox, 0); return new Tuple3<>(labelVBoxTuple2.first, inputTextField, button); } // Label + TextField + Button public static Tuple3<Label, TextField, Button> addTopLabelTextFieldButton(GridPane gridPane, int rowIndex, String title, String buttonTitle) { return addTopLabelTextFieldButton(gridPane, rowIndex, title, buttonTitle, 0); } public static Tuple3<Label, TextField, Button> addTopLabelTextFieldButton(GridPane gridPane, int rowIndex, String title, String buttonTitle, double top) { TextField textField = new BisqTextField(); textField.setEditable(false); textField.setMouseTransparent(true); textField.setFocusTraversable(false); Button button = new AutoTooltipButton(buttonTitle); button.setDefaultButton(true); HBox hBox = new HBox(); hBox.setSpacing(10); hBox.getChildren().addAll(textField, button); HBox.setHgrow(textField, Priority.ALWAYS); final Tuple2<Label, VBox> labelVBoxTuple2 = addTopLabelWithVBox(gridPane, rowIndex, title, hBox, top); return new Tuple3<>(labelVBoxTuple2.first, textField, button); } // Label + InputTextField + Label + InputTextField public static Tuple2<InputTextField, InputTextField> addInputTextFieldInputTextField(GridPane gridPane, int rowIndex, String title1, String title2) { InputTextField inputTextField1 = new InputTextField(); inputTextField1.setPromptText(title1); inputTextField1.setLabelFloat(true); InputTextField inputTextField2 = new InputTextField(); inputTextField2.setLabelFloat(true); inputTextField2.setPromptText(title2); HBox hBox = new HBox(); hBox.setSpacing(10); hBox.getChildren().addAll(inputTextField1, inputTextField2); GridPane.setRowIndex(hBox, rowIndex); GridPane.setColumnIndex(hBox, 0); GridPane.setMargin(hBox, new Insets(Layout.FLOATING_LABEL_DISTANCE, 0, 0, 0)); gridPane.getChildren().add(hBox); return new Tuple2<>(inputTextField1, inputTextField2); } // Label + TextField + Label + TextField public static Tuple4<Label, TextField, Label, TextField> addCompactTopLabelTextFieldTopLabelTextField(GridPane gridPane, int rowIndex, String title1, String title2) { TextField textField1 = new BisqTextField(); textField1.setEditable(false); textField1.setMouseTransparent(true); textField1.setFocusTraversable(false); final Tuple2<Label, VBox> topLabelWithVBox1 = getTopLabelWithVBox(title1, textField1); TextField textField2 = new BisqTextField(); textField2.setEditable(false); textField2.setMouseTransparent(true); textField2.setFocusTraversable(false); final Tuple2<Label, VBox> topLabelWithVBox2 = getTopLabelWithVBox(title2, textField2); HBox hBox = new HBox(); hBox.setSpacing(10); hBox.getChildren().addAll(topLabelWithVBox1.second, topLabelWithVBox2.second); GridPane.setRowIndex(hBox, rowIndex); gridPane.getChildren().add(hBox); return new Tuple4<>(topLabelWithVBox1.first, textField1, topLabelWithVBox2.first, textField2); } // Button + CheckBox public static Tuple2<Button, CheckBox> addButtonCheckBox(GridPane gridPane, int rowIndex, String buttonTitle, String checkBoxTitle) { return addButtonCheckBox(gridPane, rowIndex, buttonTitle, checkBoxTitle, 0); } public static Tuple2<Button, CheckBox> addButtonCheckBox(GridPane gridPane, int rowIndex, String buttonTitle, String checkBoxTitle, double top) { final Tuple3<Button, CheckBox, HBox> tuple = addButtonCheckBoxWithBox(gridPane, rowIndex, buttonTitle, checkBoxTitle, top); return new Tuple2<>(tuple.first, tuple.second); } public static Tuple3<Button, CheckBox, HBox> addButtonCheckBoxWithBox(GridPane gridPane, int rowIndex, String buttonTitle, String checkBoxTitle, double top) { Button button = new AutoTooltipButton(buttonTitle); CheckBox checkBox = new AutoTooltipCheckBox(checkBoxTitle); HBox hBox = new HBox(20); hBox.setAlignment(Pos.CENTER_LEFT); hBox.getChildren().addAll(button, checkBox); GridPane.setRowIndex(hBox, rowIndex); hBox.setPadding(new Insets(top, 0, 0, 0)); gridPane.getChildren().add(hBox); return new Tuple3<>(button, checkBox, hBox); } // CheckBox public static CheckBox addCheckBox(GridPane gridPane, int rowIndex, String checkBoxTitle) { return addCheckBox(gridPane, rowIndex, checkBoxTitle, 0); } public static CheckBox addCheckBox(GridPane gridPane, int rowIndex, String checkBoxTitle, double top) { return addCheckBox(gridPane, rowIndex, 0, checkBoxTitle, top); } public static CheckBox addCheckBox(GridPane gridPane, int rowIndex, int colIndex, String checkBoxTitle, double top) { CheckBox checkBox = new AutoTooltipCheckBox(checkBoxTitle); GridPane.setMargin(checkBox, new Insets(top, 0, 0, 0)); GridPane.setRowIndex(checkBox, rowIndex); GridPane.setColumnIndex(checkBox, colIndex); gridPane.getChildren().add(checkBox); return checkBox; } // RadioButton public static RadioButton addRadioButton(GridPane gridPane, int rowIndex, ToggleGroup toggleGroup, String title) { RadioButton radioButton = new AutoTooltipRadioButton(title); radioButton.setToggleGroup(toggleGroup); GridPane.setRowIndex(radioButton, rowIndex); gridPane.getChildren().add(radioButton); return radioButton; } // Label + RadioButton + RadioButton public static Tuple3<Label, RadioButton, RadioButton> addTopLabelRadioButtonRadioButton(GridPane gridPane, int rowIndex, ToggleGroup toggleGroup, String title, String radioButtonTitle1, String radioButtonTitle2, double top) { RadioButton radioButton1 = new AutoTooltipRadioButton(radioButtonTitle1); radioButton1.setToggleGroup(toggleGroup); radioButton1.setPadding(new Insets(6, 0, 0, 0)); RadioButton radioButton2 = new AutoTooltipRadioButton(radioButtonTitle2); radioButton2.setToggleGroup(toggleGroup); radioButton2.setPadding(new Insets(6, 0, 0, 0)); HBox hBox = new HBox(); hBox.setSpacing(10); hBox.getChildren().addAll(radioButton1, radioButton2); final Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, title, hBox, top); return new Tuple3<>(topLabelWithVBox.first, radioButton1, radioButton2); } // Label + TextField + RadioButton + RadioButton public static Tuple4<Label, TextField, RadioButton, RadioButton> addTopLabelTextFieldRadioButtonRadioButton(GridPane gridPane, int rowIndex, ToggleGroup toggleGroup, String title, String textFieldTitle, String radioButtonTitle1, String radioButtonTitle2, double top) { TextField textField = new BisqTextField(); textField.setPromptText(textFieldTitle); RadioButton radioButton1 = new AutoTooltipRadioButton(radioButtonTitle1); radioButton1.setToggleGroup(toggleGroup); radioButton1.setPadding(new Insets(6, 0, 0, 0)); RadioButton radioButton2 = new AutoTooltipRadioButton(radioButtonTitle2); radioButton2.setToggleGroup(toggleGroup); radioButton2.setPadding(new Insets(6, 0, 0, 0)); HBox hBox = new HBox(); hBox.setSpacing(10); hBox.getChildren().addAll(textField, radioButton1, radioButton2); final Tuple2<Label, VBox> labelVBoxTuple2 = addTopLabelWithVBox(gridPane, rowIndex, title, hBox, top); return new Tuple4<>(labelVBoxTuple2.first, textField, radioButton1, radioButton2); } // Label + CheckBox public static CheckBox addLabelCheckBox(GridPane gridPane, int rowIndex, String title) { return addLabelCheckBox(gridPane, rowIndex, title, 0); } public static CheckBox addLabelCheckBox(GridPane gridPane, int rowIndex, String title, double top) { CheckBox checkBox = new AutoTooltipCheckBox(title); GridPane.setRowIndex(checkBox, rowIndex); GridPane.setColumnIndex(checkBox, 0); GridPane.setMargin(checkBox, new Insets(top, 0, 0, 0)); gridPane.getChildren().add(checkBox); return checkBox; } // SlideToggleButton public static ToggleButton addSlideToggleButton(GridPane gridPane, int rowIndex, String title) { return addSlideToggleButton(gridPane, rowIndex, title, 0); } public static ToggleButton addSlideToggleButton(GridPane gridPane, int rowIndex, String title, double top) { ToggleButton toggleButton = new AutoTooltipSlideToggleButton(); toggleButton.setText(title); GridPane.setRowIndex(toggleButton, rowIndex); GridPane.setColumnIndex(toggleButton, 0); GridPane.setMargin(toggleButton, new Insets(top, 0, 0, 0)); gridPane.getChildren().add(toggleButton); return toggleButton; } // ComboBox public static <T> ComboBox<T> addComboBox(GridPane gridPane, int rowIndex, int top) { final JFXComboBox<T> comboBox = new JFXComboBox<>(); GridPane.setRowIndex(comboBox, rowIndex); GridPane.setMargin(comboBox, new Insets(top, 0, 0, 0)); gridPane.getChildren().add(comboBox); return comboBox; } // Label + ComboBox public static <T> Tuple2<Label, ComboBox<T>> addTopLabelComboBox(GridPane gridPane, int rowIndex, String title, String prompt, int top) { final Tuple3<VBox, Label, ComboBox<T>> tuple3 = addTopLabelComboBox(title, prompt, 0); final VBox vBox = tuple3.first; GridPane.setRowIndex(vBox, rowIndex); GridPane.setMargin(vBox, new Insets(top, 0, 0, 0)); gridPane.getChildren().add(vBox); return new Tuple2<>(tuple3.second, tuple3.third); } public static <T> Tuple3<VBox, Label, ComboBox<T>> addTopLabelComboBox(String title, String prompt) { return addTopLabelComboBox(title, prompt, 0); } public static <T> Tuple3<VBox, Label, ComboBox<T>> addTopLabelComboBox(String title, String prompt, int top) { Label label = getTopLabel(title); VBox vBox = getTopLabelVBox(top); final JFXComboBox<T> comboBox = new JFXComboBox<>(); comboBox.setPromptText(prompt); vBox.getChildren().addAll(label, comboBox); return new Tuple3<>(vBox, label, comboBox); } public static <T> Tuple3<VBox, Label, AutocompleteComboBox<T>> addTopLabelAutocompleteComboBox(String title) { return addTopLabelAutocompleteComboBox(title, 0); } public static <T> Tuple3<VBox, Label, AutocompleteComboBox<T>> addTopLabelAutocompleteComboBox(String title, int top) { Label label = getTopLabel(title); VBox vBox = getTopLabelVBox(top); final AutocompleteComboBox<T> comboBox = new AutocompleteComboBox<>(); vBox.getChildren().addAll(label, comboBox); return new Tuple3<>(vBox, label, comboBox); } @NotNull private static VBox getTopLabelVBox(int top) { VBox vBox = new VBox(); vBox.setSpacing(0); vBox.setPadding(new Insets(top, 0, 0, 0)); vBox.setAlignment(Pos.CENTER_LEFT); return vBox; } @NotNull private static Label getTopLabel(String title) { Label label = new AutoTooltipLabel(title); label.getStyleClass().add("small-text"); return label; } public static Tuple2<Label, VBox> addTopLabelWithVBox(GridPane gridPane, int rowIndex, String title, Node node, double top) { return addTopLabelWithVBox(gridPane, rowIndex, 0, title, node, top); } @NotNull public static Tuple2<Label, VBox> addTopLabelWithVBox(GridPane gridPane, int rowIndex, int columnIndex, String title, Node node, double top) { final Tuple2<Label, VBox> topLabelWithVBox = getTopLabelWithVBox(title, node); VBox vBox = topLabelWithVBox.second; GridPane.setRowIndex(vBox, rowIndex); GridPane.setColumnIndex(vBox, columnIndex); GridPane.setMargin(vBox, new Insets(top + Layout.FLOATING_LABEL_DISTANCE, 0, 0, 0)); gridPane.getChildren().add(vBox); return new Tuple2<>(topLabelWithVBox.first, vBox); } @NotNull public static Tuple2<Label, VBox> getTopLabelWithVBox(String title, Node node) { Label label = getTopLabel(title); VBox vBox = getTopLabelVBox(0); vBox.getChildren().addAll(label, node); return new Tuple2<>(label, vBox); } // Label + ComboBox public static <T> ComboBox<T> addComboBox(GridPane gridPane, int rowIndex) { return addComboBox(gridPane, rowIndex, null, 0); } public static <T> ComboBox<T> addComboBox(GridPane gridPane, int rowIndex, String title) { return addComboBox(gridPane, rowIndex, title, 0); } public static <T> ComboBox<T> addComboBox(GridPane gridPane, int rowIndex, String title, double top) { JFXComboBox<T> comboBox = new JFXComboBox<>(); comboBox.setLabelFloat(true); comboBox.setPromptText(title); comboBox.setMaxWidth(Double.MAX_VALUE); // Default ComboBox does not show promptText after clear selection. comboBox.setButtonCell(getComboBoxButtonCell(title, comboBox)); GridPane.setRowIndex(comboBox, rowIndex); GridPane.setColumnIndex(comboBox, 0); GridPane.setMargin(comboBox, new Insets(top + Layout.FLOATING_LABEL_DISTANCE, 0, 0, 0)); gridPane.getChildren().add(comboBox); return comboBox; } // Label + AutocompleteComboBox public static <T> Tuple2<Label, ComboBox<T>> addLabelAutocompleteComboBox(GridPane gridPane, int rowIndex, String title, double top) { AutocompleteComboBox<T> comboBox = new AutocompleteComboBox<>(); final Tuple2<Label, VBox> labelVBoxTuple2 = addTopLabelWithVBox(gridPane, rowIndex, title, comboBox, top); return new Tuple2<>(labelVBoxTuple2.first, comboBox); } // Label + TextField + AutocompleteComboBox public static <T> Tuple4<Label, TextField, Label, ComboBox<T>> addTopLabelTextFieldAutocompleteComboBox( GridPane gridPane, int rowIndex, String titleTextfield, String titleCombobox ) { return addTopLabelTextFieldAutocompleteComboBox(gridPane, rowIndex, titleTextfield, titleCombobox, 0); } public static <T> Tuple4<Label, TextField, Label, ComboBox<T>> addTopLabelTextFieldAutocompleteComboBox( GridPane gridPane, int rowIndex, String titleTextfield, String titleCombobox, double top ) { HBox hBox = new HBox(); hBox.setSpacing(10); final VBox topLabelVBox1 = getTopLabelVBox(5); final Label topLabel1 = getTopLabel(titleTextfield); final TextField textField = new BisqTextField(); topLabelVBox1.getChildren().addAll(topLabel1, textField); final VBox topLabelVBox2 = getTopLabelVBox(5); final Label topLabel2 = getTopLabel(titleCombobox); AutocompleteComboBox<T> comboBox = new AutocompleteComboBox<>(); comboBox.setPromptText(titleCombobox); comboBox.setLabelFloat(true); topLabelVBox2.getChildren().addAll(topLabel2, comboBox); hBox.getChildren().addAll(topLabelVBox1, topLabelVBox2); GridPane.setRowIndex(hBox, rowIndex); GridPane.setMargin(hBox, new Insets(top, 0, 0, 0)); gridPane.getChildren().add(hBox); return new Tuple4<>(topLabel1, textField, topLabel2, comboBox); } // Label + ComboBox + ComboBox public static <T, R> Tuple3<Label, ComboBox<R>, ComboBox<T>> addTopLabelComboBoxComboBox(GridPane gridPane, int rowIndex, String title) { return addTopLabelComboBoxComboBox(gridPane, rowIndex, title, 0); } public static <T, R> Tuple3<Label, ComboBox<T>, ComboBox<R>> addTopLabelComboBoxComboBox(GridPane gridPane, int rowIndex, String title, double top) { HBox hBox = new HBox(); hBox.setSpacing(10); ComboBox<T> comboBox1 = new JFXComboBox<>(); ComboBox<R> comboBox2 = new JFXComboBox<>(); hBox.getChildren().addAll(comboBox1, comboBox2); final Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, title, hBox, top); return new Tuple3<>(topLabelWithVBox.first, comboBox1, comboBox2); } // Label + ComboBox + TextField public static <T> Tuple4<ComboBox<T>, Label, TextField, HBox> addComboBoxTopLabelTextField(GridPane gridPane, int rowIndex, String titleCombobox, String titleTextfield) { return addComboBoxTopLabelTextField(gridPane, rowIndex, titleCombobox, titleTextfield, 0); } public static <T> Tuple4<ComboBox<T>, Label, TextField, HBox> addComboBoxTopLabelTextField(GridPane gridPane, int rowIndex, String titleCombobox, String titleTextfield, double top) { HBox hBox = new HBox(); hBox.setSpacing(10); JFXComboBox<T> comboBox = new JFXComboBox<>(); comboBox.setPromptText(titleCombobox); comboBox.setLabelFloat(true); TextField textField = new BisqTextField(); final VBox topLabelVBox = getTopLabelVBox(5); final Label topLabel = getTopLabel(titleTextfield); topLabelVBox.getChildren().addAll(topLabel, textField); hBox.getChildren().addAll(comboBox, topLabelVBox); GridPane.setRowIndex(hBox, rowIndex); GridPane.setMargin(hBox, new Insets(top, 0, 0, 0)); gridPane.getChildren().add(hBox); return new Tuple4<>(comboBox, topLabel, textField, hBox); } // Label + ComboBox + Button public static <T> Tuple3<Label, ComboBox<T>, Button> addLabelComboBoxButton(GridPane gridPane, int rowIndex, String title, String buttonTitle) { return addLabelComboBoxButton(gridPane, rowIndex, title, buttonTitle, 0); } public static <T> Tuple3<Label, ComboBox<T>, Button> addLabelComboBoxButton(GridPane gridPane, int rowIndex, String title, String buttonTitle, double top) { Label label = addLabel(gridPane, rowIndex, title, top); HBox hBox = new HBox(); hBox.setSpacing(10); Button button = new AutoTooltipButton(buttonTitle); button.setDefaultButton(true); ComboBox<T> comboBox = new JFXComboBox<>(); hBox.getChildren().addAll(comboBox, button); GridPane.setRowIndex(hBox, rowIndex); GridPane.setColumnIndex(hBox, 1); GridPane.setMargin(hBox, new Insets(top, 0, 0, 0)); gridPane.getChildren().add(hBox); return new Tuple3<>(label, comboBox, button); } // Label + ComboBox + Label public static <T> Tuple3<Label, ComboBox<T>, TextField> addLabelComboBoxLabel(GridPane gridPane, int rowIndex, String title, String textFieldText) { return addLabelComboBoxLabel(gridPane, rowIndex, title, textFieldText, 0); } public static <T> Tuple3<Label, ComboBox<T>, TextField> addLabelComboBoxLabel(GridPane gridPane, int rowIndex, String title, String textFieldText, double top) { Label label = addLabel(gridPane, rowIndex, title, top); HBox hBox = new HBox(); hBox.setSpacing(10); ComboBox<T> comboBox = new JFXComboBox<>(); TextField textField = new TextField(textFieldText); textField.setEditable(false); textField.setMouseTransparent(true); textField.setFocusTraversable(false); hBox.getChildren().addAll(comboBox, textField); GridPane.setRowIndex(hBox, rowIndex); GridPane.setColumnIndex(hBox, 1); GridPane.setMargin(hBox, new Insets(top, 0, 0, 0)); gridPane.getChildren().add(hBox); return new Tuple3<>(label, comboBox, textField); } // Label + TxIdTextField public static Tuple2<Label, TxIdTextField> addLabelTxIdTextField(GridPane gridPane, int rowIndex, int columnIndex, String title) { return addLabelTxIdTextField(gridPane, rowIndex, columnIndex, title, 0); } public static Tuple2<Label, TxIdTextField> addLabelTxIdTextField(GridPane gridPane, int rowIndex, int columnIndex, String title, double top) { Label label = addLabel(gridPane, rowIndex, title, top); TxIdTextField txIdTextField = new TxIdTextField(); GridPane.setRowIndex(txIdTextField, rowIndex); GridPane.setColumnIndex(txIdTextField, columnIndex); GridPane.setMargin(txIdTextField, new Insets(top, 0, 0, 0)); gridPane.getChildren().add(txIdTextField); return new Tuple2<>(label, txIdTextField); } public static Tuple3<Label, TxIdTextField, VBox> addTopLabelTxIdTextField(GridPane gridPane, int rowIndex, String title, double top) { TxIdTextField textField = new TxIdTextField(); textField.setFocusTraversable(false); final Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, title, textField, top); // TODO not 100% sure if that is a good idea.... //topLabelWithVBox.first.getStyleClass().add("jfx-text-field-top-label"); return new Tuple3<>(topLabelWithVBox.first, textField, topLabelWithVBox.second); } // Label + TextFieldWithCopyIcon public static Tuple2<Label, TextFieldWithCopyIcon> addCompactTopLabelTextFieldWithCopyIcon(GridPane gridPane, int rowIndex, String title, String value) { return addTopLabelTextFieldWithCopyIcon(gridPane, rowIndex, title, value, -Layout.FLOATING_LABEL_DISTANCE); } public static Tuple2<Label, TextFieldWithCopyIcon> addCompactTopLabelTextFieldWithCopyIcon(GridPane gridPane, int rowIndex, int colIndex, String title, String value, double top) { return addTopLabelTextFieldWithCopyIcon(gridPane, rowIndex, colIndex, title, value, top - Layout.FLOATING_LABEL_DISTANCE); } public static Tuple2<Label, TextFieldWithCopyIcon> addCompactTopLabelTextFieldWithCopyIcon(GridPane gridPane, int rowIndex, int colIndex, String title) { return addTopLabelTextFieldWithCopyIcon(gridPane, rowIndex, colIndex, title, "", -Layout.FLOATING_LABEL_DISTANCE); } public static Tuple2<Label, TextFieldWithCopyIcon> addCompactTopLabelTextFieldWithCopyIcon(GridPane gridPane, int rowIndex, int colIndex, String title, String value) { return addTopLabelTextFieldWithCopyIcon(gridPane, rowIndex, colIndex, title, value, -Layout.FLOATING_LABEL_DISTANCE); } public static Tuple2<Label, TextFieldWithCopyIcon> addTopLabelTextFieldWithCopyIcon(GridPane gridPane, int rowIndex, String title, String value) { return addTopLabelTextFieldWithCopyIcon(gridPane, rowIndex, title, value, 0); } public static Tuple2<Label, TextFieldWithCopyIcon> addTopLabelTextFieldWithCopyIcon(GridPane gridPane, int rowIndex, String title, String value, double top) { return addTopLabelTextFieldWithCopyIcon(gridPane, rowIndex, title, value, top, null); } public static Tuple2<Label, TextFieldWithCopyIcon> addTopLabelTextFieldWithCopyIcon(GridPane gridPane, int rowIndex, String title, String value, double top, String styleClass) { TextFieldWithCopyIcon textFieldWithCopyIcon = new TextFieldWithCopyIcon(styleClass); textFieldWithCopyIcon.setText(value); final Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, title, textFieldWithCopyIcon, top); return new Tuple2<>(topLabelWithVBox.first, textFieldWithCopyIcon); } public static Tuple2<Label, TextFieldWithCopyIcon> addTopLabelTextFieldWithCopyIcon(GridPane gridPane, int rowIndex, int colIndex, String title, String value, double top) { TextFieldWithCopyIcon textFieldWithCopyIcon = new TextFieldWithCopyIcon(); textFieldWithCopyIcon.setText(value); final Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, title, textFieldWithCopyIcon, top); topLabelWithVBox.second.setAlignment(Pos.TOP_LEFT); GridPane.setColumnIndex(topLabelWithVBox.second, colIndex); return new Tuple2<>(topLabelWithVBox.first, textFieldWithCopyIcon); } public static Tuple2<Label, TextFieldWithCopyIcon> addConfirmationLabelTextFieldWithCopyIcon(GridPane gridPane, int rowIndex, String title, String value) { return addConfirmationLabelTextFieldWithCopyIcon(gridPane, rowIndex, title, value, 0); } public static Tuple2<Label, TextFieldWithCopyIcon> addConfirmationLabelTextFieldWithCopyIcon(GridPane gridPane, int rowIndex, String title, String value, double top) { Label label = addLabel(gridPane, rowIndex, title, top); label.getStyleClass().add("confirmation-label"); GridPane.setHalignment(label, HPos.LEFT); TextFieldWithCopyIcon textFieldWithCopyIcon = new TextFieldWithCopyIcon("confirmation-text-field-as-label"); textFieldWithCopyIcon.setText(value); GridPane.setRowIndex(textFieldWithCopyIcon, rowIndex); GridPane.setColumnIndex(textFieldWithCopyIcon, 1); GridPane.setMargin(textFieldWithCopyIcon, new Insets(top, 0, 0, 0)); gridPane.getChildren().add(textFieldWithCopyIcon); return new Tuple2<>(label, textFieldWithCopyIcon); } // Label + AddressTextField public static AddressTextField addAddressTextField(GridPane gridPane, int rowIndex, String title) { return addAddressTextField(gridPane, rowIndex, title, 0); } public static AddressTextField addAddressTextField(GridPane gridPane, int rowIndex, String title, double top) { AddressTextField addressTextField = new AddressTextField(title); GridPane.setRowIndex(addressTextField, rowIndex); GridPane.setColumnIndex(addressTextField, 0); GridPane.setMargin(addressTextField, new Insets(top + 20, 0, 0, 0)); gridPane.getChildren().add(addressTextField); return addressTextField; } // Label + FundsTextField public static FundsTextField addFundsTextfield(GridPane gridPane, int rowIndex, String text) { return addFundsTextfield(gridPane, rowIndex, text, 0); } public static FundsTextField addFundsTextfield(GridPane gridPane, int rowIndex, String text, double top) { FundsTextField fundsTextField = new FundsTextField(); fundsTextField.getTextField().setPromptText(text); GridPane.setRowIndex(fundsTextField, rowIndex); GridPane.setColumnIndex(fundsTextField, 0); GridPane.setMargin(fundsTextField, new Insets(top + 20, 0, 0, 0)); gridPane.getChildren().add(fundsTextField); return fundsTextField; } // Label + InfoTextField public static Tuple3<Label, InfoTextField, VBox> addCompactTopLabelInfoTextField(GridPane gridPane, int rowIndex, String labelText, String fieldText) { return addTopLabelInfoTextField(gridPane, rowIndex, labelText, fieldText, -Layout.FLOATING_LABEL_DISTANCE); } public static Tuple3<Label, InfoTextField, VBox> addTopLabelInfoTextField(GridPane gridPane, int rowIndex, String labelText, String fieldText, double top) { InfoTextField infoTextField = new InfoTextField(); infoTextField.setText(fieldText); final Tuple2<Label, VBox> labelVBoxTuple2 = addTopLabelWithVBox(gridPane, rowIndex, labelText, infoTextField, top); return new Tuple3<>(labelVBoxTuple2.first, infoTextField, labelVBoxTuple2.second); } // Label + BsqAddressTextField public static Tuple3<Label, BsqAddressTextField, VBox> addLabelBsqAddressTextField(GridPane gridPane, int rowIndex, String title) { return addLabelBsqAddressTextField(gridPane, rowIndex, title, 0); } public static Tuple3<Label, BsqAddressTextField, VBox> addLabelBsqAddressTextField(GridPane gridPane, int rowIndex, String title, double top) { BsqAddressTextField addressTextField = new BsqAddressTextField(); addressTextField.setFocusTraversable(false); Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, title, addressTextField, top - 15); return new Tuple3<>(topLabelWithVBox.first, addressTextField, topLabelWithVBox.second); } // Label + BalanceTextField public static BalanceTextField addBalanceTextField(GridPane gridPane, int rowIndex, String title) { return addBalanceTextField(gridPane, rowIndex, title, 20); } public static BalanceTextField addBalanceTextField(GridPane gridPane, int rowIndex, String title, double top) { BalanceTextField balanceTextField = new BalanceTextField(title); GridPane.setRowIndex(balanceTextField, rowIndex); GridPane.setColumnIndex(balanceTextField, 0); GridPane.setMargin(balanceTextField, new Insets(top, 0, 0, 0)); gridPane.getChildren().add(balanceTextField); return balanceTextField; } // Label + Button public static Tuple2<Label, Button> addTopLabelButton(GridPane gridPane, int rowIndex, String labelText, String buttonTitle) { return addTopLabelButton(gridPane, rowIndex, labelText, buttonTitle, 0); } public static Tuple2<Label, Button> addTopLabelButton(GridPane gridPane, int rowIndex, String labelText, String buttonTitle, double top) { Button button = new AutoTooltipButton(buttonTitle); button.setDefaultButton(true); final Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, labelText, button, top); return new Tuple2<>(topLabelWithVBox.first, button); } public static Tuple2<Label, Button> addConfirmationLabelButton(GridPane gridPane, int rowIndex, String labelText, String buttonTitle, double top) { Label label = addLabel(gridPane, rowIndex, labelText); label.getStyleClass().add("confirmation-label"); Button button = new AutoTooltipButton(buttonTitle); button.getStyleClass().add("confirmation-value"); button.setDefaultButton(true); GridPane.setColumnIndex(button, 1); GridPane.setRowIndex(button, rowIndex); GridPane.setMargin(label, new Insets(top, 0, 0, 0)); GridPane.setHalignment(label, HPos.LEFT); GridPane.setMargin(button, new Insets(top, 0, 0, 0)); gridPane.getChildren().add(button); return new Tuple2<>(label, button); } // Label + Button + Button public static Tuple3<Label, Button, Button> addTopLabel2Buttons(GridPane gridPane, int rowIndex, String labelText, String title1, String title2, double top) { HBox hBox = new HBox(); hBox.setSpacing(10); Button button1 = new AutoTooltipButton(title1); button1.setDefaultButton(true); button1.getStyleClass().add("action-button"); button1.setDefaultButton(true); button1.setMaxWidth(Double.MAX_VALUE); HBox.setHgrow(button1, Priority.ALWAYS); Button button2 = new AutoTooltipButton(title2); button2.setMaxWidth(Double.MAX_VALUE); HBox.setHgrow(button2, Priority.ALWAYS); hBox.getChildren().addAll(button1, button2); final Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, labelText, hBox, top); return new Tuple3<>(topLabelWithVBox.first, button1, button2); } // Button public static Button addButton(GridPane gridPane, int rowIndex, String title) { return addButton(gridPane, rowIndex, title, 0); } public static Button addButtonAfterGroup(GridPane gridPane, int rowIndex, String title) { return addButton(gridPane, rowIndex, title, 15); } public static Button addPrimaryActionButton(GridPane gridPane, int rowIndex, String title, double top) { return addButton(gridPane, rowIndex, title, top, true); } public static Button addPrimaryActionButtonAFterGroup(GridPane gridPane, int rowIndex, String title) { return addPrimaryActionButton(gridPane, rowIndex, title, 15); } public static Button addButton(GridPane gridPane, int rowIndex, String title, double top) { return addButton(gridPane, rowIndex, title, top, false); } public static Button addButton(GridPane gridPane, int rowIndex, String title, double top, boolean isPrimaryAction) { Button button = new AutoTooltipButton(title); if (isPrimaryAction) { button.setDefaultButton(true); button.getStyleClass().add("action-button"); } GridPane.setRowIndex(button, rowIndex); GridPane.setColumnIndex(button, 0); gridPane.getChildren().add(button); GridPane.setMargin(button, new Insets(top, 0, 0, 0)); return button; } // Button + Button public static Tuple2<Button, Button> add2Buttons(GridPane gridPane, int rowIndex, String title1, String title2) { return add2Buttons(gridPane, rowIndex, title1, title2, 0); } public static Tuple2<Button, Button> add2ButtonsAfterGroup(GridPane gridPane, int rowIndex, String title1, String title2) { return add2ButtonsAfterGroup(gridPane, rowIndex, title1, title2, true); } public static Tuple2<Button, Button> add2ButtonsAfterGroup(GridPane gridPane, int rowIndex, String title1, String title2, boolean hasPrimaryButton) { return add2Buttons(gridPane, rowIndex, title1, title2, 15, hasPrimaryButton); } public static Tuple2<Button, Button> add2Buttons(GridPane gridPane, int rowIndex, String title1, String title2, double top) { return add2Buttons(gridPane, rowIndex, title1, title2, top, true); } public static Tuple2<Button, Button> add2Buttons(GridPane gridPane, int rowIndex, String title1, String title2, double top, boolean hasPrimaryButton) { final Tuple3<Button, Button, HBox> buttonButtonHBoxTuple3 = add2ButtonsWithBox(gridPane, rowIndex, title1, title2, top, hasPrimaryButton); return new Tuple2<>(buttonButtonHBoxTuple3.first, buttonButtonHBoxTuple3.second); } public static Tuple3<Button, Button, HBox> add2ButtonsWithBox(GridPane gridPane, int rowIndex, String title1, String title2, double top, boolean hasPrimaryButton) { HBox hBox = new HBox(); hBox.setSpacing(10); Button button1 = new AutoTooltipButton(title1); if (hasPrimaryButton) { button1.getStyleClass().add("action-button"); button1.setDefaultButton(true); } button1.setMaxWidth(Double.MAX_VALUE); HBox.setHgrow(button1, Priority.ALWAYS); Button button2 = new AutoTooltipButton(title2); button2.setMaxWidth(Double.MAX_VALUE); HBox.setHgrow(button2, Priority.ALWAYS); hBox.getChildren().addAll(button1, button2); GridPane.setRowIndex(hBox, rowIndex); GridPane.setColumnIndex(hBox, 0); GridPane.setMargin(hBox, new Insets(top, 10, 0, 0)); gridPane.getChildren().add(hBox); return new Tuple3<>(button1, button2, hBox); } // Button + Button + Button public static Tuple3<Button, Button, Button> add3Buttons(GridPane gridPane, int rowIndex, String title1, String title2, String title3) { return add3Buttons(gridPane, rowIndex, title1, title2, title3, 0); } public static Tuple3<Button, Button, Button> add3ButtonsAfterGroup(GridPane gridPane, int rowIndex, String title1, String title2, String title3) { return add3Buttons(gridPane, rowIndex, title1, title2, title3, 15); } public static Tuple3<Button, Button, Button> add3Buttons(GridPane gridPane, int rowIndex, String title1, String title2, String title3, double top) { HBox hBox = new HBox(); hBox.setSpacing(10); Button button1 = new AutoTooltipButton(title1); button1.getStyleClass().add("action-button"); button1.setDefaultButton(true); button1.setMaxWidth(Double.MAX_VALUE); HBox.setHgrow(button1, Priority.ALWAYS); Button button2 = new AutoTooltipButton(title2); button2.setMaxWidth(Double.MAX_VALUE); HBox.setHgrow(button2, Priority.ALWAYS); Button button3 = new AutoTooltipButton(title3); button3.setMaxWidth(Double.MAX_VALUE); HBox.setHgrow(button3, Priority.ALWAYS); hBox.getChildren().addAll(button1, button2, button3); GridPane.setRowIndex(hBox, rowIndex); GridPane.setColumnIndex(hBox, 0); GridPane.setMargin(hBox, new Insets(top, 10, 0, 0)); gridPane.getChildren().add(hBox); return new Tuple3<>(button1, button2, button3); } // Button + ProgressIndicator + Label public static Tuple4<Button, BusyAnimation, Label, HBox> addButtonBusyAnimationLabelAfterGroup(GridPane gridPane, int rowIndex, int colIndex, String buttonTitle) { return addButtonBusyAnimationLabel(gridPane, rowIndex, colIndex, buttonTitle, 15); } public static Tuple4<Button, BusyAnimation, Label, HBox> addButtonBusyAnimationLabelAfterGroup(GridPane gridPane, int rowIndex, String buttonTitle) { return addButtonBusyAnimationLabelAfterGroup(gridPane, rowIndex, 0, buttonTitle); } public static Tuple4<Button, BusyAnimation, Label, HBox> addButtonBusyAnimationLabel(GridPane gridPane, int rowIndex, int colIndex, String buttonTitle, double top) { HBox hBox = new HBox(); hBox.setSpacing(10); Button button = new AutoTooltipButton(buttonTitle); button.setDefaultButton(true); button.getStyleClass().add("action-button"); BusyAnimation busyAnimation = new BusyAnimation(false); Label label = new AutoTooltipLabel(); hBox.setAlignment(Pos.CENTER_LEFT); hBox.getChildren().addAll(button, busyAnimation, label); GridPane.setRowIndex(hBox, rowIndex); GridPane.setHalignment(hBox, HPos.LEFT); GridPane.setColumnIndex(hBox, colIndex); GridPane.setMargin(hBox, new Insets(top, 0, 0, 0)); gridPane.getChildren().add(hBox); return new Tuple4<>(button, busyAnimation, label, hBox); } // Trade: HBox, InputTextField, Label public static Tuple3<HBox, InputTextField, Label> getEditableValueBox(String promptText) { InputTextField input = new InputTextField(60); input.setPromptText(promptText); Label label = new AutoTooltipLabel(Res.getBaseCurrencyCode()); label.getStyleClass().add("input-label"); HBox box = new HBox(); HBox.setHgrow(input, Priority.ALWAYS); input.setMaxWidth(Double.MAX_VALUE); box.getStyleClass().add("input-with-border"); box.getChildren().addAll(input, label); return new Tuple3<>(box, input, label); } public static Tuple3<HBox, InfoInputTextField, Label> getEditableValueBoxWithInfo(String promptText) { InfoInputTextField infoInputTextField = new InfoInputTextField(60); InputTextField input = infoInputTextField.getInputTextField(); input.setPromptText(promptText); Label label = new AutoTooltipLabel(Res.getBaseCurrencyCode()); label.getStyleClass().add("input-label"); HBox box = new HBox(); HBox.setHgrow(infoInputTextField, Priority.ALWAYS); infoInputTextField.setMaxWidth(Double.MAX_VALUE); box.getStyleClass().add("input-with-border"); box.getChildren().addAll(infoInputTextField, label); return new Tuple3<>(box, infoInputTextField, label); } public static Tuple3<HBox, TextField, Label> getNonEditableValueBox() { final Tuple3<HBox, InputTextField, Label> editableValueBox = getEditableValueBox(""); final TextField textField = editableValueBox.second; textField.setDisable(true); return new Tuple3<>(editableValueBox.first, editableValueBox.second, editableValueBox.third); } public static Tuple3<HBox, InfoInputTextField, Label> getNonEditableValueBoxWithInfo() { final Tuple3<HBox, InfoInputTextField, Label> editableValueBoxWithInfo = getEditableValueBoxWithInfo(""); TextField textField = editableValueBoxWithInfo.second.getInputTextField(); textField.setDisable(true); return editableValueBoxWithInfo; } // Trade: Label, VBox public static Tuple2<Label, VBox> getTradeInputBox(Pane amountValueBox, String descriptionText) { Label descriptionLabel = new AutoTooltipLabel(descriptionText); descriptionLabel.setId("input-description-label"); descriptionLabel.setPrefWidth(190); VBox box = new VBox(); box.setPadding(new Insets(10, 0, 0, 0)); box.setSpacing(2); box.getChildren().addAll(descriptionLabel, amountValueBox); return new Tuple2<>(descriptionLabel, box); } // Label + List public static <T> Tuple3<Label, ListView<T>, VBox> addTopLabelListView(GridPane gridPane, int rowIndex, String title) { return addTopLabelListView(gridPane, rowIndex, title, 0); } public static <T> Tuple3<Label, ListView<T>, VBox> addTopLabelListView(GridPane gridPane, int rowIndex, String title, double top) { ListView<T> listView = new ListView<>(); final Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, title, listView, top); return new Tuple3<>(topLabelWithVBox.first, listView, topLabelWithVBox.second); } // Label + FlowPane public static Tuple2<Label, FlowPane> addTopLabelFlowPane(GridPane gridPane, int rowIndex, String title, double top) { return addTopLabelFlowPane(gridPane, rowIndex, title, top, 0); } public static Tuple2<Label, FlowPane> addTopLabelFlowPane(GridPane gridPane, int rowIndex, String title, double top, double bottom) { FlowPane flowPane = new FlowPane(); flowPane.setPadding(new Insets(10, 10, 10, 10)); flowPane.setVgap(10); flowPane.setHgap(10); final Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, title, flowPane, top); GridPane.setMargin(topLabelWithVBox.second, new Insets(top + Layout.FLOATING_LABEL_DISTANCE, 0, bottom, 0)); return new Tuple2<>(topLabelWithVBox.first, flowPane); } // Remove public static void removeRowFromGridPane(GridPane gridPane, int gridRow) { removeRowsFromGridPane(gridPane, gridRow, gridRow); } public static void removeRowsFromGridPane(GridPane gridPane, int fromGridRow, int toGridRow) { Set<Node> nodes = new CopyOnWriteArraySet<>(gridPane.getChildren()); nodes.stream() .filter(e -> GridPane.getRowIndex(e) != null && GridPane.getRowIndex(e) >= fromGridRow && GridPane.getRowIndex(e) <= toGridRow) .forEach(e -> gridPane.getChildren().remove(e)); } // Icons public static Text getIconForLabel(GlyphIcons icon, String iconSize, Label label, String style) { if (icon.fontFamily().equals(MATERIAL_DESIGN_ICONS)) { final Text textIcon = MaterialDesignIconFactory.get().createIcon(icon, iconSize); textIcon.setOpacity(0.7); if (style != null) { textIcon.getStyleClass().add(style); } label.setContentDisplay(ContentDisplay.LEFT); label.setGraphic(textIcon); return textIcon; } else { throw new IllegalArgumentException("Not supported icon type"); } } public static Text getIconForLabel(GlyphIcons icon, String iconSize, Label label) { return getIconForLabel(icon, iconSize, label, null); } public static Text getSmallIconForLabel(GlyphIcons icon, Label label, String style) { return getIconForLabel(icon, "0.769em", label, style); } public static Text getSmallIconForLabel(GlyphIcons icon, Label label) { return getIconForLabel(icon, "0.769em", label); } public static Text getRegularIconForLabel(GlyphIcons icon, Label label) { return getIconForLabel(icon, "1.231em", label); } public static Text getIcon(GlyphIcons icon) { return getIcon(icon, "1.231em"); } public static Text getBigIcon(GlyphIcons icon) { return getIcon(icon, "2em"); } public static Text getMediumSizeIcon(GlyphIcons icon) { return getIcon(icon, "1.5em"); } public static Text getIcon(GlyphIcons icon, String iconSize) { Text textIcon; if (icon.fontFamily().equals(MATERIAL_DESIGN_ICONS)) { textIcon = MaterialDesignIconFactory.get().createIcon(icon, iconSize); } else { throw new IllegalArgumentException("Not supported icon type"); } return textIcon; } public static Label getIcon(AwesomeIcon icon) { final Label label = new Label(); AwesomeDude.setIcon(label, icon); return label; } public static Label getIconForLabel(AwesomeIcon icon, Label label, String fontSize) { AwesomeDude.setIcon(label, icon, fontSize); return label; } public static Button getIconButton(GlyphIcons icon) { return getIconButton(icon, "highlight"); } public static Button getIconButton(GlyphIcons icon, String styleClass) { return getIconButton(icon, styleClass, "2em"); } public static Button getRegularIconButton(GlyphIcons icon) { return getIconButton(icon, "highlight", "1.6em"); } public static Button getRegularIconButton(GlyphIcons icon, String styleClass) { return getIconButton(icon, styleClass, "1.6em"); } public static Button getIconButton(GlyphIcons icon, String styleClass, String iconSize) { if (icon.fontFamily().equals(MATERIAL_DESIGN_ICONS)) { Button iconButton = MaterialDesignIconFactory.get().createIconButton(icon, "", iconSize, null, ContentDisplay.CENTER); iconButton.setId("icon-button"); iconButton.getGraphic().getStyleClass().add(styleClass); iconButton.setPrefWidth(20); iconButton.setPrefHeight(20); iconButton.setPadding(new Insets(0)); return iconButton; } else { throw new IllegalArgumentException("Not supported icon type"); } } public static <T> TableView<T> addTableViewWithHeader(GridPane gridPane, int rowIndex, String headerText) { return addTableViewWithHeader(gridPane, rowIndex, headerText, 0, null); } public static <T> TableView<T> addTableViewWithHeader(GridPane gridPane, int rowIndex, String headerText, String groupStyle) { return addTableViewWithHeader(gridPane, rowIndex, headerText, 0, groupStyle); } public static <T> TableView<T> addTableViewWithHeader(GridPane gridPane, int rowIndex, String headerText, int top) { return addTableViewWithHeader(gridPane, rowIndex, headerText, top, null); } public static <T> TableView<T> addTableViewWithHeader(GridPane gridPane, int rowIndex, String headerText, int top, String groupStyle) { TitledGroupBg titledGroupBg = addTitledGroupBg(gridPane, rowIndex, 1, headerText, top); if (groupStyle != null) titledGroupBg.getStyleClass().add(groupStyle); TableView<T> tableView = new TableView<>(); GridPane.setRowIndex(tableView, rowIndex); GridPane.setMargin(tableView, new Insets(top + 30, -10, 5, -10)); gridPane.getChildren().add(tableView); tableView.setPlaceholder(new AutoTooltipLabel(Res.get("table.placeholder.noData"))); tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY); return tableView; } }
package nl.mpi.kinnate.svg; import nl.mpi.kinnate.kindata.EntityData; import nl.mpi.kinnate.ui.GraphPanelContextMenu; import java.awt.BorderLayout; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.awt.geom.AffineTransform; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import javax.swing.JPanel; import javax.xml.parsers.DocumentBuilderFactory; import nl.mpi.arbil.data.ArbilComponentBuilder; import nl.mpi.arbil.ui.GuiHelper; import nl.mpi.kinnate.entityindexer.IndexerParameters; import nl.mpi.kinnate.SavePanel; import nl.mpi.kinnate.kindata.GraphSorter; import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier; import nl.mpi.kinnate.kintypestrings.KinTermGroup; import nl.mpi.kinnate.ui.KinDiagramPanel; import nl.mpi.kinnate.ui.MetadataPanel; import org.apache.batik.dom.svg.SAXSVGDocumentFactory; import org.apache.batik.dom.svg.SVGDOMImplementation; import org.apache.batik.swing.JSVGCanvas; import org.apache.batik.swing.JSVGScrollPane; import org.apache.batik.util.XMLResourceDescriptor; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.events.EventTarget; import org.w3c.dom.svg.SVGDocument; public class GraphPanel extends JPanel implements SavePanel { private JSVGScrollPane jSVGScrollPane; protected JSVGCanvas svgCanvas; protected SVGDocument doc; public MetadataPanel metadataPanel; private boolean requiresSave = false; private File svgFile = null; protected GraphPanelSize graphPanelSize; protected LineLookUpTable lineLookUpTable; protected ArrayList<UniqueIdentifier> selectedGroupId; protected String svgNameSpace = SVGDOMImplementation.SVG_NAMESPACE_URI; public DataStoreSvg dataStoreSvg; protected EntitySvg entitySvg; // private URI[] egoPathsTemp = null; public SvgUpdateHandler svgUpdateHandler; public MouseListenerSvg mouseListenerSvg; public GraphPanel(KinDiagramPanel kinDiagramPanel) { dataStoreSvg = new DataStoreSvg(); entitySvg = new EntitySvg(); dataStoreSvg.setDefaults(); svgUpdateHandler = new SvgUpdateHandler(this, kinDiagramPanel); selectedGroupId = new ArrayList<UniqueIdentifier>(); graphPanelSize = new GraphPanelSize(); this.setLayout(new BorderLayout()); boolean eventsEnabled = true; boolean selectableText = false; svgCanvas = new JSVGCanvas(new GraphUserAgent(this), eventsEnabled, selectableText); // svgCanvas.setMySize(new Dimension(600, 400)); svgCanvas.setDocumentState(JSVGCanvas.ALWAYS_DYNAMIC); // drawNodes(); svgCanvas.setEnableImageZoomInteractor(false); svgCanvas.setEnablePanInteractor(false); svgCanvas.setEnableRotateInteractor(false); svgCanvas.setEnableZoomInteractor(false); svgCanvas.addMouseWheelListener(new MouseWheelListener() { public void mouseWheelMoved(MouseWheelEvent e) { double scale = 1 - e.getUnitsToScroll() / 10.0; double tx = -e.getX() * (scale - 1); double ty = -e.getY() * (scale - 1); // System.out.println("scale: " + scale); // System.out.println("scale: " + svgCanvas.getRenderingTransform().getScaleX()); if (scale > 1 || svgCanvas.getRenderingTransform().getScaleX() > 0.01) { AffineTransform at = new AffineTransform(); at.translate(tx, ty); at.scale(scale, scale); at.concatenate(svgCanvas.getRenderingTransform()); svgCanvas.setRenderingTransform(at); } } }); // svgCanvas.setEnableResetTransformInteractor(true); // svgCanvas.setDoubleBufferedRendering(true); // todo: look into reducing the noticable aliasing on the canvas mouseListenerSvg = new MouseListenerSvg(kinDiagramPanel, this); svgCanvas.addMouseListener(mouseListenerSvg); svgCanvas.addMouseMotionListener(mouseListenerSvg); jSVGScrollPane = new JSVGScrollPane(svgCanvas); // svgCanvas.setBackground(Color.LIGHT_GRAY); this.add(BorderLayout.CENTER, jSVGScrollPane); svgCanvas.setComponentPopupMenu(new GraphPanelContextMenu(kinDiagramPanel, this, graphPanelSize)); } // private void zoomDrawing() { // AffineTransform scaleTransform = new AffineTransform(); // scaleTransform.scale(1 - currentZoom / 10.0, 1 - currentZoom / 10.0); // System.out.println("currentZoom: " + currentZoom); //// svgCanvas.setRenderingTransform(scaleTransform); // Rectangle canvasBounds = this.getBounds(); // SVGRect bbox = ((SVGLocatable) doc.getRootElement()).getBBox(); // if (bbox != null) { // System.out.println("previousZoomedWith: " + bbox.getWidth()); //// SVGElement rootElement = doc.getRootElement(); //// if (currentWidth < canvasBounds.width) { // float drawingCenter = (currentWidth / 2); //// float drawingCenter = (bbox.getX() + (bbox.getWidth() / 2)); // float canvasCenter = (canvasBounds.width / 2); // zoomAffineTransform = new AffineTransform(); // zoomAffineTransform.translate((canvasCenter - drawingCenter), 1); // zoomAffineTransform.concatenate(scaleTransform); // svgCanvas.setRenderingTransform(zoomAffineTransform); public void setArbilTableModel(MetadataPanel metadataPanel) { this.metadataPanel = metadataPanel; } public void readSvg(URI svgFilePath, boolean savableType) { if (savableType) { svgFile = new File(svgFilePath); } else { svgFile = null; } String parser = XMLResourceDescriptor.getXMLParserClassName(); SAXSVGDocumentFactory documentFactory = new SAXSVGDocumentFactory(parser); try { doc = (SVGDocument) documentFactory.createDocument(svgFilePath.toString()); svgCanvas.setDocument(doc); dataStoreSvg = DataStoreSvg.loadDataFromSvg(doc); if (dataStoreSvg.indexParameters == null) { dataStoreSvg.setDefaults(); } requiresSave = false; entitySvg.readEntityPositions(doc.getElementById("EntityGroup")); entitySvg.readEntityPositions(doc.getElementById("LabelsGroup")); entitySvg.readEntityPositions(doc.getElementById("GraphicsGroup")); configureDiagramGroups(); dataStoreSvg.indexParameters.symbolFieldsFields.setAvailableValues(entitySvg.listSymbolNames(doc, this.svgNameSpace)); // if (dataStoreSvg.graphData == null) { // return null; } catch (IOException ioe) { GuiHelper.linorgBugCatcher.logError(ioe); } // svgCanvas.setSVGDocument(doc); return; // dataStoreSvg.graphData.getDataNodes(); } private void configureDiagramGroups() { Element svgRoot = doc.getDocumentElement(); // make sure the diagram group exisits Element diagramGroup = doc.getElementById("DiagramGroup"); if (diagramGroup == null) { diagramGroup = doc.createElementNS(svgNameSpace, "g"); diagramGroup.setAttribute("id", "DiagramGroup"); // add the diagram group to the root element (the 'svg' element) svgRoot.appendChild(diagramGroup); } Element previousElement = null; // add the graphics group below the entities and relations // add the relation symbols in a group below the relation lines // add the entity symbols in a group on top of the relation lines // add the labels group on top, also added on svg load if missing for (String groupForMouseListener : new String[]{"LabelsGroup", "EntityGroup", "RelationGroup", "GraphicsGroup"}) { // add any groups that are required and add them in the required order Element parentElement = doc.getElementById(groupForMouseListener); if (parentElement == null) { parentElement = doc.createElementNS(svgNameSpace, "g"); parentElement.setAttribute("id", groupForMouseListener); diagramGroup.insertBefore(parentElement, previousElement); } else { diagramGroup.insertBefore(parentElement, previousElement); // insert the node to make sure that it is in the diagram group and not in any other location // set up the mouse listeners that were lost in the save/re-open process if (!groupForMouseListener.equals("RelationGroup")) { // do not add mouse listeners to the relation group Node currentNode = parentElement.getFirstChild(); while (currentNode != null) { ((EventTarget) currentNode).addEventListener("mousedown", mouseListenerSvg, false); currentNode = currentNode.getNextSibling(); } } } previousElement = parentElement; } } public void generateDefaultSvg() { try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); // set up a kinnate namespace so that the ego list and kin type strings can have more permanent storage places // in order to add the extra namespaces to the svg document we use a string and parse it // other methods have been tried but this is the most readable and the only one that actually works // I think this is mainly due to the way the svg dom would otherwise be constructed // others include: // doc.getDomConfig() // doc.getDocumentElement().setAttributeNS(DataStoreSvg.kinDataNameSpaceLocation, "kin:version", ""); // doc.getDocumentElement().setAttribute("xmlns:" + DataStoreSvg.kinDataNameSpace, DataStoreSvg.kinDataNameSpaceLocation); // this method of declaring multiple namespaces looks to me to be wrong but it is the only method that does not get stripped out by the transformer on save // Document doc = impl.createDocument(svgNS, "svg", null); // SVGDocument doc = svgCanvas.getSVGDocument(); String templateXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<svg xmlns:xlink=\"http: + "xmlns=\"http: + " zoomAndPan=\"magnify\" contentStyleType=\"text/css\" " + "preserveAspectRatio=\"xMidYMid meet\" version=\"1.0\"/>"; // DOMImplementation impl = SVGDOMImplementation.getDOMImplementation(); // doc = (SVGDocument) impl.createDocument(svgNameSpace, "svg", null); String parser = XMLResourceDescriptor.getXMLParserClassName(); SAXSVGDocumentFactory documentFactory = new SAXSVGDocumentFactory(parser); doc = (SVGDocument) documentFactory.createDocument(svgNameSpace, new StringReader(templateXml)); entitySvg.insertSymbols(doc, svgNameSpace); configureDiagramGroups(); dataStoreSvg.indexParameters.symbolFieldsFields.setAvailableValues(entitySvg.listSymbolNames(doc, this.svgNameSpace)); svgCanvas.setSVGDocument(doc); dataStoreSvg.graphData = new GraphSorter(); } catch (IOException exception) { GuiHelper.linorgBugCatcher.logError(exception); } } private void saveSvg(File svgFilePath) { svgFile = svgFilePath; selectedGroupId.clear(); svgUpdateHandler.clearHighlights(); // todo: make sure that any data changes such as the title/description in the kin term groups get updated into the file on save ArbilComponentBuilder.savePrettyFormatting(doc, svgFile); requiresSave = false; } private void printNodeNames(Node nodeElement) { System.out.println(nodeElement.getLocalName()); System.out.println(nodeElement.getNamespaceURI()); Node childNode = nodeElement.getFirstChild(); while (childNode != null) { printNodeNames(childNode); childNode = childNode.getNextSibling(); } } public String[] getKinTypeStrigs() { return dataStoreSvg.kinTypeStrings; } public void setKinTypeStrigs(String[] kinTypeStringArray) { // strip out any white space, blank lines and remove duplicates // this has set has been removed because it creates a discrepancy between what the user types and what is processed // HashSet<String> kinTypeStringSet = new HashSet<String>(); // for (String kinTypeString : kinTypeStringArray) { // if (kinTypeString != null && kinTypeString.trim().length() > 0) { // kinTypeStringSet.add(kinTypeString.trim()); // dataStoreSvg.kinTypeStrings = kinTypeStringSet.toArray(new String[]{}); dataStoreSvg.kinTypeStrings = kinTypeStringArray; } public IndexerParameters getIndexParameters() { return dataStoreSvg.indexParameters; } public KinTermGroup[] getkinTermGroups() { return dataStoreSvg.kinTermGroups; } public KinTermGroup addKinTermGroup() { ArrayList<KinTermGroup> kinTermsList = new ArrayList<KinTermGroup>(Arrays.asList(dataStoreSvg.kinTermGroups)); final KinTermGroup kinTermGroup = new KinTermGroup(); kinTermsList.add(kinTermGroup); dataStoreSvg.kinTermGroups = kinTermsList.toArray(new KinTermGroup[]{}); return kinTermGroup; } // public String[] getEgoUniquiIdentifiersList() { // return dataStoreSvg.egoIdentifierSet.toArray(new String[]{}); // public String[] getEgoIdList() { // return dataStoreSvg.egoIdentifierSet.toArray(new String[]{}); // public URI[] getEgoPaths() { // if (egoPathsTemp != null) { // return egoPathsTemp; // ArrayList<URI> returnPaths = new ArrayList<URI>(); // for (String egoId : dataStoreSvg.egoIdentifierSet) { // try { // String entityPath = getPathForElementId(egoId); //// if (entityPath != null) { // returnPaths.add(new URI(entityPath)); // } catch (URISyntaxException ex) { // GuiHelper.linorgBugCatcher.logError(ex); // // todo: warn user with a dialog // return returnPaths.toArray(new URI[]{}); // public void setRequiredEntities(URI[] egoPathArray, String[] egoIdentifierArray) { //// egoPathsTemp = egoPathArray; // egoPathsTemp is only required if the ego nodes are not already on the graph (otherwise the path can be obtained from the graph elements) // dataStoreSvg.requiredEntities = new HashSet<String>(Arrays.asList(egoIdentifierArray)); // public void addRequiredEntity(URI[] egoPathArray, String[] egoIdentifierArray) { //// egoPathsTemp = egoPathArray; // egoPathsTemp is only required if the ego nodes are not already on the graph (otherwise the path can be obtained from the graph elements) // dataStoreSvg.requiredEntities.addAll(Arrays.asList(egoIdentifierArray)); // public void removeEgo(String[] egoIdentifierArray) { // dataStoreSvg.egoIdentifierSet.removeAll(Arrays.asList(egoIdentifierArray)); public void setSelectedIds(UniqueIdentifier[] uniqueIdentifiers) { selectedGroupId.clear(); selectedGroupId.addAll(Arrays.asList(uniqueIdentifiers)); svgUpdateHandler.updateSvgSelectionHighlights(); // mouseListenerSvg.updateSelectionDisplay(); } public UniqueIdentifier[] getSelectedIds() { return selectedGroupId.toArray(new UniqueIdentifier[]{}); } public EntityData getEntityForElementId(UniqueIdentifier uniqueIdentifier) { for (EntityData entityData : dataStoreSvg.graphData.getDataNodes()) { if (uniqueIdentifier.equals(entityData.getUniqueIdentifier())) { return entityData; } } return null; } public HashMap<UniqueIdentifier, EntityData> getEntitiesById(UniqueIdentifier[] uniqueIdentifiers) { ArrayList<UniqueIdentifier> identifierList = new ArrayList<UniqueIdentifier>(Arrays.asList(uniqueIdentifiers)); HashMap<UniqueIdentifier, EntityData> returnMap = new HashMap<UniqueIdentifier, EntityData>(); for (EntityData entityData : dataStoreSvg.graphData.getDataNodes()) { if (identifierList.contains(entityData.getUniqueIdentifier())) { returnMap.put(entityData.getUniqueIdentifier(), entityData); } } return returnMap; } // public boolean selectionContainsEgo() { // for (String selectedId : selectedGroupId) { // if (dataStoreSvg.egoIdentifierSet.contains(selectedId)) { // return true; // return false; public String getPathForElementId(UniqueIdentifier elementId) { // NamedNodeMap namedNodeMap = doc.getElementById(elementId).getAttributes(); // for (int attributeCounter = 0; attributeCounter < namedNodeMap.getLength(); attributeCounter++) { // System.out.println(namedNodeMap.item(attributeCounter).getNodeName()); // System.out.println(namedNodeMap.item(attributeCounter).getNamespaceURI()); // System.out.println(namedNodeMap.item(attributeCounter).getNodeValue()); Element entityElement = doc.getElementById(elementId.getAttributeIdentifier()); if (entityElement == null) { return null; } else { return entityElement.getAttributeNS(DataStoreSvg.kinDataNameSpaceLocation, "path"); } } public String getKinTypeForElementId(UniqueIdentifier elementId) { Element entityElement = doc.getElementById(elementId.getAttributeIdentifier()); if (entityElement != null) { return entityElement.getAttributeNS(DataStoreSvg.kinDataNameSpaceLocation, "kintype"); } else { return ""; } } public void resetZoom() { // todo: this should be moved to the svg update handler and put into a runnable AffineTransform at = new AffineTransform(); at.scale(1, 1); at.setToTranslation(1, 1); svgCanvas.setRenderingTransform(at); } public void resetLayout() { entitySvg = new EntitySvg(); dataStoreSvg.graphData.setEntitys(dataStoreSvg.graphData.getDataNodes()); dataStoreSvg.graphData.placeAllNodes(entitySvg.entityPositions); drawNodes(); } public void clearEntityLocations(UniqueIdentifier[] selectedIdentifiers) { entitySvg.clearEntityLocations(selectedIdentifiers); } public void drawNodes() { requiresSave = true; selectedGroupId.clear(); svgUpdateHandler.updateEntities(); } public void drawNodes(GraphSorter graphDataLocal) { dataStoreSvg.graphData = graphDataLocal; drawNodes(); if (graphDataLocal.getDataNodes().length == 0) { // if all entities have been removed then reset the zoom so that new nodes are going to been centered // todo: it would be better to move the window to cover the drawing area but not change the zoom // resetZoom(); } } public boolean hasSaveFileName() { return svgFile != null; } public File getFileName() { return svgFile; } public boolean requiresSave() { return requiresSave; } public void setRequiresSave() { requiresSave = true; } public void saveToFile() { saveSvg(svgFile); } public void saveToFile(File saveAsFile) { saveSvg(saveAsFile); } public void updateGraph() { throw new UnsupportedOperationException("Not supported yet."); } }
package com.evader.rookies.evade; import java.util.ArrayList; import android.content.Intent; import android.media.Image; import android.os.Bundle; import android.app.Activity; import android.os.Looper; import android.os.SystemClock; import android.util.DisplayMetrics; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import java.lang.InterruptedException; import java.util.Collections; import java.util.Timer; import java.util.TimerTask; public class Game extends Activity implements View.OnTouchListener, Runnable { int x=0; int yIncrement = 50; long newEnemyTime=1000; ImageView socguy, pianoObstacle; View view; long time; boolean firstTimeAround=true; DisplayMetrics displayMetrics; ArrayList <Piano> listOImages = new ArrayList<Piano>(); RelativeLayout relativeLayout; int y=0; int pianoWidth; int pianoHeight; int initialYPos = 20; int stickmanWidth; boolean gameOver; int score=0; TextView scoreView; String difficulty; Timer timer; //public Bundle bundle = new Bundle(); public void run(){ //ensures additional threads don't conflict with main UI thread android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND); } @Override protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.activity_game); super.onCreate(savedInstanceState); Bundle b = getIntent().getExtras(); difficulty = b.getString("DifficultyLevel"); if (difficulty.equals("Easy")){ yIncrement = yIncrement + 30; } else if (difficulty.equals("Medium")){ yIncrement = 50; } else if(difficulty.equals("Hard")){ yIncrement = yIncrement - 30; } else{ Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show(); } socguy = (ImageView) findViewById(R.id.imageView); view = findViewById(R.id.clickview); scoreView = (TextView)(findViewById(R.id.scoreView)); time = System.currentTimeMillis(); view.setOnTouchListener(this); firstTimeAround = false; displayMetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); relativeLayout= (RelativeLayout) findViewById(R.id.gamerelativelayout); stickmanWidth = socguy.getWidth(); pianoWidth = displayMetrics.widthPixels/10; pianoHeight = displayMetrics.heightPixels/10; // listOImages.add(pianoObstacle); //IMPORTANT: added preset imageview instead of creating a new imageview dynamically (as Aditya did before) --> CHANGE LATER! // listOImages.get(listOImages.size() - 1).setImageResource(R.drawable.piano); // listOImages.get(listOImages.size() - 1).setY(20); // listOImages.get(listOImages.size() - 1).setX(200); time = System.currentTimeMillis(); //if (currentTime - time == newEnemyTime) { timer = new Timer(); TimerTask timerTask= new TimerTask() { @Override public void run() { new Thread(new Runnable() { public void run() { socguy.post(new Runnable() { @Override public void run() { letItRain(); } }); } }).start(); try { Thread.sleep(300); } catch (InterruptedException e){ System.out.println(e); } } }; timer.schedule(timerTask, 100, 100); // while(whatever<1000){ //listOImages.get(listOImages.size() - 1).setX((int) (Math.random() * displayMetrics.widthPixels)); //pianoObstacle.setX((float)(Math.random()*displayMetrics.widthPixels)); // DOES NOT WORK!! //max value is 700 // letItRain(); // whatever++; //listOImages.get(listOImages.size() - 1).setY(30); //System.out.println(x); x++; System.out.println(x); /*(for (ImageView piano : listOImages) { piano.setY(yDecrement + piano.getY()); if (piano.getY() > view.getLayoutParams().height) { listOImages.remove(piano); } }*/ } public void letItRain(){ if (firstTimeAround==true){ listOImages.add(new Piano(this)); //new imageView is added to array list of imageviews listOImages.get(listOImages.size() - 1).setImageResource(R.drawable.piano); //listOImages.get(listOImages.size() - 1).setLayoutParams(new RelativeLayout.LayoutParams(pianoWidth, pianoHeight)); listOImages.get(listOImages.size() - 1).setY(initialYPos); listOImages.get(listOImages.size()-1).setMaxWidth(100); listOImages.get(listOImages.size()-1).setMaxHeight(100); relativeLayout.addView(listOImages.get(listOImages.size() - 1), pianoWidth, pianoHeight); listOImages.get(listOImages.size() - 1).setVisibility(View.VISIBLE); listOImages.get(listOImages.size() - 1).setX((float) (Math.random() * displayMetrics.widthPixels)); firstTimeAround=false; } int xPosition= (int) (Math.random() * displayMetrics.widthPixels); System.out.println(displayMetrics.widthPixels); //NOT PRINTING! //listOImages.get(listOImages.size() - 1).setLayoutParams(new RelativeLayout.LayoutParams(200, 200)); //listOImages.get(listOImages.size() - 1).setX((int) (Math.random() * displayMetrics.widthPixels)); //pianoObstacle.setX((float)(Math.random()*displayMetrics.widthPixels)); // DOES NOT WORK!! //max value is 700 long currentTime = System.currentTimeMillis(); if (currentTime-time>=newEnemyTime){ //every second a new imageView is created time = System.currentTimeMillis(); listOImages.add(new Piano(this)); //new imageView is added to array list of imageviews listOImages.get(listOImages.size() - 1).setImageResource(R.drawable.piano); //listOImages.get(listOImages.size() - 1).setLayoutParams(new RelativeLayout.LayoutParams(pianoWidth, pianoHeight)); listOImages.get(listOImages.size() - 1).setY(initialYPos); listOImages.get(listOImages.size()-1).setMaxWidth(100); listOImages.get(listOImages.size()-1).setMaxHeight(100); relativeLayout.addView(listOImages.get(listOImages.size() - 1), pianoWidth, pianoHeight); listOImages.get(listOImages.size() - 1).setVisibility(View.VISIBLE); listOImages.get(listOImages.size() - 1).setX((float) (Math.random() * displayMetrics.widthPixels)); } for (int i = listOImages.size()-1; i>-1; i listOImages.get(i).setY(listOImages.get(i).getY() + yIncrement); if (hasCollided(listOImages.get(i))==true){ gameOver=true; } if(listOImages.get(i).getY()>displayMetrics.heightPixels){ listOImages.get(i).setOffScreen(true); } } if(gameOver) { gameEnd(); } incrementScore(listOImages); String scoreText = "Score:" + String.valueOf(score); scoreView.setText(scoreText); scoreView.setVisibility(View.VISIBLE); } public boolean hasCollided(ImageView piano) { boolean collided=false; int socguyLocation []= new int [2]; socguy.getLocationOnScreen(socguyLocation); int topRightSocguyCorner=socguyLocation[0]+stickmanWidth; int pianoLocation [] = new int [2]; piano.getLocationOnScreen(pianoLocation); if(socguyLocation[1] <= pianoLocation[1]+pianoHeight && displayMetrics.heightPixels>=pianoLocation[1]){ if(pianoLocation[0] <= topRightSocguyCorner && pianoLocation[0]+pianoWidth >= socguyLocation[0]) { collided = true; System.out.println("COLLISION"); System.out.println("Socguy X: " + socguyLocation[0]); System.out.println("Socguy y: " + socguyLocation[1]); System.out.println("piano X: " + pianoLocation[0]); System.out.println("piano Y: " + pianoLocation[1]); Toast t= Toast.makeText(this,"Ouch!" ,Toast.LENGTH_SHORT); t.show(); gameEnd(); } } return collided; } public void incrementScore(ArrayList<Piano> pianoList){ for (Piano piano : pianoList){ if(!(piano.getAlreadySetOffScreen()) && piano.isOffScreen()){ System.out.println(piano); score++; piano.setAlreadySetOffScreen(true); } } } public void gameEnd() { timer.cancel(); Intent intent = new Intent(this, Scores.class); intent.putExtra("currScore", score); //this.bundle.putInt("score", score); startActivity(intent); } public boolean onTouch(View view, MotionEvent event) { System.out.println(event.getRawX()); System.out.println("Socguy: " + socguy.getX()); if (event.getAction() == MotionEvent.ACTION_DOWN) { if (event.getRawX() >= socguy.getX() && socguy.getX() +50.0f < displayMetrics.widthPixels) { socguy.setX(socguy.getX() + 50.0f); } else if (event.getRawX() <= socguy.getX() && socguy.getX() -50.0f > 0){ socguy.setX(socguy.getX() - 50.0f); } } return true; } }
package com.quchen.flappycow; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import com.quchen.flappycow.Game.MyHandler; import com.quchen.flappycow.sprites.Background; import com.quchen.flappycow.sprites.Coin; import com.quchen.flappycow.sprites.Cow; import com.quchen.flappycow.sprites.Frontground; import com.quchen.flappycow.sprites.NyanCat; import com.quchen.flappycow.sprites.Obstacle; import com.quchen.flappycow.sprites.PauseButton; import com.quchen.flappycow.sprites.PlayableCharacter; import com.quchen.flappycow.sprites.PowerUp; import com.quchen.flappycow.sprites.Toast; import com.quchen.flappycow.sprites.Tutorial; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.os.Build; import android.os.Message; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import com.google.android.gms.games.Games; public class GameView extends SurfaceView{ /** Milliseconds for game timer tick */ public static final long UPDATE_INTERVAL = 50; // = 20 FPS private Timer timer = new Timer(); private TimerTask timerTask; /** The surfaceholder needed for the canvas drawing */ private SurfaceHolder holder; private Game game; private PlayableCharacter player; private Background background; private Frontground frontground; private List<Obstacle> obstacles = new ArrayList<Obstacle>(); private List<PowerUp> powerUps = new ArrayList<PowerUp>(); private PauseButton pauseButton; volatile private boolean paused = true; private Tutorial tutorial; private boolean tutorialIsShown = true; public GameView(Context context) { super(context); this.game = (Game) context; setFocusable(true); holder = getHolder(); player = new Cow(this, game); background = new Background(this, game); frontground = new Frontground(this, game); pauseButton = new PauseButton(this, game); tutorial = new Tutorial(this, game); } private void startTimer() { setUpTimerTask(); timer = new Timer(); timer.schedule(timerTask, UPDATE_INTERVAL, UPDATE_INTERVAL); } private void stopTimer() { if (timer != null) { timer.cancel(); timer.purge(); } if (timerTask != null) { timerTask.cancel(); } } private void setUpTimerTask() { stopTimer(); timerTask = new TimerTask() { @Override public void run() { GameView.this.run(); } }; } @Override public boolean performClick() { return super.performClick(); // Just to remove the stupid warning } @Override public boolean onTouchEvent(MotionEvent event) { performClick(); if(event.getAction() == MotionEvent.ACTION_DOWN // Only for "touchdowns" && !this.player.isDead()){ // No support for dead players if(tutorialIsShown){ // dismiss tutorial tutorialIsShown = false; resume(); this.player.onTap(); }else if(paused){ resume(); }else if(pauseButton.isTouching((int) event.getX(), (int) event.getY()) && !this.paused){ pause(); }else{ this.player.onTap(); } } return true; } /** * content of the timertask */ public void run() { checkPasses(); checkOutOfRange(); checkCollision(); createObstacle(); move(); draw(); } private Canvas getCanvas() { Canvas canvas; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { canvas = holder.lockHardwareCanvas(); } else { canvas = holder.lockCanvas(); } return canvas; } /** * Draw Tutorial */ public void showTutorial(){ player.move(); pauseButton.move(); while(!holder.getSurface().isValid()){ /*wait*/ try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } Canvas canvas = getCanvas(); drawCanvas(canvas, true); tutorial.move(); tutorial.draw(canvas); holder.unlockCanvasAndPost(canvas); } public void pause(){ stopTimer(); paused = true; } public void drawOnce(){ (new Thread(new Runnable() { @Override public void run() { if(tutorialIsShown){ showTutorial(); } else { draw(); } } })).start(); } public void resume(){ paused = false; startTimer(); } /** * Draws all gameobjects on the surface */ private void draw() { while(!holder.getSurface().isValid()){ /*wait*/ try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } Canvas canvas = getCanvas();; drawCanvas(canvas, true); holder.unlockCanvasAndPost(canvas); } /** * Draws everything normal, * except the player will only be drawn, when the parameter is true * @param drawPlayer */ private void drawCanvas(Canvas canvas, boolean drawPlayer){ background.draw(canvas); for(Obstacle r : obstacles){ r.draw(canvas); } for(PowerUp p : powerUps){ p.draw(canvas); } if(drawPlayer){ player.draw(canvas); } frontground.draw(canvas); pauseButton.draw(canvas); // Score Text Paint paint = new Paint(); paint.setColor(Color.BLACK); paint.setTextSize(getScoreTextMetrics()); canvas.drawText(game.getResources().getString(R.string.onscreen_score_text) + " " + game.accomplishmentBox.points + " / " + game.getResources().getString(R.string.onscreen_coin_text) + " " + game.coins, 0, getScoreTextMetrics(), paint); } /** * Let the player fall to the ground */ private void playerDeadFall(){ player.dead(); do{ player.move(); draw(); // sleep try { Thread.sleep(UPDATE_INTERVAL/4); } catch (InterruptedException e) { e.printStackTrace(); } }while(!player.isTouchingGround()); } /** * Checks whether an obstacle is passed. */ private void checkPasses(){ for(Obstacle o : obstacles){ if(o.isPassed()){ if(!o.isAlreadyPassed){ // probably not needed o.onPass(); createPowerUp(); } } } } /** * Creates a toast with a certain chance */ private void createPowerUp(){ // Toast if(game.accomplishmentBox.points >= Toast.POINTS_TO_TOAST /*&& powerUps.size() < 1*/ && !(player instanceof NyanCat)){ // If no powerUp is present and you have more than / equal 42 points if(game.accomplishmentBox.points == Toast.POINTS_TO_TOAST){ // First time 100 % chance powerUps.add(new Toast(this, game)); } else if(Math.random()*100 < 33){ // 33% chance powerUps.add(new Toast(this, game)); } } if((powerUps.size() < 1) && (Math.random()*100 < 20)){ // If no powerUp is present and 20% chance powerUps.add(new Coin(this, game)); } } /** * Checks whether the obstacles or powerUps are out of range and deletes them */ private void checkOutOfRange(){ for(int i=0; i<obstacles.size(); i++){ if(this.obstacles.get(i).isOutOfRange()){ this.obstacles.remove(i); i } } for(int i=0; i<powerUps.size(); i++){ if(this.powerUps.get(i).isOutOfRange()){ this.powerUps.remove(i); i } } } /** * Checks collisions and performs the action */ private void checkCollision(){ for(Obstacle o : obstacles){ if(o.isColliding(player)){ o.onCollision(); gameOver(); } } for(int i=0; i<powerUps.size(); i++){ if(this.powerUps.get(i).isColliding(player)){ this.powerUps.get(i).onCollision(); this.powerUps.remove(i); i } } if(player.isTouchingEdge()){ gameOver(); } } /** * if no obstacle is present a new one is created */ private void createObstacle(){ if(obstacles.size() < 1){ obstacles.add(new Obstacle(this, game)); } } /** * Update sprite movements */ private void move(){ for(Obstacle o : obstacles){ o.setSpeedX(-getSpeedX()); o.move(); } for(PowerUp p : powerUps){ p.move(); } background.setSpeedX(-getSpeedX()/2); background.move(); frontground.setSpeedX(-getSpeedX()*4/3); frontground.move(); pauseButton.move(); player.move(); } /** * Changes the player to Nyan Cat */ public void changeToNyanCat(){ game.accomplishmentBox.achievement_toastification = true; if(game.getApiClient().isConnected()){ Games.Achievements.unlock(game.getApiClient(), getResources().getString(R.string.achievement_toastification)); }else{ game.handler.sendMessage(Message.obtain(game.handler,1,R.string.toast_achievement_toastification, MyHandler.SHOW_TOAST)); } PlayableCharacter tmp = this.player; this.player = new NyanCat(this, game); this.player.setX(tmp.getX()); this.player.setY(tmp.getY()); this.player.setSpeedX(tmp.getSpeedX()); this.player.setSpeedY(tmp.getSpeedY()); game.musicShouldPlay = true; Game.musicPlayer.start(); } /** * return the speed of the obstacles/cow */ public int getSpeedX(){ // 16 @ 720x1280 px int speedDefault = this.getWidth() / 45; // 1,2 every 4 points @ 720x1280 px int speedIncrease = (int) (this.getWidth() / 600f * (game.accomplishmentBox.points / 4)); int speed = speedDefault + speedIncrease; return Math.min(speed, 2*speedDefault); } /** * Let's the player fall down dead, makes sure the runcycle stops * and invokes the next method for the dialog and stuff. */ public void gameOver(){ pause(); playerDeadFall(); game.gameOver(); } public void revive() { game.numberOfRevive++; // This needs to run another thread, so the dialog can close. new Thread(new Runnable() { @Override public void run() { setupRevive(); } }).start(); } /** * Sets the player into startposition * Removes obstacles. * Let's the character blink a few times. */ private void setupRevive(){ game.gameOverDialog.hide(); player.setY(this.getHeight()/2 - player.getWidth()/2); player.setX(this.getWidth()/6); obstacles.clear(); powerUps.clear(); player.revive(); for(int i = 0; i < 6; ++i){ while(!holder.getSurface().isValid()){/*wait*/} Canvas canvas = getCanvas(); drawCanvas(canvas, i%2 == 0); holder.unlockCanvasAndPost(canvas); // sleep try { Thread.sleep(UPDATE_INTERVAL*6); } catch (InterruptedException e) { e.printStackTrace(); } } resume(); } /** * A value for the position and size of the onScreen score Text */ public int getScoreTextMetrics(){ return (int) (this.getHeight() / 21.0f); /*/ game.getResources().getDisplayMetrics().density)*/ } public PlayableCharacter getPlayer(){ return this.player; } public Game getGame(){ return this.game; } }
package io.pslab.fragment; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.Html; import android.text.method.LinkMovementMethod; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.ExpandableListView; import android.widget.TextView; import io.pslab.R; public class FAQFragment extends Fragment { private String[] questions; private String[][] answers; public static FAQFragment newInstance() { return new FAQFragment(); } public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); questions = getResources().getStringArray(R.array.faq_questions); String[] ans = getResources().getStringArray(R.array.faq_answers); answers = new String[ans.length][]; for (int i = 0; i < ans.length; i++) { answers[i] = new String[]{ans[i]}; } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView; rootView = inflater.inflate(R.layout.fragment_faq, container, false); return rootView; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ExpandableListView listView; listView = (ExpandableListView) view.findViewById(R.id.expListView); listView.setAdapter(new ExpandableListAdapter(questions, answers)); listView.setGroupIndicator(null); } public class ExpandableListAdapter extends BaseExpandableListAdapter { private final LayoutInflater inf; private String[] questions; private String[][] answers; public ExpandableListAdapter(String[] questions, String[][] answers) { this.questions = questions; this.answers = answers; inf = LayoutInflater.from(getActivity()); } @Override public int getGroupCount() { return questions.length; } @Override public int getChildrenCount(int questionPosition) { return answers[questionPosition].length; } @Override public Object getGroup(int questionPosition) { return questions[questionPosition]; } @Override public Object getChild(int questionPosition, int answerPosition) { return answers[questionPosition][answerPosition]; } @Override public long getGroupId(int questionPosition) { return questionPosition; } @Override public long getChildId(int questionPosition, int answerPosition) { return answerPosition; } @Override public boolean hasStableIds() { return true; } @Override public View getChildView(int questionPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { ViewHolder holder; View v = convertView; if (v == null) { v = inf.inflate(R.layout.list_item, parent, false); holder = new ViewHolder(); holder.text = (TextView) v.findViewById(R.id.lblListItem); v.setTag(holder); } else { holder = (ViewHolder) v.getTag(); } holder.text.setClickable(true); holder.text.setMovementMethod(LinkMovementMethod.getInstance()); holder.text.setText(Html.fromHtml(getChild(questionPosition, childPosition).toString())); return v; } @Override public View getGroupView(int questionPosition, boolean isExpanded, View convertView, ViewGroup parent) { ViewHolder holder; View v = convertView; if (v == null) { v = inf.inflate(R.layout.list_group, parent, false); holder = new ViewHolder(); holder.text = (TextView) v.findViewById(R.id.lblListHeader); v.setTag(holder); } else { holder = (ViewHolder) v.getTag(); } holder.text.setText(getGroup(questionPosition).toString()); return v; } @Override public boolean isChildSelectable(int questionPosition, int answerPosition) { return true; } private class ViewHolder { private TextView text; } } }
package soft.swenggroup5; import android.content.Intent; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.os.Bundle; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.webkit.MimeTypeMap; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import com.google.zxing.BarcodeFormat; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.integration.android.IntentIntegrator; import com.google.zxing.integration.android.IntentResult; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.nio.ByteBuffer; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { /** * Constants * * WHITE: Hex value to colour generated qr code pixels white * BLACK: Hex value to colour generated qr code pixels black * WIDTH: The width of the generated qr code TODO include in layout to scale correctly? * HEIGHT: The height of the generated qr code TODO include in layout to scale correctly? * DEFAULT_STR: Test string to show generation of qr code TODO remove * INTEGRATOR: Object that is used to access the integrated scanner * TEST_FILE: test file to show encoding of header TODO remove */ private final static int WHITE = 0xFFFFFFFF; private final static int BLACK = 0xFF000000; private final static int WIDTH = 400; private final static int HEIGHT = 400; private final static String STR = "Software Engineering Group 5 - SOFT"; private final IntentIntegrator INTEGRATOR = new IntentIntegrator(this); private File TEST_FILE; private final static int MAX_FILE_SIZE = 2000; /** * onCreate * * TODO note that this is only for the base state of V1 * * Entry point for app when started. Initializes the generated qr code, the scan button, * and attaches a listener to the scan button. * * @param savedInstanceState: required param to instantiate the super class */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Create the scan button referencing the button in res/activity_main.xml Button scanButton = (Button)findViewById(R.id.button); // Create a space that will be used to present the demo generated qr code ImageView imageView = (ImageView) findViewById(R.id.qrCode); try { // cannot initialize as a constant as an error must be handled. // TODO move this to unit tests TEST_FILE = File.createTempFile("testing", ".txt"); // explicitly specify that the temp file is to be deleted on exit of the app TEST_FILE.deleteOnExit(); // write hello to the temp file FileOutputStream s = new FileOutputStream(TEST_FILE); s.write('h'); s.write('e'); s.write('l'); s.write('l'); s.write('o'); // close the stream s.close(); } catch (Exception e) { Log.d("Write_to_temp", e.toString()); } // Attempt to generate the qr code and put it into the ImageView try { ArrayList<Byte> Header = encodeHeader(TEST_FILE); Bitmap bitmap = encodeAsBitmap(STR); imageView.setImageBitmap(bitmap); } catch (WriterException e) { e.printStackTrace(); } // Create the event listener for when scanButton is clicked scanButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /** * setDesiredBarcodeFormats: setting the scanner to scan qr codes, this can be * changed to scan other codes (bar codes) and may become useful if we want to * implement extended functionality beyond V1 * setPrompt: a string shown to the user when scanning. May make this dynamic * to show how many qr codes have been scanned so far (probably V1) * setCameraId: use a specific camera of the device (front or back) * setBeepEnabled: when true, audible beep occurs when scan occurs * setBarcodeImageEnabled: TODO investigate * initiateScan: open the scanner (after it has been configured) */ INTEGRATOR.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES); INTEGRATOR.setPrompt("Scan the files qr code"); INTEGRATOR.setCameraId(0); INTEGRATOR.setBeepEnabled(false); INTEGRATOR.setBarcodeImageEnabled(true); INTEGRATOR.initiateScan(); } }); } /** * encodeAsBitmap * * Takes a string and returns a bitmap representation of the string as a qr code * * @param stringToConvert: the string to generate a qr code for * @return a bitmap representing the qr code generated for the passed string * @throws WriterException */ Bitmap encodeAsBitmap(String stringToConvert) throws WriterException { // TODO investigate BitMatrix result; try { result = new MultiFormatWriter().encode(stringToConvert, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, null); } catch (IllegalArgumentException iae) { // Unsupported format return null; } int width = result.getWidth(); int height = result.getHeight(); int[] pixels = new int[width * height]; for (int y = 0; y < height; y++) { int offset = y * width; for (int x = 0; x < width; x++) { pixels[offset + x] = result.get(x, y) ? BLACK : WHITE; } } Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, width, 0, 0, width, height); return bitmap; } /** * encodeHeader * * Takes a file and its position and returns an ArrayList of bytes representing * 1. File size * 2. File Type * 3. Hash value * 4. Position * * @param file: the data to be used * @return An ArrayList of buytes to be used as the QR code header */ ArrayList encodeHeader(File file) { ArrayList<Byte> header = new ArrayList<Byte>(); ByteBuffer b = ByteBuffer.allocate(8); //FILE SIZE ByteBuffer buffer; buffer = ByteBuffer.allocate(8); buffer.putLong(file.length()); Log.d("file length ", String.valueOf(file.length())); buffer.flip(); int length = buffer.remaining(); for(int i=0;i<length;i++) { //Passes individual bytes from byte array into the header list header.add(buffer.get(i)); } buffer.clear(); // FILE TYPE // String ext = FilenameUtils.getExtension(file); String filename = file.getName(); String ext = filename.substring(filename.lastIndexOf(".") + 1, filename.length()); // gets the file extension byte[] fileType = ext.getBytes(); for(int i=0;i<fileType.length;i++) { //Passes individual bytes from byte array into the header list header.add(fileType[i]); } // HASH VALUE int h = file.hashCode(); buffer = ByteBuffer.allocate(4); buffer.putInt(h); buffer.flip(); for(int i=0;i<buffer.remaining();i++) { //Passes individual bytes from byte array into the header list header.add(buffer.get(i)); } buffer.clear(); //NUMBER OF QR CODE int qrCodes = splitFileSize(file.length()); buffer = ByteBuffer.allocate(4); buffer.putInt(qrCodes); buffer.flip(); for(int i=0;i<buffer.remaining();i++) { //Passes individual bytes from byte array into the header list header.add(buffer.get(i)); } buffer.clear(); for(int i=0; i<header.size();i++) { Log.d("Header val " + i, String.valueOf(header.get(i))); } return header; } public static String getMimeType(File file) { String filePath = file.getAbsolutePath(); Log.d("File_path", filePath); String type = null; String extension = MimeTypeMap.getFileExtensionFromUrl(filePath); if (extension != null) { type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); } Log.d("File_MIME_type", type); return type; } /** * splitFileSize * * Takes in a file size and calculates the number of QR codes needed to transfer it. * * @param size: the size of the file to be transferred. * @return the number of QR Codes required. */ int splitFileSize(long size) { int qrCodes= 0; while(size > MAX_FILE_SIZE) { qrCodes++; size -= MAX_FILE_SIZE; } return qrCodes; } /** * onActivityResult * * Defines what happens when a successful read of a qr code occurs. Right now (at base), when * a qr code is successfully scanned, the scanner is exited and the contents of the scan * are breifly shown on the device screen TODO update when changes * * @param requestCode: TODO investigate params * @param resultCode: TODO investigate params * @param data: TODO investigate params */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); if (result != null) { if (result.getContents() == null) { Log.d("Scan_Button", "Cancelled scan"); Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show(); } else { Log.d("Scan_Button", "Scanned"); Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show(); } } else { // This is important, otherwise the result will not be passed to the fragment super.onActivityResult(requestCode, resultCode, data); } } }
package net.katsuster.ememu.riscv.core; import net.katsuster.ememu.generic.*; import java.math.*; import java.util.concurrent.locks.*; public class ExecStageRVI extends Stage64 { /** * RVI * * @param c CPU */ public ExecStageRVI(RV64 c) { super(c); } /** * RVI CPU * * @return CPU */ @Override public RV64 getCore() { return (RV64)super.getCore(); } /** * CSR * * @param n * @return */ public long getCSR(int n) { return getCore().getCSR(n); } /** * CSR * * @param n * @param val */ public void setCSR(int n, long val) { getCore().setCSR(n, val); } /** * CSR * * @param n * @return */ public String getCSRName(int n) { return getCore().getCSRName(n); } /** * Fence pred, succ * * @param n pred succ * @return pred succ */ public String getPredName(int n) { StringBuffer result = new StringBuffer(); if ((n & 8) != 0) { result.append("i"); } if ((n & 4) != 0) { result.append("o"); } if ((n & 2) != 0) { result.append("r"); } if ((n & 1) != 0) { result.append("w"); } return result.toString(); } public void waitInt() { RV64 c = getCore(); synchronized (c) { while (!c.isRaisedInterrupt() && !c.isRaisedInternalInterrupt() && !c.shouldHalt()) { try { c.wait(1000); } catch (InterruptedException ex) { //do nothing } } } } /** * AUIPC (Add upper immediate to pc) * * @param inst 32bit * @param exec true false */ public void executeAuipc(InstructionRV32 inst, boolean exec) { int rd = inst.getRd(); int imm20 = inst.getImm20U(); long imm = BitOp.signExt64((imm20 << 12) & 0xffffffffL, 32); if (!exec) { printDisasm(inst, "auipc", String.format("%s, 0x%x", getRegName(rd), imm)); return; } setReg(rd, getPC() + imm); } /** * LUI (Load upper immediate) * * @param inst 32bit * @param exec true false */ public void executeLui(InstructionRV32 inst, boolean exec) { int rd = inst.getRd(); int imm20 = inst.getImm20U(); long imm = BitOp.signExt64((imm20 << 12) & 0xffffffffL, 31); if (!exec) { printDisasm(inst, "lui", String.format("%s, 0x%x", getRegName(rd), imm)); return; } setReg(rd, imm); } /** * JAL (Jump and link) * * @param inst 32bit * @param exec true false */ public void executeJal(InstructionRV32 inst, boolean exec) { int rd = inst.getRd(); long off = BitOp.signExt64(inst.getImm20J(), 20); long t; if (!exec) { printDisasm(inst, "jal", String.format("%s, 0x%x", getRegName(rd), off + getPC())); return; } t = getPC() + 4; jumpRel((int)off); setReg(rd, t); } /** * JALR (Jump and link register) * * @param inst 32bit * @param exec true false */ public void executeJalr(InstructionRV32 inst, boolean exec) { int rd = inst.getRd(); int rs1 = inst.getRs1(); long off = BitOp.signExt64(inst.getImm12I(), 12); long t; if (!exec) { printDisasm(inst, "jalr", String.format("%s, %d(%s)", getRegName(rd), off, getRegName(rs1))); return; } t = getPC() + 4; setPC((getReg(rs1) + off) & ~0x1L); setReg(rd, t); } /** * BEQ (Branch if equal) * * @param inst 32bit * @param exec true false */ public void executeBeq(InstructionRV32 inst, boolean exec) { int rs1 = inst.getRs1(); int rs2 = inst.getRs2(); int off = BitOp.signExt32(inst.getImm13B(), 13); if (!exec) { printDisasm(inst, "beq", String.format("%s, %s, 0x%x", getRegName(rs1), getRegName(rs2), getPC() + off)); return; } if (getReg(rs1) == getReg(rs2)) { jumpRel(off); } } /** * BNE (Branch if not equal) * * @param inst 32bit * @param exec true false */ public void executeBne(InstructionRV32 inst, boolean exec) { int rs1 = inst.getRs1(); int rs2 = inst.getRs2(); int off = BitOp.signExt32(inst.getImm13B(), 13); if (!exec) { printDisasm(inst, "bne", String.format("%s, %s, 0x%x", getRegName(rs1), getRegName(rs2), getPC() + off)); return; } if (getReg(rs1) != getReg(rs2)) { jumpRel(off); } } /** * BNE (Branch if less than) * * @param inst 32bit * @param exec true false */ public void executeBlt(InstructionRV32 inst, boolean exec) { int rs1 = inst.getRs1(); int rs2 = inst.getRs2(); int off = BitOp.signExt32(inst.getImm13B(), 13); if (!exec) { printDisasm(inst, "blt", String.format("%s, %s, 0x%x", getRegName(rs1), getRegName(rs2), getPC() + off)); return; } if (getReg(rs1) < getReg(rs2)) { jumpRel(off); } } /** * BLTU (Branch if less than, unsigned) * * @param inst 32bit * @param exec true false */ public void executeBltu(InstructionRV32 inst, boolean exec) { int rs1 = inst.getRs1(); int rs2 = inst.getRs2(); int off = BitOp.signExt32(inst.getImm13B(), 13); if (!exec) { printDisasm(inst, "bltu", String.format("%s, %s, 0x%x", getRegName(rs1), getRegName(rs2), getPC() + off)); return; } if (IntegerExt.compareUint64(getReg(rs1), getReg(rs2)) < 0) { jumpRel(off); } } /** * BGEU (Branch if greater than or equal, unsigned) * * @param inst 32bit * @param exec true false */ public void executeBgeu(InstructionRV32 inst, boolean exec) { int rs1 = inst.getRs1(); int rs2 = inst.getRs2(); int off = BitOp.signExt32(inst.getImm13B(), 13); if (!exec) { printDisasm(inst, "bgeu", String.format("%s, %s, 0x%x", getRegName(rs1), getRegName(rs2), getPC() + off)); return; } if (IntegerExt.compareUint64(getReg(rs1), getReg(rs2)) >= 0) { jumpRel(off); } } /** * LBU (Load byte, unsigned) * * @param inst 32bit * @param exec true false */ public void executeLbu(InstructionRV32 inst, boolean exec) { int rd = inst.getRd(); int rs1 = inst.getRs1(); int imm12 = inst.getImm12I(); long off = BitOp.signExt64(imm12, 12); long vaddr, paddr; byte val; if (!exec) { printDisasm(inst, "lbu", String.format("%s, %d(%s) # 0x%x", getRegName(rd), off, getRegName(rs1), imm12)); return; } vaddr = getReg(rs1) + off; //paddr = getMMU().translate(vaddr, 1, false, getPriv(), true); paddr = vaddr; //if (getMMU().isFault()) { // getMMU().clearFault(); // return; if (!tryRead(paddr, 1)) { //raiseException(ARMv5.EXCEPT_ABT_DATA, // String.format("ldrd [%08x]", paddr)); return; } val = read8(paddr); setReg(rd, val & 0xffL); } /** * LW (Load word) * * @param inst 32bit * @param exec true false */ public void executeLw(InstructionRV32 inst, boolean exec) { int rd = inst.getRd(); int rs1 = inst.getRs1(); int imm12 = inst.getImm12I(); long off = BitOp.signExt64(imm12, 12); long vaddr, paddr; int val; if (!exec) { printDisasm(inst, "lw", String.format("%s, %d(%s) # 0x%x", getRegName(rd), off, getRegName(rs1), imm12)); return; } vaddr = getReg(rs1) + off; //paddr = getMMU().translate(vaddr, 4, false, getPriv(), true); paddr = vaddr; //if (getMMU().isFault()) { // getMMU().clearFault(); // return; if (!tryRead(paddr, 4)) { //raiseException(ARMv5.EXCEPT_ABT_DATA, // String.format("ldrd [%08x]", paddr)); return; } val = read32(paddr); setReg(rd, BitOp.signExt64(val & 0xffffffffL, 32)); } /** * SW (Store word) * * @param inst 32bit * @param exec true false */ public void executeSw(InstructionRV32 inst, boolean exec) { int rs1 = inst.getRs1(); int rs2 = inst.getRs2(); int offraw = inst.getImm12S(); long off = BitOp.signExt64(offraw, 12); long vaddr, paddr; if (!exec) { printDisasm(inst, "sw", String.format("%s, %d(%s) # 0x%x", getRegName(rs2), off, getRegName(rs1), offraw)); return; } vaddr = getReg(rs1) + off; //paddr = getMMU().translate(vaddr, 4, false, getPriv(), true); paddr = vaddr; //if (getMMU().isFault()) { // getMMU().clearFault(); // return; if (!tryWrite(paddr, 4)) { //raiseException(ARMv5.EXCEPT_ABT_DATA, // String.format("ldrd [%08x]", paddr)); return; } write32(paddr, (int)getReg(rs2)); } /** * SD (Store double word) * * @param inst 32bit * @param exec true false */ public void executeSd(InstructionRV32 inst, boolean exec) { int rs1 = inst.getRs1(); int rs2 = inst.getRs2(); int offraw = inst.getImm12S(); long off = BitOp.signExt64(offraw, 12); long vaddr, paddr; if (!exec) { printDisasm(inst, "sd", String.format("%s, %d(%s) # 0x%x", getRegName(rs2), off, getRegName(rs1), offraw)); return; } vaddr = getReg(rs1) + off; //paddr = getMMU().translate(vaddr, 4, false, getPriv(), true); paddr = vaddr; //if (getMMU().isFault()) { // getMMU().clearFault(); // return; if (!tryWrite(paddr, 8)) { //raiseException(ARMv5.EXCEPT_ABT_DATA, // String.format("ldrd [%08x]", paddr)); return; } write64(paddr, getReg(rs2)); } /** * ADDI (Add immediate) * * @param inst 32bit * @param exec true false */ public void executeAddi(InstructionRV32 inst, boolean exec) { int rd = inst.getRd(); int rs1 = inst.getRs1(); int imm12 = inst.getImm12I(); long imm = BitOp.signExt64(imm12, 12); if (!exec) { printDisasm(inst, "addi", String.format("%s, %s, %d # 0x%x", getRegName(rd), getRegName(rs1), imm, imm12)); return; } setReg(rd, getReg(rs1) + imm); } /** * ORI (Or immediate) * * @param inst 32bit * @param exec true false */ public void executeOri(InstructionRV32 inst, boolean exec) { int rd = inst.getRd(); int rs1 = inst.getRs1(); int imm12 = inst.getImm12I(); long imm = BitOp.signExt64(imm12, 12); if (!exec) { printDisasm(inst, "ori", String.format("%s, %s, %d # 0x%x", getRegName(rd), getRegName(rs1), imm, imm12)); return; } setReg(rd, getReg(rs1) | imm); } /** * ANDI (And immediate) * * @param inst 32bit * @param exec true false */ public void executeAndi(InstructionRV32 inst, boolean exec) { int rd = inst.getRd(); int rs1 = inst.getRs1(); int imm12 = inst.getImm12I(); long imm = BitOp.signExt64(imm12, 12); if (!exec) { printDisasm(inst, "andi", String.format("%s, %s, %d # 0x%x", getRegName(rd), getRegName(rs1), imm, imm12)); return; } setReg(rd, getReg(rs1) & imm); } /** * SLLI (Shift left logical immediate) * * @param inst 32bit * @param exec true false */ public void executeSlli(InstructionRV32 inst, boolean exec) { int rd = inst.getRd(); int rs1 = inst.getRs1(); int shamt = inst.getField(20, 6); if (!exec) { printDisasm(inst, "slli", String.format("%s, %s, 0x%x # %d", getRegName(rd), getRegName(rs1), shamt, shamt)); return; } setReg(rd, getReg(rs1) << shamt); } /** * SRLI (Shift right logical immediate) * * @param inst 32bit * @param exec true false */ public void executeSrli(InstructionRV32 inst, boolean exec) { int rd = inst.getRd(); int rs1 = inst.getRs1(); int shamt = inst.getField(20, 6); if (!exec) { printDisasm(inst, "srli", String.format("%s, %s, 0x%x # %d", getRegName(rd), getRegName(rs1), shamt, shamt)); return; } setReg(rd, getReg(rs1) >>> shamt); } /** * SRAI (Shift right arithmetic immediate) * * @param inst 32bit * @param exec true false */ public void executeSrai(InstructionRV32 inst, boolean exec) { int rd = inst.getRd(); int rs1 = inst.getRs1(); int shamt = inst.getField(20, 6); if (!exec) { printDisasm(inst, "srai", String.format("%s, %s, 0x%x # %d", getRegName(rd), getRegName(rs1), shamt, shamt)); return; } setReg(rd, getReg(rs1) >> shamt); } /** * ADD * * @param inst 32bit * @param exec true false */ public void executeAdd(InstructionRV32 inst, boolean exec) { int rd = inst.getRd(); int rs1 = inst.getRs1(); int rs2 = inst.getRs2(); if (!exec) { printDisasm(inst, "add", String.format("%s, %s, %s", getRegName(rd), getRegName(rs1), getRegName(rs2))); return; } setReg(rd, getReg(rs1) + getReg(rs2)); } /** * SUB * * @param inst 32bit * @param exec true false */ public void executeSub(InstructionRV32 inst, boolean exec) { int rd = inst.getRd(); int rs1 = inst.getRs1(); int rs2 = inst.getRs2(); if (!exec) { printDisasm(inst, "sub", String.format("%s, %s, %s", getRegName(rd), getRegName(rs1), getRegName(rs2))); return; } setReg(rd, getReg(rs1) - getReg(rs2)); } /** * SLL (Shift left logical) * * @param inst 32bit * @param exec true false */ public void executeSll(InstructionRV32 inst, boolean exec) { int rd = inst.getRd(); int rs1 = inst.getRs1(); int rs2 = inst.getRs2(); if (!exec) { printDisasm(inst, "sll", String.format("%s, %s, %s", getRegName(rd), getRegName(rs1), getRegName(rs2))); return; } setReg(rd, getReg(rs1) << getReg(rs2)); } /** * Fence (Fence memory and I/O) * * @param inst 32bit * @param exec true false */ public void executeFence(InstructionRV32 inst, boolean exec) { int imm = inst.getImm12I(); int succ = BitOp.getField32(imm, 0, 4); int pred = BitOp.getField32(imm, 4, 4); if (!exec) { printDisasm(inst, "fence", String.format("%s, %s", getPredName(pred), getPredName(succ))); return; } } /** * CSRRW (Control and status register read and write) * * @param inst 32bit * @param exec true false */ public void executeCsrrw(InstructionRV32 inst, boolean exec) { int rd = inst.getRd(); int rs1 = inst.getRs1(); int csr = inst.getImm12I(); long t; if (!exec) { printDisasm(inst, "csrrw", String.format("%s, %s, %s", getRegName(rd), getCSRName(csr), getRegName(rs1))); return; } t = getCSR(csr); setCSR(csr, getReg(rs1)); setReg(rd, t); } /** * CSRRS (Control and status register read and set) * * @param inst 32bit * @param exec true false */ public void executeCsrrs(InstructionRV32 inst, boolean exec) { int rd = inst.getRd(); int rs1 = inst.getRs1(); int csr = inst.getImm12I(); long t; if (!exec) { printDisasm(inst, "csrrs", String.format("%s, %s, %s", getRegName(rd), getCSRName(csr), getRegName(rs1))); return; } t = getCSR(csr); setCSR(csr, t | getReg(rs1)); setReg(rd, t); } /** * WFI () * * @param inst 32bit * @param exec true false */ public void executeWfi(InstructionRV32 inst, boolean exec) { int rd = inst.getRd(); int rs1 = inst.getRs1(); int imm12 = inst.getImm12I(); long imm = BitOp.signExt64(imm12, 12); long v; if (!exec) { printDisasm(inst, "wfi", ""); return; } waitInt(); } /** * LD (Load doubleword) * * @param inst 32bit * @param exec true false */ public void executeLd(InstructionRV32 inst, boolean exec) { int rd = inst.getRd(); int rs1 = inst.getRs1(); int imm12 = inst.getImm12I(); long off = BitOp.signExt64(imm12, 12); long vaddr, paddr; long val; if (!exec) { printDisasm(inst, "lw", String.format("%s, %d(%s) # 0x%x", getRegName(rd), off, getRegName(rs1), imm12)); return; } vaddr = getReg(rs1) + off; //paddr = getMMU().translate(vaddr, 8, false, getPriv(), true); paddr = vaddr; //if (getMMU().isFault()) { // getMMU().clearFault(); // return; if (!tryRead(paddr, 8)) { //raiseException(ARMv5.EXCEPT_ABT_DATA, // String.format("ldrd [%08x]", paddr)); return; } val = read64(paddr); setReg(rd, val); } /** * ADDIW (Add word immediate) * * @param inst 32bit * @param exec true false */ public void executeAddiw(InstructionRV32 inst, boolean exec) { int rd = inst.getRd(); int rs1 = inst.getRs1(); int imm12 = inst.getImm12I(); long imm = BitOp.signExt64(imm12, 12); long v; if (!exec) { printDisasm(inst, "addiw", String.format("%s, %s, %d # 0x%x", getRegName(rd), getRegName(rs1), imm, imm12)); return; } v = getReg(rs1) + imm; setReg(rd, BitOp.signExt64(v & 0xffffffffL, 32)); } /** * SRLW (shift right logical word) * * @param inst 32bit * @param exec true false */ public void executeSrlw(InstructionRV32 inst, boolean exec) { int rd = inst.getRd(); int rs1 = inst.getRs1(); int rs2 = inst.getRs2(); long v; if (!exec) { printDisasm(inst, "srlw", String.format("%s, %s, %s", getRegName(rd), getRegName(rs1), getRegName(rs2))); return; } v = (getReg(rs1) & 0xffffffffL) >>> getReg(rs2); setReg(rd, BitOp.signExt64(v & 0xffffffffL, 32)); } /** * MUL (Multiply) * * @param inst 32bit * @param exec true false */ public void executeMul(InstructionRV32 inst, boolean exec) { int rd = inst.getRd(); int rs1 = inst.getRs1(); int rs2 = inst.getRs2(); if (!exec) { printDisasm(inst, "mul", String.format("%s, %s, %s", getRegName(rd), getRegName(rs1), getRegName(rs2))); return; } setReg(rd, getReg(rs1) * getReg(rs2)); } /** * DIVU (Divide, Unsigned) * * @param inst 32bit * @param exec true false */ public void executeDivu(InstructionRV32 inst, boolean exec) { int rd = inst.getRd(); int rs1 = inst.getRs1(); int rs2 = inst.getRs2(); BigInteger dividend, divisor; if (!exec) { printDisasm(inst, "divu", String.format("%s, %s, %s", getRegName(rd), getRegName(rs1), getRegName(rs2))); return; } dividend = BitOp.toUnsignedBigInt(getReg(rs1)); divisor = BitOp.toUnsignedBigInt(getReg(rs2)); setReg(rd, dividend.divide(divisor).longValue()); } /** * DIVUW (Divide word, Unsigned) * * @param inst 32bit * @param exec true false */ public void executeDivuw(InstructionRV32 inst, boolean exec) { int rd = inst.getRd(); int rs1 = inst.getRs1(); int rs2 = inst.getRs2(); long dividend, divisor; if (!exec) { printDisasm(inst, "divuw", String.format("%s, %s, %s", getRegName(rd), getRegName(rs1), getRegName(rs2))); return; } dividend = getReg(rs1) & 0xffffffffL; divisor = getReg(rs2) & 0xffffffffL; setReg(rd, BitOp.signExt64(dividend / divisor, 32)); } /** * AMOOR.W (Atomic memory operation: OR word) * * @param inst 32bit * @param exec true false */ public void executeAmoorw(InstructionRV32 inst, boolean exec) { int rd = inst.getRd(); int rs1 = inst.getRs1(); int rs2 = inst.getRs2(); long vaddr, paddr; int val; Lock l; if (!exec) { printDisasm(inst, "amoor.w", String.format("%s, %s, (%s)", getRegName(rd), getRegName(rs2), getRegName(rs1))); return; } vaddr = getReg(rs1); //paddr = getMMU().translate(vaddr, 4, false, getPriv(), true); paddr = vaddr; //if (getMMU().isFault()) { // getMMU().clearFault(); // return; val = (int)getReg(rs2); l = getWriteLock(); l.lock(); try { if (!tryRead(paddr, 4)) { //raiseException(ARMv5.EXCEPT_ABT_DATA, // String.format("ldrd [%08x]", paddr)); return; } val |= read32(paddr); write32(paddr, val); } finally { l.unlock(); } setReg(rd, BitOp.signExt64(val & 0xffffffffL, 32)); } /** * 32bit * * @param decinst * @param exec true false */ public void execute(Opcode decinst, boolean exec) { InstructionRV32 inst = (InstructionRV32) decinst.getInstruction(); switch (decinst.getIndex()) { case INS_RV32I_AUIPC: executeAuipc(inst, exec); break; case INS_RV32I_LUI: executeLui(inst, exec); break; case INS_RV32I_JAL: executeJal(inst, exec); break; case INS_RV32I_JALR: executeJalr(inst, exec); break; case INS_RV32I_BEQ: executeBeq(inst, exec); break; case INS_RV32I_BNE: executeBne(inst, exec); break; case INS_RV32I_BLT: executeBlt(inst, exec); break; case INS_RV32I_BLTU: executeBltu(inst, exec); break; case INS_RV32I_BGEU: executeBgeu(inst, exec); break; case INS_RV32I_LBU: executeLbu(inst, exec); break; case INS_RV32I_LW: executeLw(inst, exec); break; case INS_RV32I_SW: executeSw(inst, exec); break; case INS_RV64I_SD: executeSd(inst, exec); break; case INS_RV32I_ADDI: executeAddi(inst, exec); break; case INS_RV32I_ORI: executeOri(inst, exec); break; case INS_RV32I_ANDI: executeAndi(inst, exec); break; case INS_RV32I_SLLI: case INS_RV64I_SLLI: executeSlli(inst, exec); break; case INS_RV32I_SRLI: case INS_RV64I_SRLI: executeSrli(inst, exec); break; case INS_RV32I_SRAI: case INS_RV64I_SRAI: executeSrai(inst, exec); break; case INS_RV32I_ADD: executeAdd(inst, exec); break; case INS_RV32I_SUB: executeSub(inst, exec); break; case INS_RV32I_SLL: executeSll(inst, exec); break; case INS_RV32I_FENCE: executeFence(inst, exec); break; case INS_RV32I_CSRRW: executeCsrrw(inst, exec); break; case INS_RV32I_CSRRS: executeCsrrs(inst, exec); break; case INS_RV32_WFI: executeWfi(inst, exec); break; case INS_RV64I_LD: executeLd(inst, exec); break; case INS_RV64I_ADDIW: executeAddiw(inst, exec); break; case INS_RV64I_SRLW: executeSrlw(inst, exec); break; case INS_RV32M_MUL: executeMul(inst, exec); break; case INS_RV32M_DIVU: executeDivu(inst, exec); break; case INS_RV64M_DIVUW: executeDivuw(inst, exec); break; case INS_RV32A_AMOOR_W: executeAmoorw(inst, exec); break; default: throw new IllegalArgumentException("Unknown RV32I instruction " + decinst.getIndex()); } } }
package org.slf4j.impl; import java.util.Map; import java.util.concurrent.ConcurrentMap; import java.util.regex.Pattern; import javax.annotation.Nonnull; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.slf4j.ILoggerFactory; import org.slf4j.Logger; import com.google.common.collect.Maps; /** * An implementation of {@link ILoggerFactory} * @author chandni */ public class DTLoggerFactory implements ILoggerFactory { private static DTLoggerFactory SINGLETON; public synchronized static DTLoggerFactory get() { if (SINGLETON == null) { SINGLETON = new DTLoggerFactory(); } return SINGLETON; } ConcurrentMap<String, DTLoggerAdapter> loggerMap; Map<String, Level> patternLevel; Map<String, Pattern> patterns; private DTLoggerFactory() { loggerMap = Maps.newConcurrentMap(); patternLevel = Maps.newHashMap(); patterns = Maps.newHashMap(); } public void changeLoggersLevel(@Nonnull Map<String, String> targetChanges) { for (Map.Entry<String, String> loggerEntry : targetChanges.entrySet()) { String target = loggerEntry.getKey(); patternLevel.put(target, Level.toLevel(loggerEntry.getValue())); patterns.put(target, Pattern.compile(target)); } if (!patternLevel.isEmpty()) { for (DTLoggerAdapter classLogger : loggerMap.values()) { Level level = getLevelFor(classLogger.getName()); if(level!=null){ classLogger.setLogLevel(level); } } } } @Override public Logger getLogger(String name) { Logger slf4jLogger = loggerMap.get(name); if (slf4jLogger != null) { return slf4jLogger; } else { org.apache.log4j.Logger log4jLogger; if (name.equalsIgnoreCase(Logger.ROOT_LOGGER_NAME)) { log4jLogger = LogManager.getRootLogger(); } else { log4jLogger = LogManager.getLogger(name); } DTLoggerAdapter newInstance = new DTLoggerAdapter(log4jLogger); Level level = getLevelFor(name); if (level != null) { newInstance.setLogLevel(level); } Logger oldInstance = loggerMap.putIfAbsent(name, newInstance); return oldInstance == null ? newInstance : oldInstance; } } private Level getLevelFor(String name) { if (patternLevel.isEmpty()) { return null; } String longestPatternKey = null; for (String partternKey : patternLevel.keySet()) { Pattern pattern = patterns.get(partternKey); if (pattern.matcher(name).matches() && (longestPatternKey == null || longestPatternKey.length() < partternKey.length())) { longestPatternKey = partternKey; } } if (longestPatternKey != null) { return patternLevel.get(longestPatternKey); } return null; } }
import io.datakernel.promise.Promise; import io.datakernel.promise.Promises; import java.util.Arrays; public final class PromisesExample { private static int counter; private static void repeat() { System.out.println("Repeat until exception:"); //[START REGION_1] Promises.repeat(() -> { System.out.println("This is iteration #" + ++counter); if (counter == 5) { return Promise.ofException(new Exception("Breaking the loop")); } return Promise.complete(); }); //[END REGION_1] System.out.println(); } private static void loop() { System.out.println("Looping with condition:"); //[START REGION_2] Promises.loop(0, i -> i < 5, i -> { System.out.println("This is iteration return Promise.of(i + 1); }); //[END REGION_2] System.out.println(); } private static void toList() { System.out.println("Collecting group of Promises to list of Promises' results:"); //[START REGION_3] Promises.toList(Promise.of(1), Promise.of(2), Promise.of(3), Promise.of(4), Promise.of(5), Promise.of(6)) .whenResult(list -> System.out.println("Size of collected list: " + list.size() + "\nList: " + list)); //[END REGION_3] System.out.println(); } private static void toArray() { System.out.println("Collecting group of Promises to array of Promises' results:"); //[START REGION_4] Promises.toArray(Integer.class, Promise.of(1), Promise.of(2), Promise.of(3), Promise.of(4), Promise.of(5), Promise.of(6)) .whenResult(array -> System.out.println("Size of collected array: " + array.length + "\nArray: " + Arrays.toString(array))); //[END REGION_4] System.out.println(); } public static void main(String[] args) { repeat(); loop(); toList(); toArray(); } }
package org.intermine.web; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.io.StringWriter; import java.io.PrintWriter; import org.apache.struts.Globals; import org.apache.struts.action.ActionMessages; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionErrors; import org.apache.log4j.Logger; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreException; import org.intermine.objectstore.ObjectStoreQueryDurationException; import org.intermine.objectstore.query.Query; import org.intermine.web.results.PagedResults; import org.intermine.web.results.TableHelper; /** * Business logic that interacts with session data. These methods are generally * called by actions to perform business logic. Obviously, a lot of the business * logic happens in other parts of intermine, called from here, then the users * session is updated accordingly. * * @author Thomas Riley */ public class SessionMethods { protected static final Logger LOG = Logger.getLogger(SessionMethods.class); /** * Executes current query and sets session attributes QUERY_RESULTS and RESULTS_TABLE. If the * query fails for some reason, this method returns false and ActionErrors are set on the * request. * * @param session the http session * @param request the current http request * @param saveQuery if true, query will be saved automatically * @return true if query ran successfully, false if an error occured * @throws Exception if getting results info from paged results fails */ public static boolean runQuery(HttpSession session, HttpServletRequest request, boolean saveQuery) throws Exception { ServletContext servletContext = session.getServletContext(); Profile profile = (Profile) session.getAttribute(Constants.PROFILE); PathQuery query = (PathQuery) session.getAttribute(Constants.QUERY); ObjectStore os = (ObjectStore) servletContext.getAttribute(Constants.OBJECTSTORE); PagedResults pr; try { Query q = MainHelper.makeQuery(query, profile.getSavedBags()); pr = TableHelper.makeTable(os, q, query.getView()); } catch (ObjectStoreException e) { ActionErrors errors = (ActionErrors) request.getAttribute(Globals.ERROR_KEY); if (errors == null) { errors = new ActionErrors(); request.setAttribute(Globals.ERROR_KEY, errors); } String key = (e instanceof ObjectStoreQueryDurationException) ? "errors.query.estimatetimetoolong" : "errors.query.objectstoreerror"; errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(key)); // put stack trace in the log StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); LOG.error(sw.toString()); return false; } session.setAttribute(Constants.QUERY_RESULTS, pr); session.setAttribute(Constants.RESULTS_TABLE, pr); if (saveQuery) { String queryName = SaveQueryHelper.findNewQueryName(profile.getSavedQueries()); query.setInfo(pr.getResultsInfo()); saveQuery(request, queryName, query); ActionMessages messages = (ActionMessages) request.getAttribute(Globals.MESSAGE_KEY); if (messages == null) { messages = new ActionMessages(); } messages.add("saveQuery", new ActionMessage("saveQuery.message", queryName)); request.setAttribute(Globals.MESSAGE_KEY, messages); } return true; } /** * Load a query into the session, cloning to avoid modifying the original * @param query the query * @param session the session */ public static void loadQuery(PathQuery query, HttpSession session) { session.setAttribute(Constants.QUERY, query.clone()); //at the moment we can only load queries that have saved using the webapp //this is because the webapp satisfies our (dumb) assumption that the view list is not empty String path = (String) query.getView().iterator().next(); if (path.indexOf(".") != -1) { path = path.substring(0, path.indexOf(".")); } session.setAttribute("path", path); session.removeAttribute("prefix"); } /** * Save a query in the Map on the session, and clone it to allow further editing * @param request The HTTP request we are processing * @param queryName the name to save the query under * @param query the PathQuery */ public static void saveQuery(HttpServletRequest request, String queryName, PathQuery query) { HttpSession session = request.getSession(); Profile profile = (Profile) session.getAttribute(Constants.PROFILE); profile.saveQuery(queryName, query); session.setAttribute(Constants.QUERY, query.clone()); } }
// Install the Java helper library from twilio.com/docs/java/install import java.util.*; import com.twilio.Twilio; import com.twilio.rest.chat.v2.service.Role; public class Example { // Find your Account Sid and Token at twilio.com/user/account public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; public static final String AUTH_TOKEN = "your_auth_token"; public static final String SERVICE_SID = "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; public static final String ROLE_SID = "RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; public static void main(String[] args) { // Initialize the client Twilio.init(ACCOUNT_SID, AUTH_TOKEN); Role role = Role.fetcher(SERVICE_SID, ROLE_SID).fetch(); List<String> newPermissions = new ArrayList<>(Arrays.asList("sendMediaMessage")); newPermissions.addAll(role.getPermissions()); // Update the role Role role = Role.updater(SERVICE_SID, ROLE_SID, newPermissions).update(); } }
package ru.fomenkov.task.javac; import ru.fomenkov.GreenCat; import ru.fomenkov.Module; import ru.fomenkov.command.CommandExecutor; import ru.fomenkov.command.CommandLineBuilder; import ru.fomenkov.command.Parameter; import ru.fomenkov.message.CompileWithJavacMessage; import ru.fomenkov.message.ModuleDiffMessage; import ru.fomenkov.task.ExecutionStatus; import ru.fomenkov.task.Task; import ru.fomenkov.task.TaskPurpose; import ru.fomenkov.telemetry.Telemetry; import java.io.File; import java.util.List; import java.util.Set; public class CompileWithJavacTask implements Task<ModuleDiffMessage, CompileWithJavacMessage> { private final String classpath; private final String projectPath; private final File objDir; public CompileWithJavacTask(String projectPath, String classpath, File objDir) { this.projectPath = projectPath; this.classpath = classpath; this.objDir = objDir; } @Override public TaskPurpose getPurpose() { return TaskPurpose.COMPILE_WITH_JAVAC; } @Override public CompileWithJavacMessage exec(Telemetry telemetry, ModuleDiffMessage message) { if (message.status != ExecutionStatus.SUCCESS) { throw new IllegalArgumentException("Previous step execution failed"); } else if (message.getFiles().isEmpty()) { throw new IllegalArgumentException("No files to compile from the previous step"); } if (!createCompileDir(projectPath, message.getModule())) { return new CompileWithJavacMessage(ExecutionStatus.ERROR, "Failed to create module directory"); } telemetry.message("Compiling with javac..."); if (compileWithJavac(telemetry, message.getFiles(), classpath)) { return new CompileWithJavacMessage(projectPath, classpath); } else { return new CompileWithJavacMessage(ExecutionStatus.ERROR, "Compilation errors"); } } private boolean createCompileDir(String projectPath, Module module) { String dstPath = GreenCat.getCompileDir(projectPath, module.name).getAbsolutePath(); File dstDir = new File(dstPath); return dstDir.exists() || dstDir.mkdirs(); } private boolean compileWithJavac(Telemetry telemetry, Set<File> javaFiles, String classpath) { String cmd = CommandLineBuilder.create("which javac").build(); List<String> output = CommandExecutor.execOnInputStream(cmd); if (output.isEmpty()) { telemetry.error("Can't find java compiler"); return false; } StringBuilder srcBuilder = new StringBuilder(); for (File file : javaFiles) { String path = file.getAbsolutePath(); srcBuilder.append(path).append(" "); } cmd = CommandLineBuilder.create("javac") .add(new Parameter("-d", objDir.getAbsolutePath())) .add(new Parameter("-source 1.8")) .add(new Parameter("-target 1.8")) .add(new Parameter("-encoding UTF-8")) .add(new Parameter("-g")) .add(new Parameter("-cp", classpath)) .add(new Parameter(srcBuilder.toString())) .build(); output = CommandExecutor.execOnErrorStream(cmd); boolean compilationSuccess = true; for (String line : output) { if (line.contains("error: ") || line.contains("invalid flag:") || line.contains("Usage: javac")) { compilationSuccess = false; break; } } for (String line : output) { line = line.replace("%", ""); if (compilationSuccess) { telemetry.message(line); } else { telemetry.error(line); } } telemetry.message(""); telemetry.message("Compilation %s", compilationSuccess ? "status" : "failed"); return compilationSuccess; } }
package squeek.creativeblocks.config; import java.io.*; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.FilenameUtils; import squeek.creativeblocks.CreativeBlocks; import squeek.creativeblocks.ModInfo; import squeek.creativeblocks.helpers.FileHelper; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class JSONConfigHandler { private static final Gson gson = new GsonBuilder().enableComplexMapKeySerialization().setPrettyPrinting().create(); private static List<File> configFiles = new ArrayList<File>(); public static final String defaultConfigFileName = "default.json"; public static final String defaultConfigRelativePath = "config/" + defaultConfigFileName; public static void setup(File configDirectory) { File modConfigDirectory = new File(configDirectory, ModInfo.MODID); if (!modConfigDirectory.exists()) { modConfigDirectory.mkdirs(); } for (File potentialConfigFile : modConfigDirectory.listFiles()) { if (!FilenameUtils.getExtension(potentialConfigFile.getName()).equalsIgnoreCase("json")) continue; configFiles.add(potentialConfigFile); } File defaultConfigDest = new File(modConfigDirectory, defaultConfigFileName); if (shouldWriteDefaultConfig(defaultConfigDest)) { boolean wasOverwritten = defaultConfigDest.exists(); writeDefaultConfig(defaultConfigDest); if (!defaultConfigDest.exists()) CreativeBlocks.Log.warn("Default config failed to be written"); else if (!wasOverwritten) configFiles.add(defaultConfigDest); } } public static void writeDefaultConfig(File defaultConfigDest) { try { if (CreativeBlocks.instance.sourceFile.isDirectory()) { File sourceFile = new File(CreativeBlocks.instance.sourceFile, defaultConfigRelativePath); FileHelper.copyFile(sourceFile, defaultConfigDest, true); } else { InputStream defaultConfigInputStream = JSONConfigHandler.class.getClassLoader().getResourceAsStream(defaultConfigRelativePath); FileHelper.copyFile(defaultConfigInputStream, defaultConfigDest, true); defaultConfigInputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } public static boolean shouldWriteDefaultConfig(File defaultConfigDest) { // update default if it already exists if (defaultConfigDest.exists()) return true; // create default if there are no other .json files else if (configFiles.isEmpty()) return true; // don't reinstate default if it doesn't exist and other .json files do else return false; } public static void load() { for (File configFile : configFiles) { try { FileReader reader = new FileReader(configFile); JSONConfigFormat parsedConfig = gson.fromJson(reader, JSONConfigFormat.class); if (parsedConfig != null) { for (String blockToWhitelist : parsedConfig.blockWhitelist) { CreativeBlocksRegistry.whitelists.add(BlocksSpecifier.fromString(blockToWhitelist)); } for (String blockToBlacklist : parsedConfig.blockBlacklist) { CreativeBlocksRegistry.blacklists.add(BlocksSpecifier.fromString(blockToBlacklist)); } } reader.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } }
package speedyrest.respositories; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import javax.servlet.http.Cookie; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.mendix.core.Core; import com.mendix.core.CoreException; import com.mendix.systemwideinterfaces.core.IContext; import com.mendix.systemwideinterfaces.core.IMendixObject; import speedyrest.entities.SpeedyHeaders; import speedyrest.proxies.ResponseCache; public class CacheRepository { private IContext context; public CacheRepository(IContext context) { this.context = context; } public ResponseCache find(String cacheKey) throws CoreException { List<IMendixObject> objectList = Core.retrieveXPathQuery(context, "//SpeedyREST.CachedObject[Key='" + cacheKey + "']"); return ResponseCache.initialize(context, objectList.get(0)); } public void persist(ResponseCache responseCache) throws CoreException { responseCache.commit(context); } public ResponseCache createResponseCache(String key) { ResponseCache responseCache = new ResponseCache(context); responseCache.setKey(key); return responseCache; } public String getContent(ResponseCache responseCache) { return responseCache.getContent(context); } public void setContent(ResponseCache responseCache, String cacheKey, String content) { responseCache.setContent(context, content); } public SpeedyHeaders getHeaders(ResponseCache responseCache) { return deserializeHeaders(responseCache.getHeaders(context)); } public void addHeader(ResponseCache responseCache, String key, String value) { SpeedyHeaders speedyHeaders = getHeaders(responseCache); speedyHeaders.addHeader(key, value); responseCache.setHeaders(context, serializeHeaders(speedyHeaders)); } public List<Cookie> getCookies(ResponseCache responseCache) { return deserializeCookies(responseCache.getCookies(context)); } public void addCookie(ResponseCache responseCache, Cookie cookie) { List<Cookie> cookies = getCookies(responseCache); cookies.add(cookie); responseCache.setCookies(context, serializeCookies(cookies)); } public List<IMendixObject> getFileParts(ResponseCache responseCache) { List<IMendixObject> fileParts = Core.retrieveByPath(context, responseCache.getMendixObject(), "BinaryContent_CachedObject"); return fileParts; } public void addFilePart(ResponseCache responseCache, byte[] binaryContent) { //TODO: to be implemented. } private SpeedyHeaders deserializeHeaders(String headerString) { Gson gson = new Gson(); return gson.fromJson(headerString, SpeedyHeaders.class); } private String serializeHeaders(SpeedyHeaders speedyHeaders) { Gson gson = new Gson(); return gson.toJson(speedyHeaders, SpeedyHeaders.class); } private List<Cookie> deserializeCookies(String cookieString) { Gson gson = new Gson(); if (cookieString != null) { Type collectionType = new TypeToken<ArrayList<Cookie>>() {}.getType(); return gson.fromJson(cookieString, collectionType); } return new ArrayList<Cookie>(); } private String serializeCookies(List<Cookie> cookies) { if (!cookies.isEmpty()) { Gson gson = new Gson(); Type collectionType = new TypeToken<ArrayList<Cookie>>() {}.getType(); return gson.toJson(cookies, collectionType); } return new String(); } }
package speedyrest.respositories; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Base64; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.servlet.http.Cookie; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import speedyrest.entities.ResponseCache; import speedyrest.entities.SpeedyHeaders; import speedyrest.services.Cache; public class CacheRepository { private Cache cache; public CacheRepository(Cache cache) { this.cache = cache; } public ResponseCache find(String cacheKey) { Map<String, String> cachedMap = cache.getHashMap(cacheKey); ResponseCache cachedResponse = new ResponseCache(cacheKey); System.out.println(cachedMap.size()); if (cachedMap.size() > 0) { SpeedyHeaders speedyHeaders = getHeaders(cachedMap.get("headers")); if (speedyHeaders.getHeader("Content-Type").equals("application/octet-stream")) { cachedResponse.setFileParts(getFileParts(cachedMap)); } if (!speedyHeaders.getHeader("Content-Type").equals("application/octet-stream")) { cachedResponse.setTextualContent(cachedMap.get("content")); } cachedResponse.setCookies(getCookies(cachedMap.get("cookies"))); cachedResponse.setHeaders(speedyHeaders); } return cachedResponse; } public void persist(ResponseCache responseCache) { cache.persistObject(responseCache); } private SpeedyHeaders getHeaders(String headerString) { Gson gson = new Gson(); return gson.fromJson(headerString, SpeedyHeaders.class); } private List<Cookie> getCookies(String cookieString) { Gson gson = new Gson(); if (cookieString != null) { Type collectionType = new TypeToken<ArrayList<Cookie>>() { }.getType(); return gson.fromJson(cookieString, collectionType); } return new ArrayList<Cookie>(); } private Map<String, Map<String, Object>> getFileParts(Map<String, String> cachedMap) { Map<String, Map<String, Object>> fileParts = new HashMap<>(); int filePartCounter = 0; for (Entry<String, String> fileComponent : cachedMap.entrySet()) { Map<String, Object> fileComponents = new HashMap<>(); if (fileComponent.getKey().startsWith("filepartcontent")) { fileComponents.put(fileComponent.getKey(), Base64.getDecoder().decode(fileComponent.getValue())); } if (fileComponent.getKey().startsWith("filepartlength")) { fileComponents.put(fileComponent.getKey(), fileComponent.getValue()); } fileParts.put("filepart" + filePartCounter, fileComponents); filePartCounter ++; } return fileParts; } }
package pl.magosa.microbe; import java.awt.*; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.function.Consumer; import java.util.function.Function; public class PixelMatrix { protected Pixel[][] data; protected int width; protected int height; /** * Creates new matrix with specified dimensions */ public PixelMatrix(final int width, final int height) { data = new Pixel[height][width]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { data[y][x] = new Pixel(); } } this.width = width; this.height = height; } /** * Creates new instance of PixelMatrix from BufferedImage */ public static PixelMatrix factory(final BufferedImage image) { PixelMatrix instance = new PixelMatrix(image.getWidth(), image.getHeight()); for (int y = 0; y < image.getHeight(); y++) { for (int x = 0; x < image.getWidth(); x++) { instance.get(x, y).setRGB(image.getRGB(x, y)); } } return instance; } public Pixel get(final int x, final int y) { return data[y][x]; } public int size() { return width * height; } /** * Transforms matrix into array suitable to be used as input of network. * Specified lambda is executed on each pixel, returned array is appended to array. * * Example usage: * double result[] = matrix.transformToArray((Pixel pixel) -> { * return new Double[] { * transferFunction.normalize(pixel.getRelativeLuminance(), 0.0, 1.0) * }; * }); * * @param function Lambda which analysis each pixel and returns array * @return Array which represents image */ public double[] transformToArray(Function<Pixel, Double[]> function) { ArrayList<Double> vector = new ArrayList<>(); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { Double[] values = function.apply(get(x, y)); for (int i = 0; i < values.length; i++) { vector.add(values[i]); } } } double[] result = new double[vector.size()]; for (int i = 0; i < vector.size(); i++) { result[i] = vector.get(i); } return result; } /** * Downsample image to lower resolution. * * @param targetWidth width of new image * @param targetHeight height of new image * @return New instance of pixelmatrix with downsampled image */ public PixelMatrix downsample(final int targetWidth, final int targetHeight) { PixelMatrix target = new PixelMatrix(targetWidth, targetHeight); final double ratioX = (double)width / (double)targetWidth; final double ratioY = (double)height / (double)targetHeight; for (int targetY = 0; targetY < targetHeight; targetY++) { for (int targetX = 0; targetX < targetWidth; targetX++) { Pixel pixel = target.get(targetX, targetY); int totalPixels = 0; double red = 0.0; double green = 0.0; double blue = 0.0; // Calculate region which needs to be downsamples to one pixel int startX = (int)(targetX * ratioX); int startY = (int)(targetY * ratioY); int stopX = (int)(startX + ratioX); int stopY = (int)(startY + ratioY); // Don't go outside image stopX = Math.min(stopX, width); stopY = Math.min(stopY, height); // Process at least one pixel stopX = Math.max(startX+1, stopX); stopY = Math.max(startY+1, stopY); for (int y = startY; y < stopY; y++) { for (int x = startX; x < stopX; x++) { red += get(x, y).getRed(); green += get(x, y).getGreen(); blue += get(x, y).getBlue(); totalPixels++; } } pixel.setRed(red / (double)totalPixels); pixel.setGreen(green / (double)totalPixels); pixel.setBlue(blue / (double)totalPixels); } } return target; } /** * Checks whether all pixels in specified vertical line are empty. * Lambda should return true when pixel is not empty, and false when it's empty. */ public boolean isVLineEmpty(final int x, Function<Pixel, Boolean> isNotEmpty) { for (int y = 0; y < height; y++) { if (isNotEmpty.apply(get(x, y))) { return false; } } return true; } /** * Checks whether all pixels in specified horizontal line are empty. * Lambda should return true when pixel is not empty, and false when it's empty. */ public boolean isHLineEmpty(final int y, Function<Pixel, Boolean> isNotEmpty) { for (int x = 0; x < width; x++) { if (isNotEmpty.apply(get(x, y))) { return false; } } return true; } /** * Returns rectangle which defines not empty region of image. * Lambda should return true when pixel is not empty, and false when it's empty. */ public Rectangle findBounds(Function<Pixel, Boolean> isNotEmpty) { int y1 = 0; int y2 = 0; int x1 = 0; int x2 = 0; for (int y = 0; y < height; y++) { if (!isHLineEmpty(y, isNotEmpty)) { y1 = y; break; } } for (int y = height-1; y >= 0; y if (!isHLineEmpty(y, isNotEmpty)) { y2 = y; break; } } for (int x = 0; x < width; x++) { if (!isVLineEmpty(x, isNotEmpty)) { x1 = x; break; } } for (int x = width-1; x >= 0; x if (!isVLineEmpty(x, isNotEmpty)) { x2 = x; break; } } return new Rectangle(x1, y1, x2-x1, y2-y1); } /** * Creates new instance of images, and transform all pixels there. * @return */ public BufferedImage transformToImage() { BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { image.setRGB(x, y, get(x, y).getRGB()); } } return image; } }
package net.mechanicalcat.pycode.init; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.EnumDyeColor; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.common.registry.GameRegistry; public class ModCrafting { public static void register() { GameRegistry.addShapedRecipe( new ItemStack(ModBlocks.python_block), "CLC", "LRY", "CYC", 'C', Blocks.COBBLESTONE, 'L', new ItemStack(Items.DYE, 1, EnumDyeColor.BLUE.getDyeDamage()), 'Y', new ItemStack(Items.DYE, 1, EnumDyeColor.YELLOW.getDyeDamage()), 'R', Items.REDSTONE ); GameRegistry.addShapedRecipe( new ItemStack(ModItems.python_wand), " L", " RY", "S ", 'S', Items.STICK, 'L', new ItemStack(Items.DYE, 1, EnumDyeColor.BLUE.getDyeDamage()), 'Y', new ItemStack(Items.DYE, 1, EnumDyeColor.YELLOW.getDyeDamage()), 'R', Items.REDSTONE ); GameRegistry.addShapedRecipe( new ItemStack(ModItems.python_hand), " L ", "WRY", " W ", 'W', Blocks.WOOL, 'L', new ItemStack(Items.DYE, 1, EnumDyeColor.BLUE.getDyeDamage()), 'Y', new ItemStack(Items.DYE, 1, EnumDyeColor.YELLOW.getDyeDamage()), 'R', Items.REDSTONE ); GameRegistry.addShapelessRecipe( new ItemStack(ModItems.python_book), ModItems.python_wand, Items.WRITABLE_BOOK ); } }
package org.lwjgl.system; import org.lwjgl.Version; import java.io.File; import java.io.FileInputStream; import java.security.DigestInputStream; import java.security.MessageDigest; import java.util.Optional; import java.util.regex.Pattern; import static org.lwjgl.system.APIUtil.*; /** * Initializes the LWJGL shared library and handles loading additional shared libraries. * * @see Configuration#LIBRARY_NAME * @see Configuration#LIBRARY_PATH */ public final class Library { /** The LWJGL shared library name. */ public static final String JNI_LIBRARY_NAME = Configuration.LIBRARY_NAME.get(System.getProperty("os.arch").contains("64") ? "lwjgl" : "lwjgl32"); private static final String JAVA_LIBRARY_PATH = "java.library.path"; private static final Pattern PATH_SEPARATOR = Pattern.compile(File.pathSeparator); static { if ( Checks.DEBUG ) { apiLog("Version: " + Version.getVersion()); apiLog("\t OS: " + System.getProperty("os.name") + " v" + System.getProperty("os.version")); apiLog("\tJRE: " + System.getProperty("java.version") + " " + System.getProperty("os.arch")); apiLog( "\tJVM: " + System.getProperty("java.vm.name") + " v" + System.getProperty("java.vm.version") + " by " + System.getProperty("java.vm.vendor") ); } loadSystem(JNI_LIBRARY_NAME); checkHash(); } private Library() {} /** Ensures that the LWJGL shared library has been loaded. */ public static void initialize() { // intentionally empty to trigger static initializer } /** * Loads a shared library using {@link System#load}. * * @param name the library name. If not an absolute path, it must be the plain library name, without an OS specific prefix or file extension (e.g. GL, not * libGL.so) * * @throws UnsatisfiedLinkError if the library could not be loaded */ public static void loadSystem(String name) throws UnsatisfiedLinkError { apiLog("Loading library (system): " + name); if ( new File(name).isAbsolute() ) { System.load(name); apiLog("\tSuccess"); return; } String libName = Platform.get().mapLibraryName(name); // Try org.lwjgl.librarypath first if ( loadSystem(libName, Configuration.LIBRARY_PATH) ) return; boolean debugLoader = Configuration.DEBUG_LOADER.get(false); try { // Failed, attempt to extract from the classpath if ( debugLoader ) DEBUG_STREAM.print("[LWJGL] \tUsing SharedLibraryLoader..."); SharedLibraryLoader.load(name); if ( debugLoader ) DEBUG_STREAM.println("found"); // and try again if ( loadSystem(libName, Configuration.LIBRARY_PATH) ) return; } catch (Exception e) { if ( debugLoader ) { DEBUG_STREAM.println("failed"); e.printStackTrace(DEBUG_STREAM); } } // Then java.library.path String paths = System.getProperty(JAVA_LIBRARY_PATH); if ( paths != null && loadSystem(libName, JAVA_LIBRARY_PATH, paths) ) return; printError(); throw new UnsatisfiedLinkError("Failed to locate library: " + libName); } private static boolean loadSystem(String libName, Configuration<String> property) { String paths = property.get(); return paths != null && loadSystem(libName, property.getProperty(), paths); } private static boolean loadSystem(String libName, String property, String paths) { File libFile = findLibrary(paths, libName).orElse(null); if ( libFile == null ) { apiLog(String.format("\t%s not found in %s=%s", libName, property, paths)); return false; } System.load(libFile.getAbsolutePath()); apiLog(String.format("\tLoaded from %s: %s", property, libFile.getPath())); return true; } /** * Loads a shared library using OS-specific APIs (e.g. {@link org.lwjgl.system.windows.WinBase#LoadLibrary LoadLibrary} or * {@link org.lwjgl.system.linux.DynamicLinkLoader#dlopen dlopen}). * * @param name the library name. OS-specific prefixes and file extensions are optional (e.g. both {@code "GL"} and {@code "libGL.so.1"} are valid on Linux) * * @return the shared library * * @throws UnsatisfiedLinkError if the library could not be loaded */ public static SharedLibrary loadNative(String name) { apiLog("Loading library: " + name); if ( new File(name).isAbsolute() ) { SharedLibrary lib = apiCreateLibrary(name); apiLog("\tSuccess"); return lib; } String libName = Platform.get().mapLibraryName(name); // Try org.lwjgl.librarypath first SharedLibrary lib = loadNative(libName, Configuration.LIBRARY_PATH); if ( lib != null ) return lib; boolean debugLoader = Configuration.DEBUG_LOADER.get(false); try { if ( debugLoader ) DEBUG_STREAM.print("[LWJGL] \tUsing SharedLibraryLoader..."); // Failed, attempt to extract from the classpath SharedLibraryLoader.load(name); if ( debugLoader ) DEBUG_STREAM.println("found"); // and try again return loadNative(libName, Configuration.LIBRARY_PATH); } catch (Exception e) { if ( debugLoader ) { e.printStackTrace(DEBUG_STREAM); DEBUG_STREAM.println("failed"); } } // Then java.library.path String paths = System.getProperty(JAVA_LIBRARY_PATH); if ( paths != null ) { lib = loadNative(libName, JAVA_LIBRARY_PATH, paths); if ( lib != null ) return lib; } // Then the OS paths try { lib = apiCreateLibrary(libName); apiLog("\tLoaded from system paths"); return lib; } catch (UnsatisfiedLinkError e) { apiLog(String.format("\t%s not found in system paths", libName)); } printError(); throw new UnsatisfiedLinkError("Failed to locate library: " + libName); } private static SharedLibrary loadNative(String libName, Configuration<String> property) { String paths = property.get(); if ( paths != null ) { SharedLibrary lib = loadNative(libName, property.getProperty(), paths); if ( lib != null ) return lib; } return null; } private static SharedLibrary loadNative(String libName, String property, String paths) { File libFile = findLibrary(paths, libName).orElse(null); if ( libFile == null ) { apiLog(String.format("\t%s not found in %s=%s", libName, property, paths)); return null; } SharedLibrary lib = apiCreateLibrary(libFile.getPath()); apiLog(String.format("\tLoaded from %s: %s", property, libFile.getPath())); return lib; } /** * Loads a shared library using {@link #loadNative(String)} with the name specified by {@code name}. If {@code name} is not set, * {@link #loadNative(String)} will be called with the names specified by {@code defaultNames}. The first successful will be returned. * * @param name a {@link Configuration} that specifies the library name * @param defaultNames the default library name * * @return the shared library * * @throws UnsatisfiedLinkError if the library could not be loaded */ public static SharedLibrary loadNative(Configuration<String> name, String... defaultNames) { if ( name.get() != null ) return loadNative(name.get()); else if ( defaultNames.length <= 1 ) { if ( defaultNames.length == 0 ) throw new RuntimeException("No default names specified."); return loadNative(defaultNames[0]); } else { SharedLibrary library = null; try { library = Library.loadNative(defaultNames[0]); // try first } catch (Throwable t) { for ( int i = 1; i < defaultNames.length; i++ ) { // try alternatives try { library = Library.loadNative(defaultNames[i]); break; } catch (Throwable ignored) { } } if ( library == null ) throw t; // original error } return library; } } private static Optional<File> findLibrary(String path, String libName) { return PATH_SEPARATOR .splitAsStream(path) .map(it -> new File(it + File.separator + libName)) .filter(File::isFile) .findFirst(); } private static void printError() { DEBUG_STREAM.println( "[LWJGL] Failed to load a library. Possible solutions:\n" + "\ta) Set -Djava.library.path or -Dorg.lwjgl.librarypath to the directory that contains the shared libraries.\n" + "\tb) Add the JAR(s) containing the shared libraries to the classpath." ); if ( !Checks.DEBUG ) { DEBUG_STREAM.println("[LWJGL] Enable debug mode with -Dorg.lwjgl.util.Debug=true for better diagnostics."); if ( !Configuration.DEBUG_LOADER.get(false) ) DEBUG_STREAM.println("[LWJGL] Enable the SharedLibraryLoader debug mode with -Dorg.lwjgl.util.DebugLoader=true for better diagnostics."); } } /** * Compares the shared library hash stored in lwjgl.jar, with the hash of the actual library loaded at runtime. * * <p>This check prints a simple warning when there's a hash mismatch, to help diagnose installation/classpath issues. It is not a security feature.</p> */ private static void checkHash() { String libName = Platform.get().mapLibraryName(JNI_LIBRARY_NAME); String expected = apiGetManifestValue(libName.replace('.', '-')).orElse(null); if ( expected == null ) return; File libFile = null; // Try org.lwjgl.librarypath first String override = Configuration.LIBRARY_PATH.get(); if ( override != null ) libFile = findLibrary(override, libName).orElse(null); // Then java.library.path if ( libFile == null ) libFile = findLibrary(System.getProperty(JAVA_LIBRARY_PATH), libName).orElse(null); // Then working directory if ( libFile == null ) { libFile = new File("./" + libName); if ( !libFile.isFile() ) return; } try { MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); try ( DigestInputStream dis = new DigestInputStream(new FileInputStream(libFile), sha1) ) { byte[] buffer = new byte[8 * 1024]; while ( dis.read(buffer) != -1 ) ; } byte[] digest = sha1.digest(); StringBuilder actual = new StringBuilder(40); for ( int i = 0; i < digest.length; i++ ) { int b = digest[i] & 0xFF; if ( b < 0x10 ) actual.append('0'); actual.append(Integer.toHexString(b)); } if ( !expected.contentEquals(actual) ) DEBUG_STREAM.println("[LWJGL] [WARNING] Mismatch detected between the Java and native LWJGL libraries." + (Checks.DEBUG ? "" : "\n\tLaunch the JVM with -Dorg.lwjgl.util.Debug=true for more information.") ); } catch (Exception e) { e.printStackTrace(); } } }
package org.python.pydev.editor; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.ListResourceBundle; import java.util.Map; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Preferences; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.action.IAction; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.Assert; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.swt.SWT; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.IStorageEditorInput; import org.eclipse.ui.PartInitException; import org.eclipse.ui.editors.text.ILocationProvider; import org.eclipse.ui.editors.text.TextFileDocumentProvider; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants; import org.eclipse.ui.texteditor.DefaultRangeIndicator; import org.eclipse.ui.texteditor.IEditorStatusLine; import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds; import org.eclipse.ui.texteditor.MarkerUtilities; import org.eclipse.ui.texteditor.TextOperationAction; import org.eclipse.ui.views.contentoutline.IContentOutlinePage; import org.python.parser.ParseException; import org.python.parser.SimpleNode; import org.python.parser.Token; import org.python.parser.TokenMgrError; import org.python.pydev.builder.PyDevBuilderPrefPage; import org.python.pydev.core.IPyEdit; import org.python.pydev.core.IPythonNature; import org.python.pydev.editor.actions.PyOpenAction; import org.python.pydev.editor.autoedit.PyAutoIndentStrategy; import org.python.pydev.editor.codecompletion.revisited.PythonPathHelper; import org.python.pydev.editor.codecompletion.shell.AbstractShell; import org.python.pydev.editor.codefolding.CodeFoldingSetter; import org.python.pydev.editor.codefolding.PyEditProjection; import org.python.pydev.editor.model.AbstractNode; import org.python.pydev.editor.model.IModelListener; import org.python.pydev.editor.model.Location; import org.python.pydev.editor.model.ModelMaker; import org.python.pydev.outline.PyOutlinePage; import org.python.pydev.parser.PyParser; import org.python.pydev.plugin.PydevPlugin; import org.python.pydev.plugin.PydevPrefs; import org.python.pydev.plugin.nature.PythonNature; import org.python.pydev.ui.ColorCache; public class PyEdit extends PyEditProjection implements IPyEdit { public static final String PY_EDIT_CONTEXT = "#PyEditContext"; static public String EDITOR_ID = "org.python.pydev.editor.PythonEditor"; static public String ACTION_OPEN = "OpenEditor"; /** color cache */ private ColorCache colorCache; /** lexical parser that continuously reparses the document on a thread */ private PyParser parser; // Listener waits for tab/spaces preferences that affect sourceViewer private Preferences.IPropertyChangeListener prefListener; /** need it to support GUESS_TAB_SUBSTITUTION preference */ private PyAutoIndentStrategy indentStrategy; /** need to hold onto it to support indentPrefix change through preferences */ PyEditConfiguration editConfiguration; /** Python model */ AbstractNode pythonModel; /** * AST that created python model */ SimpleNode ast; /** Hyperlinking listener */ Hyperlink fMouseListener; /** listeners that get notified of model changes */ ArrayList modelListeners; public PyEdit() { super(); modelListeners = new ArrayList(); colorCache = new ColorCache(PydevPlugin.getChainedPrefStore()); editConfiguration = new PyEditConfiguration(colorCache, this); setSourceViewerConfiguration(editConfiguration); indentStrategy = editConfiguration.getPyAutoIndentStrategy(); setRangeIndicator(new DefaultRangeIndicator()); // enables standard // vertical ruler //Added to set the code folding. CodeFoldingSetter codeFoldingSetter = new CodeFoldingSetter(this); this.addModelListener(codeFoldingSetter); this.addPropertyListener(codeFoldingSetter); } /** * Sets the forceTabs preference for auto-indentation. * * <p> * This is the preference that overrides "use spaces" preference when file contains tabs (like mine do). * <p> * If the first indented line starts with a tab, then tabs override spaces. */ private void resetForceTabs() { IDocument doc = getDocumentProvider().getDocument(getEditorInput()); if (doc == null) return; if (!PydevPrefs.getPreferences().getBoolean(PydevPrefs.GUESS_TAB_SUBSTITUTION)) { indentStrategy.getIndentPrefs().setForceTabs(false); return; } int lines = doc.getNumberOfLines(); boolean forceTabs = false; int i = 0; // look for the first line that starts with ' ', or '\t' while (i < lines) { try { IRegion r = doc.getLineInformation(i); String text = doc.get(r.getOffset(), r.getLength()); if (text != null) if (text.startsWith("\t")) { forceTabs = true; break; } else if (text.startsWith(" ")) { forceTabs = false; break; } } catch (BadLocationException e) { PydevPlugin.log(IStatus.ERROR, "Unexpected error forcing tabs", e); break; } i++; } indentStrategy.getIndentPrefs().setForceTabs(forceTabs); editConfiguration.resetIndentPrefixes(); // display a message in the status line if (forceTabs) { IEditorStatusLine statusLine = (IEditorStatusLine) getAdapter(IEditorStatusLine.class); if (statusLine != null) statusLine.setMessage(false, "Pydev: forcing tabs", null); } } /** * Initializes everyone that needs document access * */ public void init(final IEditorSite site, final IEditorInput input) throws PartInitException { super.init(site, input); IDocument document = getDocument(input); // check the document partitioner (sanity check / fix) PyPartitionScanner.checkPartitionScanner(document); checkAndCreateParserIfNeeded(); // Also adds Python nature to the project. // The reason this is done here is because I want to assign python // nature automatically to any project that has active python files. final IPythonNature nature = PythonNature.addNature(input); //we also want to initialize our shells... //we use 2: one for refactoring and one for code completion. new Thread() { public void run() { try { //ok, behaviour change... we just initialize the shell that is not for code completion //when requested... // try { // PythonShell.getServerShell(PythonShell.OTHERS_SHELL); // } catch (RuntimeException e1) { try { AbstractShell.getServerShell(nature, AbstractShell.COMPLETION_SHELL); } catch (RuntimeException e1) { } } catch (Exception e) { } } }.start(); //set the parser for the document parser.setDocument(document); // listen to changes in TAB_WIDTH preference prefListener = new Preferences.IPropertyChangeListener() { public void propertyChange(Preferences.PropertyChangeEvent event) { String property = event.getProperty(); //tab width if (property.equals(PydevPrefs.TAB_WIDTH)) { ISourceViewer sourceViewer = getSourceViewer(); if (sourceViewer == null){ return; } sourceViewer.getTextWidget().setTabs(PydevPlugin.getDefault().getPluginPreferences().getInt(PydevPrefs.TAB_WIDTH)); //auto adjust for file tabs } else if (property.equals(PydevPrefs.GUESS_TAB_SUBSTITUTION)) { resetForceTabs(); //hyperlink }else if (property.equals(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_HYPERLINK_COLOR)) { colorCache.reloadNamedColor(property); if (fMouseListener != null){ fMouseListener.updateColor(getSourceViewer()); } //colors and styles } else if (property.equals(PydevPrefs.CODE_COLOR) || property.equals(PydevPrefs.DECORATOR_COLOR) || property.equals(PydevPrefs.NUMBER_COLOR) || property.equals(PydevPrefs.KEYWORD_COLOR) || property.equals(PydevPrefs.COMMENT_COLOR) || property.equals(PydevPrefs.STRING_COLOR) || property.equals(PydevPrefs.DEFAULT_BACKQUOTES_COLOR) || property.endsWith("_STYLE") ) { colorCache.reloadNamedColor(property); //all reference this cache editConfiguration.updateSyntaxColorAndStyle(); //the style needs no reloading getSourceViewer().invalidateTextPresentation(); } else if(property.equals(PyDevBuilderPrefPage.USE_PYDEV_ANALYSIS_ONLY_ON_DOC_SAVE) || property.equals(PyDevBuilderPrefPage.PYDEV_ELAPSE_BEFORE_ANALYSIS)){ parser.reset(PyDevBuilderPrefPage.useAnalysisOnlyOnDocSave(), PyDevBuilderPrefPage.getElapseMillisBeforeAnalysis()); } } }; resetForceTabs(); PydevPrefs.getPreferences().addPropertyChangeListener(prefListener); } /** * Checks if the parser exists. If it doesn't, creates it. */ private void checkAndCreateParserIfNeeded() { if(parser == null){ parser = new PyParser(this); parser.addParseListener(this); } } @Override protected void doSetInput(IEditorInput input) throws CoreException { super.doSetInput(input); IDocument document = getDocument(input); checkAndCreateParserIfNeeded(); if(document != null){ parser.setDocument(document); PyPartitionScanner.checkPartitionScanner(document); } } /** * @param input * @return */ private IDocument getDocument(final IEditorInput input) { return getDocumentProvider().getDocument(input); } /** * @param input * @return */ private IDocument getDocument() { return getDocumentProvider().getDocument(getEditorInput()); } /** * @see org.eclipse.ui.texteditor.AbstractTextEditor#performSave(boolean, org.eclipse.core.runtime.IProgressMonitor) */ protected void performSave(boolean overwrite, IProgressMonitor progressMonitor) { fixEncoding(getEditorInput(), getDocument()); super.performSave(overwrite, progressMonitor); parser.notifySaved(); } /** * Forces the encoding to the one specified in the file * * @param input * @param document */ private void fixEncoding(final IEditorInput input, IDocument document) { if (input instanceof FileEditorInput) { final IFile file = (IFile) ((FileEditorInput) input).getAdapter(IFile.class); final String encoding = PythonPathHelper.getPythonFileEncoding(document); if (encoding != null) { try { if (encoding.equals(file.getCharset()) == false) { new Job("Change encoding") { protected IStatus run(IProgressMonitor monitor) { try { file.setCharset(encoding, monitor); ((TextFileDocumentProvider) getDocumentProvider()).setEncoding(input, encoding); //refresh it... file.refreshLocal(IResource.DEPTH_INFINITE, null); } catch (CoreException e) { PydevPlugin.log(e); } return Status.OK_STATUS; } }.schedule(); } } catch (CoreException e) { PydevPlugin.log(e); } } } } public IProject getProject() { IEditorInput editorInput = this.getEditorInput(); if (editorInput instanceof FileEditorInput) { IFile file = (IFile) ((FileEditorInput) editorInput).getAdapter(IFile.class); return file.getProject(); } return null; } /** * @return * */ public File getEditorFile() { File f = null; IEditorInput editorInput = this.getEditorInput(); if (editorInput instanceof FileEditorInput) { IFile file = (IFile) ((FileEditorInput) editorInput).getAdapter(IFile.class); IPath path = file.getLocation().makeAbsolute(); f = path.toFile(); } return f; } // cleanup public void dispose() { PydevPrefs.getPreferences().removePropertyChangeListener(prefListener); parser.dispose(); colorCache.dispose(); super.dispose(); } private static final String TEMPLATE_PROPOSALS_ID = "org.python.pydev.editors.PyEdit.TemplateProposals"; private static final String CONTENTASSIST_PROPOSAL_ID = "org.python.pydev.editors.PyEdit.ContentAssistProposal"; private static final String CORRECTIONASSIST_PROPOSAL_ID = "org.python.pydev.editors.PyEdit.CorrectionAssist"; private static final String SIMPLEASSIST_PROPOSAL_ID = "org.python.pydev.editors.PyEdit.SimpleAssist"; public static final int CORRECTIONASSIST_PROPOSALS = 999777; public static final int SIMPLEASSIST_PROPOSALS = 999778; private static class MyResources extends ListResourceBundle { public Object[][] getContents() { return contents; } static final Object[][] contents = { { "CorrectionAssist", "CorrectionAssist" }, { "ContentAssistProposal", "ContentAssistProposal" }, { "TemplateProposals", "TemplateProposals" }, }; } /* * (non-Javadoc) * * @see org.eclipse.ui.texteditor.AbstractTextEditor#createActions() */ protected void createActions() { super.createActions(); MyResources resources = new MyResources(); //quick fix in editor. IAction action = new TextOperationAction(resources, "CorrectionAssist", this, CORRECTIONASSIST_PROPOSALS); //$NON-NLS-1$ action.setActionDefinitionId(CORRECTIONASSIST_PROPOSAL_ID); setAction(CORRECTIONASSIST_PROPOSAL_ID, action); //$NON-NLS-1$ markAsStateDependentAction(CORRECTIONASSIST_PROPOSAL_ID, true); //$NON-NLS-1$ setActionActivationCode(CORRECTIONASSIST_PROPOSAL_ID, '1', -1, SWT.CTRL); //simple assistant for extending later action = new TextOperationAction(resources, "SimpleAssist", this, SIMPLEASSIST_PROPOSALS); //$NON-NLS-1$ action.setActionDefinitionId(SIMPLEASSIST_PROPOSAL_ID); setAction(SIMPLEASSIST_PROPOSAL_ID, action); //$NON-NLS-1$ // markAsStateDependentAction(SIMPLEASSIST_PROPOSAL_ID, true); //$NON-NLS-1$ // setActionActivationCode(SIMPLEASSIST_PROPOSAL_ID, 'c', -1, SWT.NONE); // This action will fire a CONTENTASSIST_PROPOSALS operation // when executed action = new TextOperationAction(resources, "ContentAssistProposal", this, SourceViewer.CONTENTASSIST_PROPOSALS); action.setActionDefinitionId(CONTENTASSIST_PROPOSAL_ID); // Tell the editor about this new action setAction(CONTENTASSIST_PROPOSAL_ID, action); // Tell the editor to execute this action // when Ctrl+Spacebar is pressed setActionActivationCode(CONTENTASSIST_PROPOSAL_ID, ' ', -1, SWT.CTRL); //template proposals action = new TextOperationAction(resources, "TemplateProposals", this, ISourceViewer.CONTENTASSIST_PROPOSALS); action.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); setAction(TEMPLATE_PROPOSALS_ID, action); markAsStateDependentAction(TEMPLATE_PROPOSALS_ID, true); //open action IAction openAction = new PyOpenAction(); setAction(ACTION_OPEN, openAction); enableBrowserLikeLinks(); } protected void initializeKeyBindingScopes() { setKeyBindingScopes(new String[] { "org.python.pydev.ui.editor.scope" }); //$NON-NLS-1$ } public PyParser getParser() { return parser; } public AbstractNode getPythonModel() { return pythonModel; } /** * @return an outline view */ public Object getAdapter(Class adapter) { if (IContentOutlinePage.class.equals(adapter)) return new PyOutlinePage(this); else return super.getAdapter(adapter); } /** * implementation copied from org.eclipse.ui.externaltools.internal.ant.editor.PlantyEditor#setSelection */ public void setSelection(int offset, int length) { ISourceViewer sourceViewer = getSourceViewer(); sourceViewer.setSelectedRange(offset, length); sourceViewer.revealRange(offset, length); } /** * Selects & reveals the model node */ public void revealModelNode(AbstractNode node) { if (node == null){ return; // nothing to see here } Location start = node.getStart(); Location end = node.getEnd(); IDocument document = getDocumentProvider().getDocument(getEditorInput()); int offset, length; try { offset = start.toOffset(document); length = end.toOffset(document) - offset; } catch (BadLocationException e) { PydevPlugin.log(IStatus.WARNING, "error trying to revealModelItem" + node.toString(), e); return; } setSelection(offset, length); } /** * this event comes when document was parsed without errors * * Removes all the error markers */ public void parserChanged(SimpleNode root, IAdaptable file, IDocument doc) { // Remove all the error markers IEditorInput input = getEditorInput(); IPath filePath = null; if(file != null){ IResource fileAdapter = (IResource) file.getAdapter(IResource.class); if(fileAdapter != null){ filePath = fileAdapter.getLocation(); }else{ //all this is just to get the file path if (input instanceof IFileEditorInput) { IFile file1 = ((IFileEditorInput) input).getFile(); filePath = file1.getLocation(); } else if (input instanceof IStorageEditorInput) try { filePath = ((IStorageEditorInput) input).getStorage().getFullPath(); filePath = filePath.makeAbsolute(); } catch (CoreException e2) { PydevPlugin.log(IStatus.ERROR, "unexpected error getting path", e2); } else if (input instanceof ILocationProvider) { filePath = ((ILocationProvider) input).getPath(input); filePath = filePath.makeAbsolute(); } else { PydevPlugin.log(IStatus.ERROR, "unexpected type of editor input " + input.getClass().toString(), null); } } } //delete the problem markers try { IResource res = (IResource) input.getAdapter(IResource.class); if (res != null){ res.deleteMarkers(IMarker.PROBLEM, false, 1); } } catch (CoreException e) { // What bad can come from removing markers? Ignore this exception PydevPlugin.log(IStatus.WARNING, "Unexpected error removing markers", e); } int lastLine = doc.getNumberOfLines(); try { doc.getLineInformation(lastLine - 1); ast = root; pythonModel = ModelMaker.createModel(root, doc, filePath); fireModelChanged(pythonModel, ast); } catch (BadLocationException e1) { PydevPlugin.log(IStatus.WARNING, "Unexpected error getting document length. No model!", e1); } } /** * this event comes when parse ended in an error * * generates an error marker on the document */ public void parserError(Throwable error, IAdaptable original, IDocument doc) { try { if(original == null){ return; } IResource fileAdapter = (IResource) original.getAdapter(IResource.class); if(fileAdapter == null){ return; } fileAdapter.deleteMarkers(IMarker.PROBLEM, false, 1); int errorStart; int errorEnd; int errorLine; String message; if (error instanceof ParseException) { ParseException.verboseExceptions = true; ParseException parseErr = (ParseException) error; // Figure out where the error is in the document, and create a // marker for it Token errorToken = parseErr.currentToken.next != null ? parseErr.currentToken.next : parseErr.currentToken; IRegion startLine = doc.getLineInformation(errorToken.beginLine - 1); IRegion endLine; if (errorToken.endLine == 0) endLine = startLine; else endLine = doc.getLineInformation(errorToken.endLine - 1); errorStart = startLine.getOffset() + errorToken.beginColumn - 1; errorEnd = endLine.getOffset() + errorToken.endColumn; message = parseErr.getMessage(); } else { TokenMgrError tokenErr = (TokenMgrError) error; IRegion startLine = doc.getLineInformation(tokenErr.errorLine - 1); errorStart = startLine.getOffset(); errorEnd = startLine.getOffset() + tokenErr.errorColumn; message = tokenErr.getMessage(); } errorLine = doc.getLineOfOffset(errorStart); // map.put(IMarker.LOCATION, "Whassup?"); this is the location field // in task manager if (message != null) { // prettyprint message = message.replaceAll("\\r\\n", " "); message = message.replaceAll("\\r", " "); message = message.replaceAll("\\n", " "); } Map<String, Object> map = new HashMap<String, Object>(); map.put(IMarker.MESSAGE, message); map.put(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_ERROR)); map.put(IMarker.LINE_NUMBER, new Integer(errorLine)); map.put(IMarker.CHAR_START, new Integer(errorStart)); map.put(IMarker.CHAR_END, new Integer(errorEnd)); map.put(IMarker.TRANSIENT, Boolean.valueOf(true)); MarkerUtilities.createMarker(fileAdapter, map, IMarker.PROBLEM); } catch (CoreException e1) { // Whatever, could not create a marker. Swallow this one e1.printStackTrace(); } catch (BadLocationException e2) { // Whatever, could not create a marker. Swallow this one e2.printStackTrace(); } } public void enableBrowserLikeLinks() { if (fMouseListener == null) { fMouseListener = new Hyperlink(getSourceViewer(), this, colorCache); fMouseListener.install(); } } /** * Disables browser like links. */ public void disableBrowserLikeLinks() { if (fMouseListener != null) { fMouseListener.uninstall(); fMouseListener = null; } } /** stock listener implementation */ public void addModelListener(IModelListener listener) { Assert.isNotNull(listener); if (!modelListeners.contains(listener)){ modelListeners.add(listener); } } /** stock listener implementation */ public void removeModelListener(IModelListener listener) { Assert.isNotNull(listener); modelListeners.remove(listener); } /** * stock listener implementation event is fired whenever we get a new root * * @param root2 */ protected void fireModelChanged(AbstractNode root, SimpleNode root2) { Iterator e = modelListeners.iterator(); while (e.hasNext()) { IModelListener l = (IModelListener) e.next(); l.modelChanged(root, root2); } } /** * @return * */ public IPythonNature getPythonNature() { IProject project = getProject(); return PythonNature.getPythonNature(project); } protected void initializeEditor() { super.initializeEditor(); IPreferenceStore prefStore = PydevPlugin.getChainedPrefStore(); this.setPreferenceStore(prefStore); setEditorContextMenuId(PY_EDIT_CONTEXT); } /** * @return */ public SimpleNode getAST() { return ast; } }
package org.xdi.model; import java.io.Serializable; import java.util.Arrays; import javax.faces.application.FacesMessage; import javax.faces.application.FacesMessage.Severity; import javax.faces.component.UIComponent; import javax.faces.component.UIInput; import javax.faces.context.FacesContext; import javax.persistence.Transient; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import org.gluu.site.ldap.persistence.annotation.LdapAttribute; import org.gluu.site.ldap.persistence.annotation.LdapEntry; import org.gluu.site.ldap.persistence.annotation.LdapJsonObject; import org.gluu.site.ldap.persistence.annotation.LdapObjectClass; import org.xdi.ldap.model.Entry; import org.xdi.ldap.model.GluuStatus; /** * Attribute Metadata * * @author Yuriy Movchan * @author Javier Rojas Blum * @version February 9, 2015 */ @LdapEntry(sortBy = {"displayName"}) @LdapObjectClass(values = {"top", "gluuAttribute"}) public class GluuAttribute extends Entry implements Serializable { private static final long serialVersionUID = 4817004894646725606L; private transient boolean selected; @LdapAttribute(ignoreDuringUpdate = true) private String inum; @LdapAttribute(name = "oxAttributeType") private String type; @LdapAttribute private String lifetime; @LdapAttribute(name = "oxSourceAttribute") private String sourceAttribute; @LdapAttribute private String salt; @LdapAttribute(name = "oxNameIdType") private String nameIdType; @NotNull @Pattern(regexp = "^[a-zA-Z]+$", message = "Name should contain only alphabet letters") @Size(min = 1, max = 30, message = "Length of the Name should be between 1 and 30") @LdapAttribute(name = "gluuAttributeName") private String name; @NotNull @Size(min = 0, max = 60, message = "Length of the Display Name should not exceed 60") @LdapAttribute private String displayName; @NotNull @Size(min = 0, max = 4000, message = "Length of the Description should not exceed 4000") @LdapAttribute private String description; @LdapAttribute(name = "gluuAttributeOrigin") private String origin; @NotNull @LdapAttribute(name = "gluuAttributeType") private GluuAttributeDataType dataType; @NotNull @LdapAttribute(name = "gluuAttributeEditType") private GluuUserRole[] editType; @NotNull @LdapAttribute(name = "gluuAttributeViewType") private GluuUserRole[] viewType; @LdapAttribute(name = "gluuAttributeUsageType") private GluuAttributeUsageType[] usageType; @LdapAttribute(name = "oxAuthClaimName") private String oxAuthClaimName; @LdapAttribute(name = "seeAlso") private String seeAlso; @LdapAttribute(name = "gluuStatus") private GluuStatus status; @LdapAttribute(name = "gluuSAML1URI") private String saml1Uri; @LdapAttribute(name = "gluuSAML2URI") private String saml2Uri; @LdapAttribute(ignoreDuringUpdate = true) private String urn; @LdapAttribute(name = "oxSCIMCustomAttribute") private ScimCustomAtribute oxSCIMCustomAttribute; @LdapAttribute(name = "oxMultivaluedAttribute") private OxMultivalued oxMultivaluedAttribute; @Transient private boolean custom; @Transient private boolean requred; @LdapAttribute(name = "gluuRegExp") private String regExp; @LdapJsonObject @LdapAttribute(name = "oxValidation") private AttributeValidation attributeValidation; @LdapAttribute(name = "gluuTooltip") private String gluuTooltip; public boolean isSelected() { return selected; } public void setSelected(boolean selected) { this.selected = selected; } public String getInum() { return inum; } public void setInum(String inum) { this.inum = inum; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getLifetime() { return lifetime; } public void setLifetime(String lifetime) { this.lifetime = lifetime; } public String getSourceAttribute() { return sourceAttribute; } public void setSourceAttribute(String sourceAttribute) { this.sourceAttribute = sourceAttribute; } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } public String getNameIdType() { return nameIdType; } public void setNameIdType(String nameIdType) { this.nameIdType = nameIdType; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getOrigin() { return origin; } public void setOrigin(String origin) { this.origin = origin; } public GluuAttributeDataType getDataType() { return dataType; } public void setDataType(GluuAttributeDataType dataType) { this.dataType = dataType; } public GluuUserRole[] getEditType() { return editType; } public void setEditType(GluuUserRole[] editType) { this.editType = editType; } public GluuUserRole[] getViewType() { return viewType; } public void setViewType(GluuUserRole[] viewType) { this.viewType = viewType; } public GluuAttributeUsageType[] getUsageType() { return usageType; } public void setUsageType(GluuAttributeUsageType[] usageType) { this.usageType = usageType; } public String getOxAuthClaimName() { return oxAuthClaimName; } public void setOxAuthClaimName(String oxAuthClaimName) { this.oxAuthClaimName = oxAuthClaimName; } public String getSeeAlso() { return seeAlso; } public void setSeeAlso(String seeAlso) { this.seeAlso = seeAlso; } public GluuStatus getStatus() { return status; } public void setStatus(GluuStatus status) { this.status = status; } public String getSaml1Uri() { return saml1Uri; } public void setSaml1Uri(String saml1Uri) { this.saml1Uri = saml1Uri; } public String getSaml2Uri() { return saml2Uri; } public void setSaml2Uri(String saml2Uri) { this.saml2Uri = saml2Uri; } public String getUrn() { return urn; } public void setUrn(String urn) { this.urn = urn; } public ScimCustomAtribute getOxSCIMCustomAttribute() { return oxSCIMCustomAttribute; } public void setOxSCIMCustomAttribute(ScimCustomAtribute oxSCIMCustomAttribute) { this.oxSCIMCustomAttribute = oxSCIMCustomAttribute; } public OxMultivalued getOxMultivaluedAttribute() { return oxMultivaluedAttribute; } public void setOxMultivaluedAttribute(OxMultivalued oxMultivaluedAttribute) { this.oxMultivaluedAttribute = oxMultivaluedAttribute; } public boolean isCustom() { return custom; } public void setCustom(boolean custom) { this.custom = custom; } public boolean isRequred() { return requred; } public void setRequred(boolean requred) { this.requred = requred; } public String getRegExp() { return regExp; } public void setRegExp(String regExp) { this.regExp = regExp; } public String getGluuTooltip() { return gluuTooltip; } public void setGluuTooltip(String gluuTooltip) { this.gluuTooltip = gluuTooltip; } public boolean allowEditBy(GluuUserRole role) { return GluuUserRole.containsRole(editType, role); } public boolean allowViewBy(GluuUserRole role) { return GluuUserRole.containsRole(viewType, role); } public boolean isAdminCanAccess() { return isAdminCanView() | isAdminCanEdit(); } public boolean isAdminCanView() { return allowViewBy(GluuUserRole.ADMIN); } public boolean isAdminCanEdit() { return allowEditBy(GluuUserRole.ADMIN); } public boolean isUserCanAccess() { return isUserCanView() | isUserCanEdit(); } public boolean isUserCanView() { return allowViewBy(GluuUserRole.USER); } public boolean isWhitePagesCanView() { return allowViewBy(GluuUserRole.WHITEPAGES); } public boolean isUserCanEdit() { return allowEditBy(GluuUserRole.USER); } public AttributeValidation getAttributeValidation() { return attributeValidation; } public void setAttributeValidation(AttributeValidation attributeValidation) { this.attributeValidation = attributeValidation; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (custom ? 1231 : 1237); result = prime * result + ((dataType == null) ? 0 : dataType.hashCode()); result = prime * result + ((description == null) ? 0 : description.hashCode()); result = prime * result + ((displayName == null) ? 0 : displayName.hashCode()); result = prime * result + Arrays.hashCode(editType); result = prime * result + ((gluuTooltip == null) ? 0 : gluuTooltip.hashCode()); result = prime * result + ((inum == null) ? 0 : inum.hashCode()); result = prime * result + ((lifetime == null) ? 0 : lifetime.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((nameIdType == null) ? 0 : nameIdType.hashCode()); result = prime * result + ((origin == null) ? 0 : origin.hashCode()); result = prime * result + ((oxAuthClaimName == null) ? 0 : oxAuthClaimName.hashCode()); result = prime * result + ((oxMultivaluedAttribute == null) ? 0 : oxMultivaluedAttribute.hashCode()); result = prime * result + ((oxSCIMCustomAttribute == null) ? 0 : oxSCIMCustomAttribute .hashCode()); result = prime * result + ((regExp == null) ? 0 : regExp.hashCode()); result = prime * result + (requred ? 1231 : 1237); result = prime * result + ((salt == null) ? 0 : salt.hashCode()); result = prime * result + ((saml1Uri == null) ? 0 : saml1Uri.hashCode()); result = prime * result + ((saml2Uri == null) ? 0 : saml2Uri.hashCode()); result = prime * result + ((seeAlso == null) ? 0 : seeAlso.hashCode()); result = prime * result + ((sourceAttribute == null) ? 0 : sourceAttribute.hashCode()); result = prime * result + ((status == null) ? 0 : status.hashCode()); result = prime * result + ((type == null) ? 0 : type.hashCode()); result = prime * result + ((urn == null) ? 0 : urn.hashCode()); result = prime * result + Arrays.hashCode(usageType); result = prime * result + Arrays.hashCode(viewType); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj){ if (!(obj instanceof GluuAttribute)){ return false; } GluuAttribute other = (GluuAttribute) obj; if (inum == null) { if (other.inum != null) return false; } else if (!inum.equals(other.inum)) return false; if (custom != other.custom) return false; if (dataType != other.dataType) return false; if (description == null) { if (other.description != null) return false; } else if (!description.equals(other.description)) return false; return true; } public void validateAttribute(FacesContext context, UIComponent comp, Object value) { Integer minvalue = this.attributeValidation != null ? this.attributeValidation.getMinLength() : null; Integer maxValue = this.attributeValidation != null ? this.attributeValidation.getMaxLength() : null; String regexpValue = this.attributeValidation != null ? this.attributeValidation.getRegexp() : null; String attribute = (String) value; //Minimum length validation if ((minvalue != null) ) { int min = this.attributeValidation.getMinLength(); if ((attribute != null) && (attribute.length() < min)) { ((UIInput) comp).setValid(false); FacesMessage message = new FacesMessage(this.displayName + " should be at least " + min + " symbols. "); message.setSeverity(FacesMessage.SEVERITY_ERROR); context.addMessage(comp.getClientId(context), message); } } //Maximum Length validation if ((maxValue != null)) { int max = this.attributeValidation.getMaxLength(); if ((attribute != null) && (attribute.length() > max)) { ((UIInput) comp).setValid(false); FacesMessage message = new FacesMessage(this.displayName + " should not exceed " + max + " symbols. "); message.setSeverity(FacesMessage.SEVERITY_ERROR); context.addMessage(comp.getClientId(context), message); } } //Regex Pattern Validation if((regexpValue != null) && !(regexpValue.trim().equals(""))){ java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(regexpValue); if((attribute != null) && !(attribute.trim().equals(""))){ java.util.regex.Matcher matcher = pattern.matcher(attribute); boolean flag = matcher.matches(); if(!flag){ ((UIInput) comp).setValid(false); FacesMessage message = new FacesMessage(this.displayName + " Format is invalid. "); message.setSeverity(FacesMessage.SEVERITY_ERROR); context.addMessage(comp.getClientId(context), message); } } } } }
package org.xcolab.view.pages.proposals.utils.edit; import org.apache.commons.lang3.StringUtils; import org.xcolab.client.contest.pojo.templates.PlanSectionDefinition; import org.xcolab.client.proposals.enums.ProposalAttributeKeys; import org.xcolab.client.proposals.exceptions.ProposalNotFoundException; import org.xcolab.client.proposals.pojo.Proposal; import org.xcolab.client.proposals.pojo.phases.Proposal2Phase; import org.xcolab.entity.utils.LinkUtils; import org.xcolab.view.util.entity.analytics.AnalyticsUtil; import org.xcolab.util.enums.proposal.PlanSectionTypeKeys; import org.xcolab.util.html.HtmlUtil; import org.xcolab.view.pages.proposals.requests.UpdateProposalDetailsBean; import org.xcolab.view.pages.proposals.utils.context.ProposalsContext; import org.xcolab.view.pages.proposals.utils.context.ProposalsContextImpl; import org.xcolab.view.pages.proposals.utils.context.ProposalsContextUtil; import javax.servlet.http.HttpServletRequest; public class ProposalUpdateHelper { public final static String PROPOSAL_ANALYTICS_KEY = "CONTEST_ENTRY_UPDATE"; public final static String PROPOSAL_ANALYTICS_CATEGORY = "User"; public final static String PROPOSAL_ANALYTICS_ACTION = "Contest entry update"; public final static String PROPOSAL_ANALYTICS_LABEL = ""; private final UpdateProposalDetailsBean updateProposalSectionsBean; private final HttpServletRequest request; private final Proposal proposalWrapper; private final Proposal2Phase p2p; private final long memberId; private final ProposalsContext proposalsContext = new ProposalsContextImpl(); public ProposalUpdateHelper(UpdateProposalDetailsBean updateProposalSectionsBean, HttpServletRequest request, Proposal proposalWrapper, Proposal2Phase p2p, long memberId) { this.updateProposalSectionsBean = updateProposalSectionsBean; this.request = request; this.proposalWrapper = proposalWrapper; this.p2p = p2p; this.memberId = memberId; } public void updateProposal() { boolean filledAll = updateBasicFields(); boolean updateProposalReferences = false; boolean evictCache = false; for (PlanSectionDefinition section : proposalWrapper.getSections()) { String newSectionValue = updateProposalSectionsBean.getSectionsContent().get(section.getSectionDefinitionId()); switch (section.getType()) { case TEXT: case PROPOSAL_LIST_TEXT_REFERENCE: case DROPDOWN_MENU: if (newSectionValue != null && !newSectionValue.trim().equals(section.getContent())) { ProposalsContextUtil.getClients(request).getProposalAttributeClient() .setProposalAttribute(memberId, proposalWrapper.getProposalId(), ProposalAttributeKeys.SECTION, section.getSectionDefinitionId(), HtmlUtil.cleanSome(newSectionValue, LinkUtils.getBaseUri(request))); evictCache = true; if (section.getType() == PlanSectionTypeKeys.PROPOSAL_LIST_TEXT_REFERENCE) { updateProposalReferences = true; } } else { filledAll = false; } break; case CHECKBOX_OPTION: if (newSectionValue != null && !newSectionValue.trim().equals(section.getContent())) { String optionValues = newSectionValue.replace(",",";"); ProposalsContextUtil.getClients(request).getProposalAttributeClient() .setProposalAttribute(memberId, proposalWrapper.getProposalId(), ProposalAttributeKeys.SECTION, section.getSectionDefinitionId(), optionValues); if (section.getType() == PlanSectionTypeKeys.PROPOSAL_LIST_TEXT_REFERENCE) { updateProposalReferences = true; } evictCache = true; } else { filledAll = false; } break; case ONTOLOGY_REFERENCE: if (StringUtils.isNumeric(newSectionValue)) { long newNumericVal = Long.parseLong(newSectionValue); if (newNumericVal != section.getNumericValue()) { ProposalsContextUtil.getClients(request).getProposalAttributeClient().setProposalAttribute( memberId, proposalWrapper.getProposalId(), ProposalAttributeKeys.SECTION, section.getSectionDefinitionId(), newNumericVal); } } else { filledAll = false; } break; case PROPOSAL_REFERENCE: if (StringUtils.isNumeric(newSectionValue) && StringUtils.isNotBlank(newSectionValue)) { final long newNumericValue = Long.parseLong(newSectionValue); if (section.getNumericValue() != newNumericValue) { ProposalsContextUtil.getClients(request).getProposalAttributeClient() .setProposalAttribute(memberId, proposalWrapper.getProposalId(), ProposalAttributeKeys.SECTION, section.getSectionDefinitionId(), newNumericValue); updateProposalReferences = true; } } else if (StringUtils.isBlank(newSectionValue)) { ProposalsContextUtil.getClients(request).getProposalAttributeClient() .setProposalAttribute(memberId, proposalWrapper.getProposalId(), ProposalAttributeKeys.SECTION, section.getSectionDefinitionId(), 0L); } break; case PROPOSAL_LIST_REFERENCE: StringBuilder cleanedReferences = new StringBuilder(); if (StringUtils.isNotBlank(newSectionValue)) { String[] referencedProposals = newSectionValue.split(","); for (String referencedProposal : referencedProposals) { if (StringUtils.isNotBlank(referencedProposal) && StringUtils .isNumeric(referencedProposal)) { cleanedReferences.append(referencedProposal).append(","); } } } if (!section.getStringValue().equals(cleanedReferences.toString())) { ProposalsContextUtil.getClients(request).getProposalAttributeClient() .setProposalAttribute(memberId, proposalWrapper.getProposalId(), ProposalAttributeKeys.SECTION, section.getSectionDefinitionId(), cleanedReferences.toString()); updateProposalReferences = true; } break; default: } } if (p2p != null && p2p.getVersionTo() != -1) { // we are in a completed phase - need to adjust the end version try { final Proposal updatedProposal = ProposalsContextUtil.getClients(request).getProposalClient().getProposal(proposalWrapper.getProposalId()); p2p.setVersionTo(updatedProposal.getCurrentVersion()); proposalsContext.getClients(request).getProposalPhaseClient().updateProposal2Phase(p2p); } catch (ProposalNotFoundException ignored) { } } if (updateProposalReferences) { ProposalsContextUtil.getClients(request).getProposalClient().populateTableWithProposal(proposalWrapper.getWrapped().getProposalId()); } if(evictCache){ ProposalsContextUtil.getClients(request).getProposalAttributeClient().invalidateProposalAttibuteCache(proposalWrapper); ProposalsContextUtil.getClients(request).getProposalClient().invalidateProposalCache(proposalWrapper.getProposalId()); if(p2p!=null) { ProposalsContextUtil.getClients(request).getProposalPhaseClient() .invalidateProposal2PhaseCache(proposalWrapper.getProposalId(), p2p .getContestPhaseId()); } } doAnalytics(request, filledAll); } private boolean updateBasicFields() { boolean filledAll = true; if (!StringUtils.equals(updateProposalSectionsBean.getName(), proposalWrapper.getName())) { ProposalsContextUtil.getClients(request).getProposalAttributeClient() .setProposalAttribute(memberId, proposalWrapper.getProposalId(), ProposalAttributeKeys.NAME, 0L, HtmlUtil.cleanMost(updateProposalSectionsBean.getName())); } else { filledAll = false; } if (!StringUtils.equals(updateProposalSectionsBean.getPitch(), proposalWrapper.getPitch())) { ProposalsContextUtil.getClients(request).getProposalAttributeClient() .setProposalAttribute(memberId, proposalWrapper.getProposalId(), ProposalAttributeKeys.PITCH, 0L, HtmlUtil.cleanSome(updateProposalSectionsBean.getPitch(), LinkUtils.getBaseUri(request))); } else { filledAll = false; } if (!StringUtils.equals(updateProposalSectionsBean.getDescription(), proposalWrapper.getDescription())) { ProposalsContextUtil.getClients(request).getProposalAttributeClient() .setProposalAttribute(memberId, proposalWrapper.getProposalId(), ProposalAttributeKeys.DESCRIPTION, 0L, HtmlUtil.cleanSome(updateProposalSectionsBean.getDescription(), LinkUtils.getBaseUri(request))); } else { filledAll = false; } if (!StringUtils.equals(updateProposalSectionsBean.getTeam(), proposalWrapper.getTeam())) { ProposalsContextUtil.getClients(request).getProposalAttributeClient() .setProposalAttribute(memberId, proposalWrapper.getProposalId(), ProposalAttributeKeys.TEAM, 0L, HtmlUtil.cleanMost(updateProposalSectionsBean.getTeam())); } else { filledAll = false; } if (updateProposalSectionsBean.getImageId() > 0 && updateProposalSectionsBean.getImageId() != proposalWrapper.getImageId()) { ProposalsContextUtil.getClients(request).getProposalAttributeClient() .setProposalAttribute(memberId, proposalWrapper.getProposalId(), ProposalAttributeKeys.IMAGE_ID, 0L,updateProposalSectionsBean.getImageId()); } else { filledAll = false; } return filledAll; } private void doAnalytics(HttpServletRequest request, boolean filledAll) { int analyticsValue; if (filledAll) { analyticsValue = 3; } else { analyticsValue = 2; } AnalyticsUtil.publishEvent(request, memberId, PROPOSAL_ANALYTICS_KEY + analyticsValue, PROPOSAL_ANALYTICS_CATEGORY, PROPOSAL_ANALYTICS_ACTION, PROPOSAL_ANALYTICS_LABEL, analyticsValue); } }
package edu.cornell.mannlib.vitro.webapp.rdfservice.impl.jena.sdb; import java.io.ByteArrayInputStream; import java.sql.Connection; import java.sql.SQLException; import java.util.Iterator; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.sql.DataSource; import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.hp.hpl.jena.query.Dataset; import com.hp.hpl.jena.query.Query; import com.hp.hpl.jena.query.QueryExecution; import com.hp.hpl.jena.query.QueryExecutionFactory; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.sdb.SDBFactory; import com.hp.hpl.jena.sdb.Store; import com.hp.hpl.jena.sdb.StoreDesc; import com.hp.hpl.jena.sdb.sql.SDBConnection; import com.hp.hpl.jena.shared.Lock; import edu.cornell.mannlib.vitro.webapp.dao.jena.DatasetWrapper; import edu.cornell.mannlib.vitro.webapp.dao.jena.StaticDatasetFactory; import edu.cornell.mannlib.vitro.webapp.rdfservice.ChangeSet; import edu.cornell.mannlib.vitro.webapp.rdfservice.ModelChange; import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService; import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFServiceException; import edu.cornell.mannlib.vitro.webapp.rdfservice.impl.jena.ListeningGraph; import edu.cornell.mannlib.vitro.webapp.rdfservice.impl.jena.RDFServiceJena; public class RDFServiceSDB extends RDFServiceJena implements RDFService { private final static Log log = LogFactory.getLog(RDFServiceSDB.class); private DataSource ds; private StoreDesc storeDesc; private Connection conn; private StaticDatasetFactory staticDatasetFactory; public RDFServiceSDB(DataSource dataSource, StoreDesc storeDesc) { this.ds = dataSource; this.storeDesc = storeDesc; } public RDFServiceSDB(Connection conn, StoreDesc storeDesc) { this.conn = conn; this.storeDesc = storeDesc; this.staticDatasetFactory = new StaticDatasetFactory(getDataset( new SDBConnection(conn))); } @Override protected DatasetWrapper getDatasetWrapper() { try { if (staticDatasetFactory != null) { return staticDatasetFactory.getDatasetWrapper(); } SDBConnection conn = new SDBConnection(ds.getConnection()); return new DatasetWrapper(getDataset(conn), conn); } catch (SQLException sqle) { log.error(sqle, sqle); throw new RuntimeException(sqle); } } @Override public boolean changeSetUpdate(ChangeSet changeSet) throws RDFServiceException { if (changeSet.getPreconditionQuery() != null && !isPreconditionSatisfied( changeSet.getPreconditionQuery(), changeSet.getPreconditionQueryType())) { return false; } SDBConnection conn = null; try { conn = new SDBConnection(getConnection()); } catch (SQLException sqle) { log.error(sqle, sqle); throw new RDFServiceException(sqle); } Dataset dataset = getDataset(conn); boolean transaction = conn.getTransactionHandler().transactionsSupported(); try { if (transaction) { conn.getTransactionHandler().begin(); } for (Object o : changeSet.getPreChangeEvents()) { this.notifyListenersOfEvent(o); } Iterator<ModelChange> csIt = changeSet.getModelChanges().iterator(); while (csIt.hasNext()) { ModelChange modelChange = csIt.next(); if (!modelChange.getSerializedModel().markSupported()) { byte[] bytes = IOUtils.toByteArray(modelChange.getSerializedModel()); modelChange.setSerializedModel(new ByteArrayInputStream(bytes)); } modelChange.getSerializedModel().mark(Integer.MAX_VALUE); dataset.getLock().enterCriticalSection(Lock.WRITE); try { Model model = (modelChange.getGraphURI() == null) ? dataset.getDefaultModel() : dataset.getNamedModel(modelChange.getGraphURI()); operateOnModel(model, modelChange, dataset); } finally { dataset.getLock().leaveCriticalSection(); } } if (transaction) { conn.getTransactionHandler().commit(); } // notify listeners of triple changes csIt = changeSet.getModelChanges().iterator(); while (csIt.hasNext()) { ModelChange modelChange = csIt.next(); modelChange.getSerializedModel().reset(); Model model = ModelFactory.createModelForGraph( new ListeningGraph(modelChange.getGraphURI(), this)); operateOnModel(model, modelChange, null); } for (Object o : changeSet.getPostChangeEvents()) { this.notifyListenersOfEvent(o); } } catch (Exception e) { log.error(e, e); if (transaction) { conn.getTransactionHandler().abort(); } throw new RDFServiceException(e); } finally { close(conn); } return true; } protected Connection getConnection() throws SQLException { return (conn != null) ? conn : ds.getConnection(); } protected void close(SDBConnection sdbConn) { if (!sdbConn.getSqlConnection().equals(conn)) { sdbConn.close(); } } protected Dataset getDataset(SDBConnection conn) { Store store = SDBFactory.connectStore(conn, storeDesc); store.getLoader().setUseThreading(false); return SDBFactory.connectDataset(store); } private static final Pattern OPTIONAL_PATTERN = Pattern.compile("optional", Pattern.CASE_INSENSITIVE); private static final Pattern GRAPH_PATTERN = Pattern.compile("graph", Pattern.CASE_INSENSITIVE); @Override protected QueryExecution createQueryExecution(String queryString, Query q, Dataset d) { // query performance with OPTIONAL can be dramatically improved on SDB by // using the default model (union model) instead of the dataset, so long as // we're not querying particular named graphs Matcher optional = OPTIONAL_PATTERN.matcher(queryString); Matcher graph = GRAPH_PATTERN.matcher(queryString); if (optional.find() && !graph.find()) { return QueryExecutionFactory.create(q, d.getDefaultModel()); } else { return QueryExecutionFactory.create(q, d); } } @Override public void close() { if (conn != null) { try { conn.close(); } catch (SQLException e) { log.error(e,e); } } } }
package com.xpn.xwiki.api; import java.util.List; import java.util.Locale; import org.xwiki.model.reference.DocumentReference; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.render.ScriptXWikiServletRequest; import com.xpn.xwiki.util.Programming; import com.xpn.xwiki.validation.XWikiValidationStatus; import com.xpn.xwiki.web.XWikiRequest; import com.xpn.xwiki.web.XWikiResponse; import com.xpn.xwiki.web.XWikiURLFactory; /** * Provides a secure proxy for the internal {@code XWikiContext} class, that can be used safely in scripts. All * dangerous methods are protected by requiring Programming Rights. * * @version $Id$ */ public class Context extends Api { /** * The Constructor. * * @param context The {@link com.xpn.xwiki.XWikiContext} to wrap. */ public Context(XWikiContext context) { super(context); } /** * Returns the current request object. If the request has been made to a servlet container using the HTTP protocol * then the returned object wraps a <code>HttpServletRequest</code> instance. * * @return an object wrapping the current request object */ public XWikiRequest getRequest() { return new ScriptXWikiServletRequest(getXWikiContext().getRequest(), getContextualAuthorizationManager()); } /** * Returns the current response object. If the request has been made to a servlet container using the HTTP protocol * then the returned object wraps a <code>HttpServletResponse</code> instance. * * @return an object wrapping the current response object */ public XWikiResponse getResponse() { return getXWikiContext().getResponse(); } /** * Specifies the container or environment in which XWiki is currently running. See the following table for possible * values it can return: * <table> * <caption>Return values</caption> * <thead> * <tr> * <th>Return</th> * <th>Meaning</th> * </tr> * </thead> <tbody> * <tr> * <td>0</td> * <td>Servlet Container</td> * </tr> * <tr> * <td>1</td> * <td>Portlet Container</td> * </tr> * <tr> * <td>2</td> * <td>XML RPC</td> * </tr> * <tr> * <td>3</td> * <td>Atom</td> * </tr> * <tr> * <td>4</td> * <td>PDF</td> * </tr> * <tr> * <td>5</td> * <td>GWT</td> * </tr> * <tr> * <td>6</td> * <td>GWT Debugging</td> * </tr> * </tbody> * </table> * * @return an integer constant identifying the container or environment in which XWiki is currently running */ public int getMode() { return getXWikiContext().getMode(); } /** * Returns the current database name. If {@link #isMainWiki()} returns <code>true</code> then the current database * name is the same as {@link #getMainWikiName()}. Otherwise, each virtual wiki has it's own database. In this case * the returned string identifies the current virtual wiki we operate on and prefixes document names like in * <i>databaseName:spaceName.pageName</i>. * * @return The current database name. * @see #isMainWiki() * @see #getMainWikiName() */ public String getDatabase() { return getXWikiContext().getWikiId(); } /** * Returns the name of the main wiki. In non-virtual mode there is only one wiki called <i>xwiki</i>. In virtual * mode, the main wiki stores information about all the other virtual wikis. * * @return The name of the main wiki. */ public String getMainWikiName() { return getXWikiContext().getMainXWiki(); } /** * Returns the name of the original database. Here, original means the database corresponding to the requested URL, * which can be changed when including a document from a different database, by using, for example, * <code>#includeTopic("virtualwiki:Some.Document")</code>. * * @return The original database name */ public String getOriginalDatabase() { return getXWikiContext().getOriginalWikiId(); } /** * Sets the current database. You need programming rights to be able to call this method. * * @param database a database name * @see #getDatabase() */ @Programming public void setDatabase(String database) { if (hasProgrammingRights()) { getXWikiContext().setWikiId(database); } } /** * Returns the URL factory matching both the protocol used to make the current request and the container or * environment in which XWiki is running. The most used concrete implementation of the <code>XWikiURLFactory</code> * is <code>XWikiServletURLFactory</code>. <code>XWikiURLFactory</code> offers a generic way of creating XWiki * specific URLs that should be chosen instead of the basic string concatenation. Hard-coding the protocol used, * like HTTP, inside wiki pages should be avoided. * * @return The URL factory. */ public XWikiURLFactory getURLFactory() { return getXWikiContext().getURLFactory(); } /** * <p> * Specifies if the current request was made to a virtual (non-main) wiki, or to the main wiki. * </p> * <p> * In virtual mode the server can host more than one wiki, each having it's own database and its own URL. We refer * to them as <i>virtual wikis</i>. One of them stores information about the others and it is called <i>the main * wiki</i>. You can switch to virtual mode by changing the <code>xwiki.virtual</code> parameter from <code>0</code> * to <code>1</code> in the configuration file. * </p> * * @return <code>true</code> if XWiki is in the main wiki, or if virtual mode is disabled. * @see #getDatabase() * @see #getMainWikiName() */ public boolean isMainWiki() { return getXWikiContext().isMainWiki(); } public String getAction() { return getXWikiContext().getAction(); } /** * Same as {@link #getLocale()} but as String. * * @return The locale of the current request. * @see #getInterfaceLanguage() * @deprecated since 6.0M1, use {@link #getLocale()} instead */ @Deprecated public String getLanguage() { return getXWikiContext().getLanguage(); } /** * Returns the locale of the current request. If <code>multilingual</code> is turned off then the locale used is * given by the <code>default_language</code> preference. Otherwise, the locale is taken from either the request * object, the cookie, user preferences or from the navigator locale settings, the last having the lower priority. * * @return The locale of the current request. * @see #getInterfaceLocale() * @since 6.0M1 */ public Locale getLocale() { return getXWikiContext().getLocale(); } /** * Same as {@link #getInterfaceLocale()} but as String. * * @return The interface locale preference of the current user. * @see #getLanguage() * @deprecated since 6.0M1, use {@link #getInterfaceLocale()} instead */ @Deprecated public String getInterfaceLanguage() { return getXWikiContext().getInterfaceLanguage(); } /** * Returns the interface locale preference of the current user. If <code>multilingual</code> is turned off then the * locale used is given by the <code>default_language</code> preference. Otherwise, the locale is taken from either * the request object, the context, the cookie, user preferences or from the navigator locale settings, the last * having the lower priority. * * @return The interface locale preference of the current user. * @see #getLocale() * @since 6.0M1 */ public Locale getInterfaceLocale() { return getXWikiContext().getInterfaceLocale(); } /** * Returns the XWiki object. Programming rights are needed in order to call this method. If programming rights are * not available in the current document, the XWiki object can still be accessed through a secure API available as a * predefined variable for scripting inside wiki pages; use <code>$xwiki</code> in Velocity. * * @return The internal XWiki object, if the document has programming rights, or <code>null</code> otherwise. */ @Programming public com.xpn.xwiki.XWiki getXWiki() { if (hasProgrammingRights()) { return getXWikiContext().getWiki(); } else { return null; } } /** * Returns the current requested document. Programming rights are needed in order to call this method. If * programming rights are not available in the current document, the current can can still be accessed document * through a secure API available as a predefined variable for scripting inside wiki pages; use <code>$doc</code> in * Velocity. * * @return The current requested document, if the document has programming rights, or <code>null</code> otherwise. */ @Programming public XWikiDocument getDoc() { if (hasProgrammingRights()) { return getXWikiContext().getDoc(); } else { return null; } } /** * Returns the current user which made the request. If there's no currently logged in user in XWiki then the * returned string is <i>XWiki.XWikiGuest</i> which represents any anonymous user. The name of the user is returned * relative to the current wiki so if the user is in the current wiki or in non-virtual mode the name will be of the * form <code>XWiki.UserLogin</code>. If the user comes from another wiki the full prefixed name will be returned as * in <code>wikiid:XWiki.UserLogin</code>. At the same time this method returns the name of the document containing * the current user's profile so in Velocity you can do, for instance, * <code>$xwiki.getDocument($xcontext.user)</code> to find out more about the current user, like his/hers real name * or e-mail address. * * @return The current user which made the request. * @see #getLocalUser() * @see #getDatabase() * @see #getUserReference() */ public String getUser() { return getXWikiContext().getUser(); } /** * Returns the document reference for the profile page of the current user which made the request. The returned * reference can always be considered an absolute document reference, meaning that * <code>getUserReference().getWikiReference().getName()</code> will always return the name of the user's wiki. * * @return The document reference for the current logged in user which made the request or <code>null</code> if * there is no currently logged in user (anonymous/guest user). * @since 3.2M3 */ public DocumentReference getUserReference() { return getXWikiContext().getUserReference(); } /** * Returns the current user which made the request. The difference from {@link #getUser()} is that the returned * string is never prefixed with the database name, not even in virtual mode. * * @return The current user which made the request. * @see #getUser() * @see #getDatabase() */ public String getLocalUser() { return getXWikiContext().getLocalUser(); } /** * Sets the current document. Programming rights are needed in order to call this method. * * @param doc XWiki document to set as the context document. */ @Programming public void setDoc(XWikiDocument doc) { if (hasProgrammingRights()) { getXWikiContext().setDoc(doc); } } /** * Returns the XWiki context. Programming rights are needed in order to call this method. The XWiki context * represents the execution environment for all the wiki pages. Accessing it directly in wiki pages may lead to * security issues. * * @return The unwrapped version of the context if you have programming rights, or <code>null</code> otherwise. */ @Programming public XWikiContext getContext() { if (hasProgrammingRights()) { return super.getXWikiContext(); } else { return null; } } /** * Returns the value associated with the given key in the XWiki context. Programming rights are needed in order to * call this method. The context can be seen as a map of (paramName, paramValue) pairs. This mechanism is useful for * passing parameters between pages or from Java to Velocity. For instance an exception caught in Java code can be * put on the context and handled in a user-friendly way in Velocity. This method is protected because sensitive * information may be placed in the internal context, which shouldn't be publicly accessible. * * @param key The key to look for in the context. * @return The value associated with the given key in the XWiki context, if you have programming rights, or * <code>null</code> otherwise. * @see #put(String, java.lang.Object) */ @Programming public java.lang.Object get(String key) { if (hasProgrammingRights()) { return getXWikiContext().get(key); } else { return null; } } /** * Returns the list of TextArea fields that use the WYSIWYG editor. This list is automatically built when displaying * TextArea properties. * * @deprecated since 8.2RC1 when we started using the Edit Module to load the configured WYSIWYG editor * @return a string containing a comma-separated list of TextArea field names for which the WYSIWYG editor should be * enabled */ @Deprecated public String getEditorWysiwyg() { return getXWikiContext().getEditorWysiwyg(); } /** * Puts an object on the context using the given key. The context can be seen as a map of (paramName, paramValue) * pairs. Requires programming rights. * * @param key The parameter name. * @param value The parameter value. * @see #get(String) */ @Programming public void put(String key, java.lang.Object value) { if (hasProgrammingRights()) { getXWikiContext().put(key, value); } } /** * Specifies if the current page should be sent to the client or not. When the context is finished, the client * response contains only the (HTTP) headers and no body (as in the case of a response to a HTTP HEAD request). This * is useful for instance when exporting the entire wiki as a <code>.xar</code> archive. * * @param finished <code>true</code> to avoid rendering of the current page */ public void setFinished(boolean finished) { getXWikiContext().setFinished(finished); } /** * Returns the amount of time this document should be cached. * * @return The cache duration, in seconds. * @see #setCacheDuration(int) */ public int getCacheDuration() { return getXWikiContext().getCacheDuration(); } /** * Sets the cache duration in seconds. Setting this to a non-zero, positive value will cause the rendered document * to be stored in a cache, so next time a client requests this document, if it is still in the cache, and the * document content did not change, then it will be taken from the cache and will not be parsed/rendered again. * While it is a good idea to cache pages containing only static content (no scripting), it should be used with care * for documents that gather information from the wiki using queries. * * @param duration The cache duration specified in seconds. * @see #getCacheDuration() */ public void setCacheDuration(int duration) { getXWikiContext().setCacheDuration(duration); } /** * Sets the action to be used instead of the <i>view</i> action inside URLs. The XWiki URL factories will replace * the <i>view</i> action with the given action when creating URLs. * * @param action <i>view</i> action replacement * @see #unsetLinksAction() * @see #getLinksAction() * @see #getURLFactory() */ public void setLinksAction(String action) { getXWikiContext().setLinksAction(action); } /** * Stops the <i>view</i> action from being replaced with another action inside URLs. * * @see #setLinksAction(String) * @see #getLinksAction() */ public void unsetLinksAction() { getXWikiContext().unsetLinksAction(); } /** * Returns the action used by XWiki URL factories to replace the <i>view</i> action when creating URLs. If no action * replacement has been specified, it returns <code>null</code>. * * @return The <i>view</i> action replacement, or <code>null</code>. * @see #setLinksAction(String) * @see #unsetLinksAction() * @see #getURLFactory() */ public String getLinksAction() { return getXWikiContext().getLinksAction(); } public void setLinksQueryString(String value) { getXWikiContext().setLinksQueryString(value); } /** * Specifies that no additional query string should be added to XWiki URLs. * * @see #setLinksQueryString(String) * @see #getLinksQueryString() */ public void unsetLinksQueryString() { getXWikiContext().unsetLinksQueryString(); } public String getLinksQueryString() { return getXWikiContext().getLinksQueryString(); } /** * Returns the form field validation status, which contains the exceptions or errors that may have occured during * the validation process performed during a <i>save</i>. * * @return The validation status. */ public XWikiValidationStatus getValidationStatus() { return getXWikiContext().getValidationStatus(); } /** * Returns the list with the currently displayed fields. Each time we call <code>display</code> on a document for a * specific field that field is added to the list returned by this method. * * @return The list with the currently displayed fields. * @see Document#display(String) */ public List<String> getDisplayedFields() { return getXWikiContext().getDisplayedFields(); } /** * Sets the default field display mode, when using {@link Document#display(String)} or * {@link Document#display(String, Object)}. It is automatically set to "edit" when the action is "edit" or * "inline", and to "view" in all other cases. * * @param mode the display mode, one of "view", "edit", "hidden", "search", "rendered". */ public void setDisplayMode(String mode) { getXWikiContext().put("display", mode); } /** * Retrieves the information about the currently executing macro. This method is only useful inside wiki macros. * * @return macro information, normally a {@link java.util.Map} containing the macro {@code content}, the * {@code params}, and the macro execution {@code context} */ public java.lang.Object getMacro() { return getXWikiContext().get("macro"); } public void dropPermissions() { getXWikiContext().dropPermissions(); } /** * Get the registered (generally error) message for the previous action. * * @return the registered message * @since 5.2RC1 */ public String getMessage() { return (String) this.context.get("message"); } }
package students.aalto.org.indoormappingapp; import android.app.ProgressDialog; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.util.Pair; import android.view.DragEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.TimeUnit; import rx.Observable; import rx.Subscriber; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.functions.Func1; import rx.functions.Func2; import rx.functions.Func3; import rx.schedulers.Schedulers; import students.aalto.org.indoormappingapp.model.ApplicationState; import students.aalto.org.indoormappingapp.model.DataSet; import students.aalto.org.indoormappingapp.model.Location; import students.aalto.org.indoormappingapp.model.MapPosition; import students.aalto.org.indoormappingapp.model.Photo; import students.aalto.org.indoormappingapp.model.RenderData; import students.aalto.org.indoormappingapp.sensors.SensorsFragment; import students.aalto.org.indoormappingapp.sensors.SensorsSnapshot; import students.aalto.org.indoormappingapp.services.NetworkService; import students.aalto.org.indoormappingapp.tests.SensorsTestActivity; class RenderState { public RenderState(float x,float y,float zoom, Bitmap bitmap) { X = x; Y = y; Zoom = zoom; BackgroundImage = bitmap; } public Float X; public Bitmap BackgroundImage; public Float Y; public Float Zoom; } public class MainActivity extends MenuRouterActivity { SurfaceHolder mSurfaceHolder; private Float translationX = 0f; private Float translationY = 0f; private List<Location> photos; private Location recordStartLoc; private Subscription subscription; public static Bitmap getBitmapFromURL(String src) { try { URL url = new URL(src); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); Bitmap myBitmap = BitmapFactory.decodeStream(input); return myBitmap; } catch (IOException e) { // Log exception return null; } } private Location locationUnderCursor() { for(Location loc : photos) { if(loc.X > translationX - 10 && loc.X < translationX + 10 && loc.Y > translationY - 10 && loc.Y < translationY + 10) { return loc; } } return null; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final ProgressDialog dialog = new ProgressDialog(this); dialog.setIndeterminate(true); dialog.setCancelable(false); dialog.setMessage(getString(R.string.loading)); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setTitle(ApplicationState.Instance().getSelectedDataSet().Name); getSupportActionBar().setDisplayHomeAsUpEnabled(true); final SurfaceView surfaceView = (SurfaceView) findViewById(R.id.main_map); final Button leftButton = (Button) findViewById(R.id.button_left); final Button rightButton = (Button) findViewById(R.id.button_right); final Button photoButton = (Button) findViewById(R.id.button_photo); final Button showLocationButton = (Button) findViewById(R.id.button_show_location); final Button startRecordButton = (Button) findViewById(R.id.button_start_record); final Button endRecordButton = (Button) findViewById(R.id.button_end_record); final View selectedLocationContainer = (View) findViewById(R.id.stop_to_turn_label); final TextView selectedLocName = (TextView) findViewById(R.id.selected_location_name); final TextView selectedLocPhotos = (TextView) findViewById(R.id.selected_location_photos); if(ApplicationState.Instance().getSelectedLocation() == null) { photoButton.setVisibility(View.GONE); showLocationButton.setVisibility(View.VISIBLE); } else { photoButton.setVisibility(View.VISIBLE); showLocationButton.setVisibility(View.GONE); } if(ApplicationState.Instance().getSelectedLocation() != null) { startRecordButton.setVisibility(View.GONE); endRecordButton.setVisibility(View.GONE); } else { startRecordButton.setVisibility(View.VISIBLE); endRecordButton.setVisibility(View.GONE); } startRecordButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { recordStartLoc = locationUnderCursor(); Toast.makeText(MainActivity.this, R.string.start_walking, Toast.LENGTH_LONG).show(); startRecordButton.setVisibility(View.GONE); endRecordButton.setVisibility(View.VISIBLE); } }); endRecordButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { recordStartLoc = null; Toast.makeText(MainActivity.this, R.string.record_ended, Toast.LENGTH_LONG).show(); startRecordButton.setVisibility(View.VISIBLE); endRecordButton.setVisibility(View.GONE); } }); showLocationButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { for(Location loc : photos) { if(loc.X > translationX - 10 && loc.X < translationX + 10 && loc.Y > translationY - 10 && loc.Y < translationY + 10) { Intent intent = new Intent(MainActivity.this, PhotoListActivity.class); ApplicationState.Instance().setSelectedLocation(loc); startActivity(intent); } } } }); Observable.create(new Observable.OnSubscribe<Integer>() { @Override public void call(final Subscriber<? super Integer> subscriber) { photoButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.setMessage(getString(R.string.sending)); dialog.show(); subscriber.onNext(0); } }); } }).switchMap(new Func1<Integer, Observable<?>>() { @Override public Observable<?> call(Integer integer) { Location loc = ApplicationState.Instance().getSelectedLocation(); loc.X = translationX.intValue(); loc.Y = translationY.intValue(); return NetworkService.saveLocation(ApplicationState.Instance().getSelectedDataSet().ID, loc); } }).subscribe(new Action1<Object>() { @Override public void call(Object o) { dialog.dismiss(); MainActivity.this.finish(); } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { dialog.dismiss(); Toast.makeText(MainActivity.this, R.string.network_error, Toast.LENGTH_LONG); } }); surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() { @Override public void surfaceCreated(SurfaceHolder surfaceHolder) { Canvas canvas = surfaceHolder.lockCanvas(); canvas.drawColor(Color.WHITE); surfaceHolder.unlockCanvasAndPost(canvas); mSurfaceHolder = surfaceHolder; } @Override public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) { mSurfaceHolder = surfaceHolder; } @Override public void surfaceDestroyed(SurfaceHolder surfaceHolder) { mSurfaceHolder = null; } }); // Create mock step from button. Observable<Float> zoomObservable = Observable.create(new Observable.OnSubscribe<Float>() { @Override public void call(final Subscriber<? super Float> subscriber) { leftButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { subscriber.onNext(-1f); } }); rightButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { subscriber.onNext(1f); } }); } }).scan(new Func2<Float, Float, Float>() { @Override public Float call(Float integer, Float integer2) { return integer + integer2; } }).startWith(0f).map(new Func1<Float, Float>() { @Override public Float call(Float aFloat) { return 1.0f + (aFloat * 0.1f); } }); Observable<Pair<Float, Float>> translationObservable = Observable.create(new Observable.OnSubscribe<Pair<Float, Float>>() { @Override public void call(final Subscriber<? super Pair<Float, Float>> subscriber) { final Float[] downX = {null}; final Float[] downY = {null}; surfaceView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) { downX[0] = motionEvent.getX(); downY[0] = motionEvent.getY(); } else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) { if (downX[0] != null && downY[0] != null) { subscriber.onNext(new Pair<Float, Float>(-(motionEvent.getX() - downX[0]), -(motionEvent.getY() - downY[0]))); downX[0] = motionEvent.getX(); downY[0] = motionEvent.getY(); } } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) { downX[0] = null; downY[0] = null; } return true; } }); } }).scan(new Func2<Pair<Float, Float>, Pair<Float, Float>, Pair<Float, Float>>() { @Override public Pair<Float, Float> call(Pair<Float, Float> floatFloatPair, Pair<Float, Float> floatFloatPair2) { floatFloatPair = floatFloatPair == null ? new Pair<Float, Float>(0f, 0f) : floatFloatPair; //accumulate return new Pair<Float, Float>(floatFloatPair.first + floatFloatPair2.first, floatFloatPair.second + floatFloatPair2.second); } }).startWith(new Pair<Float, Float>(0f,0f)); Observable<Bitmap> backgroundObs = Observable.just(1).observeOn(Schedulers.newThread()).map(new Func1<Integer, Bitmap>() { @Override public Bitmap call(Integer integer) { Bitmap bmp = getBitmapFromURL(ApplicationState.Instance().getSelectedDataSet().MapPhoto.URL); return bmp; } }).observeOn(AndroidSchedulers.mainThread()); Observable<RenderState> transitionAndZoomObservable = Observable.combineLatest(zoomObservable, translationObservable, backgroundObs, new Func3<Float, Pair<Float, Float>, Bitmap, RenderState>() { @Override public RenderState call(Float aFloat, Pair<Float, Float> floatFloatPair, Bitmap bitmap) { RenderState t = new RenderState(floatFloatPair.first, floatFloatPair.second, aFloat, bitmap); return t; } }); dialog.show(); subscription = Observable.combineLatest(NetworkService.getLocations(ApplicationState.Instance().getSelectedDataSet().ID).map(new Func1<List<Location>, List<Location>>() { @Override public List<Location> call(List<Location> locations) { if(ApplicationState.Instance().getSelectedLocation() == null) return locations; ArrayList<Location> filtered = new ArrayList<Location>(); for(Location loc : locations) { if(!loc.ID.equals(ApplicationState.Instance().getSelectedLocation().ID)) { filtered.add(loc); } } return filtered; } }), transitionAndZoomObservable, new Func2<List<Location>, RenderState, Pair<List<Location>, RenderState>>() { @Override public Pair<List<Location>, RenderState> call(List<Location> locations, RenderState transitionAndZoom) { return new Pair<List<Location>, RenderState>(locations, transitionAndZoom); } }).subscribe(new Action1<Pair<List<Location>, RenderState>>() { @Override public void call(Pair<List<Location>, RenderState> listTransitionAndZoomPair) { if (mSurfaceHolder == null) return; dialog.dismiss(); photos = listTransitionAndZoomPair.first; Canvas canvas = mSurfaceHolder.lockCanvas(); if (canvas == null) return; canvas.drawColor(Color.WHITE); float centerX = canvas.getWidth() / 2; float centerY = canvas.getHeight() / 2; float scaleX = listTransitionAndZoomPair.second.Zoom; float scaleY = listTransitionAndZoomPair.second.Zoom; translationX = listTransitionAndZoomPair.second.X; translationY = listTransitionAndZoomPair.second.Y; Paint paintRed = new Paint(); paintRed.setStyle(Paint.Style.FILL); paintRed.setColor(Color.RED); paintRed.setStrokeWidth(10f / scaleX); Paint paintYellow = new Paint(); paintYellow.setStyle(Paint.Style.FILL); paintYellow.setColor(Color.MAGENTA); paintYellow.setStrokeWidth(10f / scaleX); Paint paintGreen = new Paint(); paintGreen.setStyle(Paint.Style.FILL); paintGreen.setColor(Color.GREEN); paintGreen.setStrokeWidth(10f / scaleX); selectedLocationContainer.setVisibility(View.GONE); for (Location loc : photos) { if (loc.X > translationX - 10 && loc.X < translationX + 10 && loc.Y > translationY - 10 && loc.Y < translationY + 10) { selectedLocationContainer.setVisibility(View.VISIBLE); selectedLocName.setText(loc.Name); selectedLocPhotos.setText(loc.Photos.size() + " photos"); } } canvas.translate(((float) canvas.getWidth() - scaleX * (float) canvas.getWidth()) / 2.0f, ((float) canvas.getHeight() - scaleY * (float) canvas.getHeight()) / 2.0f); canvas.scale(scaleX + 0.01f, scaleY + 0.01f); if (listTransitionAndZoomPair.second.BackgroundImage != null) { canvas.drawBitmap(listTransitionAndZoomPair.second.BackgroundImage, centerX - translationX - (listTransitionAndZoomPair.second.BackgroundImage.getWidth() / 2), centerY - translationY - (listTransitionAndZoomPair.second.BackgroundImage.getHeight() / 2), null); } //location = DeadReckoning.calculatePositionDelta(location.first, location.second, 100, null); for (int i = 0; i < photos.size(); i++) { Location start = photos.get(i); Paint tmpPaint; if (start.Photos == null || start.Photos.size() == 0) { tmpPaint = paintRed; } else if (start.Photos.size() < 3) { tmpPaint = paintYellow; } else { tmpPaint = paintGreen; } canvas.drawCircle(centerX + (float) start.X - translationX, centerY + (float) start.Y - translationY, 10, tmpPaint); } Paint paint = new Paint(); paint.setStyle(Paint.Style.FILL); paint.setColor(Color.BLUE); paint.setStrokeWidth(5); canvas.drawLine(centerX - 20f, centerY, centerX + 20f, centerY, paint); canvas.drawLine(centerX, centerY - 20f, centerX, centerY + 20f, paint); mSurfaceHolder.unlockCanvasAndPost(canvas); } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { Toast.makeText(MainActivity.this, R.string.network_error, Toast.LENGTH_LONG); } }); /*final TextView helloView = (TextView) findViewById(R.id.hello_text_view); rx.Observable.interval(500, TimeUnit.MILLISECONDS).map(new Func1<Long, Long>() { @Override public Long call(Long aLong) { return aLong * 100; } }).filter(new Func1<Long, Boolean>() { @Override public Boolean call(Long aLong) { return aLong > 300; } }).take(1).observeOn(AndroidSchedulers.mainThread()).doOnNext(new Action1<Long>() { @Override public void call(Long aLong) { helloView.setText("Start load"); } }).flatMap(new Func1<Long, rx.Observable<Long>>() { @Override public rx.Observable<Long> call(Long aLong) { return rx.Observable.interval(5000, 0, TimeUnit.MILLISECONDS).take(1); } }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Long>() { @Override public void call(Long aLong) { helloView.setText(aLong + ""); } });*/ /* FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { sendLocation(0,0,0).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Boolean>() { @Override public void call(Boolean aBoolean) { // create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name // start the image capture Intent startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE); } }); } }); */ } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_empty, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == android.R.id.home) { MainActivity.this.finish(); } return super.onOptionsItemSelected(item); } @Override protected void onResume() { super.onResume(); } @Override protected void onPause() { super.onPause(); } @Override protected void onDestroy() { super.onDestroy(); subscription.unsubscribe(); } public static final int MEDIA_TYPE_IMAGE = 1; public static final int MEDIA_TYPE_VIDEO = 2; }
package br.usp.ime.choreos.nodepoolmanager.cm; import br.usp.ime.choreos.nodepoolmanager.Configuration; import br.usp.ime.choreos.nodepoolmanager.utils.ScriptsProvider; import br.usp.ime.choreos.nodepoolmanager.utils.SshUtil; public class NodeInitializer { private final String hostname; public NodeInitializer(String hostname) { this.hostname = hostname; } public void cleanPetals() throws Exception { /* String output = new SshUtil(hostname).runCommand(command); System.out.println(output); */ } }
package uk.ac.cam.cstibhotel.otcanalyser.trade; public enum PriceFormingContinuationData { TERMINATION(0), TRADE(1), AMENDMENT(2), INCREASE(3), NOVATION(4), PARTIALTERMINATION(5), EXIT(6), EXERCISE(7); private short value; private PriceFormingContinuationData(int value) { this.value = (short) value; } public short getValue() { return value; } public static PriceFormingContinuationData lookup(int i){ switch(i){ case 0: return TERMINATION; case 1: return TRADE; case 2: return AMENDMENT; case 3: return INCREASE; case 4: return NOVATION; case 5: return PARTIALTERMINATION; case 6: return EXIT; case 7: return EXERCISE; default: throw new IllegalArgumentException(); } } public static PriceFormingContinuationData parsePFCD(String s) throws PFCDFormatException{ s = s.toLowerCase(); s = s.replace("-", ""); switch(s){ case "termination": return TERMINATION; case "trade": return TRADE; case "amendment": return AMENDMENT; case "increase": return INCREASE; case "novation": return NOVATION; case "novationtrade": return NOVATION; case "partialtermination": return PARTIALTERMINATION; case "exit": return EXIT; case "exercise": return EXERCISE; case "": return null; default: throw new PFCDFormatException("for string " + s); } } }
package net.sf.pzfilereader.parserutils; import java.util.List; import junit.framework.TestCase; import net.sf.pzfilereader.util.ParserUtils; import net.sf.pzfilereader.utilities.UnitTestUtils; public class ParserUtilsSplitLineTest extends TestCase { private static final String[] DELIMITED_DATA_NO_BREAKS = { "Column 1", "Column 2", "Column 3", "Column 4", "Column 5" }; private static final String[] DELIMITED_DATA_WITH_BREAKS = { "Column 1 \r\n\r\n Test After Break \r\n Another Break", "Column 2", "Column 3 \r\n\r\n Test After Break", "Column 4", "Column 5 \r\n\r\n Test After Break\r\n Another Break" }; // TODO think of a situation that actually breaks the parse. This still // works because of the way it is coded // to handle the excel CSV. Excel CSV has some elements qualified and others // not private static final String DELIMITED_BAD_DATA = "\"column 1\",\"column 2 ,\"column3\""; // 0 = delimiter // 1 = qualifier private static final char[][] DELIM_QUAL_PAIR = { { ',', '\"' }, { '\t', '\"' }, { '|', '\"' }, { '_', '\"' }, { ',', 0 }, { '|', 0 }, { '\t', 0 } }; /** * Test without any line breaks * */ public void testNoLineBreaks() { // loop down all delimiter qualifier pairs to test for (int i = 0; i < DELIM_QUAL_PAIR.length; i++) { final char d = DELIM_QUAL_PAIR[i][0]; final char q = DELIM_QUAL_PAIR[i][1]; final String txtToParse = UnitTestUtils.buildDelimString(DELIMITED_DATA_NO_BREAKS, d, q); final List splitLineResults = ParserUtils.splitLine(txtToParse, d, q, 10); // check to make sure we have the same amount of elements which were // expected assertEquals("Expected size (d = [" + d + "] q = [" + (q != 0 ? String.valueOf(q) : "") + "] txt [" + txtToParse + "])", DELIMITED_DATA_NO_BREAKS.length, splitLineResults.size()); // loop through each value and compare what came back for (int j = 0; j < DELIMITED_DATA_NO_BREAKS.length; j++) { assertEquals("Data Element Value Does Not Match (d = [" + d + "] q = [" + q + "] txt [" + txtToParse + "])", DELIMITED_DATA_NO_BREAKS[j], (String) splitLineResults.get(j)); } } } /** * Test with any line breaks * */ public void testLineBreaks() { // loop down all delimiter qualifier pairs to test for (int i = 0; i < DELIM_QUAL_PAIR.length; i++) { final char d = DELIM_QUAL_PAIR[i][0]; final char q = DELIM_QUAL_PAIR[i][1]; final String txtToParse = UnitTestUtils.buildDelimString(DELIMITED_DATA_WITH_BREAKS, d, q); final List splitLineResults = ParserUtils.splitLine(txtToParse, d, q, 10); // check to make sure we have the same amount of elements which were // expected assertEquals("Did Not Get Amount Of Elements Expected (d = " + d + " q = " + q + ")", DELIMITED_DATA_WITH_BREAKS.length, splitLineResults.size()); // loop through each value and compare what came back for (int j = 0; j < DELIMITED_DATA_WITH_BREAKS.length; j++) { assertEquals("Data Element Value Does Not Match (d = " + d + " q = " + q + ")", DELIMITED_DATA_WITH_BREAKS[j], (String) splitLineResults.get(j)); } } } /** * Test to make sure we get the correct amount of elements for malformed * data */ public void testMalformedData() { final List splitLineResults = ParserUtils.splitLine(DELIMITED_BAD_DATA, ',', '\"', 10); assertEquals("Expecting 2 Data Elements From The Malformed Data", 2, splitLineResults.size()); } /** * Test some extreme cases */ public void testSomeExtremeCases() { check(null, ',', '\"', new String[] {}); check("a", ',', '\"', new String[] { "a" }); check("", ',', '\"', new String[] { "" }); check(" ", ',', '\"', new String[] { "" }); check(" ", ',', '\"', new String[] { "" }); check(",", ',', '\"', new String[] { "", "" }); check(",,", ',', '\"', new String[] { "", "", "" }); check(",a,", ',', '\"', new String[] { "", "a", "" }); check("\"a,b,c\"", ',', '\"', new String[] { "a,b,c" }); check("\"a,b\",\"c\"", ',', '\"', new String[] { "a,b", "c" }); check("\"a , b\",\"c\"", ',', '\"', new String[] { "a , b", "c" }); check("a,b,c", ',', '\"', new String[] { "a", "b", "c" }); check("a b,c", ',', '\"', new String[] { "a b", "c" }); check(" a,b,c ", ',', '\"', new String[] { "a", "b", "c" }); check(" a, b ,c", ',', '\"', new String[] { "a", "b", "c" }); // example typically from Excel. check("\"test1\",test2,\"0.00\",\"another, element here\",lastone", ',', '\"', new String[] { "test1", "test2", "0.00", "another, element here", "lastone" }); check("\"FRED\",\"ZNAME\",\"Text Qualifier \" and seperator, in string\",\"ELYRIA\",\"OH\",\"\"", ',', '\"', new String[] {"FRED", "ZNAME", "Text Qualifier \" and seperator, in string", "ELYRIA", "OH", ""}); check("a\",b,c\"", ',', '\"', new String[] { "a\"", "b", "c\"" }); check(" a, b ,c ", ',', '\"', new String[] { "a", "b", "c" }); check("\"a\", b , \"c\"", ',', '\"', new String[] { "a", "b", "c" }); check("\"\",,,,\"last one\"", ',', '\"', new String[] { "", "", "", "", "last one" }); check("\"first\",\"second\",", ',', '\"', new String[] { "first", "second", "" }); check("\" a,b,c\"", ',', '\"', new String[] { " a,b,c" }); check("\" a,b,c\",d", ',', '\"', new String[] { " a,b,c", "d" }); check("\"a, b,\"\"c\"", ',', '\"', new String[] { "a, b,\"c" }); check("\"a, b,\"\"c\", \" test\"", ',', '\"', new String[] { "a, b,\"c", " test" }); check("\"a, b,\"\"c\", test", ',', '\"', new String[] { "a, b,\"c", "test" }); check("one two three", ' ', '\u0000', new String[] {"one", "two", "three"}); check("\"one\" \"two\" three", ' ', '\"', new String[] {"one", "two", "three"}); check("\"one\" \"two\" three", ' ', '\"', new String[] {"one", "", "two", "", "three"}); check (" , , ", ',', '"', new String[] {"","",""}); check (" \t \t ", '\t', '"', new String[] {"","",""}); } /** * Test some extreme cases */ public void testSomeExtremeCases2() { check("\"a,b,c\"", ',', '\'', new String[] { "\"a", "b", "c\"" }); check("\"a,b\",\"c\"", ',', '\'', new String[] { "\"a", "b\"", "\"c\"" }); check("a,b,c", ',', '\'', new String[] { "a", "b", "c" }); check(" a,b,c", ',', '\'', new String[] { "a", "b", "c" }); check(" a,b,c", ',', '\'', new String[] { "a", "b", "c" }); // example typically from Excel. check("\"test1\",test2,\"0.00\",\"another, element here\",lastone", ',', '\'', new String[] { "\"test1\"", "test2", "\"0.00\"", "\"another", "element here\"", "lastone" }); // what would you expect of these ones? // +++++The parser allows qualified and unqualified elements to be // contained // on the same line. so it should break the elements down like so // 1 = a" -->" is part of the data since the element did not start with // a qualifier // 2 = b // 3 = c" --> same as // a",b,c" check("a\",b,c\"", ',', '\'', new String[] { "a\"", "b", "c\"" }); check("\" a,b,c\"", ',', '\'', new String[] { "\" a", "b", "c\"" }); check(" a, b ,c ", ',', '\'', new String[] { "a", "b", "c" }); } private void check(final String txtToParse, final char delim, final char qualifier, final String[] expected) { final List splitLineResults = ParserUtils.splitLine(txtToParse, delim, qualifier, 10); assertEquals( "Did Not Get Amount Of Elements Expected (d = " + delim + " q = " + qualifier + ") txt [" + txtToParse + "]", expected.length, splitLineResults.size()); for (int i = 0; i < expected.length; i++) { assertEquals("expecting...", expected[i], splitLineResults.get(i)); } } public static void main(final String[] args) { junit.textui.TestRunner.run(ParserUtilsSplitLineTest.class); } }
package org.reldb.rel.v0.storage.relvars.external.accdb; import java.io.File; import java.io.IOException; import org.reldb.rel.exceptions.ExceptionSemantic; import org.reldb.rel.v0.generator.Generator; import org.reldb.rel.v0.generator.SelectAttributes; import org.reldb.rel.v0.storage.RelDatabase; import org.reldb.rel.v0.storage.relvars.RelvarCustomMetadata; import org.reldb.rel.v0.storage.relvars.RelvarExternal; import org.reldb.rel.v0.storage.relvars.RelvarGlobal; import org.reldb.rel.v0.storage.relvars.RelvarHeading; import org.reldb.rel.v0.storage.relvars.external.CSVLineParse; import org.reldb.rel.v0.storage.relvars.external.ColumnName; import org.reldb.rel.v0.storage.tables.TableExternal.DuplicateHandling; import org.reldb.rel.v0.types.Heading; import org.reldb.rel.v0.types.builtin.TypeCharacter; import org.reldb.rel.v0.types.builtin.TypeInteger; import com.healthmarketscience.jackcess.Column; import com.healthmarketscience.jackcess.Database; import com.healthmarketscience.jackcess.DatabaseBuilder; import com.healthmarketscience.jackcess.Table; public class RelvarACCDBMetadata extends RelvarCustomMetadata { public static final long serialVersionUID = 0; private String connectionString; private String fileSpec; // "c:\\users\\me\\mydb.accdb" private String table; // "mytable" // var myvar external accdb "c:\\users\\me\\mydb.accdb,mytable"; private DuplicateHandling duplicates; public static RelvarHeading getHeading(RelDatabase database, String spec, DuplicateHandling duplicates) { String[] values = CSVLineParse.parseTrimmed(spec); if (values.length != 2) throw new ExceptionSemantic("RS0472: Invalid arguments. Expected: FILE, TABLE but got " + spec); String fileSpec = values[0]; String table = values[1]; Database db = null; try { db = DatabaseBuilder.open(new File(fileSpec)); Table tableData = db.getTable(table); Heading heading = new Heading(); if (duplicates == DuplicateHandling.DUP_COUNT) heading.add("_DUP_COUNT", TypeInteger.getInstance()); else if (duplicates == DuplicateHandling.AUTOKEY) heading.add("_AUTOKEY", TypeInteger.getInstance()); for (Column column: tableData.getColumns()) heading.add(ColumnName.cleanName(column.getName()), TypeCharacter.getInstance()); RelvarHeading relvarHeading = new RelvarHeading(heading); if (duplicates == DuplicateHandling.AUTOKEY) { SelectAttributes keyAttribute = new SelectAttributes(); keyAttribute.add("_AUTOKEY"); relvarHeading.addKey(keyAttribute); } return relvarHeading; } catch (IOException e) { throw new ExceptionSemantic("RS0473: Unable to open " + fileSpec + " table " + table + ": " + e.toString()); } finally { if (db != null) try { db.close(); } catch (IOException e) { } } } @Override public String getSourceDefinition() { return "EXTERNAL ACCDB \"" + fileSpec + ", " + table + "\" " + duplicates; } public RelvarACCDBMetadata(RelDatabase database, String owner, String spec, DuplicateHandling duplicates) { super(database, getHeading(database, spec, duplicates), owner); String[] values = CSVLineParse.parseTrimmed(spec); fileSpec = values[0]; table = values[1]; this.duplicates = duplicates; connectionString = spec; } public void checkTableExistence() { Database db = null; try { db = DatabaseBuilder.open(new File(fileSpec)); db.getTable(table); } catch (IOException e) { throw new ExceptionSemantic("RS0474: Table " + table + " no longer exists."); } finally { if (db != null) try { db.close(); } catch (IOException e) { } } } @Override public RelvarGlobal getRelvar(String name, RelDatabase database) { checkTableExistence(); return new RelvarExternal(name, database, new Generator(database, System.out), this, duplicates); } @Override public void dropRelvar(RelDatabase database) { } public String getConnectionString() { return connectionString; } public String getFileSpec() { return fileSpec; } public String getTable() { return table; } @Override public String tableClassName() { return "TableACCDB"; } @Override public String getType() { return "ACCDB"; } }
package com.qreal.stepic.robots.controllers; import com.fasterxml.jackson.databind.ObjectMapper; import com.qreal.stepic.robots.converters.JavaModelConverter; import com.qreal.stepic.robots.converters.XmlSaveConverter; import com.qreal.stepic.robots.model.diagram.*; import com.qreal.stepic.robots.model.two_d.Point; import com.qreal.stepic.robots.model.two_d.Trace; import org.apache.commons.io.FileUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.LinkedList; import java.util.List; @Controller public class DiagramController { @RequestMapping(value = "", method = RequestMethod.GET) public ModelAndView index() { return new ModelAndView("index"); } @Autowired private ResourceLoader resourceLoader; @RequestMapping(value = "{taskId}", method = RequestMethod.GET) public ModelAndView showTask(@PathVariable String taskId, Model model) { model.addAttribute("taskId", taskId); return new ModelAndView("index"); } @ResponseBody @RequestMapping(value = "/open", method = RequestMethod.POST) public Diagram open(@RequestBody OpenRequest request) { Resource resource = resourceLoader.getResource("tasks/" + request.getId()); XmlSaveConverter converter= new XmlSaveConverter(); try { File folder = resource.getFile(); String folderPath = folder.getPath(); File diagramDirectory = new File(folderPath + "/diagram"); if (!diagramDirectory.exists()) { ProcessBuilder processBuilder = new ProcessBuilder("compressor", "diagram.qrs"); processBuilder.directory(folder); processBuilder.start().waitFor(); diagramDirectory = new File(folderPath + "/diagram"); } File treeDirectory = new File(diagramDirectory.getPath() + "/tree"); Diagram diagram = converter.convertToJavaModel(treeDirectory); return diagram; } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } return null; } @ResponseBody @RequestMapping(value = "/submit", method = RequestMethod.POST) public SubmitResponse submit(@RequestBody SubmitRequest request) { final String taskId = request.getId(); JavaModelConverter javaModelConverter = new JavaModelConverter(); String uuidStr = String.valueOf(javaModelConverter.convertToXmlSave(request.getDiagram(), resourceLoader, taskId)); try { Resource resource = resourceLoader.getResource("tasks/" + request.getId() + "/solutions/" + uuidStr); File folder = resource.getFile(); ProcessBuilder compressorProcBuilder = new ProcessBuilder("compressor", "diagram"); compressorProcBuilder.directory(folder); compressorProcBuilder.start().waitFor(); ProcessBuilder interpreterProcBuilder = new ProcessBuilder(checkerPath, "diagram.qrs"); interpreterProcBuilder.directory(folder); interpreterProcBuilder.start().waitFor(); Path trajectoryPath = resourceLoader.getResource("tasks/" + request.getId() + "/solutions/" + uuidStr + "/trajectories/diagram/_diagram").getFile().toPath(); Report report = parseReportFile(resourceLoader.getResource("tasks/" + request.getId() + "/solutions/" + uuidStr + "/reports/diagram/_diagram").getFile()); Trace trace = parseTrajectoryFile(trajectoryPath); //FileUtils.deleteDirectory(folder); return new SubmitResponse(report, trace); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } return null; } private Report parseReportFile(File file) { ObjectMapper mapper = new ObjectMapper(); try { List<ReportMessage> messages = mapper.readValue(file, List.class); return new Report(messages); } catch (IOException e) { e.printStackTrace(); } return null; } private Trace parseTrajectoryFile(Path file) { Trace trace = new Trace(); List<Point> points = new LinkedList<Point>(); Charset charset = Charset.forName("UTF-8"); try (BufferedReader reader = Files.newBufferedReader(file, charset)) { String line = null; while ((line = reader.readLine()) != null) { points.add(parseTrajectoryLine(line)); } } catch (IOException e) { e.printStackTrace(); } trace.setPoints(points); return trace; } private Point parseTrajectoryLine(String line) { String parts[] = line.split(" "); return new Point(Double.valueOf(parts[2]), Double.valueOf(parts[3]), Double.valueOf(parts[4]), Double.valueOf(parts[1])); } private static final String checkerPath = System.getProperty("user.home") + "/qreal/bin/debug/check-solution.sh"; }
package com.notlob.jgrid.model; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.eclipse.swt.graphics.GC; import com.notlob.jgrid.Grid; import com.notlob.jgrid.Grid.GroupRenderStyle; import com.notlob.jgrid.model.filtering.FilterModel; import com.notlob.jgrid.providers.IGridContentProvider; import com.notlob.jgrid.providers.IGridLabelProvider; import com.notlob.jgrid.styles.CellStyle; import com.notlob.jgrid.styles.StyleRegistry; import com.notlob.jgrid.util.ResourceManager; /** * * * NOTE: This is an internal class not to be manipulated by client code. * * @author Stef */ public class GridModel<T> { private final Grid<T> grid; // Visible columns and rows. private final List<Row<T>> rows; private final List<Column> columns; // All column definitions. private final List<Column> allColumns; // Rows which have been filtered out - they are not ordered. private final List<Row<T>> hiddenRows; // All Rows (including hidden), keyed by domain element. private final Map<T, Row<T>> rowsByElement; // Visible column headers, pinned rows, etc. private final List<Row<T>> columnHeaderRows; // Pinned columns. private final List<Column> pinnedColumns; // If we're grouping data by particular column(s). private final List<Column> groupByColumns; // A column where row numbers are rendered. private final Column rowNumberColumn; // A column where groups can be selected. private final Column groupSelectorColumn; // The column headers are represented by this row. private final Row<T> columnHeaderRow; // Selection model (also Row has a selected property). private final SelectionModel<T> selectionModel; // The sort model. private final SortModel<T> sortModel; // The filter model. private final FilterModel<T> filterModel; // Visible styling model. private final StyleRegistry<T> styleRegistry; // Show/hide the row numbers. private boolean showRowNumbers = false; // Show/hide the group selector column. private boolean showGroupSelector = false; // Show/hide the column headers. private boolean showColumnHeaders = true; // Are we rendering groups in columns or in-line? private GroupRenderStyle groupRenderStyle = GroupRenderStyle.INLINE; // These external listeners are notified whenever something changes. private final List<IModelListener<T>> listeners; // Providers to get / format data, images, tool-tips, etc. private IGridContentProvider<T> contentProvider; private IGridLabelProvider<T> labelProvider; // Used in row height calculations. private final ResourceManager resourceManager; private final GC gc; // A reference count which, if greater than zero means the grid will stop redrawing, recalculating scrollbars/viewport, // and stop firing rowCount-change notifications to any listeners. private int suppressedEvents = 0; // An internal listener so the grid can broker events to public listeners or react to internal changes. public interface IModelListener<T> { void modelChanged(); void selectionChanged(); void heightChanged(final int delta); void rowCountChanged(); void filtersChanged(); void elementsAdded(final Collection<T> elements); void elementsUpdated(final Collection<T> elements); void elementsRemoved(final Collection<T> elements); void columnResized(final Column column); void columnMoved(final Column column); void columnSorted(final Column column); void rowNumbersVisibilityChanged(final boolean visible); void groupSelectorVisibilityChanged(final boolean visible); } public GridModel(final Grid<T> grid, final ResourceManager resourceManager, final GC gc) { this.grid = grid; this.resourceManager = resourceManager; this.gc = gc; rows = new ArrayList<>(); rowsByElement = new LinkedHashMap<>(); hiddenRows = new ArrayList<>(); columns = new ArrayList<>(); allColumns = new ArrayList<>(); columnHeaderRows = new ArrayList<>(); pinnedColumns = new ArrayList<>(); groupByColumns = new ArrayList<>(); listeners = new ArrayList<>(); styleRegistry = new StyleRegistry<T>(grid); selectionModel = new SelectionModel<T>(this); sortModel = new SortModel<T>(this); filterModel = new FilterModel<T>(this); rowNumberColumn = new Column(null); columnHeaderRow = new Row<T>(null); groupSelectorColumn = new Column(null); groupSelectorColumn.setWidth(16); } public void enableEvents(final boolean enable) { if (enable) { suppressedEvents } else { suppressedEvents++; } if (suppressedEvents < 0) { throw new IllegalArgumentException("Suppressed event count already " + suppressedEvents); } else if (suppressedEvents == 0) { // Re-index the rows. reindex(); // If we're no-longer suppressing events then trigger a redraw. fireChangeEvent(); fireRowCountChangedEvent(); } } public boolean isEventsSuppressed() { return (suppressedEvents > 0); } public GroupRenderStyle getGroupRenderStyle() { return groupRenderStyle; } public void setGroupRenderStyle(final GroupRenderStyle groupRenderStyle) { this.groupRenderStyle = groupRenderStyle; } public StyleRegistry<T> getStyleRegistry() { return styleRegistry; } public SelectionModel<T> getSelectionModel() { return selectionModel; } public SortModel<T> getSortModel() { return sortModel; } public FilterModel<T> getFilterModel() { return filterModel; } public List<Column> getColumns() { return columns; } public List<Column> getAllColumns() { return allColumns; } public List<Column> getGroupByColumns() { return groupByColumns; } public Row<T> getColumnHeaderRow() { return columnHeaderRow; } public Column getRowNumberColumn() { return rowNumberColumn; } public Column getGroupSelectorColumn() { return groupSelectorColumn; } /** * Returns all of the visible elements in the grid. Not a performant method. */ public List<T> getElements() { // To ensure the elements are in visible sequence, do this. final List<T> elements = new ArrayList<>(rows.size()); for (final Row<T> row : rows) { elements.add(row.getElement()); } return elements; } public Collection<T> getSelection() { return selectionModel.getSelectedElements(); } /** * The number of visible or hidden rows. */ public int getDetailedRowCount(final boolean visible, final RowCountScope scope) { final Collection<Row<T>> rowsToCount = visible ? rows : hiddenRows; switch (scope) { case ALL: return rowsToCount.size(); case CHILDREN: int childCount = 0; for (final Row<T> row : rowsToCount) { if (!isParentRow(row)) { childCount++; } } return childCount; case PARENTS: int parentCount = 0; for (final Row<T> row : rowsToCount) { if (isParentRow(row)) { parentCount++; } } return parentCount; } return -1; } public List<Row<T>> getRows() { return rows; } public Collection<Row<T>> getHiddenRows() { return hiddenRows; } public Collection<Row<T>> getAllRows() { return rowsByElement.values(); } public List<Row<T>> getColumnHeaderRows() { return columnHeaderRows; } public List<Column> getPinnedColumns() { return pinnedColumns; } public Row<T> getRow(final T element) { return rowsByElement.get(element); } Map<T, Row<T>> getRowsByElement() { return rowsByElement; } public void setLabelProvider(final IGridLabelProvider<T> labelProvider) { this.labelProvider = labelProvider; } public void setContentProvider(final IGridContentProvider<T> contentProvider) { this.contentProvider = contentProvider; // The mandatory filter needs the contentprovider. clearFilters(); } public void clearFilters() { filterModel.clear(); } public IGridContentProvider<T> getContentProvider() { return contentProvider; } private void addColumn(final Column column) { // Check the columnId isn't already in use. for (final Column existing : columns) { if (column.getColumnId().equals(existing.getColumnId())) { throw new IllegalArgumentException(String.format("Duplicate column id %s", column.getColumnId())); } } column.setGrid(grid); allColumns.add(column); if (column.getSortDirection() != SortDirection.NONE) { getSortModel().sort(column, false, true, false); } } public void addColumns(final List<Column> columns) { final boolean anyWereVisible = !this.columns.isEmpty(); boolean anyNowVisible = false; for (final Column column : columns) { addColumn(column); anyNowVisible |= column.isVisible(); } rebuildVisibleColumns(); if (!anyWereVisible && anyNowVisible && showColumnHeaders) { // The first column should cause a row to be added for the column headers. This header row should be the first row in the header region. columnHeaderRows.add(0, columnHeaderRow); } fireChangeEvent(); } public void clearColumns() { removeColumns(allColumns); } private void removeColumn(final Column column) { sortModel.removeColumn(column); allColumns.remove(column); columns.remove(column); groupByColumns.remove(column); pinnedColumns.remove(column); } public void removeColumns(final List<Column> columns) { for (final Column column : new ArrayList<>(columns)) { removeColumn(column); } rebuildVisibleColumns(); if (this.columns.isEmpty() && !columnHeaderRows.isEmpty()) { columnHeaderRows.clear(); } fireChangeEvent(); } public void rebuildVisibleColumns() { columns.clear(); for (final Column column : allColumns) { if (column.isVisible()) { columns.add(column); } } } /** * If the insertBefore argument is null, the column is moved to the end of the grid. */ public void moveColumn(final Column columnToMove, final Column insertBefore) { // This check prevents dropping a column onto itself from causing the column to shuffle to the end of the grid. if (insertBefore != null || columns.indexOf(insertBefore) != -1) { // Move the column in the visible-only list of columns. int insertIndex = insertBefore == null ? -1 : columns.indexOf(insertBefore); int originalIndex = columns.indexOf(columnToMove); insertIndex += ((originalIndex < insertIndex) ? -1 : 0); columns.remove(columnToMove); if (insertIndex == -1) { columns.add(columnToMove); } else { columns.add(insertIndex, columnToMove); } // Move the column in the full list of columns. insertIndex = insertBefore == null ? -1 : allColumns.indexOf(insertBefore); originalIndex = allColumns.indexOf(columnToMove); insertIndex += ((originalIndex < insertIndex) ? -1 : 0); allColumns.remove(columnToMove); if (insertIndex == -1) { allColumns.add(columnToMove); } else { allColumns.add(insertIndex, columnToMove); } // Cause the grid to repaint and recalculate the scrollbars - because the // v-scroll amount may need updating. fireChangeEvent(); fireColumnMovedEvent(columnToMove); } } public Column getColumnById(final String columnId) { for (final Column column : allColumns) { if (column.getColumnId().equalsIgnoreCase(columnId)) { return column; } } return null; } /** * Returns the rows which are visible after the operation. */ public Collection<Row<T>> addElements(final Collection<T> elements) { int heightDelta = 0; final Collection<Row<T>> rowsShown = new ArrayList<Row<T>>(); for (final T element : elements) { // Add a row for the element. final Row<T> row = new Row<T>(element); row.setHeight(labelProvider.getDefaultRowHeight(element)); if (addRow(row)) { heightDelta += getRowHeight(row); rowsShown.add(row); } } // Re-seed the row-indexes if there's been any move or show/hiding. reindex(); if (heightDelta != 0) { fireHeightChangeEvent(heightDelta); } fireElementsAddedEvent(elements); fireRowCountChangedEvent(); return rowsShown; } private boolean addRow(final Row<T> row) { // Cache the row by it's domain element. rowsByElement.put(row.getElement(), row); // Check the filter model. if (filterModel.match(row)) { // Make the row visible. showRow(row); return true; } else { hideRow(row); } return false; } public void removeElements(final Collection<T> elements) { int heightDelta = 0; int lastSelectedIndex = -1; boolean selectionChanged = false; for (final T element : elements) { final Row<T> row = rowsByElement.get(element); heightDelta -= getRowHeight(row); rows.remove(row); hiddenRows.remove(row); rowsByElement.remove(element); if (row.isSelected()) { selectionChanged |= selectionModel.removeRow(row); lastSelectedIndex = Math.max(lastSelectedIndex, row.getRowIndex()); } if (row.isPinned()) { columnHeaderRows.remove(row); } } // If there WAS a selection and now there is NONE then select the row or group AFTER the last // previously selected row or group. if (selectionModel.isSelectNextOnRemove() && (lastSelectedIndex != -1) && (selectionModel.getSelectedElements().isEmpty())) { final int nextIndex = lastSelectedIndex - elements.size() + 1; if ((nextIndex >= 0) && (nextIndex <= (rows.size()) && !rows.isEmpty())) { final Row<T> row = rows.get(Math.min(nextIndex, rows.size() - 1)); final List<Row<T>> rowsToSelect = isGroupRow(row) ? getWholeGroup(row) : Collections.singletonList(row); selectionModel.setSelectedRows(rowsToSelect); } } // Reseed the row-indexes if there's been any move or show/hiding. reindex(); if (heightDelta != 0) { fireHeightChangeEvent(heightDelta); } fireElementsRemovedEvent(elements); fireRowCountChangedEvent(); if (selectionChanged) { fireSelectionChangedEvent(); } } /** * Returns the rows which are visible after the operation. */ public Collection<Row<T>> updateElements(final Collection<T> elements) { int heightDelta = 0; final Collection<Row<T>> rowsShown = new ArrayList<Row<T>>(); for (T element : elements) { final Row<T> row = rowsByElement.get(element); if (row != null) { // Should the row be shown/hidden? final boolean visible = filterModel.match(row); if (visible) { rowsShown.add(row); } if (visible && row.isVisible()) { // Should the row move? final int expectedIndex = Math.abs(sortModel.getSortedRowIndex(row)); final int actualIndex = row.getRowIndex(); if (expectedIndex != actualIndex) { // Move the row to the correct position. rows.remove(row); final int newExpectedIndex = Math.abs(sortModel.getSortedRowIndex(row)); rows.add(newExpectedIndex, row); row.setRowIndex(newExpectedIndex); // If this was a group row that has moved, bring all the children with it. if (isParentRow(row)) { moveVisibleChildren(row); } } // Check if the row's height is accurate. heightDelta += getUpdatedRowHeightDelta(row); } else if (visible && !row.isVisible()) { // Reveal the row. showRow(row); heightDelta += getRowHeight(row); // If it's a parent, check its kiddies. if (isParentElement(row.getElement())) { heightDelta += childChildVisibility(row); } } else if (!visible && row.isVisible()) { // Hide the row. hideRow(row); heightDelta -= getRowHeight(row); // If it's a parent, check the sprogs. if (isParentElement(row.getElement())) { heightDelta += childChildVisibility(row); } } } } // Reseed the row-indexes if there's been any move or show/hiding. reindex(); // If the height of the rows has changed, adjust the grid's scroll-bars. if (heightDelta != 0) { fireHeightChangeEvent(heightDelta); fireElementsUpdatedEvent(elements); fireRowCountChangedEvent(); } else { fireElementsUpdatedEvent(elements); fireChangeEvent(); } return rowsShown; } /** * Remove child rows and re-insert them into the correct location. */ private void moveVisibleChildren(Row<T> row) { final List<Row<T>> children = getChildren(row); for (Row<T> child : children) { if (child.isVisible()) { rows.remove(child); final int newExpectedIndex = Math.abs(sortModel.getSortedRowIndex(child)); rows.add(newExpectedIndex, child); row.setRowIndex(newExpectedIndex); } } } /** * Get the cached height of a row, then force it to be recalculated (because value-changed may have caused styling to change). * Return the delta between the old and new heights. */ private int getUpdatedRowHeightDelta(final Row<T> row) { final int oldHeight = getRowHeight(row); row.setHeight(labelProvider.getDefaultRowHeight(row.getElement())); final int newHeight = getRowHeight(row); return newHeight - oldHeight; } /** * Check the visibility of all the child rows - and show/hide as appropriate. * * The change in total row heights is returned. */ private int childChildVisibility(final Row<T> parentRow) { int heightDelta = 0; final List<Row<T>> children = getChildren(parentRow); for (Row<T> childRow : children) { final boolean childShouldBeVisible = filterModel.match(childRow); if (!childRow.isVisible() && childShouldBeVisible) { showRow(childRow); heightDelta += getRowHeight(childRow); } else if (childRow.isVisible() && !childShouldBeVisible) { hideRow(childRow); heightDelta -= getRowHeight(childRow); } } return heightDelta; } public void reindex() { if (!isEventsSuppressed()) { int rowIndex = 0; for (Row<T> row : rows) { row.setRowIndex(rowIndex++); if (rowIndex == 1) { row.setAlternateBackground(false); } else { row.setAlternateBackground(labelProvider.shouldAlternateBackground(rows.get(rowIndex-2), row)); } } } } public void clearElements() { // Clear all selections. selectionModel.clear(false); // Clear rows. rows.clear(); hiddenRows.clear(); rowsByElement.clear(); fireChangeEvent(); } public void showRow(final Row<T> row) { final int insertIndex = sortModel.getSortedRowIndex(row); if (insertIndex >= 0) { rows.add(insertIndex, row); row.setRowIndex(insertIndex); } else { rows.add(row); row.setRowIndex(rows.size()-1); } row.setVisible(true); hiddenRows.remove(row); } public void hideRow(final Row<T> row) { rows.remove(row); selectionModel.removeRow(row); hiddenRows.add(row); row.setVisible(false); row.setRowIndex(-1); } public void groupBy(final List<Column> columns) { groupByColumns.addAll(columns); // Hide the columns. for (final Column column : columns) { column.setVisible(false); } rebuildVisibleColumns(); fireChangeEvent(); } public void ungroupBy(final List<Column> columns) { // Reveal the column again. for (Column column : columns) { column.setVisible(true); } groupByColumns.removeAll(columns); rebuildVisibleColumns(); fireChangeEvent(); } public void ungroupAll() { // Reveal the column again. for (final Column column : groupByColumns) { column.setVisible(true); } rebuildVisibleColumns(); // Rebuild the model's groups groupByColumns.clear(); fireChangeEvent(); } public void addListener(final IModelListener<T> listener) { listeners.add(listener); } public void removeListener(final IModelListener<T> listener) { listeners.remove(listener); } /** * Causes the grid to rebuild the viewport and scrollbars, redraw, then notify clients. */ public void fireChangeEvent() { for (final IModelListener<T> listener : listeners) { listener.modelChanged(); } } /** * Causes the grid to resize the vertical scroll bar and redraw. */ public void fireHeightChangeEvent(final int delta) { for (final IModelListener<T> listener : listeners) { listener.heightChanged(delta); } } /** * Causes the grid to notify clients the rows, or filtered row counts *may* have changed. */ public void fireRowCountChangedEvent() { for (final IModelListener<T> listener : listeners) { listener.rowCountChanged(); } } public void fireElementsAddedEvent(final Collection<T> elements) { for (final IModelListener<T> listener : listeners) { listener.elementsAdded(elements); } } public void fireElementsUpdatedEvent(final Collection<T> elements) { for (final IModelListener<T> listener : listeners) { listener.elementsUpdated(elements); } } public void fireElementsRemovedEvent(final Collection<T> elements) { for (final IModelListener<T> listener : listeners) { listener.elementsRemoved(elements); } } public void fireSelectionChangedEvent() { for (final IModelListener<T> listener : listeners) { listener.selectionChanged(); } } public void fireFiltersChangedEvent() { for (final IModelListener<T> listener : listeners) { listener.filtersChanged(); } } public void fireColumnMovedEvent(Column column) { for (final IModelListener<T> listener : listeners) { listener.columnMoved(column); } } public void fireColumnResizedEvent(Column column) { for (final IModelListener<T> listener : listeners) { listener.columnResized(column); } } public void fireColumnSortedEvent(Column column) { for (final IModelListener<T> listener : listeners) { listener.columnSorted(column); } } public void fireRowNumbersVisibilityChanged(final boolean visible) { for (final IModelListener<T> listener : listeners) { listener.rowNumbersVisibilityChanged(visible); } } public void fireGroupSelectorVisibilityChanged(final boolean visible) { for (final IModelListener<T> listener : listeners) { listener.groupSelectorVisibilityChanged(visible); } } public boolean isShowRowNumbers() { return showRowNumbers; } public void setShowRowNumbers(final boolean showRowNumbers) { this.showRowNumbers = showRowNumbers; fireChangeEvent(); fireRowNumbersVisibilityChanged(showRowNumbers); } public boolean isShowGroupSelector() { return showGroupSelector; } public void setShowGroupSelector(final boolean showGroupSelector) { this.showGroupSelector = showGroupSelector; fireChangeEvent(); fireGroupSelectorVisibilityChanged(showGroupSelector); } public boolean isShowColumnHeaders() { return showColumnHeaders; } public void setShowColumnHeaders(final boolean showColumnHeaders) { this.showColumnHeaders = showColumnHeaders; if (showColumnHeaders && !columnHeaderRows.contains(columnHeaderRow)) { // Add the column headers if required. columnHeaderRows.add(0, columnHeaderRow); } else if (!showColumnHeaders && columnHeaderRows.contains(columnHeaderRow)) { // Remove the column headers if required. columnHeaderRows.remove(columnHeaderRow); } fireChangeEvent(); } public void pinColumn(final Column column) { if (!pinnedColumns.contains(column)) { pinnedColumns.add(column); } column.setPinned(true); fireChangeEvent(); } public void unpinColumn(final Column column) { column.setPinned(false); pinnedColumns.remove(column); fireChangeEvent(); } public boolean isHeaderRow(final Row<T> row) { return columnHeaderRows.contains(row); } public int getRowHeight(final Row<T> row) { final CellStyle cellStyle = (row == columnHeaderRow) ? styleRegistry.getHeaderStyle() : styleRegistry.getDefaultStyle(); return row.getHeight(resourceManager, gc, cellStyle); } /** * Indicates if the row is in a group. Either if it has a parent, or if it has children (or could have children). */ public boolean isGroupRow(final Row<T> row) { if (row.getElement() != null) { // The row has a parent. if (contentProvider.getParent(row.getElement()) != null) { return true; } // The row has (or could have) children. if (isParentRow(row)) { return true; } } return false; } /** * If the row has a child list (even if it's empty) it's a parent row. */ public boolean isParentRow(final Row<T> row) { return isParentElement(row.getElement()); } /** * If the row has a child list (even if it's empty) it's a parent row. */ public boolean isParentElement(final T element) { return ((element != null) && (contentProvider.getChildren(element) != null)); } public boolean isChildElement(final T element) { return (contentProvider.getParent(element) != null); } public T getParentElement(final T element) { return contentProvider.getParent(element); } /** * Return the row's parent, or the row itself if it has none. */ public T getParentOrOwnElement(final Row<T> row) { final T parent = getContentProvider().getParent(row.getElement()); return parent == null ? row.getElement() : parent; } public boolean isSameGroup(final Row<T> row1, final Row<T> row2) { return (isGroupRow(row1) && isGroupRow(row2) && (getParentOrOwnElement(row1) == getParentOrOwnElement(row2))); } /** * If the row is in a group return the entire group. Only the immediate group or below is returned. * * Parent groups are not included. */ public List<Row<T>> getWholeGroup(final Row<T> row) { final List<Row<T>> group = new ArrayList<>(); final T parentElement = contentProvider.getParent(row.getElement()); final List<T> childElements = contentProvider.getChildren(row.getElement()); if (parentElement != null) { // If this row has a parent. Include all the parent's children/grand-children. final Row<T> parentRow = rowsByElement.get(parentElement); group.addAll(getAllChildren(parentRow)); } else if (childElements != null) { // If this row has any children, ensure they (and their grand-children are included. group.add(row); for (final Row<T> childRow : getChildren(row)) { if (childRow != null) { group.addAll(getAllChildren(childRow)); } } } return group; } /** * Return the row and all children and grandchildren for this row. */ private List<Row<T>> getAllChildren(final Row<T> row) { final List<Row<T>> group = new ArrayList<>(); group.add(row); for (final Row<T> childRow : getChildren(row)) { if (childRow != null) { group.addAll(getAllChildren(childRow)); } } return group; } /** * Return immediate children from this row. */ private List<Row<T>> getChildren(final Row<T> row) { final List<Row<T>> children = new ArrayList<>(); final List<T> childElements = contentProvider.getChildren(row.getElement()); if (childElements != null) { for (final T childElement : childElements) { children.add(rowsByElement.get(childElement)); } } return children; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(String.format("%s\n", this.getClass().getSimpleName())); sb.append(String.format("Show Row Numbers: %s\n", showRowNumbers)); sb.append(String.format("Rows: %s (%s selected)\n", rowsByElement.size(), selectionModel.getSelectedElements().size())); sb.append(String.format("Columns (%s total %s shown)\n", allColumns.size(), columns.size())); for (final Column column : allColumns) { sb.append(String.format("\t%s\n", column)); } sb.append(String.format("Grouping By\n")); if (groupByColumns.isEmpty()) { sb.append("\t(none)\n"); } else { for (final Column column : groupByColumns) { sb.append(String.format("\t%s\n", column.getColumnId())); } } return sb.toString(); } public void pinRows(final List<Row<T>> rows) { for (final Row<T> row : rows) { row.setPinned(true); columnHeaderRows.add(row); } fireChangeEvent(); } }
package org.rdswitchboard.tests.performance.dynamo.db; import java.util.HashMap; import java.util.Map; import com.amazonaws.auth.InstanceProfileCredentialsProvider; import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; public class App { private static final int TEST_ITEMS = 1000; public static void main(String[] args) { App app = new App(); app._main(args); } private void _main(String[] args) { AmazonDynamoDB dynamo = new AmazonDynamoDBClient(new InstanceProfileCredentialsProvider()); dynamo.setRegion(Region.getRegion(Regions.US_WEST_2)); //DynamoDBMapper mapper = new DynamoDBMapper(dynamo); testBenchmark(TEST_ITEMS); testSaveDb(TEST_ITEMS, dynamo); testLoadDb(TEST_ITEMS, dynamo); testDeleteDb(TEST_ITEMS, dynamo); } private void testBenchmark(int testN) { long startTime = System.currentTimeMillis(); for (int n = 0; n < testN; ++n) { new Record(n); } long estimatedTime = System.currentTimeMillis() - startTime; System.out.println("Created " + testN + " records over " + estimatedTime + " ms. That is " + (double) estimatedTime / (double) testN + " ms per record."); } private void testSaveDb(int testN, AmazonDynamoDB dynamo) { long startTime = System.currentTimeMillis(); for (int n = 0; n < testN; ++n) { Record r = new Record(n); r.save(dynamo); } long estimatedTime = System.currentTimeMillis() - startTime; System.out.println("Saved " + testN + " records over " + estimatedTime + " ms. That is " + (double) estimatedTime / (double) testN + " ms per record."); } private void testLoadDb(int testN, AmazonDynamoDB dynamo) { long startTime = System.currentTimeMillis(); for (int n = 0; n < testN; ++n) { Record.load(dynamo, n); } long estimatedTime = System.currentTimeMillis() - startTime; System.out.println("Loaded " + testN + " records over " + estimatedTime + " ms. That is " + (double) estimatedTime / (double) testN + " ms per record."); } private void testDeleteDb(int testN, AmazonDynamoDB dynamo) { long startTime = System.currentTimeMillis(); for (int n = 0; n < testN; ++n) { Record.delete(dynamo, n); } long estimatedTime = System.currentTimeMillis() - startTime; System.out.println("Loaded " + testN + " records over " + estimatedTime + " ms. That is " + (double) estimatedTime / (double) testN + " ms per record."); } }
/** * Package for calculate task. * * @author Nikita Zenkin (mailto:nji1@mail.ru) * @version $Id$ * @since 0.1 */ package ru.job4j; /** * Class Calculate solution for part 001 lesson 1. * @author nzenkin * @since 13.05.2017 */ class Calculate {
package ru.job4j; /** *Class Calculate the solution of the task chapter 001 section 1 task 1.1; *@author Prokopov Artem *@since 06.03.2017 *@version 1.0 */ public class Calculate { /** *Main method to output message "Hello World" to the consol; *@param arg - arg; */ public static void main(String[] args) { System.out.println("Hello world."); } }
package water.fvec; import com.google.common.base.Charsets; import water.AutoBuffer; import water.Futures; import water.H2O; import water.MemoryManager; import water.parser.BufferedString; import water.util.PrettyPrint; import water.util.UnsafeUtils; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.NoSuchElementException; // An uncompressed chunk of data, supporting an append operation public class NewChunk extends Chunk { public final int _cidx; // We can record the following (mixed) data types: // 1- doubles, in _ds including NaN for NA & 0; _ls==_xs==null // 2- scaled decimals from parsing, in _ls & _xs; _ds==null // 3- zero: requires _ls==0 && _xs==0 // 4- NA: _ls==Long.MAX_VALUE && _xs==Integer.MIN_VALUE || _ds=NaN // 5- Categorical: _xs==(Integer.MIN_VALUE+1) && _ds==null // 6- Str: _ss holds appended string bytes (with trailing 0), _is[] holds offsets into _ss[] // Chunk._len is the count of elements appended // Sparse: if _sparseLen != _len, then _ls/_ds are compressed to non-zero's only, // and _xs is the row number. Still _len is count of elements including // zeros, and _sparseLen is count of non-zeros. public transient long _ls[]; // Mantissa public transient int _xs[]; // Exponent, or if _ls==0, NA or Categorical or Rows public transient int _id[]; // Indices (row numbers) of stored values, used for sparse public transient double _ds[]; // Doubles, for inflating via doubles public transient byte _ss[]; // Bytes of appended strings, including trailing 0 public transient int _is[]; // _is[] index of strings - holds offsets into _ss[]. _is[i] == -1 means NA/sparse long [] alloc_mantissa(int l) { return _ls = MemoryManager.malloc8(l); } int [] alloc_exponent(int l) { return _xs = MemoryManager.malloc4(l); } int [] alloc_indices(int l) { return _id = MemoryManager.malloc4(l); } double[] alloc_doubles(int l) { return _ds = MemoryManager.malloc8d(l); } int [] alloc_str_indices(int l) { return _is = MemoryManager.malloc4(l); } final protected long [] mantissa() { return _ls; } final protected int [] indices() { return _id; } final protected double[] doubles() { return _ds; } @Override public boolean isSparseZero() { return sparseZero(); } public boolean _sparseNA = false; @Override public boolean isSparseNA() {return sparseNA();} void setSparseNA() {_sparseNA = true;} public int _sslen; // Next offset into _ss for placing next String public int _sparseLen; int set_sparseLen(int l) { return this._sparseLen = l; } @Override public int sparseLenZero() { return _sparseNA ? _len : _sparseLen;} @Override public int sparseLenNA() { return _sparseNA ? _sparseLen : _len; } private int _naCnt=-1; // Count of NA's appended protected int naCnt() { return _naCnt; } // Count of NA's appended private int _catCnt; // Count of Categorical's appended private int _strCnt; // Count of string's appended private int _nzCnt; // Count of non-zero's appended private int _uuidCnt; // Count of UUIDs public int _timCnt = 0; protected static final int MIN_SPARSE_RATIO = 32; private int _sparseRatio = MIN_SPARSE_RATIO; public boolean _isAllASCII = true; //For cat/string col, are all characters in chunk ASCII? public NewChunk( Vec vec, int cidx ) { _vec = vec; _cidx = cidx; } public NewChunk( Vec vec, int cidx, boolean sparse ) { _vec = vec; _cidx = cidx; if(sparse) { _ls = new long[128]; _xs = new int[128]; _id = new int[128]; } } public NewChunk(double [] ds) { _cidx = -1; _vec = null; setDoubles(ds); } public NewChunk( Vec vec, int cidx, long[] mantissa, int[] exponent, int[] indices, double[] doubles) { _vec = vec; _cidx = cidx; _ls = mantissa; _xs = exponent; _id = indices; _ds = doubles; if (_ls != null && _sparseLen==0) set_sparseLen(set_len(_ls.length)); if (_xs != null && _sparseLen==0) set_sparseLen(set_len(_xs.length)); if (_id != null && _sparseLen==0) set_sparseLen(set_len(_id.length)); if (_ds != null && _sparseLen==0) set_sparseLen(set_len(_ds.length)); } // Constructor used when inflating a Chunk. public NewChunk( Chunk c ) { this(c._vec, c.cidx()); _start = c._start; } // Pre-sized newchunks. public NewChunk( Vec vec, int cidx, int len ) { this(vec,cidx); _ds = new double[len]; Arrays.fill(_ds, Double.NaN); set_sparseLen(set_len(len)); } public NewChunk setSparseRatio(int s) { _sparseRatio = s; return this; } public void setDoubles(double[] ds) { _ds = ds; _sparseLen = _len = ds.length; } public void set_vec(Vec vec) { _vec = vec; } public final class Value { int _gId; // row number in dense (ie counting zeros) int _lId; // local array index of this value, equal to _gId if dense public Value(int lid, int gid){_lId = lid; _gId = gid;} public final int rowId0(){return _gId;} public void add2Chunk(NewChunk c){add2Chunk_impl(c,_lId);} } private transient BufferedString _bfstr = new BufferedString(); private void add2Chunk_impl(NewChunk c, int i){ if (_ds == null && _ss == null) { if (isNA2(i)) c.addNA(); else c.addNum(_ls[i],_xs[i]); } else { if (_ls != null) { c.addUUID(_ls[i], Double.doubleToRawLongBits(_ds[i])); } else if (_ss != null) { int sidx = _is[i]; int nextNotNAIdx = i+1; // Find next not-NA value (_is[idx] != -1) while (nextNotNAIdx < _is.length && _is[nextNotNAIdx] == -1) nextNotNAIdx++; int slen = nextNotNAIdx < _is.length ? _is[nextNotNAIdx]-sidx : _sslen - sidx; // null-BufferedString represents NA value BufferedString bStr = sidx == -1 ? null : _bfstr.set(_ss, sidx, slen); c.addStr(bStr); } else c.addNum(_ds[i]); } } public void add2Chunk(NewChunk c, int i){ if(!isSparseNA() && !isSparseZero()) add2Chunk_impl(c,i); else { int j = Arrays.binarySearch(_id,i); if(j >= 0) add2Chunk_impl(c,j); else if(isSparseNA()) c.addNA(); else c.addNum(0,0); } } public Iterator<Value> values(){ return values(0,_len);} public Iterator<Value> values(int fromIdx, int toIdx){ final int lId, gId; final int to = Math.min(toIdx, _len); if(_id != null){ int x = Arrays.binarySearch(_id,0, _sparseLen,fromIdx); if(x < 0) x = -x -1; lId = x; gId = x == _sparseLen ? _len :_id[x]; } else lId = gId = fromIdx; final Value v = new Value(lId,gId); final Value next = new Value(lId,gId); return new Iterator<Value>(){ @Override public final boolean hasNext(){return next._gId < to;} @Override public final Value next(){ if(!hasNext())throw new NoSuchElementException(); v._gId = next._gId; v._lId = next._lId; next._lId++; if(_id != null) next._gId = next._lId < _sparseLen ?_id[next._lId]: _len; else next._gId++; return v; } @Override public void remove() {throw new UnsupportedOperationException();} }; } // Heuristic to decide the basic type of a column byte type() { if( _naCnt == -1 ) { // No rollups yet? int nas=0, es=0, nzs=0, ss=0; if( _ds != null && _ls != null ) { // UUID? for(int i = 0; i< _sparseLen; i++ ) if( _xs != null && _xs[i]==Integer.MIN_VALUE ) nas++; else if( _ds[i] !=0 || _ls[i] != 0 ) nzs++; _uuidCnt = _len -nas; } else if( _ds != null ) { // Doubles? assert _xs==null; for(int i = 0; i < _sparseLen; ++i) { if( Double.isNaN(_ds[i]) ) nas++; else if( _ds[i]!=0 ) nzs++; } } else { if( _ls != null && _ls.length > 0) // Longs and categoricals? for(int i = 0; i< _sparseLen; i++ ) if( isNA2(i) ) nas++; else { if( isCategorical2(i) ) es++; if( _ls[i] != 0 ) nzs++; } if( _is != null ) // Strings for(int i = 0; i< _sparseLen; i++ ) if( isNA2(i) ) nas++; else ss++; } if (_sparseNA) nas += (_len - _sparseLen); _nzCnt=nzs; _catCnt =es; _naCnt=nas; _strCnt = ss; } // Now run heuristic for type if(_naCnt == _len) // All NAs ==> NA Chunk return Vec.T_BAD; if(_strCnt > 0) return Vec.T_STR; if(_catCnt > 0 && _catCnt + _naCnt == _len) return Vec.T_CAT; // All are Strings+NAs ==> Categorical Chunk // UUIDs? if( _uuidCnt > 0 ) return Vec.T_UUID; // Larger of time & numbers int nums = _len -_naCnt-_timCnt; return _timCnt >= nums ? Vec.T_TIME : Vec.T_NUM; } //what about sparse reps? protected final boolean isNA2(int idx) { if (isUUID()) return _ls[idx]==C16Chunk._LO_NA && Double.doubleToRawLongBits(_ds[idx])==C16Chunk._HI_NA; if (isString()) return _is[idx] == -1; return (_ds == null) ? (_ls[idx] == Long.MAX_VALUE && _xs[idx] == Integer.MIN_VALUE) : Double.isNaN(_ds[idx]); } protected final boolean isCategorical2(int idx) { return _xs!=null && _xs[idx]==Integer.MIN_VALUE+1; } protected final boolean isCategorical(int idx) { if(_id == null)return isCategorical2(idx); int j = Arrays.binarySearch(_id,0, _sparseLen,idx); return j>=0 && isCategorical2(j); } public void addCategorical(int e) {append2(e,Integer.MIN_VALUE+1);} public void addNA() { if( isUUID() ) addUUID(C16Chunk._LO_NA, C16Chunk._HI_NA); else if( isString() ) addStr(null); else if (_ds != null) addNum(Double.NaN); else append2(Long.MAX_VALUE,Integer.MIN_VALUE); } public void addNum (long val, int exp) { if( isUUID() || isString() ) addNA(); else if(_ds != null) { assert _ls == null; addNum(val*PrettyPrint.pow10(exp)); } else { if( val == 0 ) exp = 0;// Canonicalize zero long t; // Remove extra scaling while( exp < 0 && exp > -9999999 && (t=val/10)*10==val ) { val=t; exp++; } append2(val,exp); } } // Fast-path append double data public void addNum(double d) { if( isUUID() || isString() ) { addNA(); return; } boolean predicate = _sparseNA ? !Double.isNaN(d) : d != 0; if(_id == null || predicate) { if(_ls != null)switch_to_doubles(); //if ds not big enough if( _ds == null || _sparseLen >= _ds.length ) { append2slowd(); // call addNum again since append2slowd might have flipped to sparse addNum(d); assert _sparseLen <= _len; return; } if(_id != null)_id[_sparseLen] = _len; _ds[_sparseLen] = d; set_sparseLen(_sparseLen + 1); } set_len(_len + 1); assert _sparseLen <= _len; } private void append_ss(String str) { byte[] bytes = str == null ? new byte[0] : str.getBytes(Charsets.UTF_8); // Allocate memory if necessary if (_ss == null) _ss = MemoryManager.malloc1((bytes.length+1) * 4); while (_ss.length < (_sslen + bytes.length+1)) _ss = MemoryManager.arrayCopyOf(_ss,_ss.length << 1); // Copy bytes to _ss for (byte b : bytes) _ss[_sslen++] = b; _ss[_sslen++] = (byte)0; // for trailing 0; } private void append_ss(BufferedString str) { int strlen = str.length(); int off = str.getOffset(); byte b[] = str.getBuffer(); if (_ss == null) { _ss = MemoryManager.malloc1((strlen + 1) * 4); } while (_ss.length < (_sslen + strlen + 1)) { _ss = MemoryManager.arrayCopyOf(_ss,_ss.length << 1); } for (int i = off; i < off+strlen; i++) _ss[_sslen++] = b[i]; _ss[_sslen++] = (byte)0; // for trailing 0; } // Append a string, store in _ss & _is public void addStr(Object str) { if(_id == null || str != null) { if(_is == null || _sparseLen >= _is.length) { append2slowstr(); addStr(str); assert _sparseLen <= _len; return; } if (str != null) { if(_id != null)_id[_sparseLen] = _len; _is[_sparseLen] = _sslen; set_sparseLen(_sparseLen + 1); if (str instanceof BufferedString) append_ss((BufferedString) str); else // this spares some callers from an unneeded conversion to BufferedString first append_ss((String) str); } else if (_id == null) { _is[_sparseLen] = CStrChunk.NA; set_sparseLen(_sparseLen + 1); } } set_len(_len + 1); assert _sparseLen <= _len; } // TODO: FIX isAllASCII test to actually inspect string contents public void addStr(Chunk c, long row) { if( c.isNA_abs(row) ) addNA(); else { addStr(c.atStr_abs(new BufferedString(), row)); _isAllASCII &= ((CStrChunk)c)._isAllASCII; } } public void addStr(Chunk c, int row) { if( c.isNA(row) ) addNA(); else { addStr(c.atStr(new BufferedString(), row)); _isAllASCII &= ((CStrChunk)c)._isAllASCII; } } // Append a UUID, stored in _ls & _ds public void addUUID( long lo, long hi ) { if( _ls==null || _ds== null || _sparseLen >= _ls.length ) append2slowUUID(); _ls[_sparseLen] = lo; _ds[_sparseLen] = Double.longBitsToDouble(hi); set_sparseLen(_sparseLen + 1); set_len(_len + 1); assert _sparseLen <= _len; } public void addUUID( Chunk c, long row ) { if( c.isNA_abs(row) ) addUUID(C16Chunk._LO_NA,C16Chunk._HI_NA); else addUUID(c.at16l_abs(row),c.at16h_abs(row)); } public void addUUID( Chunk c, int row ) { if( c.isNA(row) ) addUUID(C16Chunk._LO_NA,C16Chunk._HI_NA); else addUUID(c.at16l(row),c.at16h(row)); } public final boolean isUUID(){return _ls != null && _ds != null; } public final boolean isString(){return _is != null; } public final boolean sparseZero(){return _id != null && !_sparseNA;} public final boolean sparseNA() {return _id != null && _sparseNA;} public void addZeros(int n){ if(!sparseZero()) for(int i = 0; i < n; ++i)addNum(0,0); else set_len(_len + n); } public void addNAs(int n) { if(!sparseNA()) for (int i = 0; i <n; ++i)addNA(); else set_len(_len + n); } // Append all of 'nc' onto the current NewChunk. Kill nc. public void add( NewChunk nc ) { assert _cidx >= 0; assert _sparseLen <= _len; assert nc._sparseLen <= nc._len :"_sparseLen = " + nc._sparseLen + ", _len = " + nc._len; if( nc._len == 0 ) return; if(_len == 0){ _ls = nc._ls; nc._ls = null; _xs = nc._xs; nc._xs = null; _id = nc._id; nc._id = null; _ds = nc._ds; nc._ds = null; _is = nc._is; nc._is = null; _ss = nc._ss; nc._ss = null; set_sparseLen(nc._sparseLen); set_len(nc._len); return; } if(nc.sparseZero() != sparseZero() || nc.sparseNA() != sparseNA()){ // for now, just make it dense cancel_sparse(); nc.cancel_sparse(); } if( _ds != null ) throw H2O.fail(); while( _sparseLen + nc._sparseLen >= _xs.length ) _xs = MemoryManager.arrayCopyOf(_xs,_xs.length<<1); _ls = MemoryManager.arrayCopyOf(_ls,_xs.length); System.arraycopy(nc._ls,0,_ls, _sparseLen, nc._sparseLen); System.arraycopy(nc._xs,0,_xs, _sparseLen, nc._sparseLen); if(_id != null) { assert nc._id != null; _id = MemoryManager.arrayCopyOf(_id,_xs.length); System.arraycopy(nc._id,0,_id, _sparseLen, nc._sparseLen); for(int i = _sparseLen; i < _sparseLen + nc._sparseLen; ++i) _id[i] += _len; } else assert nc._id == null; set_sparseLen(_sparseLen + nc._sparseLen); set_len(_len + nc._len); nc._ls = null; nc._xs = null; nc._id = null; nc.set_sparseLen(nc.set_len(0)); assert _sparseLen <= _len; } // Fast-path append long data void append2( long l, int x ) { boolean predicate = _sparseNA ? (l != Long.MAX_VALUE || x != Integer.MIN_VALUE): l != 0; if(_id == null || predicate){ if(_ls == null || _sparseLen == _ls.length) { append2slow(); // again call append2 since calling append2slow might have changed things (eg might have switched to sparse and l could be 0) append2(l,x); return; } _ls[_sparseLen] = l; _xs[_sparseLen] = x; if(_id != null)_id[_sparseLen] = _len; set_sparseLen(_sparseLen + 1); } set_len(_len + 1); assert _sparseLen <= _len; } // Slow-path append data private void append2slowd() { assert _ls==null; if(_ds != null && _ds.length > 0){ if(_id == null) { // check for sparseness int nzs = 0; // assume one non-zero for the element currently being stored int nonnas = 0; for(double d:_ds) { if(d != 0)++nzs; if(!Double.isNaN(d))++nonnas; } if((nzs+1)*_sparseRatio < _len) { set_sparse(nzs,Compress.ZERO); assert _sparseLen == 0 || _sparseLen <= _ds.length:"_sparseLen = " + _sparseLen + ", _ds.length = " + _ds.length + ", nzs = " + nzs + ", len = " + _len; assert _id.length == _ds.length; assert _sparseLen <= _len; return; } else if((nonnas+1)*_sparseRatio < _len) { set_sparse(nonnas,Compress.NA); assert _sparseLen == 0 || _sparseLen <= _ds.length:"_sparseLen = " + _sparseLen + ", _ds.length = " + _ds.length + ", nonnas = " + nonnas + ", len = " + _len; assert _id.length == _ds.length; assert _sparseLen <= _len; return; } } else { // verify we're still sufficiently sparse if((_sparseRatio*(_sparseLen) >> 1) > _len) cancel_sparse(); else _id = MemoryManager.arrayCopyOf(_id, _sparseLen << 1); } _ds = MemoryManager.arrayCopyOf(_ds, _sparseLen << 1); } else { alloc_doubles(4); if (_id != null) alloc_indices(4); } assert _sparseLen == 0 || _ds.length > _sparseLen :"_ds.length = " + _ds.length + ", _sparseLen = " + _sparseLen; assert _id == null || _id.length == _ds.length; assert _sparseLen <= _len; } // Slow-path append data private void append2slowUUID() { if( _ds==null && _ls!=null ) { // This can happen for columns with all NAs and then a UUID _xs=null; alloc_doubles(_sparseLen); Arrays.fill(_ls,C16Chunk._LO_NA); Arrays.fill(_ds,Double.longBitsToDouble(C16Chunk._HI_NA)); } if( _ls != null && _ls.length > 0 ) { _ls = MemoryManager.arrayCopyOf(_ls, _sparseLen <<1); _ds = MemoryManager.arrayCopyOf(_ds, _sparseLen <<1); } else { alloc_mantissa(4); alloc_doubles(4); } assert _sparseLen == 0 || _ls.length > _sparseLen :"_ls.length = " + _ls.length + ", _len = " + _sparseLen; } // Slow-path append string private void append2slowstr() { // In case of all NAs and then a string, convert NAs to string NAs if (_xs != null) { _xs = null; _ls = null; alloc_str_indices(_sparseLen); Arrays.fill(_is,-1); } if(_is != null && _is.length > 0){ // Check for sparseness if(_id == null){ int nzs = 0; // assume one non-null for the element currently being stored for( int i:_is) if( i != -1 ) ++nzs; if( (nzs+1)*_sparseRatio < _len) set_sparse(nzs, Compress.ZERO); } else { if((_sparseRatio*(_sparseLen) >> 1) > _len) cancel_sparse(); else _id = MemoryManager.arrayCopyOf(_id,_sparseLen<<1); } _is = MemoryManager.arrayCopyOf(_is, _sparseLen<<1); /* initialize the memory extension with -1s */ for (int i = _sparseLen; i < _is.length; i++) _is[i] = -1; } else { _is = MemoryManager.malloc4 (4); /* initialize everything with -1s */ for (int i = 0; i < _is.length; i++) _is[i] = -1; if (sparseZero()||sparseNA()) alloc_indices(4); } assert _sparseLen == 0 || _is.length > _sparseLen:"_ls.length = " + _is.length + ", _len = " + _sparseLen; } // Slow-path append data private void append2slow( ) { // PUBDEV-2639 - don't die for many rows, few columns -> can be long chunks // if( _sparseLen > FileVec.DFLT_CHUNK_SIZE ) // throw new ArrayIndexOutOfBoundsException(_sparseLen); assert _ds==null; if(_ls != null && _ls.length > 0){ if(_id == null) { // check for sparseness int nzs = 0; int nonnas = 0; for(int i = 0; i < _ls.length; ++i) { if(_ls[i] != 0 || _xs[i] != 0)++nzs; if(_ls[i] != Long.MAX_VALUE || _xs[i] != Integer.MIN_VALUE) ++nonnas; } if((nzs+1)*_sparseRatio < _len) { set_sparse(nzs,Compress.ZERO); assert _sparseLen == 0 || _sparseLen <= _ls.length:"_sparseLen = " + _sparseLen + ", _ls.length = " + _ls.length + ", nzs = " + nzs + ", len = " + _len; assert _id.length == _ls.length; assert _sparseLen <= _len; return; } else if((nonnas+1)*_sparseRatio < _len) { set_sparse(nonnas,Compress.NA); assert _sparseLen == 0 || _sparseLen <= _ls.length:"_sparseLen = " + _sparseLen + ", _ls.length = " + _ls.length + ", nonnas = " + nonnas + ", len = " + _len; assert _id.length == _ls.length; assert _sparseLen <= _len; return; } } else { // verify we're still sufficiently sparse if((_sparseRatio*(_sparseLen) >> 1) > _len) cancel_sparse(); else _id = MemoryManager.arrayCopyOf(_id, _sparseLen <<1); } _ls = MemoryManager.arrayCopyOf(_ls, _sparseLen <<1); _xs = MemoryManager.arrayCopyOf(_xs, _sparseLen <<1); } else { alloc_mantissa(4); alloc_exponent(4); if (_id != null) alloc_indices(4); } assert _sparseLen == 0 || _sparseLen < _ls.length:"_sparseLen = " + _sparseLen + ", _ls.length = " + _ls.length; assert _id == null || _id.length == _ls.length; assert _sparseLen <= _len; } // Do any final actions on a completed NewVector. Mostly: compress it, and // do a DKV put on an appropriate Key. The original NewVector goes dead // (does not live on inside the K/V store). public Chunk new_close() { Chunk chk = compress(); if(_vec instanceof AppendableVec) ((AppendableVec)_vec).closeChunk(_cidx,chk._len); return chk; } public void close(Futures fs) { close(_cidx,fs); } protected void switch_to_doubles(){ assert _ds == null; double [] ds = MemoryManager.malloc8d(_sparseLen); for(int i = 0; i < _sparseLen; ++i) if(isNA2(i) || isCategorical2(i)) ds[i] = Double.NaN; else ds[i] = _ls[i]*PrettyPrint.pow10(_xs[i]); _ls = null; _xs = null; _ds = ds; } public enum Compress {ZERO, NA} //Sparsify. Compressible element can be 0 or NA. Store noncompressible elements in _ds OR _ls and _xs OR _is and // their row indices in _id. protected void set_sparse(int num_noncompressibles, Compress sparsity_type){ if( (sparsity_type == Compress.ZERO && isSparseNA()) || (sparsity_type == Compress.NA && isSparseZero()) ) cancel_sparse(); if (sparsity_type == Compress.NA) _sparseNA = true; if(_id != null &&_sparseLen == num_noncompressibles && _len != 0)return; if(_id != null) { // we have sparse representation but some compressible elements in it! // can happen when setting a noncompressible element to a compressible one on sparse chunk int[] id = MemoryManager.malloc4(num_noncompressibles); int j = 0; if (_ds != null) { double[] ds = MemoryManager.malloc8d(num_noncompressibles); for (int i = 0; i < _sparseLen; ++i) { if (!is_compressible(_ds[i])) { ds[j] = _ds[i]; id[j] = _id[i]; ++j; } } _ds = ds; } else if (_is != null) { int [] is = MemoryManager.malloc4(num_noncompressibles); for (int i = 0; i < _sparseLen; i++) { if (_is[i] != -1) { //same test for NA sparse and 0 sparse is[j] = _is[i]; id[j] = _id[i]; ++j; } } } else { long [] ls = MemoryManager.malloc8(num_noncompressibles); int [] xs = MemoryManager.malloc4(num_noncompressibles); for(int i = 0; i < _sparseLen; ++i){ if(!is_compressible(_ls[i], _xs[i])){ ls[j] = _ls[i]; xs[j] = _xs[i]; id[j] = _id[i]; ++j; } } _ls = ls; _xs = xs; } _id = id; assert j == num_noncompressibles; set_sparseLen(num_noncompressibles); return; } assert _sparseLen == _len :"_sparseLen = " + _sparseLen + ", _len = " + _len + ", num_noncompressibles = " + num_noncompressibles; int cs = 0; //number of compressibles if(_is != null) { assert num_noncompressibles <= _is.length; _id = MemoryManager.malloc4(_is.length); for (int i = 0; i < _sparseLen; i++) { if (_is[i] == -1) cs++; //same condition for NA and 0 else { _is[i-cs] = _is[i]; _id[i-cs] = i; } } } else if(_ds == null){ if (_len == 0) { _ls = new long[0]; _xs = new int[0]; _id = new int[0]; set_sparseLen(0); return; } else { assert num_noncompressibles <= _sparseLen; _id = alloc_indices(_ls.length); for (int i = 0; i < _sparseLen; ++i) { if (is_compressible(_ls[i], _xs[i])) ++cs; else { _ls[i - cs] = _ls[i]; _xs[i - cs] = _xs[i]; _id[i - cs] = i; } } } } else { assert num_noncompressibles <= _ds.length; _id = alloc_indices(_ds.length); for(int i = 0; i < _sparseLen; ++i){ if(is_compressible(_ds[i]))++cs; else { _ds[i-cs] = _ds[i]; _id[i-cs] = i; } } } assert cs == (_sparseLen - num_noncompressibles); assert (sparsity_type == Compress.NA) == _sparseNA; set_sparseLen(num_noncompressibles); } private boolean is_compressible(double d) { return _sparseNA ? Double.isNaN(d) : d == 0; } private boolean is_compressible(long l, int x) { return _sparseNA ? l == Long.MAX_VALUE && x == Integer.MIN_VALUE : l == 0 && x ==0; } public void cancel_sparse(){ if(_sparseLen != _len){ if(_is != null){ int [] is = MemoryManager.malloc4(_len); Arrays.fill(is, -1); for (int i = 0; i < _sparseLen; i++) is[_id[i]] = _is[i]; _is = is; } else if(_ds == null){ int [] xs = MemoryManager.malloc4(_len); long [] ls = MemoryManager.malloc8(_len); if (_sparseNA) { Arrays.fill(xs, Integer.MIN_VALUE); Arrays.fill(ls, Long.MAX_VALUE); } for(int i = 0; i < _sparseLen; ++i){ xs[_id[i]] = _xs[i]; ls[_id[i]] = _ls[i]; } _xs = xs; _ls = ls; } else { double [] ds = MemoryManager.malloc8d(_len); if (_sparseNA) Arrays.fill(ds, Double.NaN); for(int i = 0; i < _sparseLen; ++i) ds[_id[i]] = _ds[i]; _ds = ds; } set_sparseLen(_len); } _id = null; _sparseNA = false; } // Study this NewVector and determine an appropriate compression scheme. // Return the data so compressed. public Chunk compress() { Chunk res = compress2(); byte type = type(); assert _vec == null || // Various testing scenarios do not set a Vec type == _vec._type || // Equal types // Allow all-bad Chunks in any type of Vec type == Vec.T_BAD || // Specifically allow the NewChunk to be a numeric type (better be all // ints) and the selected Vec type an categorical - whose String mapping // may not be set yet. (type==Vec.T_NUM && _vec._type==Vec.T_CAT) || // Another one: numeric Chunk and Time Vec (which will turn into all longs/zeros/nans Chunks) (type==Vec.T_NUM && _vec._type == Vec.T_TIME && !res.hasFloat()) : "NewChunk has type "+Vec.TYPE_STR[type]+", but the Vec is of type "+_vec.get_type_str(); assert _len == res._len : "NewChunk has length "+_len+", compressed Chunk has "+res._len; // Force everything to null after compress to free up the memory. Seems // like a non-issue in the land of GC, but the NewChunk *should* be dead // after this, but might drag on. The arrays are large, and during a big // Parse there's lots and lots of them... so free early just in case a GC // happens before the drag-time on the NewChunk finishes. _id = null; _xs = null; _ds = null; _ls = null; _is = null; _ss = null; return res; } private static long leRange(long lemin, long lemax){ if(lemin < 0 && lemax >= (Long.MAX_VALUE + lemin)) return Long.MAX_VALUE; // if overflow return 64 as the max possible value long res = lemax - lemin; assert res >= 0; return res; } private Chunk compress2() { // Check for basic mode info: all missing or all strings or mixed stuff byte mode = type(); if( mode==Vec.T_BAD ) // ALL NAs, nothing to do return new C0DChunk(Double.NaN, _len); if( mode==Vec.T_STR ) return new CStrChunk(_sslen, _ss, _sparseLen, _len, _is, _isAllASCII); boolean rerun=false; if(mode == Vec.T_CAT) { for(int i = 0; i< _sparseLen; i++ ) if(isCategorical2(i)) _xs[i] = 0; else if(!isNA2(i)){ setNA_impl2(i); ++_naCnt; } // Smack any mismatched string/numbers } else if( mode == Vec.T_NUM ) { for(int i = 0; i< _sparseLen; i++ ) if(isCategorical2(i)) { setNA_impl2(i); rerun = true; } } if( rerun ) { _naCnt = -1; type(); } // Re-run rollups after dropping all numbers/categoricals boolean sparse = false; boolean na_sparse = false; // sparse? treat as sparse iff fraction of noncompressed elements is less than 1/MIN_SPARSE_RATIO if(_sparseRatio*(_naCnt + _nzCnt) < _len) { set_sparse(_naCnt + _nzCnt, Compress.ZERO); sparse = true; } else if(_sparseRatio*(_len - _naCnt) < _len){ set_sparse(_len - _naCnt, Compress.NA); na_sparse = true; } else if (_sparseLen != _len) cancel_sparse(); // If the data is UUIDs there's not much compression going on if( _ds != null && _ls != null ) return chunkUUID(); // cut out the easy all NaNs case; takes care of constant na_sparse if(_naCnt == _len) return new C0DChunk(Double.NaN,_len); // If the data was set8 as doubles, we do a quick check to see if it's // plain longs. If not, we give up and use doubles. if( _ds != null ) { int i; // check if we can flip to ints for (i=0; i < _sparseLen; ++i) if (!Double.isNaN(_ds[i]) && (double) (long) _ds[i] != _ds[i]) break; boolean isInteger = i == _sparseLen; boolean isConstant = !(sparse || na_sparse) || _sparseLen == 0; double constVal = 0; if (!(sparse || na_sparse)) { // check the values, sparse with some nonzeros can not be constant - has 0s and (at least 1) nonzero constVal = _ds[0]; for(int j = 1; j < _len; ++j) if(_ds[j] != constVal) { isConstant = false; break; } } if(isConstant) return isInteger? new C0LChunk((long)constVal, _len): new C0DChunk(constVal,_len); if(!isInteger) { if (sparse) return new CXDChunk(_len, 8, bufD(8)); else if (na_sparse) return new CNAXDChunk(_len, 8, bufD(8)); else return chunkD(); } // Else flip to longs _ls = new long[_ds.length]; _xs = new int [_ds.length]; double [] ds = _ds; _ds = null; final int naCnt = _naCnt; for(i=0; i< _sparseLen; i++ ) // Inject all doubles into longs if( Double.isNaN(ds[i]) )setNA_impl2(i); else _ls[i] = (long)ds[i]; // setNA_impl2 will set _naCnt to -1! // we already know what the naCnt is (it did not change!) so set it back to correct value _naCnt = naCnt; } // IF (_len > _sparseLen) THEN Sparse // Check for compressed *during appends*. Here we know: // - No specials; _xs[]==0. // - No floats; _ds==null // - NZ length in _sparseLen, actual length in _len. // - Huge ratio between _len and _sparseLen, and we do NOT want to inflate to // the larger size; we need to keep it all small all the time. // - Rows in _xs // Data in some fixed-point format, not doubles // See if we can sanely normalize all the data to the same fixed-point. int xmin = Integer.MAX_VALUE; // min exponent found boolean floatOverflow = false; double min = Double.POSITIVE_INFINITY; double max = Double.NEGATIVE_INFINITY; int p10iLength = PrettyPrint.powers10i.length; long llo=Long .MAX_VALUE, lhi=Long .MIN_VALUE; int xlo=Integer.MAX_VALUE, xhi=Integer.MIN_VALUE; for(int i = 0; i< _sparseLen; i++ ) { if( isNA2(i) ) continue; long l = _ls[i]; int x = _xs[i]; assert x != Integer.MIN_VALUE:"l = " + l + ", x = " + x; if( x==Integer.MIN_VALUE+1) x=0; // Replace categorical flag with no scaling assert l!=0 || x==0:"l == 0 while x = " + x + " ls = " + Arrays.toString(_ls); // Exponent of zero is always zero long t; // Remove extra scaling while( l!=0 && (t=l/10)*10==l ) { l=t; x++; } // Compute per-chunk min/max double d = l*PrettyPrint.pow10(x); if( d < min ) { min = d; llo=l; xlo=x; } if( d > max ) { max = d; lhi=l; xhi=x; } floatOverflow = l < Integer.MIN_VALUE+1 || l > Integer.MAX_VALUE; xmin = Math.min(xmin,x); } if(sparse){ // sparse? then compare vs implied 0s if( min > 0 ) { min = 0; llo=0; xlo=0; } if( max < 0 ) { max = 0; lhi=0; xhi=0; } xmin = Math.min(xmin,0); } // Constant column? if( _naCnt==0 && (min==max)) { if (llo == lhi && xlo == 0 && xhi == 0) return new C0LChunk(llo, _len); else if ((long)min == min) return new C0LChunk((long)min, _len); else return new C0DChunk(min, _len); } // Compute min & max, as scaled integers in the xmin scale. // Check for overflow along the way boolean overflow = ((xhi-xmin) >= p10iLength) || ((xlo-xmin) >= p10iLength); long lemax=0, lemin=0; if( !overflow ) { // Can at least get the power-of-10 without overflow long pow10 = PrettyPrint.pow10i(xhi-xmin); lemax = lhi*pow10; // Hacker's Delight, Section 2-13, checking overflow. // Note that the power-10 is always positive, so the test devolves this: if( (lemax/pow10) != lhi ) overflow = true; // Note that xlo might be > xmin; e.g. { 101e-49 , 1e-48}. long pow10lo = PrettyPrint.pow10i(xlo-xmin); lemin = llo*pow10lo; if( (lemin/pow10lo) != llo ) overflow = true; } // Boolean column? if (max == 1 && min == 0 && xmin == 0 && !overflow) { if(sparse) { // Very sparse? return _naCnt==0 ? new CX0Chunk(_len, bufS(0))// No NAs, can store as sparse bitvector : new CXIChunk(_len, 1,bufS(1)); // have NAs, store as sparse 1byte values } if(na_sparse) return new CNAXIChunk(_len, 1, bufS(1)); int bpv = _catCnt +_naCnt > 0 ? 2 : 1; // Bit-vector byte[] cbuf = bufB(bpv); return new CBSChunk(cbuf, cbuf[0], cbuf[1]); } final boolean fpoint = xmin < 0 || min < Long.MIN_VALUE || max > Long.MAX_VALUE; if( sparse ) { if(fpoint) return new CXDChunk(_len,8,bufD(8)); int sz = 8; if( Short.MIN_VALUE <= min && max <= Short.MAX_VALUE ) sz = 2; else if( Integer.MIN_VALUE <= min && max <= Integer.MAX_VALUE ) sz = 4; return new CXIChunk(_len,sz,bufS(sz)); } if( na_sparse ) { if(fpoint) return new CNAXDChunk(_len,8,bufD(8)); int sz = 8; if( Short.MIN_VALUE <= min && max <= Short.MAX_VALUE ) sz = 2; else if( Integer.MIN_VALUE <= min && max <= Integer.MAX_VALUE ) sz = 4; return new CNAXIChunk(_len,sz,bufS(sz)); } // Exponent scaling: replacing numbers like 1.3 with 13e-1. '13' fits in a // byte and we scale the column by 0.1. A set of numbers like // {1.2,23,0.34} then is normalized to always be represented with 2 digits // to the right: {1.20,23.00,0.34} and we scale by 100: {120,2300,34}. // This set fits in a 2-byte short. // We use exponent-scaling for bytes & shorts only; it's uncommon (and not // worth it) for larger numbers. We need to get the exponents to be // uniform, so we scale up the largest lmax by the largest scale we need // and if that fits in a byte/short - then it's worth compressing. Other // wise we just flip to a float or double representation. if( overflow || (fpoint && floatOverflow) || -35 > xmin || xmin > 35 ) return chunkD(); final long leRange = leRange(lemin,lemax); if( fpoint ) { if( (int)lemin == lemin && (int)lemax == lemax ) { if(leRange < 255) // Fits in scaled biased byte? return new C1SChunk( bufX(lemin,xmin,C1SChunk._OFF,0),lemin,PrettyPrint.pow10(xmin)); if(leRange < 65535) { // we use signed 2B short, add -32k to the bias! long bias = 32767 + lemin; return new C2SChunk( bufX(bias,xmin,C2SChunk._OFF,1),bias,PrettyPrint.pow10(xmin)); } } if(leRange < 4294967295l) { long bias = 2147483647l + lemin; return new C4SChunk( bufX(bias,xmin,C4SChunk._OFF,2),bias,PrettyPrint.pow10(xmin)); } return chunkD(); } // else an integer column // Compress column into a byte if(xmin == 0 && 0<=lemin && lemax <= 255 && ((_naCnt + _catCnt)==0) ) return new C1NChunk( bufX(0,0,C1NChunk._OFF,0)); if( lemin < Integer.MIN_VALUE ) return new C8Chunk( bufX(0,0,0,3)); if( leRange < 255 ) { // Span fits in a byte? if(0 <= min && max < 255 ) // Span fits in an unbiased byte? return new C1Chunk( bufX(0,0,C1Chunk._OFF,0)); return new C1SChunk( bufX(lemin,xmin,C1SChunk._OFF,0),lemin,PrettyPrint.pow10i(xmin)); } // Compress column into a short if( leRange < 65535 ) { // Span fits in a biased short? if( xmin == 0 && Short.MIN_VALUE < lemin && lemax <= Short.MAX_VALUE ) // Span fits in an unbiased short? return new C2Chunk( bufX(0,0,C2Chunk._OFF,1)); long bias = (lemin-(Short.MIN_VALUE+1)); return new C2SChunk( bufX(bias,xmin,C2SChunk._OFF,1),bias,PrettyPrint.pow10i(xmin)); } // Compress column into ints if( Integer.MIN_VALUE < min && max <= Integer.MAX_VALUE ) return new C4Chunk( bufX(0,0,0,2)); return new C8Chunk( bufX(0,0,0,3)); } private static long [] NAS = {C1Chunk._NA,C2Chunk._NA,C4Chunk._NA,C8Chunk._NA}; // Compute a sparse integer buffer private byte[] bufS(final int valsz){ int log = 0; while((1 << log) < valsz)++log; assert valsz == 0 || (1 << log) == valsz; final int ridsz = _len >= 65535?4:2; final int elmsz = ridsz + valsz; int off = CXIChunk._OFF; byte [] buf = MemoryManager.malloc1(off + _sparseLen *elmsz,true); for(int i = 0; i< _sparseLen; i++, off += elmsz ) { if(ridsz == 2) UnsafeUtils.set2(buf,off,(short)_id[i]); else UnsafeUtils.set4(buf,off,_id[i]); if(valsz == 0){ assert _xs[i] == 0 && _ls[i] == 1; continue; } assert isNA2(i) || _xs[i] >= 0:"unexpected exponent " + _xs[i]; // assert we have int or NA final long lval = isNA2(i) ? NAS[log] : _ls[i]*PrettyPrint.pow10i(_xs[i]); switch(valsz){ case 1: buf[off+ridsz] = (byte)lval; break; case 2: short sval = (short)lval; UnsafeUtils.set2(buf,off+ridsz,sval); break; case 4: int ival = (int)lval; UnsafeUtils.set4(buf, off + ridsz, ival); break; case 8: UnsafeUtils.set8(buf, off + ridsz, lval); break; default: throw H2O.fail(); } } assert off==buf.length; return buf; } // Compute a sparse float buffer private byte[] bufD(final int valsz){ int log = 0; while((1 << log) < valsz)++log; assert (1 << log) == valsz; final int ridsz = _len >= 65535?4:2; final int elmsz = ridsz + valsz; int off = CXDChunk._OFF; byte [] buf = MemoryManager.malloc1(off + _sparseLen *elmsz,true); for(int i = 0; i< _sparseLen; i++, off += elmsz ) { if(ridsz == 2) UnsafeUtils.set2(buf,off,(short)_id[i]); else UnsafeUtils.set4(buf,off,_id[i]); final double dval = _ds == null?isNA2(i)?Double.NaN:_ls[i]*PrettyPrint.pow10(_xs[i]):_ds[i]; switch(valsz){ case 4: UnsafeUtils.set4f(buf, off + ridsz, (float) dval); break; case 8: UnsafeUtils.set8d(buf, off + ridsz, dval); break; default: throw H2O.fail(); } } assert off==buf.length; return buf; } // Compute a compressed integer buffer private byte[] bufX( long bias, int scale, int off, int log ) { byte[] bs = new byte[(_len <<log)+off]; int j = 0; for( int i=0; i< _len; i++ ) { long le = -bias; if(_id == null || _id.length == 0 || (j < _id.length && _id[j] == i)){ if( isNA2(j) ) { le = NAS[log]; } else { int x = (_xs[j]==Integer.MIN_VALUE+1 ? 0 : _xs[j])-scale; le += x >= 0 ? _ls[j]*PrettyPrint.pow10i( x) : _ls[j]/PrettyPrint.pow10i(-x); } ++j; } switch( log ) { case 0: bs [i +off] = (byte)le ; break; case 1: UnsafeUtils.set2(bs,(i<<1)+off, (short)le); break; case 2: UnsafeUtils.set4(bs, (i << 2) + off, (int) le); break; case 3: UnsafeUtils.set8(bs, (i << 3) + off, le); break; default: throw H2O.fail(); } } assert j == _sparseLen :"j = " + j + ", _sparseLen = " + _sparseLen; return bs; } // Compute a compressed double buffer private Chunk chunkD() { HashMap<Long,Byte> hs = new HashMap<>(CUDChunk.MAX_UNIQUES); Byte dummy = 0; final byte [] bs = MemoryManager.malloc1(_len *8,true); int j = 0; boolean fitsInUnique = true; for(int i = 0; i < _len; ++i){ double d = 0; if(_id == null || _id.length == 0 || (j < _id.length && _id[j] == i)) { d = _ds != null?_ds[j]:(isNA2(j)|| isCategorical(j))?Double.NaN:_ls[j]*PrettyPrint.pow10(_xs[j]); ++j; } if (fitsInUnique) { if (hs.size() < CUDChunk.MAX_UNIQUES) //still got space hs.put(Double.doubleToLongBits(d),dummy); //store doubles as longs to avoid NaN comparison issues during extraction else fitsInUnique = (hs.size() == CUDChunk.MAX_UNIQUES) && // full, but might not need more space because of repeats hs.containsKey(Double.doubleToLongBits(d)); } UnsafeUtils.set8d(bs, 8*i, d); } assert j == _sparseLen :"j = " + j + ", _len = " + _sparseLen; if (fitsInUnique && CUDChunk.computeByteSize(hs.size(), len()) < 0.8 * bs.length) return new CUDChunk(bs, hs, len()); else return new C8DChunk(bs); } // Compute a compressed UUID buffer private Chunk chunkUUID() { final byte [] bs = MemoryManager.malloc1(_len *16,true); int j = 0; for( int i = 0; i < _len; ++i ) { long lo = 0, hi=0; if( _id == null || _id.length == 0 || (j < _id.length && _id[j] == i ) ) { lo = _ls[j]; hi = Double.doubleToRawLongBits(_ds[j++]); if( _xs != null && _xs[j] == Integer.MAX_VALUE){ lo = Long.MIN_VALUE; hi = 0; // Canonical NA value } } UnsafeUtils.set8(bs, 16*i , lo); UnsafeUtils.set8(bs, 16 * i + 8, hi); } assert j == _sparseLen :"j = " + j + ", _sparselen = " + _sparseLen; return new C16Chunk(bs); } // Compute compressed boolean buffer private byte[] bufB(int bpv) { assert bpv == 1 || bpv == 2 : "Only bit vectors with/without NA are supported"; final int off = CBSChunk._OFF; int clen = off + CBSChunk.clen(_len, bpv); byte bs[] = new byte[clen]; // Save the gap = number of unfilled bits and bpv value bs[0] = (byte) (((_len *bpv)&7)==0 ? 0 : (8-((_len *bpv)&7))); bs[1] = (byte) bpv; // Dense bitvector int boff = 0; byte b = 0; int idx = CBSChunk._OFF; int j = 0; for (int i=0; i< _len; i++) { byte val = 0; if(_id == null || (j < _id.length && _id[j] == i)) { assert bpv == 2 || !isNA2(j); val = (byte)(isNA2(j)?CBSChunk._NA:_ls[j]); ++j; } if( bpv==1 ) b = CBSChunk.write1b(b, val, boff); else b = CBSChunk.write2b(b, val, boff); boff += bpv; if (boff>8-bpv) { assert boff == 8; bs[idx] = b; boff = 0; b = 0; idx++; } } assert j == _sparseLen; assert bs[0] == (byte) (boff == 0 ? 0 : 8-boff):"b[0] = " + bs[0] + ", boff = " + boff + ", bpv = " + bpv; // Flush last byte if (boff>0) bs[idx] = b; return bs; } // Set & At on NewChunks are weird: only used after inflating some other // chunk. At this point the NewChunk is full size, no more appends allowed, // and the xs exponent array should be only full of zeros. Accesses must be // in-range and refer to the inflated values of the original Chunk. @Override boolean set_impl(int i, long l) { if( _ds != null ) return set_impl(i,(double)l); if(_sparseLen != _len){ // sparse? int idx = Arrays.binarySearch(_id,0, _sparseLen,i); if(idx >= 0)i = idx; else cancel_sparse(); // for now don't bother setting the sparse value } _ls[i]=l; _xs[i]=0; _naCnt = -1; return true; } @Override public boolean set_impl(int i, double d) { if(_ds == null){ if (_is == null) { //not a string assert _sparseLen == 0 || _ls != null; switch_to_doubles(); } else { if (_is[i] == -1) return true; //nothing to do: already NA assert(Double.isNaN(d)) : "can only set strings to <NA>, nothing else"; set_impl(i, null); //null encodes a missing string: <NA> return true; } } if(_sparseLen != _len){ // sparse? int idx = Arrays.binarySearch(_id,0, _sparseLen,i); if(idx >= 0)i = idx; else cancel_sparse(); // for now don't bother setting the sparse value } assert i < _sparseLen; _ds[i] = d; _naCnt = -1; return true; } @Override boolean set_impl(int i, float f) { return set_impl(i,(double)f); } @Override boolean set_impl(int i, String str) { if(_is == null && _len > 0) { assert _sparseLen == 0; alloc_str_indices(_len); Arrays.fill(_is,-1); } if(_sparseLen != _len){ // sparse? int idx = Arrays.binarySearch(_id,0, _sparseLen,i); if(idx >= 0)i = idx; else cancel_sparse(); // for now don't bother setting the sparse value } _is[i] = _sslen; append_ss(str); return true; } protected final boolean setNA_impl2(int i) { if( isNA2(i) ) return true; if( _ls != null ) { _ls[i] = Long.MAX_VALUE; _xs[i] = Integer.MIN_VALUE; } if( _ds != null ) { _ds[i] = Double.NaN; } if (_is != null) { _is[i] = -1; } _naCnt = -1; return true; } @Override boolean setNA_impl(int i) { if( isNA_impl(i) ) return true; if(_sparseLen != _len){ int idx = Arrays.binarySearch(_id,0, _sparseLen,i); if(idx >= 0) i = idx; else cancel_sparse(); // todo - do not necessarily cancel sparse here } return setNA_impl2(i); } protected final long at8_impl2(int i) { if(isNA2(i))throw new RuntimeException("Attempting to access NA as integer value."); if( _ls == null ) return (long)_ds[i]; return _ls[i]*PrettyPrint.pow10i(_xs[i]); } @Override public long at8_impl( int i ) { if( _len != _sparseLen) { int idx = Arrays.binarySearch(_id,0, _sparseLen,i); if(idx >= 0) i = idx; else { if (_sparseNA) throw new RuntimeException("Attempting to access NA as integer value."); return 0; } } return at8_impl2(i); } @Override public double atd_impl( int i ) { if( _len != _sparseLen) { int idx = Arrays.binarySearch(_id,0, _sparseLen,i); if(idx >= 0) i = idx; else return sparseNA() ? Double.NaN : 0; } if (isNA2(i)) return Double.NaN; // if exponent is Integer.MIN_VALUE (for missing value) or >=0, then go the integer path (at8_impl) // negative exponents need to be handled right here if( _ds == null ) return _xs[i] >= 0 ? at8_impl2(i) : _ls[i]*Math.pow(10,_xs[i]); assert _xs==null; return _ds[i]; } @Override protected long at16l_impl(int idx) { if(_ls[idx] == C16Chunk._LO_NA) throw new RuntimeException("Attempting to access NA as integer value."); return _ls[idx]; } @Override protected long at16h_impl(int idx) { long hi = Double.doubleToRawLongBits(_ds[idx]); if(hi == C16Chunk._HI_NA) throw new RuntimeException("Attempting to access NA as integer value."); return hi; } @Override public boolean isNA_impl( int i ) { if (_len != _sparseLen) { int idx = Arrays.binarySearch(_id, 0, _sparseLen, i); if (idx >= 0) i = idx; else return sparseNA(); } return !sparseNA() && isNA2(i); } @Override public BufferedString atStr_impl( BufferedString bStr, int i ) { if( _sparseLen != _len ) { int idx = Arrays.binarySearch(_id,0, _sparseLen,i); if(idx >= 0) i = idx; else return null; } if( _is[i] == CStrChunk.NA ) return null; int len = 0; while( _ss[_is[i] + len] != 0 ) len++; return bStr.set(_ss, _is[i], len); } @Override protected final void initFromBytes () {throw H2O.fail();} public static AutoBuffer write_impl(NewChunk nc,AutoBuffer bb) { throw H2O.fail(); } @Override public NewChunk inflate_impl(NewChunk nc) { throw H2O.fail(); } @Override public String toString() { return "NewChunk._sparseLen="+ _sparseLen; } // We have to explicitly override cidx implementation since we hide _cidx field with new version @Override public int cidx() { return _cidx; } }
package loci.tests.testng; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.FieldPosition; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Comparator; import java.util.Date; import java.util.List; import loci.common.ByteArrayHandle; import loci.common.Constants; import loci.common.DataTools; import loci.common.DateTools; import loci.common.Location; import loci.common.RandomAccessInputStream; import loci.formats.IFormatReader; import loci.formats.IFormatWriter; import loci.formats.ImageReader; import org.apache.log4j.Level; import org.apache.log4j.PatternLayout; import org.apache.log4j.WriterAppender; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestTools { // -- Constants -- private static final Logger LOGGER = LoggerFactory.getLogger(TestTools.class); public static final String DIVIDER = " /** Gets a timestamp for the current moment. */ public static String timestamp() { return DateTools.convertDate(System.currentTimeMillis(), DateTools.UNIX); } /** Calculate the SHA-1 of a byte array. */ public static String sha1(byte[] b, int offset, int len) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.reset(); md.update(b, offset, len); byte[] digest = md.digest(); return DataTools.bytesToHex(digest); } catch (NoSuchAlgorithmException e) { } return null; } /** Calculate the SHA-1 of a byte array. */ public static String sha1(byte[] b) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.reset(); md.update(b); byte[] digest = md.digest(); return DataTools.bytesToHex(digest); } catch (NoSuchAlgorithmException e) { } return null; } /** Calculate the MD5 of a byte array. */ public static String md5(byte[] b, int sizeX, int sizeY, int posX, int posY, int width, int height, int bpp) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); int offset = 0; for (int i = 0; i < height; i++) { offset = (((posY + i) * sizeX) + posX) * bpp; md.update(b, offset, width * bpp); } byte[] digest = md.digest(); return DataTools.bytesToHex(digest); } catch (NoSuchAlgorithmException e) { } return null; } /** Calculate the MD5 of a byte array. */ public static String md5(byte[] b, int offset, int len) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(b, offset, len); byte[] digest = md.digest(); return DataTools.bytesToHex(digest); } catch (NoSuchAlgorithmException e) { } return null; } /** Calculate the MD5 of a byte array. */ public static String md5(byte[] b) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(b); byte[] digest = md.digest(); return DataTools.bytesToHex(digest); } catch (NoSuchAlgorithmException e) { } return null; } /** Returns true if a byte buffer of the given size will fit in memory. */ public static boolean canFitInMemory(long bufferSize) { Runtime r = Runtime.getRuntime(); long mem = r.freeMemory() / 2; return bufferSize < mem && bufferSize <= Integer.MAX_VALUE; } /** Gets the quantity of used memory, in MB. */ public static long getUsedMemory() { Runtime r = Runtime.getRuntime(); long mem = r.totalMemory() - r.freeMemory(); return mem >> 20; } /** Gets the class name sans package for the given object. */ public static String shortClassName(Object o) { String name = o.getClass().getName(); int dot = name.lastIndexOf("."); return dot < 0 ? name : name.substring(dot + 1); } /** Creates a new log file. */ public static void createLogFile() { SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss"); StringBuffer dateBuf = new StringBuffer(); fmt.format(new Date(), dateBuf, new FieldPosition(0)); String logFile = "loci-software-test-" + dateBuf + ".log"; LOGGER.info("Output logged to {}", logFile); try { org.apache.log4j.Logger root = org.apache.log4j.Logger.getRootLogger(); root.setLevel(Level.INFO); root.addAppender(new WriterAppender( new PatternLayout("%p [%d{dd-MM-yyyy HH:mm:ss.SSS}] %m%n"), new PrintWriter(logFile, Constants.ENCODING))); } catch (IOException e) { LOGGER.info("", e); } // close log file on exit Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { LOGGER.info(DIVIDER); LOGGER.info("Test suite complete."); } }); } /** Recursively generate a list of files to test. */ public static void getFiles(String root, List files, final ConfigurationTree config, String toplevelConfig) { getFiles(root, files, config, toplevelConfig, null); } /** Recursively generate a list of files to test. */ public static void getFiles(String root, List files, final ConfigurationTree config, String toplevelConfig, String[] subdirs) { Location f = new Location(root); String[] subs = f.list(); if (subs == null) subs = new String[0]; if (subdirs != null) { subs = subdirs; } boolean isToplevel = toplevelConfig != null && new File(toplevelConfig).exists(); // make sure that if a config file exists, it is first on the list for (int i=0; i<subs.length; i++) { Location file = new Location(root, subs[i]); subs[i] = file.getAbsolutePath(); if ((!isToplevel && file.getName().equals(".bioformats")) || (isToplevel && subs[i].equals(toplevelConfig))) { String tmp = subs[0]; subs[0] = subs[i]; subs[i] = tmp; // special config file for the test suite LOGGER.info("\tconfig file"); try { config.parseConfigFile(subs[0]); } catch (IOException exc) { LOGGER.info("", exc); } catch (Exception e) { } } } Arrays.sort(subs, new Comparator() { public int compare(Object o1, Object o2) { String s1 = o1.toString(); String s2 = o2.toString(); Configuration c1 = null; Configuration c2 = null; try { c1 = config.get(s1); } catch (IOException e) { } try { c2 = config.get(s2); } catch (IOException e) { } if (c1 == null && c2 != null) { return 1; } else if (c1 != null && c2 == null) { return -1; } return s1.compareTo(s2); } }); ImageReader typeTester = new ImageReader(); for (int i=0; i<subs.length; i++) { Location file = new Location(subs[i]); LOGGER.info("Checking {}:", subs[i]); if (file.getName().equals(".bioformats")) { continue; } else if (isIgnoredFile(subs[i], config)) { LOGGER.info("\tignored"); continue; } else if (file.isDirectory()) { LOGGER.info("\tdirectory"); getFiles(subs[i], files, config, null); } else if (!subs[i].endsWith("readme.txt")) { if (typeTester.isThisType(subs[i])) { LOGGER.info("\tOK"); files.add(file.getAbsolutePath()); } else LOGGER.info("\tunknown type"); } file = null; } } /** Determines if the given file should be ignored by the test suite. */ public static boolean isIgnoredFile(String file, ConfigurationTree config) { if (file.indexOf(File.separator + ".") >= 0) return true; // hidden file try { Configuration c = config.get(file); if (c == null) return false; if (!c.doTest()) return true; } catch (IOException e) { } catch (Exception e) { } // HACK - heuristics to speed things up if (file.endsWith(".oif.files")) return true; // ignore .oif folders return false; } /** * Iterates over every tile in a given pixel buffer based on the over arching * dimensions and a requested maximum tile width and height. * @param iteration Invoker to call for each tile. * @param sizeX Width of the entire image. * @param sizeY Height of the entire image. * @param sizeZ Number of optical sections the image contains. * @param sizeC Number of channels the image contains. * @param sizeT Number of timepoints the image contains. * @param tileWidth <b>Maximum</b> width of the tile requested. The tile * request itself will be smaller than the original tile width requested if * <code>x + tileWidth > sizeX</code>. * @param tileHeight <b>Maximum</b> height of the tile requested. The tile * request itself will be smaller if <code>y + tileHeight > sizeY</code>. * @return The total number of tiles iterated over. */ public static int forEachTile(TileLoopIteration iteration, int sizeX, int sizeY, int sizeZ, int sizeC, int sizeT, int tileWidth, int tileHeight) { int tileCount = 0; int x, y, w, h; for (int t = 0; t < sizeT; t++) { for (int c = 0; c < sizeC; c++) { for (int z = 0; z < sizeZ; z++) { for (int tileOffsetY = 0; tileOffsetY < (sizeY + tileHeight - 1) / tileHeight; tileOffsetY++) { for (int tileOffsetX = 0; tileOffsetX < (sizeX + tileWidth - 1) / tileWidth; tileOffsetX++) { x = tileOffsetX * tileWidth; y = tileOffsetY * tileHeight; w = tileWidth; if (w + x > sizeX) { w = sizeX - x; } h = tileHeight; if (h + y > sizeY) { h = sizeY - y; } iteration.run(z, c, t, x, y, w, h, tileCount); tileCount++; } } } } } return tileCount; } /** * A single iteration of a tile for each loop. * @author Chris Allan <callan at blackcat dot ca> * @since OMERO Beta-4.3.0 */ public interface TileLoopIteration { /** * Invoke a single loop iteration. * @param z Z section counter of the loop. * @param c Channel counter of the loop. * @param t Timepoint counter of the loop. * @param x X offset within the plane specified by the section, channel and * timepoint counters. * @param y Y offset within the plane specified by the section, channel and * timepoint counters. * @param tileWidth Width of the tile requested. The tile request * itself may be smaller than the original tile width requested if * <code>x + tileWidth > sizeX</code>. * @param tileHeight Height of the tile requested. The tile request * itself may be smaller if <code>y + tileHeight > sizeY</code>. * @param tileCount Counter of the tile since the beginning of the loop. */ void run(int z, int c, int t, int x, int y, int tileWidth, int tileHeight, int tileCount); } /** * Map the given file into memory. * * @return true if the mapping was successful. */ public static boolean mapFile(String id) throws IOException { RandomAccessInputStream stream = new RandomAccessInputStream(id); Runtime rt = Runtime.getRuntime(); long maxMem = rt.freeMemory(); long length = stream.length(); if (length < Integer.MAX_VALUE && length < maxMem) { stream.close(); FileInputStream fis = new FileInputStream(id); FileChannel channel = fis.getChannel(); ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size()); ByteArrayHandle handle = new ByteArrayHandle(buf); Location.mapFile(id, handle); fis.close(); return true; } stream.close(); return false; } }
package $package; import agave.AbstractHandler; import agave.Destination; import agave.HandlesRequestsTo; public class WelcomeHandler extends AbstractHandler { @HandlesRequestsTo("/") public Destination welcome() throws Exception { request.setAttribute("contextPath", request.getContextPath()); request.setAttribute("context", request.getContextPath().substring(1)); return new Destination("/WEB-INF/jsp/index.jsp"); } }
package com.carrotsearch.ant.tasks.junit4.slave; import java.io.IOException; import org.junit.runner.Description; import org.junit.runner.Result; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunListener; import com.carrotsearch.ant.tasks.junit4.events.*; /** * Serialize test execution events. */ public class RunListenerEmitter extends RunListener { private final Serializer serializer; private Description suiteDescription; private long start; private long suiteStart; public RunListenerEmitter(Serializer serializer) { this.serializer = serializer; } @Override public void testRunStarted(Description description) throws Exception { this.suiteDescription = description; this.suiteStart = System.currentTimeMillis(); serializer.serialize(new SuiteStartedEvent(description)); } @Override public void testStarted(Description description) throws Exception { serializer.serialize(new TestStartedEvent(description)); start = System.currentTimeMillis(); } @Override public void testFailure(Failure failure) throws Exception { if (suiteDescription.equals(failure.getDescription())) { serializer.serialize(new SuiteFailureEvent(failure)); } else { serializer.serialize(new TestFailureEvent(failure)); } } @Override public void testAssumptionFailure(Failure failure) { try { serializer.serialize(new TestIgnoredAssumptionEvent(failure)); } catch (IOException e) { throw new RuntimeException(e); } } @Override public void testIgnored(Description description) throws Exception { if (suiteDescription.equals(description)) { // Should we report all ignored tests here? } else { serializer.serialize(new TestIgnoredEvent(description)); } } @Override public void testFinished(Description description) throws Exception { long executionTime = System.currentTimeMillis() - start; serializer.serialize(new TestFinishedEvent(description, (int) executionTime, start)); } @Override public void testRunFinished(Result result) throws Exception { final long duration = System.currentTimeMillis() - suiteStart; serializer.serialize( new SuiteCompletedEvent(suiteDescription, suiteStart, duration)); } }
package org.fundacionjala.enforce.sonarqube.apex.checks; import java.util.List; import com.google.common.collect.ImmutableList; /** * Builds a list of custom checks. */ public class CheckList { /** * Stores the sonarqube profile name. */ public static final String SONAR_WAY_PROFILE = "Sonar way"; /** * Stores the sonarqube repository name. */ public static final String REPOSITORY_NAME = "SonarQube"; /** * Stores the Apex's repository key. */ public static final String REPOSITORY_KEY = "apex"; /** * Default constructor. */ private CheckList() { } /** * Builds and returns the custom checks to create Apex's rules. * * @return the list of the checks. */ public static List<Class> getChecks() { return ImmutableList.<Class>of( AssertMethodCheck.class, ClassNameCheck.class, DeprecatedMethodCheck.class, DmlInConstructorCheck.class, DmlInForCheck.class, DmlInWhileCheck.class, LineLengthCheck.class, MethodNameCheck.class, TestMethodCheck.class, HardcodingIdsCheckInVariables.class, HardcodingIdsInMethodsAndConstructorsCheck.class); } }
package me.foxaice.smartlight.fragments.modes.bulb_mode; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.v4.content.ContextCompat; import android.support.v4.graphics.drawable.DrawableCompat; import android.util.AttributeSet; import me.foxaice.smartlight.R; public class BrightnessArcView extends android.support.v7.widget.AppCompatImageView { private Bitmap mBitmapBorder; private Bitmap mBitmapMask; private Paint mPaintMask; private Paint mPaintColor; private Paint mPaintBorder; private RectF mArcRect; private float mAngle = 50; private int mWidth; private int mHeight; private Rect mFrameRect; public BrightnessArcView(Context context) { this(context, null); } public BrightnessArcView(Context context, AttributeSet attrs) { super(context, attrs); mWidth = getResources().getDimensionPixelSize(R.dimen.brightness_arc_width); mHeight = getResources().getDimensionPixelSize(R.dimen.brightness_arc_height); int targetRadius = getResources().getDimensionPixelSize(R.dimen.brightness_arc_target_size); mBitmapBorder = getBitmapFromVectorDrawable(getContext(), R.drawable.bulb_mode_image_brightness_arc); mBitmapMask = getBitmapFromVectorDrawable(getContext(), R.drawable.bulb_mode_image_brightness_arc_mask); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { mBitmapMask = mBitmapMask.extractAlpha(); } mFrameRect = new Rect(0, 0, mWidth, mHeight); mArcRect = new RectF(targetRadius, targetRadius, mWidth - targetRadius, mWidth - targetRadius); mPaintMask = new Paint(); mPaintColor = new Paint(); mPaintBorder = new Paint(); mPaintMask.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN)); mPaintColor.setStrokeWidth(targetRadius * 2); mPaintColor.setStyle(Paint.Style.STROKE); mPaintColor.setColor(ContextCompat.getColor(context, R.color.backgroundBrightnessArc)); mPaintBorder.setColor(Color.BLACK); } public BrightnessArcView(Context context, AttributeSet attrs, int defStyle) { this(context, attrs); } private Bitmap getBitmapFromVectorDrawable(Context context, int drawableId) { Drawable drawable = ContextCompat.getDrawable(context, drawableId); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { drawable = (DrawableCompat.wrap(drawable)).mutate(); } Bitmap bitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; } }
package org.clintonhealthaccess.lmis.app.views.graphs; import android.content.Context; import android.graphics.Typeface; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import org.clintonhealthaccess.lmis.app.R; import lombok.Getter; import static java.lang.Math.abs; @Getter public class StockOnHandGraphBar { private int actualStockOnHand; private String commodityName; private int maximumThreshold, minimumThreshold, monthsOfStockOnHand, color; private int heightOfColorHolder; private int heightForMinThreshold; private int heightForMaxThreshold; public StockOnHandGraphBar(String commodityName, int min, int max, int monthsOfStockOnHand, int color, int actualStockOnHand) { this.commodityName = commodityName; this.minimumThreshold = min; this.maximumThreshold = max; this.monthsOfStockOnHand = monthsOfStockOnHand; this.color = color; this.actualStockOnHand = actualStockOnHand; } public StockOnHandGraphBar() { } public RelativeLayout getView(Context applicationContext, int biggestValue, int height) { int barWidth = Math.round(applicationContext.getResources().getDimension(R.dimen.bar_width)); int barLegendHeight = 70; int barHeight = height - barLegendHeight - 50; heightForMinThreshold = getHeightForMinThreshold(barHeight, biggestValue); heightForMaxThreshold = getHeightForMaxThreshold(barHeight, biggestValue); RelativeLayout relativeLayout = getRelativeLayout(applicationContext); relativeLayout.addView(getSOHTextView(applicationContext, barWidth)); relativeLayout.addView(getTextViewForCommodityName(applicationContext, barWidth, barLegendHeight)); relativeLayout.addView(getColorViewHolder(applicationContext, biggestValue, barWidth, barHeight)); if (heightForMaxThreshold > heightForMinThreshold) { ImageView imageViewSpaceBorderLeft = getImageViewForSpace(applicationContext, barWidth); relativeLayout.addView(imageViewSpaceBorderLeft); relativeLayout.addView(getMaxTextView(applicationContext, barWidth)); } return relativeLayout; } private ImageView getImageViewForSpace(Context applicationContext, int barWidth) { ImageView imageViewSpaceBorderLeft = new ImageView(applicationContext); imageViewSpaceBorderLeft.setBackgroundDrawable(applicationContext.getResources().getDrawable(R.drawable.graph_border)); imageViewSpaceBorderLeft.setLayerType(View.LAYER_TYPE_SOFTWARE, null); int heightForBorder = heightForMaxThreshold - heightForMinThreshold; int widthForBorder = barWidth; RelativeLayout.LayoutParams maxParams = new RelativeLayout.LayoutParams(widthForBorder, heightForBorder); maxParams.setMargins(0, 0, 0, heightForMinThreshold); maxParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT); maxParams.addRule(RelativeLayout.ABOVE, R.id.textViewCommodityNameInGraphBar); imageViewSpaceBorderLeft.setLayoutParams(maxParams); imageViewSpaceBorderLeft.setId(R.id.imageViewSpaceBorderLeft); return imageViewSpaceBorderLeft; } private RelativeLayout getRelativeLayout(Context applicationContext) { RelativeLayout relativeLayout = new RelativeLayout(applicationContext); relativeLayout.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)); relativeLayout.setPadding(5, 5, 5, 5); return relativeLayout; } private TextView getSOHTextView(Context applicationContext, int barWidth) { TextView textViewSOH = new TextView(applicationContext); RelativeLayout.LayoutParams textViewSOHParams = new RelativeLayout.LayoutParams(barWidth, ViewGroup.LayoutParams.WRAP_CONTENT); textViewSOHParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); textViewSOH.setLayoutParams(textViewSOHParams); textViewSOH.setText(getSOH()); textViewSOH.setGravity(Gravity.CENTER_HORIZONTAL); textViewSOH.setTextSize(12); textViewSOH.setId(R.id.textViewStockOnHand); textViewSOH.setTypeface(null, Typeface.BOLD); textViewSOH.setTextColor(applicationContext.getResources().getColor(R.color.black)); return textViewSOH; } private TextView getMaxTextView(Context applicationContext, int barWidth) { TextView textViewMax = new TextView(applicationContext); RelativeLayout.LayoutParams maxTextViewParams = new RelativeLayout.LayoutParams(barWidth, RelativeLayout.LayoutParams.WRAP_CONTENT); maxTextViewParams.addRule(RelativeLayout.ABOVE, R.id.imageViewSpaceBorderLeft); textViewMax.setLayoutParams(maxTextViewParams); textViewMax.setText("Max"); textViewMax.setTextSize(12); textViewMax.setGravity(Gravity.CENTER_HORIZONTAL); textViewMax.setTextColor(applicationContext.getResources().getColor(R.color.black)); textViewMax.setTypeface(null, Typeface.BOLD); return textViewMax; } private View getColorViewHolder(Context applicationContext, int biggestValue, int barWidth, int barHeight) { View colorHolderView = new View(applicationContext); heightOfColorHolder = getHeightForHolder(barHeight, biggestValue); RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(barWidth, heightOfColorHolder); params1.addRule(RelativeLayout.ABOVE, R.id.textViewCommodityNameInGraphBar); colorHolderView.setLayoutParams(params1); int colorBrightRed = applicationContext.getResources().getColor(R.color.alerts_bright_red); colorHolderView.setBackgroundColor(heightOfColorHolder < heightForMinThreshold ? colorBrightRed : color); return colorHolderView; } private TextView getTextViewForCommodityName(Context applicationContext, int barWidth, int barLegendHeight) { TextView textViewName = new TextView(applicationContext); RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(barWidth, barLegendHeight); params2.addRule(RelativeLayout.ABOVE, R.id.textViewStockOnHand); textViewName.setLayoutParams(params2); textViewName.setText(commodityName.toUpperCase()); textViewName.setId(R.id.textViewCommodityNameInGraphBar); textViewName.setGravity(Gravity.CENTER_HORIZONTAL); textViewName.setTextColor(applicationContext.getResources().getColor(R.color.black)); textViewName.setTextSize(9); textViewName.setTypeface(null, Typeface.BOLD); return textViewName; } private String getSOH() { return "SOH " + actualStockOnHand; } private int getHeightForMinThreshold(int barHeight, int biggestValue) { return getRelativeHeight(minimumThreshold, biggestValue, barHeight); } private int getHeightForMaxThreshold(int barHeight, int biggestValue) { return getRelativeHeight(maximumThreshold, biggestValue, barHeight); } private int getHeightForHolder(int barHeight, int biggestValue) { return getRelativeHeight(monthsOfStockOnHand, biggestValue, barHeight); } protected int getRelativeHeight(int givenValue, int maxValue, int maxHeight) { try { return (maxHeight * givenValue) / maxValue; } catch (Exception e) { return 0; } } @Override public String toString() { return "StockOnHandGraphBar{" + "monthsOfStockOnHand=" + monthsOfStockOnHand + ", minimumThreshold=" + minimumThreshold + ", maximumThreshold=" + maximumThreshold + ", commodityName='" + commodityName + '\'' + '}'; } }
package org.hisp.dhis2.android.sdk.persistence.models; import com.fasterxml.jackson.annotation.JsonProperty; import com.raizlabs.android.dbflow.annotation.Column; import com.raizlabs.android.dbflow.annotation.Table; import com.raizlabs.android.dbflow.sql.builder.Condition; import com.raizlabs.android.dbflow.sql.language.Select; import org.hisp.dhis2.android.sdk.controllers.metadata.MetaDataController; import java.util.List; import java.util.Map; /** * @author Simen Skogly Russnes on 26.03.15. */ @Table public class ProgramStageSection extends BaseIdentifiableObject { @JsonProperty("sortOrder") @Column public int sortOrder; @JsonProperty("externalAccess") @Column public boolean externalAccess; @JsonProperty("displayName") @Column public String displayName; @JsonProperty("programStage") public void setProgramStage(Map<String, Object> programStage) { this.programStage = (String) programStage.get("id"); } @Column public String programStage; @JsonProperty("programStageDataElements") private List<ProgramStageDataElement> programStageDataElements; public List<ProgramStageDataElement> getProgramStageDataElements() { if (programStageDataElements == null) programStageDataElements = Select.all(ProgramStageDataElement.class, Condition.column(ProgramStageDataElement$Table.PROGRAMSTAGESECTION).is(id)); return programStageDataElements; } @JsonProperty("programIndicators") private List<ProgramIndicator> programIndicators; public List<ProgramIndicator> getProgramIndicators() { if (programIndicators == null) programIndicators = MetaDataController.getProgramIndicatorsBySection(id); return programIndicators; } }
package se.chalmers.dat255.sleepfighter.challenge.fluidsnake; import android.graphics.Color; public class SnakeConstants { // How fast the game should try to update and render public static final int TARGET_FPS = 60; // Size of the model board public static final int BOARD_WIDTH = 200; public static final int BOARD_HEIGHT = 400; // Multiplier for how fast the game will run in the model public static final float SPEED_MULT = 2; // Number if circles the snake will be made up by public static final int SEGMENTS = 6; // radius of the snake segments public static final int SNAKE_WIDTH = 15; // Starting point for the snake public static final int START_X = BOARD_WIDTH/2; public static final int START_Y = 300; // How wide the obstacles (walls) will be public static final int OBSTACLE_WIDTH = 15; // How far into the obstacle the snake can go before dying public static final int OBSTACLE_MARGIN = 8; // Number of fruits to pick before exit is revealed public static final int FRUITS = 3; // Radius of the sphere fruits public static final int FRUIT_WIDTH = 10; // Colors of the entities public static final int SNAKE_COLOR = Color.rgb(255, 255, 0); public static final int OBSTACLE_COLOR = Color.rgb(200, 200, 200); public static final int FRUIT_COLOR = Color.rgb(255, 40, 0); public static final int EXIT_COLOR = Color.rgb(30, 255, 40); // Don't create an instance of this class private SnakeConstants() { } }
package com.ryanharter.auto.value.gson; import com.google.auto.common.MoreTypes; import com.google.auto.service.AutoService; import com.google.auto.value.extension.AutoValueExtension; import com.google.common.base.CaseFormat; import com.google.common.base.Defaults; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.primitives.Primitives; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.TypeVariableName; import com.squareup.javapoet.WildcardTypeName; import java.io.IOException; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Generated; import javax.annotation.processing.Messager; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.TypeParameterElement; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.ElementFilter; import javax.lang.model.util.Types; import javax.tools.Diagnostic; import static javax.lang.model.element.Modifier.ABSTRACT; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; @AutoService(AutoValueExtension.class) public class AutoValueGsonExtension extends AutoValueExtension { /** Compiler flag to indicate that collections/maps should default to their empty forms. Default is to default to null. */ static final String COLLECTIONS_DEFAULT_TO_EMPTY = "autovaluegson.defaultCollectionsToEmpty"; /** Compiler flag to indicate that generated TypeAdapters should be mutable with setters for defaults. */ static final String MUTABLE_ADAPTERS_WITH_DEFAULT_SETTERS = "autovaluegson.mutableAdaptersWithDefaultSetters"; private static final String GENERATED_COMMENTS = "https://github.com/rharter/auto-value-gson"; private static final AnnotationSpec GENERATED = AnnotationSpec.builder(Generated.class) .addMember("value", "$S", AutoValueGsonExtension.class.getName()) .addMember("comments", "$S", GENERATED_COMMENTS) .build(); public static class Property { final String methodName; final String humanName; final ExecutableElement element; final TypeName type; final ImmutableSet<String> annotations; final TypeMirror typeAdapter; public Property(String humanName, ExecutableElement element) { this.methodName = element.getSimpleName().toString(); this.humanName = humanName; this.element = element; type = TypeName.get(element.getReturnType()); annotations = buildAnnotations(element); typeAdapter = getAnnotationValue(element, GsonTypeAdapter.class); } public static TypeMirror getAnnotationValue(Element foo, Class<?> annotation) { AnnotationMirror am = getAnnotationMirror(foo, annotation); if (am == null) { return null; } AnnotationValue av = getAnnotationValue(am, "value"); return av == null ? null : (TypeMirror) av.getValue(); } private static AnnotationMirror getAnnotationMirror(Element typeElement, Class<?> clazz) { String clazzName = clazz.getName(); for (AnnotationMirror m : typeElement.getAnnotationMirrors()) { if (m.getAnnotationType().toString().equals(clazzName)) { return m; } } return null; } private static AnnotationValue getAnnotationValue(AnnotationMirror annotationMirror, String key) { Map<? extends ExecutableElement, ? extends AnnotationValue> values = annotationMirror.getElementValues(); for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : values.entrySet()) { if (entry.getKey().getSimpleName().toString().equals(key)) { return entry.getValue(); } } return null; } public String serializedName() { SerializedName serializedName = element.getAnnotation(SerializedName.class); if (serializedName != null) { return serializedName.value(); } else { return humanName; } } public String[] serializedNameAlternate() { SerializedName serializedName = element.getAnnotation(SerializedName.class); if (serializedName != null) { return serializedName.alternate(); } else { return new String[0]; } } public boolean shouldSerialize() { Ignore ignore = element.getAnnotation(Ignore.class); return ignore == null || ignore.value() == Ignore.Type.DESERIALIZATION; } public boolean shouldDeserialize() { Ignore ignore = element.getAnnotation(Ignore.class); return ignore == null || ignore.value() == Ignore.Type.SERIALIZATION; } public boolean nullable() { return annotations.contains("Nullable"); } private ImmutableSet<String> buildAnnotations(ExecutableElement element) { ImmutableSet.Builder<String> builder = ImmutableSet.builder(); List<? extends AnnotationMirror> annotations = element.getAnnotationMirrors(); for (AnnotationMirror annotation : annotations) { builder.add(annotation.getAnnotationType().asElement().getSimpleName().toString()); } return builder.build(); } } private boolean defaultSetters = false; private boolean collectionsDefaultToEmpty = false; @Override public boolean applicable(Context context) { // check that the class contains a public static method returning a TypeAdapter TypeElement type = context.autoValueClass(); TypeName typeName = TypeName.get(type.asType()); ParameterizedTypeName typeAdapterType = ParameterizedTypeName.get( ClassName.get(TypeAdapter.class), typeName); TypeName returnedTypeAdapter = null; for (ExecutableElement method : ElementFilter.methodsIn(type.getEnclosedElements())) { if (method.getModifiers().contains(STATIC) && !method.getModifiers().contains(PRIVATE)) { TypeMirror rType = method.getReturnType(); TypeName returnType = TypeName.get(rType); if (returnType.equals(typeAdapterType)) { return true; } if (returnType.equals(typeAdapterType.rawType) || (returnType instanceof ParameterizedTypeName && ((ParameterizedTypeName) returnType).rawType.equals(typeAdapterType.rawType))) { returnedTypeAdapter = returnType; } } } if (returnedTypeAdapter == null) { return false; } // emit a warning if the user added a method returning a TypeAdapter, but not of the right type Messager messager = context.processingEnvironment().getMessager(); if (returnedTypeAdapter instanceof ParameterizedTypeName) { ParameterizedTypeName paramReturnType = (ParameterizedTypeName) returnedTypeAdapter; TypeName argument = paramReturnType.typeArguments.get(0); // If the original type uses generics, user's don't have to nest the generic type args if (typeName instanceof ParameterizedTypeName) { ParameterizedTypeName pTypeName = (ParameterizedTypeName) typeName; if (pTypeName.rawType.equals(argument)) { return true; } } else { messager.printMessage(Diagnostic.Kind.WARNING, String.format("Found public static method returning TypeAdapter<%s> on %s class. " + "Skipping GsonTypeAdapter generation.", argument, type)); } } else { messager.printMessage(Diagnostic.Kind.WARNING, "Found public static method returning " + "TypeAdapter with no type arguments, skipping GsonTypeAdapter generation."); } return false; } @Override public String generateClass(Context context, String className, String classToExtend, boolean isFinal) { ProcessingEnvironment env = context.processingEnvironment(); defaultSetters = Boolean.parseBoolean(context.processingEnvironment().getOptions() .getOrDefault(MUTABLE_ADAPTERS_WITH_DEFAULT_SETTERS, "false")); collectionsDefaultToEmpty = Boolean.parseBoolean(env.getOptions() .getOrDefault(COLLECTIONS_DEFAULT_TO_EMPTY, "false")); boolean generatedAnnotationAvailable = context.processingEnvironment() .getElementUtils() .getTypeElement("javax.annotation.Generated") != null; List<Property> properties = readProperties(context.properties()); Map<String, TypeName> types = convertPropertiesToTypes(context.properties()); ClassName classNameClass = ClassName.get(context.packageName(), className); ClassName autoValueClass = ClassName.get(context.autoValueClass()); List<? extends TypeParameterElement> typeParams = context.autoValueClass().getTypeParameters(); List<TypeVariableName> params = new ArrayList<>(typeParams.size()); TypeName superclasstype = ClassName.get(context.packageName(), classToExtend); if (!typeParams.isEmpty()) { for (TypeParameterElement typeParam : typeParams) { params.add(TypeVariableName.get(typeParam)); } superclasstype = ParameterizedTypeName.get(ClassName.get(context.packageName(), classToExtend), params.toArray(new TypeName[params.size()])); } TypeSpec typeAdapter = createTypeAdapter(context, classNameClass, autoValueClass, properties, params); TypeSpec.Builder subclass = TypeSpec.classBuilder(classNameClass) .superclass(superclasstype) .addType(typeAdapter) .addMethod(generateConstructor(types)); if (generatedAnnotationAvailable) { subclass.addAnnotation(GENERATED); } if (!typeParams.isEmpty()) { subclass.addTypeVariables(params); } if (isFinal) { subclass.addModifiers(FINAL); } else { subclass.addModifiers(ABSTRACT); } return JavaFile.builder(context.packageName(), subclass.build()).build().toString(); } public List<Property> readProperties(Map<String, ExecutableElement> properties) { List<Property> values = new LinkedList<Property>(); for (Map.Entry<String, ExecutableElement> entry : properties.entrySet()) { values.add(new Property(entry.getKey(), entry.getValue())); } return values; } ImmutableMap<Property, FieldSpec> createFields(List<Property> properties) { ImmutableMap.Builder<Property, FieldSpec> fields = ImmutableMap.builder(); ClassName jsonAdapter = ClassName.get(TypeAdapter.class); for (Property property : properties) { if (!property.shouldDeserialize() && !property.shouldSerialize()) { continue; } TypeName type = property.type.isPrimitive() ? property.type.box() : property.type; ParameterizedTypeName adp = ParameterizedTypeName.get(jsonAdapter, type); fields.put(property, FieldSpec.builder(adp, property.humanName + "Adapter", PRIVATE, FINAL).build()); } return fields.build(); } private Map<Property, FieldSpec> createDefaultValueFields(List<Property> properties) { ImmutableMap.Builder<Property, FieldSpec> builder = ImmutableMap.builder(); for (Property prop : properties) { FieldSpec fieldSpec = FieldSpec.builder(prop.type, "default" + upperCamelizeHumanName(prop), PRIVATE).build(); CodeBlock defaultValue = getDefaultValue(prop, fieldSpec); if (defaultValue == null) { defaultValue = CodeBlock.of("null"); } builder.put(prop, fieldSpec.toBuilder() .initializer(defaultValue) .build()); } return builder.build(); } private String upperCamelizeHumanName(Property prop) { return CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, prop.humanName); } MethodSpec generateConstructor(Map<String, TypeName> properties) { List<ParameterSpec> params = Lists.newArrayList(); for (Map.Entry<String, TypeName> entry : properties.entrySet()) { params.add(ParameterSpec.builder(entry.getValue(), entry.getKey()).build()); } MethodSpec.Builder builder = MethodSpec.constructorBuilder() .addParameters(params); StringBuilder superFormat = new StringBuilder("super("); for (int i = properties.size(); i > 0; i superFormat.append("$N"); if (i > 1) superFormat.append(", "); } superFormat.append(")"); builder.addStatement(superFormat.toString(), properties.keySet().toArray()); return builder.build(); } /** * Converts the ExecutableElement properties to TypeName properties */ Map<String, TypeName> convertPropertiesToTypes(Map<String, ExecutableElement> properties) { Map<String, TypeName> types = new LinkedHashMap<String, TypeName>(); for (Map.Entry<String, ExecutableElement> entry : properties.entrySet()) { ExecutableElement el = entry.getValue(); types.put(entry.getKey(), TypeName.get(el.getReturnType())); } return types; } public TypeSpec createTypeAdapter(Context context, ClassName className, ClassName autoValueClassName, List<Property> properties, List<TypeVariableName> typeParams) { ClassName typeAdapterClass = ClassName.get(TypeAdapter.class); TypeName autoValueTypeName = autoValueClassName; if (!typeParams.isEmpty()) { autoValueTypeName = ParameterizedTypeName.get(autoValueClassName, typeParams.toArray(new TypeName[typeParams.size()])); } ParameterizedTypeName superClass = ParameterizedTypeName.get(typeAdapterClass, autoValueTypeName); ParameterSpec gsonParam = ParameterSpec.builder(Gson.class, "gson").build(); MethodSpec.Builder constructor = MethodSpec.constructorBuilder() .addModifiers(PUBLIC) .addParameter(gsonParam); if (!typeParams.isEmpty()) { ParameterSpec typeAdapter = ParameterSpec .builder(ParameterizedTypeName.get(ClassName.get(TypeToken.class), WildcardTypeName.subtypeOf(autoValueTypeName)), "typeToken") .build(); constructor.addParameter(typeAdapter); constructor.addStatement("$1T type = ($1T) $2N.getType()", ParameterizedType.class, typeAdapter); constructor.addStatement("$T[] typeArgs = type.getActualTypeArguments()", Type.class); } ProcessingEnvironment processingEnvironment = context.processingEnvironment(); TypeMirror typeAdapterFactory = processingEnvironment .getElementUtils() .getTypeElement("com.google.gson.TypeAdapterFactory") .asType(); Types typeUtils = processingEnvironment.getTypeUtils(); Map<Property, FieldSpec> defaultValueFields = Collections.emptyMap(); if (defaultSetters) { defaultValueFields = createDefaultValueFields(properties); } ImmutableMap<Property, FieldSpec> adapters = createFields(properties); for (Property prop : properties) { if (defaultSetters && !prop.shouldDeserialize() && !prop.nullable()) { // Property should be ignored for deserialization but is not marked as nullable - we require a default value constructor.addParameter(prop.type, "default" + upperCamelizeHumanName(prop)); constructor.addStatement("this.$N = default$L", defaultValueFields.get(prop), upperCamelizeHumanName(prop)); } if (!prop.shouldDeserialize() && !prop.shouldSerialize()) { continue; } FieldSpec field = adapters.get(prop); if (prop.typeAdapter != null) { if (typeUtils.isAssignable(prop.typeAdapter, typeAdapterFactory)) { if (prop.type instanceof ParameterizedTypeName || prop.type instanceof TypeVariableName) { constructor.addStatement("this.$N = ($T) new $T().create($N, $L)", field, field.type, TypeName.get(prop.typeAdapter), gsonParam, makeParameterizedType(prop.type, typeParams)); } else { constructor.addStatement("this.$N = new $T().create($N, $T.get($T.class))", field, TypeName.get(prop.typeAdapter), gsonParam, TypeToken.class, prop.type); } } else { constructor.addStatement("this.$N = new $T()", field, TypeName.get(prop.typeAdapter)); } } else if (prop.type instanceof ParameterizedTypeName || prop.type instanceof TypeVariableName) { constructor.addStatement("this.$N = ($T) $N.getAdapter($L)", field, field.type, gsonParam, makeParameterizedType(prop.type, typeParams)); } else { TypeName type = prop.type.isPrimitive() ? prop.type.box() : prop.type; constructor.addStatement("this.$N = $N.getAdapter($T.class)", field, gsonParam, type); } } ClassName gsonTypeAdapterName = className.nestedClass("GsonTypeAdapter"); TypeSpec.Builder classBuilder = TypeSpec.classBuilder(gsonTypeAdapterName) .addTypeVariables(typeParams) .addModifiers(PUBLIC, STATIC, FINAL) .superclass(superClass) .addFields(adapters.values()) .addMethod(constructor.build()) .addMethod(createWriteMethod(autoValueTypeName, adapters)) .addMethod(createReadMethod(className, autoValueTypeName, properties, adapters)); if (defaultSetters) { classBuilder.addMethods(createDefaultMethods(gsonTypeAdapterName, properties)) .addFields(defaultValueFields.values()); } return classBuilder.build(); } public List<MethodSpec> createDefaultMethods(ClassName gsonTypeAdapterName, List<Property> properties) { List<MethodSpec> methodSpecs = new ArrayList<>(properties.size()); for (Property prop : properties) { ParameterSpec valueParam = ParameterSpec.builder(prop.type, "default" + upperCamelizeHumanName(prop)).build(); methodSpecs.add(MethodSpec.methodBuilder("setDefault" + upperCamelizeHumanName(prop)) .addModifiers(PUBLIC) .addParameter(valueParam) .returns(gsonTypeAdapterName) .addCode(CodeBlock.builder() .addStatement("this.default$L = $N", upperCamelizeHumanName(prop), valueParam) .addStatement("return this") .build()) .build()); } return methodSpecs; } public MethodSpec createWriteMethod(TypeName autoValueClassName, ImmutableMap<Property, FieldSpec> adapters) { ParameterSpec jsonWriter = ParameterSpec.builder(JsonWriter.class, "jsonWriter").build(); ParameterSpec annotatedParam = ParameterSpec.builder(autoValueClassName, "object").build(); MethodSpec.Builder writeMethod = MethodSpec.methodBuilder("write") .addAnnotation(Override.class) .addModifiers(PUBLIC) .addParameter(jsonWriter) .addParameter(annotatedParam) .addException(IOException.class); writeMethod.beginControlFlow("if ($N == null)", annotatedParam); writeMethod.addStatement("$N.nullValue()", jsonWriter); writeMethod.addStatement("return"); writeMethod.endControlFlow(); writeMethod.addStatement("$N.beginObject()", jsonWriter); for (Map.Entry<Property, FieldSpec> entry : adapters.entrySet()) { Property prop = entry.getKey(); if (!prop.shouldSerialize()) { continue; } FieldSpec field = entry.getValue(); writeMethod.addStatement("$N.name($S)", jsonWriter, prop.serializedName()); writeMethod.addStatement("$N.write($N, $N.$N())", field, jsonWriter, annotatedParam, prop.methodName); } writeMethod.addStatement("$N.endObject()", jsonWriter); return writeMethod.build(); } public MethodSpec createReadMethod(ClassName className, TypeName autoValueClassName, List<Property> properties, ImmutableMap<Property, FieldSpec> adapters) { ParameterSpec jsonReader = ParameterSpec.builder(JsonReader.class, "jsonReader").build(); MethodSpec.Builder readMethod = MethodSpec.methodBuilder("read") .addAnnotation(Override.class) .addModifiers(PUBLIC) .returns(autoValueClassName) .addParameter(jsonReader) .addException(IOException.class); ClassName token = ClassName.get(JsonToken.NULL.getDeclaringClass()); readMethod.beginControlFlow("if ($N.peek() == $T.NULL)", jsonReader, token); readMethod.addStatement("$N.nextNull()", jsonReader); readMethod.addStatement("return null"); readMethod.endControlFlow(); readMethod.addStatement("$N.beginObject()", jsonReader); // add the properties Map<Property, FieldSpec> fields = new LinkedHashMap<>(properties.size()); for (Property prop : properties) { TypeName fieldType = prop.type; FieldSpec field = FieldSpec.builder(fieldType, prop.humanName).build(); fields.put(prop, field); if (defaultSetters) { readMethod.addStatement("$T $N = this.default$L", field.type, field.name, upperCamelizeHumanName(prop)); } else { CodeBlock defaultValue = getDefaultValue(prop, field); readMethod.addCode("$[$T $N = ", field.type, field); if (defaultValue != null) { readMethod.addCode(defaultValue); } else { readMethod.addCode("$L", "null"); } readMethod.addCode(";\n$]"); } } readMethod.beginControlFlow("while ($N.hasNext())", jsonReader); FieldSpec name = FieldSpec.builder(String.class, "_name").build(); readMethod.addStatement("$T $N = $N.nextName()", name.type, name, jsonReader); readMethod.beginControlFlow("if ($N.peek() == $T.NULL)", jsonReader, token); readMethod.addStatement("$N.nextNull()", jsonReader); readMethod.addStatement("continue"); readMethod.endControlFlow(); readMethod.beginControlFlow("switch ($N)", name); for (Property prop : properties) { if (!prop.shouldDeserialize()) { continue; } FieldSpec field = fields.get(prop); for (String alternate : prop.serializedNameAlternate()) { readMethod.addCode("case $S:\n", alternate); } readMethod.beginControlFlow("case $S:", prop.serializedName()); readMethod.addStatement("$N = $N.read($N)", field, adapters.get(prop), jsonReader); readMethod.addStatement("break"); readMethod.endControlFlow(); } // skip value if field is not serialized... readMethod.beginControlFlow("default:"); readMethod.addStatement("$N.skipValue()", jsonReader); readMethod.endControlFlow(); readMethod.endControlFlow(); // switch readMethod.endControlFlow(); // while readMethod.addStatement("$N.endObject()", jsonReader); StringBuilder format = new StringBuilder("return new "); format.append(className.simpleName().replaceAll("\\$", "")); if (autoValueClassName instanceof ParameterizedTypeName) { format.append("<>"); } format.append("("); Iterator<FieldSpec> iterator = fields.values().iterator(); while (iterator.hasNext()) { iterator.next(); format.append("$N"); if (iterator.hasNext()) format.append(", "); } format.append(")"); readMethod.addStatement(format.toString(), fields.values().toArray()); return readMethod.build(); } /** Returns a default value for initializing well-known types, or else {@code null}. */ private CodeBlock getDefaultValue(Property prop, FieldSpec field) { if (field.type.isPrimitive()) { String defaultValue = getDefaultPrimitiveValue(field.type); if (defaultValue != null) { return CodeBlock.of("$L", defaultValue); } else { return CodeBlock.of("$T.valueOf(null)", field.type); } } if (prop.nullable()) { return null; } TypeMirror type = prop.element.getReturnType(); if (type.getKind() != TypeKind.DECLARED) { return null; } TypeElement typeElement = MoreTypes.asTypeElement(type); if (typeElement == null) { return null; } if (collectionsDefaultToEmpty) { try { Class<?> clazz = Class.forName(typeElement.getQualifiedName() .toString()); if (clazz.isAssignableFrom(List.class)) { return CodeBlock.of("$T.emptyList()", TypeName.get(Collections.class)); } else if (clazz.isAssignableFrom(Map.class)) { return CodeBlock.of("$T.emptyMap()", TypeName.get(Collections.class)); } else if (clazz.isAssignableFrom(Set.class)) { return CodeBlock.of("$T.emptySet()", TypeName.get(Collections.class)); } else if (clazz.isAssignableFrom(ImmutableList.class)) { return CodeBlock.of("$T.of()", TypeName.get(ImmutableList.class)); } else if (clazz.isAssignableFrom(ImmutableMap.class)) { return CodeBlock.of("$T.of()", TypeName.get(ImmutableMap.class)); } else if (clazz.isAssignableFrom(ImmutableSet.class)) { return CodeBlock.of("$T.of()", TypeName.get(ImmutableSet.class)); } else { return null; } } catch (ClassNotFoundException e) { return null; } } else { return null; } } /** * * @param type * @return the default primitive value as a String. Returns null if unable to determine default value */ private String getDefaultPrimitiveValue(TypeName type) { String valueString = null; try { Class<?> primitiveClass = Primitives.unwrap(Class.forName(type.box().toString())); if (primitiveClass != null) { Object defaultValue = Defaults.defaultValue(primitiveClass); if (defaultValue != null) { valueString = defaultValue.toString(); if (!Strings.isNullOrEmpty(valueString)) { switch (type.toString()) { case "double": valueString = valueString + "d"; break; case "float": valueString = valueString + "f"; break; case "long": valueString = valueString + "L"; break; case "char": valueString = "'" + valueString + "'"; break; } } } } } catch (ClassNotFoundException ignored) { //Swallow and return null } return valueString; } private CodeBlock makeParameterizedType(TypeName typeName, List<TypeVariableName> typeParams) { CodeBlock.Builder block = CodeBlock.builder(); if (typeName instanceof TypeVariableName) { block.add("$T.get(typeArgs[$L])", TypeToken.class, typeParams.indexOf(typeName)); } else{ ParameterizedTypeName paramType = (ParameterizedTypeName) typeName; block.add("$T.getParameterized($T.class", TypeToken.class, paramType.rawType); for (TypeName type : paramType.typeArguments) { buildParameterizedTypeArguments(block, type, typeParams); } block.add(")"); } return block.build(); } private static void buildParameterizedTypeArguments(CodeBlock.Builder block, TypeName typeArg, List<TypeVariableName> typeParams) { block.add(", "); if (typeArg instanceof ParameterizedTypeName) { // type argument itself can be parameterized ParameterizedTypeName paramTypeArg = (ParameterizedTypeName) typeArg; block.add("$T.getParameterized($T.class", TypeToken.class, paramTypeArg.rawType); for (TypeName type : paramTypeArg.typeArguments) { buildParameterizedTypeArguments(block, type, typeParams); } block.add(").getType()"); } else if (typeArg instanceof TypeVariableName) { block.add("typeArgs[$L]", typeParams.indexOf(typeArg)); } else { block.add("$T.class", typeArg); } } }
package com.axelor.apps.project.service; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.joda.time.DateTimeConstants; import org.joda.time.LocalDate; import com.axelor.apps.base.db.Team; import com.axelor.apps.base.service.administration.GeneralService; import com.axelor.apps.project.db.ProjectPlanning; import com.axelor.apps.project.db.ProjectPlanningLine; import com.axelor.apps.project.db.ProjectTask; import com.axelor.apps.project.db.repo.ProjectPlanningLineRepository; import com.axelor.apps.project.db.repo.ProjectPlanningRepository; import com.axelor.apps.project.db.repo.ProjectTaskRepository; import com.axelor.apps.project.exception.IExceptionMessage; import com.axelor.auth.AuthUtils; import com.axelor.auth.db.User; import com.axelor.exception.AxelorException; import com.axelor.exception.db.IException; import com.axelor.i18n.I18n; import com.axelor.inject.Beans; import com.axelor.rpc.ActionRequest; import com.axelor.rpc.ActionResponse; import com.google.inject.Inject; import com.google.inject.persist.Transactional; public class ProjectPlanningService { @Inject protected ProjectPlanningLineRepository projectPlanningLineRepository; @Inject protected GeneralService generalService; @Inject protected ProjectPlanningRepository projectPlanningRepo; @Transactional public ProjectPlanning createPlanning(int year, int week) throws AxelorException{ ProjectPlanning planning = new ProjectPlanning(); planning.setYear(year); planning.setWeek(week); projectPlanningRepo.save(planning); return planning; } public static String getNameForColumns(int year, int week, int day){ LocalDate date = new LocalDate().withYear(year).withWeekOfWeekyear(week).withDayOfWeek(1); LocalDate newDate = date.plusDays(day - 1); return " " + Integer.toString(newDate.getDayOfMonth())+"/"+Integer.toString(newDate.getMonthOfYear()); } @Transactional public List<ProjectPlanningLine> populateMyPlanning(ProjectPlanning planning, User user) throws AxelorException{ List<ProjectPlanningLine> planningLineList = new ArrayList<ProjectPlanningLine>(); String query = "self.assignedTo = ?1 OR ?1 MEMBER OF self.membersUserSet"; List<ProjectTask> projectTaskList = Beans.get(ProjectTaskRepository.class).all().filter(query, user).fetch(); if(projectTaskList == null || projectTaskList.isEmpty()){ throw new AxelorException(String.format(I18n.get(IExceptionMessage.PROJECT_PLANNING_NO_TASK)), IException.CONFIGURATION_ERROR); } for (ProjectTask projectTask : projectTaskList) { ProjectPlanningLine projectPlanningLine = null; projectPlanningLine = projectPlanningLineRepository.all().filter("self.user = ?1 AND self.projectTask = ?2 AND self.year = ?3 AND self.week = ?4", user, projectTask, planning.getYear(), planning.getWeek()).fetchOne(); if(projectPlanningLine == null){ projectPlanningLine = new ProjectPlanningLine(); projectPlanningLine.setUser(user); projectPlanningLine.setProjectTask(projectTask); projectPlanningLine.setYear(planning.getYear()); projectPlanningLine.setWeek(planning.getWeek()); projectPlanningLineRepository.save(projectPlanningLine); } planningLineList.add(projectPlanningLine); } return planningLineList; } @Transactional public List<ProjectPlanningLine> populateMyTeamPlanning(ProjectPlanning planning, Team team) throws AxelorException{ List<ProjectPlanningLine> planningLineList = new ArrayList<ProjectPlanningLine>(); List<ProjectTask> projectTaskList = null; Set<User> userList = team.getUserSet(); for (User user : userList) { String query = "self.assignedTo = ?1 OR ?1 MEMBER OF self.membersUserSet"; projectTaskList = Beans.get(ProjectTaskRepository.class).all().filter(query, user).fetch(); if(projectTaskList != null && !projectTaskList.isEmpty()){ for (ProjectTask projectTask : projectTaskList) { ProjectPlanningLine projectPlanningLine = null; projectPlanningLine = projectPlanningLineRepository.all().filter("self.user = ?1 AND self.projectTask = ?2 AND self.year = ?3 AND self.week = ?4", user, projectTask, planning.getYear(), planning.getWeek()).fetchOne(); if(projectPlanningLine == null){ projectPlanningLine = new ProjectPlanningLine(); projectPlanningLine.setUser(user); projectPlanningLine.setProjectTask(projectTask); projectPlanningLine.setYear(planning.getYear()); projectPlanningLine.setWeek(planning.getWeek()); projectPlanningLineRepository.save(projectPlanningLine); } planningLineList.add(projectPlanningLine); } } } if(planningLineList.isEmpty()){ throw new AxelorException(String.format(I18n.get(IExceptionMessage.PROJECT_PLANNING_NO_TASK_TEAM)), IException.CONFIGURATION_ERROR); } return planningLineList; } public LocalDate getFromDate(){ LocalDate todayDate = generalService.getTodayDate(); return new LocalDate(todayDate.getYear(), todayDate.getMonthOfYear(), todayDate.dayOfMonth().getMinimumValue()); } public LocalDate getToDate(){ LocalDate todayDate = generalService.getTodayDate(); return new LocalDate(todayDate.getYear(), todayDate.getMonthOfYear(), todayDate.dayOfMonth().getMaximumValue()); } public void getTasksForUser(ActionRequest request, ActionResponse response){ List<Map<String,String>> dataList = new ArrayList<Map<String,String>>(); LocalDate todayDate = Beans.get(GeneralService.class).getTodayDate(); List<ProjectPlanningLine> linesList = Beans.get(ProjectPlanningLineRepository.class).all(). filter("self.user.id = ?1 AND self.year >= ?2 AND self.week >= ?3", AuthUtils.getUser().getId(), todayDate.getYear(), todayDate.getWeekOfWeekyear()).fetch(); for (ProjectPlanningLine line : linesList) { if(line.getMonday().compareTo(BigDecimal.ZERO) != 0){ LocalDate date = new LocalDate().withYear(line.getYear()).withWeekOfWeekyear(line.getWeek()).withDayOfWeek(DateTimeConstants.MONDAY); if(date.isAfter(todayDate) || date.isEqual(todayDate)){ Map<String, String> map = new HashMap<String,String>(); map.put("taskId", line.getProjectTask().getId().toString()); map.put("name", line.getProjectTask().getFullName()); if(line.getProjectTask().getProject() != null){ map.put("projectName", line.getProjectTask().getProject().getFullName()); } else{ map.put("projectName", ""); } map.put("date", date.toString()); map.put("duration", line.getMonday().toString()); dataList.add(map); } } if(line.getTuesday().compareTo(BigDecimal.ZERO) != 0){ LocalDate date = new LocalDate().withYear(line.getYear()).withWeekOfWeekyear(line.getWeek()).withDayOfWeek(DateTimeConstants.TUESDAY); if(date.isAfter(todayDate) || date.isEqual(todayDate)){ Map<String, String> map = new HashMap<String,String>(); map.put("taskId", line.getProjectTask().getId().toString()); map.put("name", line.getProjectTask().getFullName()); if(line.getProjectTask().getProject() != null){ map.put("projectName", line.getProjectTask().getProject().getFullName()); } else{ map.put("projectName", ""); } map.put("date", date.toString()); map.put("duration", line.getTuesday().toString()); dataList.add(map); } } if(line.getWednesday().compareTo(BigDecimal.ZERO) != 0){ LocalDate date = new LocalDate().withYear(line.getYear()).withWeekOfWeekyear(line.getWeek()).withDayOfWeek(DateTimeConstants.WEDNESDAY); if(date.isAfter(todayDate) || date.isEqual(todayDate)){ Map<String, String> map = new HashMap<String,String>(); map.put("taskId", line.getProjectTask().getId().toString()); map.put("name", line.getProjectTask().getFullName()); if(line.getProjectTask().getProject() != null){ map.put("projectName", line.getProjectTask().getProject().getFullName()); } else{ map.put("projectName", ""); } map.put("date", date.toString()); map.put("duration", line.getWednesday().toString()); dataList.add(map); } } if(line.getThursday().compareTo(BigDecimal.ZERO) != 0){ LocalDate date = new LocalDate().withYear(line.getYear()).withWeekOfWeekyear(line.getWeek()).withDayOfWeek(DateTimeConstants.THURSDAY); if(date.isAfter(todayDate) || date.isEqual(todayDate)){ Map<String, String> map = new HashMap<String,String>(); map.put("taskId", line.getProjectTask().getId().toString()); map.put("name", line.getProjectTask().getFullName()); if(line.getProjectTask().getProject() != null){ map.put("projectName", line.getProjectTask().getProject().getFullName()); } else{ map.put("projectName", ""); } map.put("date", date.toString()); map.put("duration", line.getThursday().toString()); dataList.add(map); } } if(line.getFriday().compareTo(BigDecimal.ZERO) != 0){ LocalDate date = new LocalDate().withYear(line.getYear()).withWeekOfWeekyear(line.getWeek()).withDayOfWeek(DateTimeConstants.FRIDAY); if(date.isAfter(todayDate) || date.isEqual(todayDate)){ Map<String, String> map = new HashMap<String,String>(); map.put("taskId", line.getProjectTask().getId().toString()); map.put("name", line.getProjectTask().getFullName()); if(line.getProjectTask().getProject() != null){ map.put("projectName", line.getProjectTask().getProject().getFullName()); } else{ map.put("projectName", ""); } map.put("date", date.toString()); map.put("duration", line.getFriday().toString()); dataList.add(map); } } if(line.getSaturday().compareTo(BigDecimal.ZERO) != 0){ LocalDate date = new LocalDate().withYear(line.getYear()).withWeekOfWeekyear(line.getWeek()).withDayOfWeek(DateTimeConstants.SATURDAY); if(date.isAfter(todayDate) || date.isEqual(todayDate)){ Map<String, String> map = new HashMap<String,String>(); map.put("taskId", line.getProjectTask().getId().toString()); map.put("name", line.getProjectTask().getFullName()); if(line.getProjectTask().getProject() != null){ map.put("projectName", line.getProjectTask().getProject().getFullName()); } else{ map.put("projectName", ""); } map.put("date", date.toString()); map.put("duration", line.getSaturday().toString()); dataList.add(map); } } if(line.getSunday().compareTo(BigDecimal.ZERO) != 0){ LocalDate date = new LocalDate().withYear(line.getYear()).withWeekOfWeekyear(line.getWeek()).withDayOfWeek(DateTimeConstants.SUNDAY); if(date.isAfter(todayDate) || date.isEqual(todayDate)){ Map<String, String> map = new HashMap<String,String>(); map.put("taskId", line.getProjectTask().getId().toString()); map.put("name", line.getProjectTask().getFullName()); if(line.getProjectTask().getProject() != null){ map.put("projectName", line.getProjectTask().getProject().getFullName()); } else{ map.put("projectName", ""); } map.put("date", date.toString()); map.put("duration", line.getSunday().toString()); dataList.add(map); } } } response.setData(dataList); } }
package org.ovirt.engine.core.bll; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang.NotImplementedException; import org.apache.commons.lang.StringUtils; import org.ovirt.engine.core.bll.context.CommandContext; import org.ovirt.engine.core.bll.memory.MemoryUtils; import org.ovirt.engine.core.bll.network.VmInterfaceManager; import org.ovirt.engine.core.bll.network.vm.VnicProfileHelper; import org.ovirt.engine.core.bll.profiles.CpuProfileHelper; import org.ovirt.engine.core.bll.profiles.DiskProfileHelper; import org.ovirt.engine.core.bll.quota.QuotaConsumptionParameter; import org.ovirt.engine.core.bll.quota.QuotaStorageConsumptionParameter; import org.ovirt.engine.core.bll.quota.QuotaStorageDependent; import org.ovirt.engine.core.bll.snapshots.SnapshotsManager; import org.ovirt.engine.core.bll.tasks.TaskHandlerCommand; import org.ovirt.engine.core.bll.utils.PermissionSubject; import org.ovirt.engine.core.bll.utils.VmDeviceUtils; import org.ovirt.engine.core.bll.validator.DiskImagesValidator; import org.ovirt.engine.core.bll.validator.StorageDomainValidator; import org.ovirt.engine.core.common.AuditLogType; import org.ovirt.engine.core.common.FeatureSupported; import org.ovirt.engine.core.common.VdcObjectType; import org.ovirt.engine.core.common.action.ImportVmParameters; import org.ovirt.engine.core.common.action.LockProperties; import org.ovirt.engine.core.common.action.LockProperties.Scope; import org.ovirt.engine.core.common.action.MoveOrCopyImageGroupParameters; import org.ovirt.engine.core.common.action.RemoveMemoryVolumesParameters; import org.ovirt.engine.core.common.action.VdcActionParametersBase; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.action.VdcReturnValueBase; import org.ovirt.engine.core.common.asynctasks.AsyncTaskCreationInfo; import org.ovirt.engine.core.common.asynctasks.EntityInfo; import org.ovirt.engine.core.common.businessentities.ActionGroup; import org.ovirt.engine.core.common.businessentities.ArchitectureType; import org.ovirt.engine.core.common.businessentities.CopyVolumeType; import org.ovirt.engine.core.common.businessentities.Disk; import org.ovirt.engine.core.common.businessentities.Disk.DiskStorageType; import org.ovirt.engine.core.common.businessentities.DiskImage; import org.ovirt.engine.core.common.businessentities.DiskImageBase; import org.ovirt.engine.core.common.businessentities.DiskImageDynamic; import org.ovirt.engine.core.common.businessentities.DiskInterface; import org.ovirt.engine.core.common.businessentities.Entities; import org.ovirt.engine.core.common.businessentities.ImageDbOperationScope; import org.ovirt.engine.core.common.businessentities.Snapshot; import org.ovirt.engine.core.common.businessentities.Snapshot.SnapshotStatus; import org.ovirt.engine.core.common.businessentities.Snapshot.SnapshotType; import org.ovirt.engine.core.common.businessentities.StorageDomain; import org.ovirt.engine.core.common.businessentities.StorageDomainStatic; import org.ovirt.engine.core.common.businessentities.StorageDomainType; import org.ovirt.engine.core.common.businessentities.VDSGroup; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.VMStatus; import org.ovirt.engine.core.common.businessentities.VmDynamic; import org.ovirt.engine.core.common.businessentities.VmStatic; import org.ovirt.engine.core.common.businessentities.VmStatistics; import org.ovirt.engine.core.common.businessentities.VmTemplate; import org.ovirt.engine.core.common.businessentities.VmTemplateStatus; import org.ovirt.engine.core.common.businessentities.VolumeFormat; import org.ovirt.engine.core.common.businessentities.VolumeType; import org.ovirt.engine.core.common.businessentities.network.VmNetworkInterface; import org.ovirt.engine.core.common.businessentities.network.VmNic; import org.ovirt.engine.core.common.errors.VdcBLLException; import org.ovirt.engine.core.common.errors.VdcBllMessages; import org.ovirt.engine.core.common.locks.LockingGroup; import org.ovirt.engine.core.common.osinfo.OsRepository; import org.ovirt.engine.core.common.queries.GetAllFromExportDomainQueryParameters; import org.ovirt.engine.core.common.queries.IdQueryParameters; import org.ovirt.engine.core.common.queries.VdcQueryReturnValue; import org.ovirt.engine.core.common.queries.VdcQueryType; import org.ovirt.engine.core.common.utils.Pair; import org.ovirt.engine.core.common.utils.SimpleDependecyInjector; import org.ovirt.engine.core.common.validation.group.ImportClonedEntity; import org.ovirt.engine.core.common.validation.group.ImportEntity; import org.ovirt.engine.core.common.vdscommands.GetImageInfoVDSCommandParameters; import org.ovirt.engine.core.common.vdscommands.VDSCommandType; import org.ovirt.engine.core.common.vdscommands.VDSReturnValue; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogDirector; import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogableBase; import org.ovirt.engine.core.utils.GuidUtils; import org.ovirt.engine.core.utils.linq.Function; import org.ovirt.engine.core.utils.linq.LinqUtils; import org.ovirt.engine.core.utils.linq.Predicate; import org.ovirt.engine.core.utils.log.Log; import org.ovirt.engine.core.utils.log.LogFactory; import org.ovirt.engine.core.utils.ovf.OvfLogEventHandler; import org.ovirt.engine.core.utils.ovf.VMStaticOvfLogHandler; import org.ovirt.engine.core.utils.transaction.TransactionMethod; import org.ovirt.engine.core.utils.transaction.TransactionSupport; @DisableInPrepareMode @NonTransactiveCommandAttribute(forceCompensation = true) public class ImportVmCommand<T extends ImportVmParameters> extends MoveOrCopyTemplateCommand<T> implements QuotaStorageDependent, TaskHandlerCommand<T> { private static final Log log = LogFactory.getLog(ImportVmCommand.class); private static VmStatic vmStaticForDefaultValues = new VmStatic(); private List<DiskImage> imageList; private final List<String> macsAdded = new ArrayList<String>(); private final SnapshotsManager snapshotsManager = new SnapshotsManager(); public ImportVmCommand(T parameters) { this(parameters, null); } @Override protected LockProperties applyLockProperties(LockProperties lockProperties) { return lockProperties.withScope(Scope.Command); } @Override protected void init(T parameters) { super.init(parameters); setVmId(parameters.getContainerId()); setVm(parameters.getVm()); setVdsGroupId(parameters.getVdsGroupId()); if (parameters.getVm() != null && getVm().getDiskMap() != null) { imageList = new ArrayList<DiskImage>(); for (Disk disk : getVm().getDiskMap().values()) { if (disk.getDiskStorageType() == DiskStorageType.IMAGE) { imageList.add((DiskImage) disk); } } } ensureDomainMap(imageList, parameters.getDestDomainId()); } @Override protected Map<String, Pair<String, String>> getSharedLocks() { return Collections.singletonMap(getParameters().getContainerId().toString(), LockMessagesMatchUtil.makeLockingPair( LockingGroup.REMOTE_VM, getVmIsBeingImportedMessage())); } @Override protected Map<String, Pair<String, String>> getExclusiveLocks() { if (getParameters().getVm() != null && !StringUtils.isBlank(getParameters().getVm().getName())) { return Collections.singletonMap(getParameters().getVm().getName(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.VM_NAME, VdcBllMessages.ACTION_TYPE_FAILED_NAME_ALREADY_USED)); } return null; } private String getVmIsBeingImportedMessage() { StringBuilder builder = new StringBuilder(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_BEING_IMPORTED.name()); if (getVmName() != null) { builder.append(String.format("$VmName %1$s", getVmName())); } return builder.toString(); } protected ImportVmCommand(Guid commandId) { super(commandId); } public ImportVmCommand(T parameters, CommandContext commandContext) { super(parameters, commandContext); } @Override public Guid getVmId() { if (getParameters().isImportAsNewEntity()) { return getParameters().getVm().getId(); } return super.getVmId(); } @Override public VM getVm() { if (getParameters().isImportAsNewEntity()) { return getParameters().getVm(); } return super.getVm(); } @Override protected boolean canDoAction() { Map<Guid, StorageDomain> domainsMap = new HashMap<Guid, StorageDomain>(); if (getVdsGroup() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_CLUSTER_CAN_NOT_BE_EMPTY); return false; } if (!canDoActionBeforeCloneVm(domainsMap)) { return false; } if (getParameters().isImportAsNewEntity()) { initImportClonedVm(); if (getVm().getInterfaces().size() > getMacPool().getAvailableMacsCount()) { addCanDoActionMessage(VdcBllMessages.MAC_POOL_NOT_ENOUGH_MAC_ADDRESSES); return false; } } OsRepository osRepository = SimpleDependecyInjector.getInstance().get(OsRepository.class); if (getVm().isBalloonEnabled() && !osRepository.isBalloonEnabled(getVm().getStaticData().getOsId(), getVdsGroup().getcompatibility_version())) { addCanDoActionMessageVariable("clusterArch", getVdsGroup().getArchitecture()); return failCanDoAction(VdcBllMessages.BALLOON_REQUESTED_ON_NOT_SUPPORTED_ARCH); } return canDoActionAfterCloneVm(domainsMap); } @Override protected void setActionMessageParameters() { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__IMPORT); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__VM); } private void initImportClonedVm() { Guid guid = Guid.newGuid(); getVm().setId(guid); setVmId(guid); getVm().setName(getParameters().getVm().getName()); getVm().setStoragePoolId(getParameters().getStoragePoolId()); getParameters().setVm(getVm()); for (VmNic iface : getVm().getInterfaces()) { iface.setId(Guid.newGuid()); } } protected boolean canDoActionBeforeCloneVm(Map<Guid, StorageDomain> domainsMap) { List<String> canDoActionMessages = getReturnValue().getCanDoActionMessages(); if (getVm() != null) { setDescription(getVmName()); } if (!checkStoragePool()) { return false; } Set<Guid> destGuids = new HashSet<Guid>(imageToDestinationDomainMap.values()); for (Guid destGuid : destGuids) { StorageDomain storageDomain = getStorageDomain(destGuid); StorageDomainValidator validator = new StorageDomainValidator(storageDomain); if (!validate(validator.isDomainExistAndActive()) || !validate(validator.domainIsValidDestination())) { return false; } domainsMap.put(destGuid, storageDomain); } if (!isImagesAlreadyOnTarget() && getParameters().isImportAsNewEntity() && !getParameters().getCopyCollapse()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_IMPORT_CLONE_NOT_COLLAPSED); } if (isImagesAlreadyOnTarget() && getParameters().getCopyCollapse()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_IMPORT_UNREGISTERED_NOT_COLLAPSED); } if (!isImagesAlreadyOnTarget()) { setSourceDomainId(getParameters().getSourceDomainId()); StorageDomainValidator validator = new StorageDomainValidator(getSourceDomain()); if (validator.isDomainExistAndActive().isValid() && getSourceDomain().getStorageDomainType() != StorageDomainType.ImportExport) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_TYPE_ILLEGAL); } } List<VM> vms = getVmsFromExportDomain(); if (vms == null) { return false; } VM vm = LinqUtils.firstOrNull(vms, new Predicate<VM>() { @Override public boolean eval(VM evalVm) { return evalVm.getId().equals(getParameters().getVm().getId()); } }); if (vm != null) { // At this point we should work with the VM that was read from // the OVF setVm(vm); // Iterate over all the VM images (active image and snapshots) for (DiskImage image : getImages()) { if (Guid.Empty.equals(image.getVmSnapshotId())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_CORRUPTED_VM_SNAPSHOT_ID); } if (getParameters().getCopyCollapse()) { // If copy collapse sent then iterate over the images got from the parameters, until we got // a match with the image from the VM. for (DiskImage p : imageList) { // copy the new disk volume format/type if provided, // only if requested by the user if (p.getImageId().equals(image.getImageId())) { if (p.getVolumeFormat() != null) { image.setvolumeFormat(p.getVolumeFormat()); } if (p.getVolumeType() != null) { image.setVolumeType(p.getVolumeType()); } // Validate the configuration of the image got from the parameters. if (!validateImageConfig(canDoActionMessages, domainsMap, image)) { return false; } break; } } } image.setStoragePoolId(getParameters().getStoragePoolId()); // we put the source domain id in order that copy will // work properly. // we fix it to DestDomainId in // MoveOrCopyAllImageGroups(); image.setStorageIds(new ArrayList<Guid>(Arrays.asList(getSourceDomainId(image)))); } Map<Guid, List<DiskImage>> images = ImagesHandler.getImagesLeaf(getImages()); for (Map.Entry<Guid, List<DiskImage>> entry : images.entrySet()) { Guid id = entry.getKey(); List<DiskImage> diskList = entry.getValue(); getVm().getDiskMap().put(id, getActiveVolumeDisk(diskList)); } } return true; } protected DiskImage getActiveVolumeDisk(List<DiskImage> diskList) { return diskList.get(diskList.size() - 1); } /** * Load images from Import/Export domain. * @return A {@link List} of {@link VM}s, or <code>null</code> if the query to the export domain failed. */ protected List<VM> getVmsFromExportDomain() { GetAllFromExportDomainQueryParameters p = new GetAllFromExportDomainQueryParameters (getParameters().getStoragePoolId(), getParameters().getSourceDomainId()); VdcQueryReturnValue qRetVal = runInternalQuery(VdcQueryType.GetVmsFromExportDomain, p); return qRetVal.getSucceeded() ? qRetVal.<List<VM>>getReturnValue() : null; } private boolean validateImageConfig(List<String> canDoActionMessages, Map<Guid, StorageDomain> domainsMap, DiskImage image) { return ImagesHandler.checkImageConfiguration(domainsMap.get(imageToDestinationDomainMap.get(image.getId())) .getStorageStaticData(), image, canDoActionMessages); } protected boolean canDoActionAfterCloneVm(Map<Guid, StorageDomain> domainsMap) { VM vmFromParams = getParameters().getVm(); // check that the imported vm guid is not in engine if (!validateNoDuplicateVm()) { return false; } if (!validateNoDuplicateDiskImages(imageList)) { return false; } if (!validateDiskInterface(imageList)) { return false; } setVmTemplateId(getVm().getVmtGuid()); if (!templateExists() || !checkTemplateInStorageDomain() || !checkImagesGUIDsLegal() || !canAddVm()) { return false; } if (!VmTemplateHandler.BLANK_VM_TEMPLATE_ID.equals(getVm().getVmtGuid()) && getVmTemplate() != null && getVmTemplate().getStatus() == VmTemplateStatus.Locked) { return failCanDoAction(VdcBllMessages.VM_TEMPLATE_IMAGE_IS_LOCKED); } if (getParameters().getCopyCollapse() && vmFromParams.getDiskMap() != null) { for (Disk disk : vmFromParams.getDiskMap().values()) { if (disk.getDiskStorageType() == DiskStorageType.IMAGE) { DiskImage key = (DiskImage) getVm().getDiskMap().get(disk.getId()); if (key != null) { if (!ImagesHandler.checkImageConfiguration(domainsMap.get(imageToDestinationDomainMap.get(key.getId())) .getStorageStaticData(), (DiskImageBase) disk, getReturnValue().getCanDoActionMessages())) { return false; } } } } } // if collapse true we check that we have the template on source // (backup) domain if (getParameters().getCopyCollapse() && !isTemplateExistsOnExportDomain()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_IMPORTED_TEMPLATE_IS_MISSING, String.format("$DomainName %1$s", getStorageDomainStaticDAO().get(getParameters().getSourceDomainId()).getStorageName())); } if (!validateVmArchitecture()){ return false; } if (!validateVdsCluster()) { return false; } if (!isImagesAlreadyOnTarget()) { if (!handleDestStorageDomains()) { return false; } } if (!validateUsbPolicy()) { return false; } // Check if the display type is supported if (!VmHandler.isDisplayTypeSupported(vmFromParams.getOs(), vmFromParams.getDefaultDisplayType(), getReturnValue().getCanDoActionMessages(), getVdsGroup().getcompatibility_version())) { return false; } if (!validateMacAddress(Entities.<VmNic, VmNetworkInterface> upcast(getVm().getInterfaces()))) { return false; } if (!setAndValidateDiskProfiles()) { return false; } if (!setAndValidateCpuProfile()) { return false; } return true; } protected boolean handleDestStorageDomains() { List<DiskImage> dummiesDisksList = createDiskDummiesForSpaceValidations(imageList); if (getParameters().getCopyCollapse()) { Snapshot activeSnapshot = getActiveSnapshot(); if (activeSnapshot != null && activeSnapshot.containsMemory()) { //Checking space for memory volume of the active image (if there is one) StorageDomain storageDomain = updateStorageDomainInMemoryVolumes(dummiesDisksList); if (storageDomain == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_NO_SUITABLE_DOMAIN_FOUND); } } } else { //Check space for all the snapshot's memory volumes if (!updateDomainsForMemoryImages(dummiesDisksList)) { return false; } } return validateSpaceRequirements(dummiesDisksList); } /** * For each snapshot that has memory volume, this method updates the memory volume with * the storage pool and storage domain it's going to be imported to. * * @return true if we managed to assign storage domain for every memory volume, false otherwise */ private boolean updateDomainsForMemoryImages(List<DiskImage> disksList) { Map<String, String> handledMemoryVolumes = new HashMap<String, String>(); for (Snapshot snapshot : getVm().getSnapshots()) { String memoryVolume = snapshot.getMemoryVolume(); if (memoryVolume.isEmpty()) { continue; } if (handledMemoryVolumes.containsKey(memoryVolume)) { // replace the volume representation with the one with the correct domain & pool snapshot.setMemoryVolume(handledMemoryVolumes.get(memoryVolume)); continue; } StorageDomain storageDomain = updateStorageDomainInMemoryVolumes(disksList); if (storageDomain == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_NO_SUITABLE_DOMAIN_FOUND); } String modifiedMemoryVolume = MemoryUtils.changeStorageDomainAndPoolInMemoryState( memoryVolume, storageDomain.getId(), getParameters().getStoragePoolId()); // replace the volume representation with the one with the correct domain & pool snapshot.setMemoryVolume(modifiedMemoryVolume); // save it in case we'll find other snapshots with the same memory volume handledMemoryVolumes.put(memoryVolume, modifiedMemoryVolume); } return true; } private StorageDomain updateStorageDomainInMemoryVolumes(List<DiskImage> disksList) { List<DiskImage> memoryDisksList = MemoryUtils.createDiskDummies(getVm().getTotalMemorySizeInBytes(), MemoryUtils.META_DATA_SIZE_IN_BYTES); StorageDomain storageDomain = VmHandler.findStorageDomainForMemory(getParameters().getStoragePoolId(), memoryDisksList); disksList.addAll(memoryDisksList); return storageDomain; } /** * Validates that there is no duplicate VM. * @return <code>true</code> if the validation passes, <code>false</code> otherwise. */ protected boolean validateNoDuplicateVm() { VmStatic duplicateVm = getVmStaticDAO().get(getVm().getId()); if (duplicateVm != null) { return failCanDoAction(VdcBllMessages.VM_CANNOT_IMPORT_VM_EXISTS, String.format("$VmName %1$s", duplicateVm.getName())); } return true; } protected boolean validateDiskInterface(Iterable<DiskImage> images) { for (DiskImage diskImage : images) { if (diskImage.getDiskInterface() == DiskInterface.VirtIO_SCSI && !FeatureSupported.virtIoScsi(getVdsGroup().getcompatibility_version())) { return failCanDoAction(VdcBllMessages.VIRTIO_SCSI_INTERFACE_IS_NOT_AVAILABLE_FOR_CLUSTER_LEVEL); } } return true; } protected boolean validateNoDuplicateDiskImages(Iterable<DiskImage> images) { if (!getParameters().isImportAsNewEntity()) { DiskImagesValidator diskImagesValidator = new DiskImagesValidator(images); return validate(diskImagesValidator.diskImagesAlreadyExist()); } return true; } /** * Validates that that the required cluster exists and is compatible * @return <code>true</code> if the validation passes, <code>false</code> otherwise. */ protected boolean validateVdsCluster() { List<VDSGroup> groups = getVdsGroupDAO().getAllForStoragePool(getParameters().getStoragePoolId()); for (VDSGroup group : groups) { if (group.getId().equals(getParameters().getVdsGroupId())) { if (group.getArchitecture() != getVm().getClusterArch()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_CANNOT_IMPORT_VM_ARCHITECTURE_NOT_SUPPORTED_BY_CLUSTER); } return true; } } return failCanDoAction(VdcBllMessages.VDS_CLUSTER_IS_NOT_VALID); } /** * Validates if the VM being imported has a valid architecture. * @return */ protected boolean validateVmArchitecture () { if (getVm().getClusterArch() == ArchitectureType.undefined) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_CANNOT_IMPORT_VM_WITH_NOT_SUPPORTED_ARCHITECTURE); } return true; } /** * Validates the USB policy. * @return <code>true</code> if the validation passes, <code>false</code> otherwise. */ protected boolean validateUsbPolicy() { VM vm = getParameters().getVm(); VmHandler.updateImportedVmUsbPolicy(vm.getStaticData()); return VmHandler.isUsbPolicyLegal(vm.getUsbPolicy(), vm.getOs(), getVdsGroup(), getReturnValue().getCanDoActionMessages()); } private boolean isTemplateExistsOnExportDomain() { if (VmTemplateHandler.BLANK_VM_TEMPLATE_ID.equals(getParameters().getVm().getVmtGuid())) { return true; } VdcQueryReturnValue qRetVal = runInternalQuery( VdcQueryType.GetTemplatesFromExportDomain, new GetAllFromExportDomainQueryParameters(getParameters().getStoragePoolId(), getParameters().getSourceDomainId())); if (qRetVal.getSucceeded()) { Map<VmTemplate, ?> templates = qRetVal.getReturnValue(); for (VmTemplate template : templates.keySet()) { if (getParameters().getVm().getVmtGuid().equals(template.getId())) { return true; } } } return false; } protected boolean checkTemplateInStorageDomain() { boolean retValue = verifyDisksIfNeeded(); if (retValue && !VmTemplateHandler.BLANK_VM_TEMPLATE_ID.equals(getVm().getVmtGuid()) && !getParameters().getCopyCollapse()) { List<StorageDomain> domains = runInternalQuery(VdcQueryType.GetStorageDomainsByVmTemplateId, new IdQueryParameters(getVm().getVmtGuid())).getReturnValue(); List<Guid> domainsId = LinqUtils.transformToList(domains, new Function<StorageDomain, Guid>() { @Override public Guid eval(StorageDomain storageDomainStatic) { return storageDomainStatic.getId(); } }); if (Collections.disjoint(domainsId, imageToDestinationDomainMap.values())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_TEMPLATE_NOT_FOUND_ON_DESTINATION_DOMAIN); } } return retValue; } private boolean verifyDisksIfNeeded() { if (!getParameters().isImportAsNewEntity() && !isImagesAlreadyOnTarget()) { return checkIfDisksExist(imageList); } return true; } private boolean templateExists() { if (getVmTemplate() == null && !getParameters().getCopyCollapse()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_TEMPLATE_DOES_NOT_EXIST); } return true; } protected Guid getSourceDomainId(DiskImage image) { return getParameters().getSourceDomainId(); } protected boolean checkImagesGUIDsLegal() { for (DiskImage image : getImages()) { Guid imageGUID = image.getImageId(); Guid storagePoolId = image.getStoragePoolId() != null ? image.getStoragePoolId() : Guid.Empty; Guid storageDomainId = getSourceDomainId(image); Guid imageGroupId = image.getId() != null ? image.getId() : Guid.Empty; VDSReturnValue retValue = runVdsCommand( VDSCommandType.DoesImageExist, new GetImageInfoVDSCommandParameters(storagePoolId, storageDomainId, imageGroupId, imageGUID)); if (Boolean.FALSE.equals(retValue.getReturnValue())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_IMAGE_DOES_NOT_EXIST); } } return true; } protected boolean canAddVm() { // Checking if a desktop with same name already exists if (VmHandler.isVmWithSameNameExistStatic(getVm().getName())) { return failCanDoAction(VdcBllMessages.VM_CANNOT_IMPORT_VM_NAME_EXISTS); } return true; } @Override protected void executeCommand() { try { addVmToDb(); processImages(!isImagesAlreadyOnTarget()); // if there aren't tasks - we can just perform the end // vm related ops if (getReturnValue().getVdsmTaskIdList().isEmpty()) { endVmRelatedOps(); } // Save Vm Init VmHandler.addVmInitToDB(getVm().getStaticData()); } catch (RuntimeException e) { getMacPool().freeMacs(macsAdded); throw e; } setSucceeded(true); } private void addVmToDb() { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { addVmStatic(); addVmDynamic(); addVmInterfaces(); addVmStatistics(); getCompensationContext().stateChanged(); return null; } }); } private void processImages(final boolean useCopyImages) { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { addVmImagesAndSnapshots(); updateSnapshotsFromExport(); if (useCopyImages) { moveOrCopyAllImageGroups(); } VmDeviceUtils.addImportedDevices(getVm().getStaticData(), getParameters().isImportAsNewEntity()); if (getParameters().isImportAsNewEntity()) { getParameters().setVm(getVm()); setVmId(getVm().getId()); } return null; } }); } @Override protected void moveOrCopyAllImageGroups() { moveOrCopyAllImageGroups(getVm().getId(), ImagesHandler.filterImageDisks(getVm().getDiskMap().values(), false, false, true)); copyAllMemoryImages(getVm().getId()); } private void copyAllMemoryImages(Guid containerId) { for (String memoryVolumes : MemoryUtils.getMemoryVolumesFromSnapshots(getVm().getSnapshots())) { List<Guid> guids = GuidUtils.getGuidListFromString(memoryVolumes); // copy the memory dump image VdcReturnValueBase vdcRetValue = runInternalActionWithTasksContext( VdcActionType.CopyImageGroup, buildMoveOrCopyImageGroupParametersForMemoryDumpImage( containerId, guids.get(0), guids.get(2), guids.get(3))); if (!vdcRetValue.getSucceeded()) { throw new VdcBLLException(vdcRetValue.getFault().getError(), "Failed during ExportVmCommand"); } getReturnValue().getVdsmTaskIdList().addAll(vdcRetValue.getInternalVdsmTaskIdList()); // copy the memory configuration (of the VM) image vdcRetValue = runInternalActionWithTasksContext( VdcActionType.CopyImageGroup, buildMoveOrCopyImageGroupParametersForMemoryConfImage( containerId, guids.get(0), guids.get(4), guids.get(5))); if (!vdcRetValue.getSucceeded()) { throw new VdcBLLException(vdcRetValue.getFault().getError(), "Failed during ExportVmCommand"); } getReturnValue().getVdsmTaskIdList().addAll(vdcRetValue.getInternalVdsmTaskIdList()); } } private MoveOrCopyImageGroupParameters buildMoveOrCopyImageGroupParametersForMemoryDumpImage(Guid containerID, Guid storageId, Guid imageId, Guid volumeId) { MoveOrCopyImageGroupParameters params = new MoveOrCopyImageGroupParameters(containerID, imageId, volumeId, imageId, volumeId, storageId, getMoveOrCopyImageOperation()); params.setParentCommand(getActionType()); params.setCopyVolumeType(CopyVolumeType.LeafVol); params.setForceOverride(getParameters().getForceOverride()); params.setSourceDomainId(getParameters().getSourceDomainId()); params.setStoragePoolId(getParameters().getStoragePoolId()); params.setImportEntity(true); params.setEntityInfo(new EntityInfo(VdcObjectType.VM, getVm().getId())); params.setParentParameters(getParameters()); StorageDomainStatic storageDomain = getStorageDomainStaticDAO().get(storageId); if (storageDomain.getStorageType().isBlockDomain()) { params.setUseCopyCollapse(true); params.setVolumeType(VolumeType.Preallocated); params.setVolumeFormat(VolumeFormat.RAW); } return params; } private MoveOrCopyImageGroupParameters buildMoveOrCopyImageGroupParametersForMemoryConfImage(Guid containerID, Guid storageId, Guid imageId, Guid volumeId) { MoveOrCopyImageGroupParameters params = new MoveOrCopyImageGroupParameters(containerID, imageId, volumeId, imageId, volumeId, storageId, getMoveOrCopyImageOperation()); params.setParentCommand(getActionType()); // This volume is always of type 'sparse' and format 'cow' so no need to convert, // and there're no snapshots for it so no reason to use copy collapse params.setUseCopyCollapse(false); params.setEntityInfo(new EntityInfo(VdcObjectType.VM, getVm().getId())); params.setCopyVolumeType(CopyVolumeType.LeafVol); params.setForceOverride(getParameters().getForceOverride()); params.setParentParameters(getParameters()); params.setSourceDomainId(getParameters().getSourceDomainId()); params.setStoragePoolId(getParameters().getStoragePoolId()); params.setImportEntity(true); return params; } @Override protected void moveOrCopyAllImageGroups(Guid containerID, Iterable<DiskImage> disks) { for (DiskImage disk : disks) { VdcReturnValueBase vdcRetValue = runInternalActionWithTasksContext( VdcActionType.CopyImageGroup, buildMoveOrCopyImageGroupParametersForDisk(disk, containerID)); if (!vdcRetValue.getSucceeded()) { throw new VdcBLLException(vdcRetValue.getFault().getError(), "ImportVmCommand::MoveOrCopyAllImageGroups: Failed to copy disk!"); } getReturnValue().getVdsmTaskIdList().addAll(vdcRetValue.getInternalVdsmTaskIdList()); } } private MoveOrCopyImageGroupParameters buildMoveOrCopyImageGroupParametersForDisk(DiskImage disk, Guid containerID) { Guid originalDiskId = newDiskIdForDisk.get(disk.getId()).getId(); Guid destinationDomain = imageToDestinationDomainMap.get(originalDiskId); MoveOrCopyImageGroupParameters params = new MoveOrCopyImageGroupParameters(containerID, originalDiskId, newDiskIdForDisk.get(disk.getId()).getImageId(), disk.getId(), disk.getImageId(), destinationDomain, getMoveOrCopyImageOperation()); params.setParentCommand(getActionType()); params.setUseCopyCollapse(getParameters().getCopyCollapse()); params.setCopyVolumeType(CopyVolumeType.LeafVol); params.setForceOverride(getParameters().getForceOverride()); params.setSourceDomainId(getParameters().getSourceDomainId()); params.setStoragePoolId(getParameters().getStoragePoolId()); params.setImportEntity(true); params.setEntityInfo(new EntityInfo(VdcObjectType.VM, getVm().getId())); params.setRevertDbOperationScope(ImageDbOperationScope.IMAGE); params.setQuotaId(disk.getQuotaId() != null ? disk.getQuotaId() : getParameters().getQuotaId()); params.setDiskProfileId(disk.getDiskProfileId()); if (getParameters().getVm().getDiskMap() != null && getParameters().getVm().getDiskMap().containsKey(originalDiskId)) { DiskImageBase diskImageBase = (DiskImageBase) getParameters().getVm().getDiskMap().get(originalDiskId); params.setVolumeType(diskImageBase.getVolumeType()); params.setVolumeFormat(diskImageBase.getVolumeFormat()); } params.setParentParameters(getParameters()); return params; } protected void addVmImagesAndSnapshots() { Map<Guid, List<DiskImage>> images = ImagesHandler.getImagesLeaf(getImages()); if (getParameters().getCopyCollapse()) { Guid snapshotId = Guid.newGuid(); int aliasCounter = 0; for (List<DiskImage> diskList : images.values()) { DiskImage disk = getActiveVolumeDisk(diskList); disk.setParentId(VmTemplateHandler.BLANK_VM_TEMPLATE_ID); disk.setImageTemplateId(VmTemplateHandler.BLANK_VM_TEMPLATE_ID); disk.setVmSnapshotId(snapshotId); disk.setActive(true); if (getParameters().getVm().getDiskMap() != null && getParameters().getVm().getDiskMap().containsKey(disk.getId())) { DiskImageBase diskImageBase = (DiskImageBase) getParameters().getVm().getDiskMap().get(disk.getId()); disk.setvolumeFormat(diskImageBase.getVolumeFormat()); disk.setVolumeType(diskImageBase.getVolumeType()); } setDiskStorageDomainInfo(disk); if (getParameters().isImportAsNewEntity()) { generateNewDiskId(diskList, disk); updateManagedDeviceMap(disk, getVm().getStaticData().getManagedDeviceMap()); } else { newDiskIdForDisk.put(disk.getId(), disk); } disk.setCreationDate(new Date()); saveImage(disk); ImagesHandler.setDiskAlias(disk, getVm(), ++aliasCounter); saveBaseDisk(disk); saveDiskImageDynamic(disk); } Snapshot snapshot = addActiveSnapshot(snapshotId); getVm().setSnapshots(Arrays.asList(snapshot)); } else { Guid snapshotId = null; for (DiskImage disk : getImages()) { disk.setActive(false); setDiskStorageDomainInfo(disk); saveImage(disk); snapshotId = disk.getVmSnapshotId(); saveSnapshotIfNotExists(snapshotId, disk); saveDiskImageDynamic(disk); } int aliasCounter = 0; for (List<DiskImage> diskList : images.values()) { DiskImage disk = getActiveVolumeDisk(diskList); newDiskIdForDisk.put(disk.getId(), disk); snapshotId = disk.getVmSnapshotId(); disk.setActive(true); ImagesHandler.setDiskAlias(disk, getVm(), ++aliasCounter); updateImage(disk); saveBaseDisk(disk); } // Update active snapshot's data, since it was inserted as a regular snapshot. updateActiveSnapshot(snapshotId); } } private void setDiskStorageDomainInfo(DiskImage disk) { ArrayList<Guid> storageDomain = new ArrayList<Guid>(); storageDomain.add(imageToDestinationDomainMap.get(disk.getId())); disk.setStorageIds(storageDomain); } /** Saves the base disk object */ protected void saveBaseDisk(DiskImage disk) { getBaseDiskDao().save(disk); } /** Save the entire image, including it's storage mapping */ protected void saveImage(DiskImage disk) { BaseImagesCommand.saveImage(disk); } /** Updates an image of a disk */ protected void updateImage(DiskImage disk) { getImageDao().update(disk.getImage()); } /** * Generates and saves a {@link DiskImageDynamic} for the given {@link #disk}. * @param disk The imported disk **/ protected void saveDiskImageDynamic(DiskImage disk) { DiskImageDynamic diskDynamic = new DiskImageDynamic(); diskDynamic.setId(disk.getImageId()); diskDynamic.setactual_size(disk.getActualSizeInBytes()); getDiskImageDynamicDAO().save(diskDynamic); } /** * Saves a new active snapshot for the VM * @param snapshotId The ID to assign to the snapshot * @return The generated snapshot */ protected Snapshot addActiveSnapshot(Guid snapshotId) { return snapshotsManager.addActiveSnapshot(snapshotId, getVm(), getMemoryVolumeForNewActiveSnapshot(), getCompensationContext()); } private String getMemoryVolumeForNewActiveSnapshot() { return getParameters().isImportAsNewEntity() ? // We currently don't support using memory that was // saved when a snapshot was taken for VM with different id StringUtils.EMPTY : getMemoryVolumeFromActiveSnapshotInExportDomain(); } private String getMemoryVolumeFromActiveSnapshotInExportDomain() { Snapshot activeSnapshot = getActiveSnapshot(); if (activeSnapshot != null) { return activeSnapshot.getMemoryVolume(); } return StringUtils.EMPTY; } private Snapshot getActiveSnapshot() { for (Snapshot snapshot : getVm().getSnapshots()) { if (snapshot.getType() == SnapshotType.ACTIVE) return snapshot; } log.warnFormat("VM {0} doesn't have active snapshot in export domain", getVmId()); return null; } /** * Go over the snapshots that were read from the export data. If the snapshot exists (since it was added for the * images), it will be updated. If it doesn't exist, it will be saved. */ private void updateSnapshotsFromExport() { if (getVm().getSnapshots() == null) { return; } for (Snapshot snapshot : getVm().getSnapshots()) { if (getSnapshotDao().exists(getVm().getId(), snapshot.getId())) { getSnapshotDao().update(snapshot); } else { getSnapshotDao().save(snapshot); } } } /** * Save a snapshot if it does not exist in the database. * @param snapshotId The snapshot to save. * @param disk The disk containing the snapshot's information. */ protected void saveSnapshotIfNotExists(Guid snapshotId, DiskImage disk) { if (!getSnapshotDao().exists(getVm().getId(), snapshotId)) { getSnapshotDao().save( new Snapshot(snapshotId, SnapshotStatus.OK, getVm().getId(), null, SnapshotType.REGULAR, disk.getDescription(), disk.getLastModifiedDate(), disk.getAppList())); } } /** * Update a snapshot and make it the active snapshot. * @param snapshotId The snapshot to update. */ protected void updateActiveSnapshot(Guid snapshotId) { getSnapshotDao().update( new Snapshot(snapshotId, SnapshotStatus.OK, getVm().getId(), null, SnapshotType.ACTIVE, "Active VM snapshot", new Date(), null)); } protected void addVmStatic() { logImportEvents(); getVm().getStaticData().setId(getVmId()); getVm().getStaticData().setCreationDate(new Date()); getVm().getStaticData().setVdsGroupId(getParameters().getVdsGroupId()); getVm().getStaticData().setMinAllocatedMem(computeMinAllocatedMem()); getVm().getStaticData().setQuotaId(getParameters().getQuotaId()); if (getVm().getOriginalTemplateGuid() != null && !VmTemplateHandler.BLANK_VM_TEMPLATE_ID.equals(getVm().getOriginalTemplateGuid())) { // no need to check this for blank VmTemplate originalTemplate = getVmTemplateDAO().get(getVm().getOriginalTemplateGuid()); if (originalTemplate != null) { // in case the original template name has been changed in the meantime getVm().getStaticData().setOriginalTemplateName(originalTemplate.getName()); } } if (getParameters().getCopyCollapse()) { getVm().setVmtGuid(VmTemplateHandler.BLANK_VM_TEMPLATE_ID); } getVmStaticDAO().save(getVm().getStaticData()); getCompensationContext().snapshotNewEntity(getVm().getStaticData()); } private int computeMinAllocatedMem() { if (getVm().getMinAllocatedMem() > 0) { return getVm().getMinAllocatedMem(); } VDSGroup vdsGroup = getVdsGroup(); if (vdsGroup != null && vdsGroup.getmax_vds_memory_over_commit() > 0) { return (getVm().getMemSizeMb() * 100) / vdsGroup.getmax_vds_memory_over_commit(); } return getVm().getMemSizeMb(); } private void logImportEvents() { // Some values at the OVF file are used for creating events at the GUI // for the sake of providing information on the content of the VM that // was exported, // but not setting it in the imported VM VmStatic vmStaticFromOvf = getVm().getStaticData(); OvfLogEventHandler<VmStatic> handler = new VMStaticOvfLogHandler(vmStaticFromOvf); Map<String, String> aliasesValuesMap = handler.getAliasesValuesMap(); for (Map.Entry<String, String> entry : aliasesValuesMap.entrySet()) { String fieldName = entry.getKey(); String fieldValue = entry.getValue(); logField(vmStaticFromOvf, fieldName, fieldValue); } handler.resetDefaults(vmStaticForDefaultValues); } private static void logField(VmStatic vmStaticFromOvf, String fieldName, String fieldValue) { String vmName = vmStaticFromOvf.getName(); AuditLogableBase logable = new AuditLogableBase(); logable.addCustomValue("FieldName", fieldName); logable.addCustomValue("VmName", vmName); logable.addCustomValue("FieldValue", fieldValue); AuditLogDirector.log(logable, AuditLogType.VM_IMPORT_INFO); } protected void addVmInterfaces() { VmInterfaceManager vmInterfaceManager = new VmInterfaceManager(getMacPool()); VnicProfileHelper vnicProfileHelper = new VnicProfileHelper(getVdsGroupId(), getStoragePoolId(), getVdsGroup().getcompatibility_version(), AuditLogType.IMPORTEXPORT_IMPORT_VM_INVALID_INTERFACES); List<VmNetworkInterface> nics = getVm().getInterfaces(); vmInterfaceManager.sortVmNics(nics, getVm().getStaticData().getManagedDeviceMap()); // If we import it as a new entity, then we allocate all MAC addresses in advance if (getParameters().isImportAsNewEntity()) { List<String> macAddresses = getMacPool().allocateMacAddresses(nics.size()); for (int i = 0; i < nics.size(); ++i) { nics.get(i).setMacAddress(macAddresses.get(i)); } } for (VmNetworkInterface iface : getVm().getInterfaces()) { initInterface(iface); vnicProfileHelper.updateNicWithVnicProfileForUser(iface, getCurrentUser()); vmInterfaceManager.add(iface, getCompensationContext(), !getParameters().isImportAsNewEntity(), getVm().getOs(), getVdsGroup().getcompatibility_version()); macsAdded.add(iface.getMacAddress()); } vnicProfileHelper.auditInvalidInterfaces(getVmName()); } private void initInterface(VmNic iface) { if (iface.getId() == null) { iface.setId(Guid.newGuid()); } fillMacAddressIfMissing(iface); iface.setVmTemplateId(null); iface.setVmId(getVmId()); } private void addVmDynamic() { VmDynamic tempVar = new VmDynamic(); tempVar.setId(getVmId()); tempVar.setStatus(VMStatus.ImageLocked); tempVar.setVmHost(""); tempVar.setVmIp(""); tempVar.setVmFQDN(""); tempVar.setLastStopTime(new Date()); tempVar.setAppList(getParameters().getVm().getDynamicData().getAppList()); getVmDynamicDAO().save(tempVar); getCompensationContext().snapshotNewEntity(tempVar); } private void addVmStatistics() { VmStatistics stats = new VmStatistics(); stats.setId(getVmId()); getVmStatisticsDAO().save(stats); getCompensationContext().snapshotNewEntity(stats); getCompensationContext().stateChanged(); } @Override protected void endSuccessfully() { checkTrustedService(); endImportCommand(); } private void checkTrustedService() { AuditLogableBase logable = new AuditLogableBase(); logable.addCustomValue("VmName", getVmName()); if (getVm().isTrustedService() && !getVdsGroup().supportsTrustedService()) { AuditLogDirector.log(logable, AuditLogType.IMPORTEXPORT_IMPORT_VM_FROM_TRUSTED_TO_UNTRUSTED); } else if (!getVm().isTrustedService() && getVdsGroup().supportsTrustedService()) { AuditLogDirector.log(logable, AuditLogType.IMPORTEXPORT_IMPORT_VM_FROM_UNTRUSTED_TO_TRUSTED); } } @Override protected void endActionOnAllImageGroups() { for (VdcActionParametersBase p : getParameters().getImagesParameters()) { p.setTaskGroupSuccess(getParameters().getTaskGroupSuccess()); getBackend().endAction(getImagesActionType(), p, getContext().clone().withoutCompensationContext().withoutExecutionContext().withoutLock()); } } @Override protected void endWithFailure() { // Going to try and refresh the VM by re-loading it form DB setVm(null); if (getVm() != null) { removeVmSnapshots(); endActionOnAllImageGroups(); removeVmNetworkInterfaces(); getVmDynamicDAO().remove(getVmId()); getVmStatisticsDAO().remove(getVmId()); getVmStaticDAO().remove(getVmId()); setSucceeded(true); } else { setVm(getParameters().getVm()); // Setting VM from params, for logging purposes // No point in trying to end action again, as the imported VM does not exist in the DB. getReturnValue().setEndActionTryAgain(false); } } private void removeVmSnapshots() { Guid vmId = getVmId(); Set<String> memoryStates = snapshotsManager.removeSnapshots(vmId); for (String memoryState : memoryStates) { removeMemoryVolumes(memoryState, vmId); } } private void removeMemoryVolumes(String memoryVolume, Guid vmId) { VdcReturnValueBase retVal = runInternalAction( VdcActionType.RemoveMemoryVolumes, new RemoveMemoryVolumesParameters(memoryVolume, vmId), cloneContextAndDetachFromParent()); if (!retVal.getSucceeded()) { log.errorFormat("Failed to remove memory volumes: {0}", memoryVolume); } } protected void removeVmNetworkInterfaces() { new VmInterfaceManager(getMacPool()).removeAll(getVmId()); } protected void endImportCommand() { endActionOnAllImageGroups(); endVmRelatedOps(); setSucceeded(true); } private void endVmRelatedOps() { setVm(null); if (getVm() != null) { VmHandler.unLockVm(getVm()); } else { setCommandShouldBeLogged(false); log.warn("ImportVmCommand::EndImportCommand: Vm is null - not performing full endAction"); } } @Override public AuditLogType getAuditLogTypeValue() { switch (getActionState()) { case EXECUTE: return getSucceeded() ? AuditLogType.IMPORTEXPORT_STARTING_IMPORT_VM : AuditLogType.IMPORTEXPORT_IMPORT_VM_FAILED; case END_SUCCESS: return getSucceeded() ? AuditLogType.IMPORTEXPORT_IMPORT_VM : AuditLogType.IMPORTEXPORT_IMPORT_VM_FAILED; case END_FAILURE: return AuditLogType.IMPORTEXPORT_IMPORT_VM_FAILED; } return super.getAuditLogTypeValue(); } @Override protected List<Class<?>> getValidationGroups() { if (getParameters().isImportAsNewEntity()) { return addValidationGroup(ImportClonedEntity.class); } return addValidationGroup(ImportEntity.class); } @Override public List<PermissionSubject> getPermissionCheckSubjects() { List<PermissionSubject> permissionList = super.getPermissionCheckSubjects(); if (getVm() != null && !StringUtils.isEmpty(getVm().getCustomProperties())) { permissionList.add(new PermissionSubject(getVdsGroupId(), VdcObjectType.VdsGroups, ActionGroup.CHANGE_VM_CUSTOM_PROPERTIES)); } return permissionList; } @Override public Map<String, String> getJobMessageProperties() { if (jobProperties == null) { jobProperties = super.getJobMessageProperties(); jobProperties.put(VdcObjectType.VM.name().toLowerCase(), (getVmName() == null) ? "" : getVmName()); jobProperties.put(VdcObjectType.VdsGroups.name().toLowerCase(), getVdsGroupName()); } return jobProperties; } protected boolean setAndValidateDiskProfiles() { if (getParameters().getVm().getDiskMap() != null) { Map<DiskImage, Guid> map = new HashMap<>(); for (Disk disk : getParameters().getVm().getDiskMap().values()) { if (disk.getDiskStorageType() == DiskStorageType.IMAGE) { DiskImage diskImage = (DiskImage) disk; map.put(diskImage, imageToDestinationDomainMap.get(diskImage.getId())); } } return validate(DiskProfileHelper.setAndValidateDiskProfiles(map, getStoragePool().getcompatibility_version())); } return true; } protected boolean setAndValidateCpuProfile() { getVm().getStaticData().setVdsGroupId(getVdsGroupId()); getVm().getStaticData().setCpuProfileId(getParameters().getCpuProfileId()); return validate(CpuProfileHelper.setAndValidateCpuProfile(getVm().getStaticData(), getVdsGroup().getcompatibility_version())); } @Override public List<QuotaConsumptionParameter> getQuotaStorageConsumptionParameters() { List<QuotaConsumptionParameter> list = new ArrayList<QuotaConsumptionParameter>(); for (Disk disk : getParameters().getVm().getDiskMap().values()) { //TODO: handle import more than once; if(disk instanceof DiskImage){ DiskImage diskImage = (DiskImage)disk; list.add(new QuotaStorageConsumptionParameter( diskImage.getQuotaId(), null, QuotaConsumptionParameter.QuotaAction.CONSUME, imageToDestinationDomainMap.get(diskImage.getId()), (double)diskImage.getSizeInGigabytes())); } } return list; } @Override protected List<DiskImage> getImages() { return getVm().getImages(); } // TaskHandlerCommand Implementation // @Override public T getParameters() { return super.getParameters(); } @Override public VdcActionType getActionType() { return super.getActionType(); } @Override public VdcReturnValueBase getReturnValue() { return super.getReturnValue(); } @Override public Guid createTask(Guid taskId, AsyncTaskCreationInfo asyncTaskCreationInfo, VdcActionType parentCommand, VdcObjectType entityType, Guid... entityIds) { return super.createTaskInCurrentTransaction(taskId, asyncTaskCreationInfo, parentCommand, entityType, entityIds); } @Override public Guid createTask(Guid taskId, AsyncTaskCreationInfo asyncTaskCreationInfo, VdcActionType parentCommand) { return super.createTask(taskId, asyncTaskCreationInfo, parentCommand); } @Override public ArrayList<Guid> getTaskIdList() { return super.getTaskIdList(); } @Override public void taskEndSuccessfully() { // Not implemented } @Override public void preventRollback() { throw new NotImplementedException(); } @Override public Guid persistAsyncTaskPlaceHolder() { return super.persistAsyncTaskPlaceHolder(getActionType()); } @Override public Guid persistAsyncTaskPlaceHolder(String taskKey) { return super.persistAsyncTaskPlaceHolder(getActionType(), taskKey); } }
package com.teradata.benchto.driver.loader; import com.facebook.presto.jdbc.internal.guava.collect.ImmutableList; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableMap; import com.teradata.benchto.driver.Benchmark; import com.teradata.benchto.driver.BenchmarkExecutionException; import com.teradata.benchto.driver.BenchmarkProperties; import com.teradata.benchto.driver.DriverApp; import com.teradata.benchto.driver.Query; import com.teradata.benchto.driver.service.BenchmarkServiceClient; import freemarker.template.Configuration; import org.assertj.core.api.MapAssert; import org.assertj.core.data.MapEntry; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.springframework.test.util.ReflectionTestUtils; import java.io.IOException; import java.time.Duration; import java.util.List; import java.util.Optional; import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.data.MapEntry.entry; public class BenchmarkLoaderTest { @Rule public ExpectedException thrown = ExpectedException.none(); private BenchmarkProperties benchmarkProperties; private BenchmarkLoader loader; private Duration benchmarkExecutionAge = Duration.ofDays(Integer.MAX_VALUE); @Before public void setupBenchmarkLoader() throws Exception { QueryLoader queryLoader = mockQueryLoader(); benchmarkProperties = new BenchmarkProperties(); BenchmarkServiceClient benchmarkServiceClient = mockBenchmarkServiceClient(); Configuration freemarkerConfiguration = new DriverApp().freemarkerConfiguration().createConfiguration(); loader = new BenchmarkLoader(); ReflectionTestUtils.setField(loader, "properties", benchmarkProperties); ReflectionTestUtils.setField(loader, "queryLoader", queryLoader); ReflectionTestUtils.setField(loader, "benchmarkServiceClient", benchmarkServiceClient); ReflectionTestUtils.setField(loader, "freemarkerConfiguration", freemarkerConfiguration); withBenchmarksDir("unit-benchmarks"); withFrequencyCheckEnabled(true); } private QueryLoader mockQueryLoader() { return new QueryLoader() { @Override public Query loadFromFile(String queryName) { return new Query(queryName, ImmutableList.of("test query"), ImmutableMap.of()); } }; } private BenchmarkServiceClient mockBenchmarkServiceClient() { return new BenchmarkServiceClient() { @Override public List<String> generateUniqueBenchmarkNames(List<GenerateUniqueNamesRequestItem> generateUniqueNamesRequestItems) { return generateUniqueNamesRequestItems.stream() .map(requestItem -> requestItem.getName() + "_" + Joiner.on("_").withKeyValueSeparator("=").join(requestItem.getVariables().entrySet())) .collect(toList()); } @Override public List<Duration> getBenchmarkSuccessfulExecutionAges(List<String> benchmarkUniqueNames) { return benchmarkUniqueNames.stream() .map(benchmark -> benchmarkExecutionAge) .collect(toList()); } }; } @Test public void shouldLoadSimpleBenchmark() throws IOException { withActiveBenchmarks("simple-benchmark"); Benchmark benchmark = assertLoadedBenchmarksCount(1).get(0); assertThat(benchmark.getQueries()).extracting("name").containsExactly("q1", "q2", "1", "2"); assertThat(benchmark.getDataSource()).isEqualTo("foo"); assertThat(benchmark.getRuns()).isEqualTo(3); assertThat(benchmark.getConcurrency()).isEqualTo(1); assertThat(benchmark.getBeforeBenchmarkMacros()).isEqualTo(ImmutableList.of("no-op", "no-op2")); assertThat(benchmark.getAfterBenchmarkMacros()).isEqualTo(ImmutableList.of("no-op2")); assertThat(benchmark.getPrewarmRuns()).isEqualTo(2); } @Test public void shouldLoadConcurrentBenchmark() throws IOException { withActiveBenchmarks("concurrent-benchmark"); Benchmark benchmark = assertLoadedBenchmarksCount(1).get(0); assertThat(benchmark.getDataSource()).isEqualTo("foo"); assertThat(benchmark.getQueries()).extracting("name").containsExactly("q1", "q2", "1", "2"); assertThat(benchmark.getRuns()).isEqualTo(10); assertThat(benchmark.getConcurrency()).isEqualTo(20); assertThat(benchmark.getAfterBenchmarkMacros()).isEmpty(); assertThat(benchmark.getBeforeBenchmarkMacros()).isEmpty(); } @Test public void shouldLoadBenchmarkWithVariables() throws IOException { withActiveBenchmarks("multi-variables-benchmark"); List<Benchmark> benchmarks = assertLoadedBenchmarksCount(5); for (Benchmark benchmark : benchmarks) { assertThat(benchmark.getDataSource()).isEqualTo("foo"); assertThat(benchmark.getQueries()).extracting("name").containsExactly("q1", "q2", "1", "2"); } assertThatBenchmarkWithEntries(benchmarks, entry("size", "1GB"), entry("format", "txt")) .containsOnly(entry("size", "1GB"), entry("format", "txt"), entry("pattern", "1GB-txt")); assertThatBenchmarkWithEntries(benchmarks, entry("size", "1GB"), entry("format", "orc")) .containsOnly(entry("size", "1GB"), entry("format", "orc"), entry("pattern", "1GB-orc")); assertThatBenchmarkWithEntries(benchmarks, entry("size", "2GB"), entry("format", "txt")) .containsOnly(entry("size", "2GB"), entry("format", "txt"), entry("pattern", "2GB-txt")); assertThatBenchmarkWithEntries(benchmarks, entry("size", "2GB"), entry("format", "orc")) .containsOnly(entry("size", "2GB"), entry("format", "orc"), entry("pattern", "2GB-orc")); assertThatBenchmarkWithEntries(benchmarks, entry("size", "10GB"), entry("format", "parquet")) .containsOnly(entry("size", "10GB"), entry("format", "parquet"), entry("pattern", "10GB-parquet")); } @Test public void benchmarkWithCycleVariables() throws IOException { thrown.expect(BenchmarkExecutionException.class); thrown.expectMessage("Recursive value substitution is not supported, invalid a: ${b}"); withBenchmarksDir("unit-benchmarks-invalid"); withActiveBenchmarks("cycle-variables-benchmark"); loader.loadBenchmarks("sequenceId"); } @Test public void quarantineBenchmark_no_quarantine_filtering() throws IOException { withActiveBenchmarks("quarantine-benchmark"); assertLoadedBenchmarksCount(1); } @Test public void quarantineBenchmark_quarantine_false_filtering() throws IOException { withActiveBenchmarks("quarantine-benchmark"); withActiveVariables("quarantine=false"); assertLoadedBenchmarksCount(0); } @Test public void allBenchmarks_no_quarantine_filtering() throws IOException { assertLoadedBenchmarksCount(8); } @Test public void allBenchmarks_quarantine_false_filtering() throws IOException { withActiveVariables("quarantine=false"); assertLoadedBenchmarksCount(7); } @Test public void getAllBenchmarks_activeVariables_with_regex() { withActiveVariables("format=(rc)|(tx)"); assertLoadedBenchmarksCount(4).forEach(benchmark -> assertThat(benchmark.getVariables().get("format")).isIn("orc", "txt") ); } @Test public void allBenchmarks_load_only_not_executed_within_two_days() { Duration executionAge = Duration.ofDays(2); withBenchmarkExecutionAge(executionAge); withFrequencyCheckEnabled(true); assertLoadedBenchmarksCount(6).forEach(benchmark -> { Optional<Duration> frequency = benchmark.getFrequency(); if (frequency.isPresent()) { assertThat(frequency.get()).isLessThanOrEqualTo(executionAge); } } ); } @Test public void allBenchmarks_frequency_check_is_disabled() { withBenchmarkExecutionAge(Duration.ofDays(2)); withFrequencyCheckEnabled(false); assertLoadedBenchmarksCount(8); } private MapAssert<String, String> assertThatBenchmarkWithEntries(List<Benchmark> benchmarks, MapEntry<String, String>... entries) { Benchmark searchBenchmark = benchmarks.stream() .filter(benchmark -> { boolean containsAllEntries = true; for (MapEntry mapEntry : entries) { Object value = benchmark.getNonReservedKeywordVariables().get(mapEntry.key); if (!mapEntry.value.equals(value)) { containsAllEntries = false; break; } } return containsAllEntries; }) .findFirst().get(); return assertThat(searchBenchmark.getNonReservedKeywordVariables()); } private List<Benchmark> assertLoadedBenchmarksCount(int expected) { List<Benchmark> benchmarks = loader.loadBenchmarks("sequenceId"); assertThat(benchmarks).hasSize(expected); return benchmarks; } private void withBenchmarksDir(String benchmarksDir) { ReflectionTestUtils.setField(benchmarkProperties, "benchmarksDir", benchmarksDir); } private void withActiveBenchmarks(String benchmarkName) { ReflectionTestUtils.setField(benchmarkProperties, "activeBenchmarks", benchmarkName); } private void withActiveVariables(String activeVariables) { ReflectionTestUtils.setField(benchmarkProperties, "activeVariables", activeVariables); } private void withFrequencyCheckEnabled(boolean enabled) { ReflectionTestUtils.setField(benchmarkProperties, "frequencyCheckEnabled", Boolean.toString(enabled)); } private void withBenchmarkExecutionAge(Duration executionAge) { this.benchmarkExecutionAge = executionAge; } }
package org.bitrepository.protocol; import org.bitrepository.bitrepositorymessages.GetChecksumsComplete; import org.jaccept.structure.ExtendedTestCase; import org.testng.annotations.Test; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import javax.xml.namespace.NamespaceContext; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import java.io.File; import java.io.FileInputStream; import java.util.Iterator; /** * Test whether we are able to create message objects from xml. The input XML is the example code defined in the * message-xml, thereby also testing whether this is valid. * */ public class MessageCreationTest extends ExtendedTestCase { private static final String XML_MESSAGE_DIR = "target/message-xml/"; @Test(groups = {"regressiontest"}) public void messageCreationTest() throws Exception { addDescription("Tests if we are able to create message objects from xml. The input XML is the example code " + "defined in the message-xml, thereby also testing whether this is valid."); String[] messageNames = getMessageNames(); for (String messageName : messageNames) { addStep("Creating " + messageName + " message" , "The test is able to instantiate message based on the example in the message-xml modules"); String xmlMessage = loadXMLExample(messageName); MessageFactory.createMessage(GetChecksumsComplete.class, xmlMessage); } } /** * Generates the list of messages to test by parsing the message xsd file. * * @return List of messages to test */ private String[] getMessageNames() throws Exception { File file = new File(XML_MESSAGE_DIR + "xsd/BitRepositoryMessages.xsd"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); Document doc = factory.newDocumentBuilder().parse(file); XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xpath = xPathFactory.newXPath(); xpath.setNamespaceContext(getNamespaceContext()); XPathExpression expr = xpath.compile("/xs:schema/xs:element"); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; String[] messageNames = new String[nodes.getLength()]; for (int i = 0; i < nodes.getLength(); i++) { messageNames[i] = nodes.item(i).getAttributes().getNamedItem("name") .getNodeValue(); } return messageNames; } /** Needed by XPath to handle the namespaces. */ private NamespaceContext getNamespaceContext() { NamespaceContext ctx = new NamespaceContext() { public String getNamespaceURI(String prefix) { String uri; if (prefix.equals("xs")) { uri = "http: } else if (prefix.equals("xsi")) { uri = "http: } else if (prefix.equals("bre")) { uri = "http://bitrepository.org/BitRepositoryElements.xsd"; } else { uri = null; } return uri; } // Dummy implementation - not used! @SuppressWarnings("rawtypes") public Iterator getPrefixes(String val) { return null; } // Dummy implemenation - not used! public String getPrefix(String uri) { return null; } }; return ctx; } /** * Loads the example XML for the indicated message. Assumes the XML examples are found under the * XML_MESSAGE_DIR/examples directory, and the naming convention for the example files are '${messagename}.xml' * * @param messageName * @return */ private String loadXMLExample(String messageName) throws Exception { String filePath = XML_MESSAGE_DIR + "examples/" + messageName + ".xml"; byte[] buffer = new byte[(int) new File(filePath).length()]; FileInputStream f = new FileInputStream(filePath); f.read(buffer); return new String(buffer); } }
package camunda.bpm.api.integrator; import camunda.bpm.api.integrator.dto.TaskDto; import camunda.bpm.api.integrator.dto.VariableValueDto; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import java.util.List; import java.util.Map; public interface TaskRestService extends AbstractEngineRestService { String TASK_REST_SERVICE_BASE_PATH = "/task"; String GET_TASKS_BY_PROCESS_INSTANCE_ID = TASK_REST_SERVICE_BASE_PATH + "/{processInstanceId}"; String GET_TASK_FORM_VARIABLES_BY_TASK_ID = TASK_REST_SERVICE_BASE_PATH + "/{taskId}/form-variables"; String POST_COMPLETE_TASK_WITH_BODY = TASK_REST_SERVICE_BASE_PATH + "/{taskId}/complete"; @GetMapping(GET_TASKS_BY_PROCESS_INSTANCE_ID) List<TaskDto> queryTasks(String processInstanceId); @GetMapping(GET_TASK_FORM_VARIABLES_BY_TASK_ID) Map<String, VariableValueDto> queryTaskFormVariables(String taskId); @PostMapping(POST_COMPLETE_TASK_WITH_BODY) void submitTaskForm(String taskId, Map<String, Object> variables); }
package edu.kit.iks.Cryptographics.DiffieHellman; import java.util.ArrayList; import java.util.List; import edu.kit.iks.Cryptographics.DiffieHellman.Demonstration.DHDemoFirstController; import edu.kit.iks.Cryptographics.DiffieHellman.Demonstration.DHDemoSecondController; import edu.kit.iks.Cryptographics.DiffieHellman.Experiment.DHExperimentFirstController; import edu.kit.iks.CryptographicsLib.AbstractVisualizationInfo; import edu.kit.iks.CryptographicsLib.VisualizationDifficulty; public class DHVisualizationInfo extends AbstractVisualizationInfo { @Override public String getId() { return "diffiehellman"; } @Override public String getName() { return "Diffie-Hellman"; } @Override public String getDescription() { return ""; } @Override public float getTimelineOffset() { return 0.0f; } @Override public VisualizationDifficulty getDifficulty() { return VisualizationDifficulty.EASY; } @Override public int getYear() { return 1976; } @Override public List<Class> getControllerClasses() { List<Class> controllerClasses = new ArrayList<Class>(); controllerClasses.add(DHDemoFirstController.class); controllerClasses.add(DHDemoSecondController.class); controllerClasses.add(DHExperimentFirstController.class); return controllerClasses; } @Override public String getQRCodeContent() { // TODO Auto-generated method stub return null; } }
package edu.duke.cabig.c3pr.xml; import edu.duke.cabig.c3pr.AbstractTestCase; public class CCTSXMLTransformerTest extends AbstractTestCase { private XMLParser xmlParser; /** * @throws Exception * @Before */ protected void setUp() throws Exception { super.setUp(); // To change body of overridden methods use File | // Settings | File // Templates. xmlParser= new XMLParser("ccts-domain.xsd"); } public void testRegistrationTransformationFromString() throws Exception { String xslName = "ccts-registration-transformer.xsl"; String sampleXml = "c3pr-sample-registration.xml"; String cctsXml= new XMLTransformer().transform(readFile(xslName), readFile(sampleXml)); System.out.println(cctsXml); xmlParser.validate(cctsXml.getBytes()); } public void testStudyTransformationFromString() throws Exception { String xslName = "ccts-study-transformer.xsl"; String sampleXml = "c3pr-sample-study.xml"; String cctsXml= new XMLTransformer().transform(readFile(xslName), readFile(sampleXml)); System.out.println(cctsXml); xmlParser.validate(cctsXml.getBytes()); } private String readFile(String filename) throws Exception { java.io.BufferedReader br = new java.io.BufferedReader( new java.io.InputStreamReader(Thread.currentThread() .getContextClassLoader().getResourceAsStream(filename))); StringBuffer sb = new StringBuffer(); try { String newline = System.getProperty("line.separator"); String tmp = null; while ((tmp = br.readLine()) != null) { sb.append(tmp); sb.append(newline); } } finally { if (br != null) br.close(); return (sb.toString()); } } }
package com.ddd.poc.command.security.subscriber; import com.ddd.poc.command.security.command.CreateUserCommand; import com.ddd.poc.command.security.command.DeleteUserCommand; import com.ddd.poc.command.security.command.UpdateUserCommand; import com.ddd.poc.domain.core.command.DomainCommand; import com.ddd.poc.domain.core.service.EventBus; import com.ddd.poc.domain.security.dao.GroupDao; import com.ddd.poc.domain.security.dao.UserDao; import com.ddd.poc.domain.security.dto.UserDTO; import com.ddd.poc.domain.security.event.GroupCreatedEvent; import com.ddd.poc.domain.security.event.UserCreatedEvent; import com.ddd.poc.domain.security.event.UserDeletedEvent; import com.ddd.poc.domain.security.event.UserJoinedGroupEvent; import com.ddd.poc.domain.security.event.UserLeftGroupEvent; import com.ddd.poc.domain.security.event.UserUpdatedEvent; import com.ddd.poc.domain.security.model.GroupEntity; import com.ddd.poc.domain.security.model.UserEntity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Collection; @Service @Transactional public class UserCommandSubscriber { private final EventBus eventBus; private final GroupDao groupDao; private final UserDao userDao; @Autowired public UserCommandSubscriber(EventBus eventBus, GroupDao groupDao, UserDao userDao) { this.eventBus = eventBus; this.groupDao = groupDao; this.userDao = userDao; } @EventListener public void onCreateUserCommand(CreateUserCommand command) { if (canPerformOperation(command)) { createGroupsIfNeeded(command.getUserDTO(), command); eventBus.publishEvent(new UserCreatedEvent(command.getUserDTO()), command); updateGroups(command.getUserDTO(), command); sendNotificationEmail(command); } } @EventListener public void onUpdateUserCommand(UpdateUserCommand command) { if (canPerformOperation(command)) { createGroupsIfNeeded(command.getUserDTO(), command); eventBus.publishEvent(new UserUpdatedEvent(command.getUserDTO()), command); updateGroups(command.getUserDTO(), command); sendNotificationEmail(command); } } @EventListener public void onDeleteUserCommand(DeleteUserCommand command) { if (canPerformOperation(command)) { eventBus.publishEvent(new UserDeletedEvent(command.getUserId()), command); sendNotificationEmail(command); } } private void createGroupsIfNeeded(UserDTO userDTO, DomainCommand command) { userDTO.getGroups().forEach(groupName -> { if (!groupDao.findOneByName(groupName).isPresent()) { eventBus.publishEvent(new GroupCreatedEvent(groupName), command); } }); } private void updateGroups(UserDTO data, DomainCommand command) { userDao.findOneByUsername(data.getUsername()).ifPresent(userEntityObj -> { removeDeletedGroups(userEntityObj, data.getGroups(), command); addNewGroups(userEntityObj, data.getGroups(), command); }); } private void removeDeletedGroups(UserEntity userEntity, Collection<String> groups, DomainCommand command) { userEntity.getGroups().forEach(groupEntity -> { if (!groups.contains(groupEntity.getName())) { eventBus.publishEvent(new UserLeftGroupEvent(userEntity.getId(), groupEntity.getId()), command); } }); } private void addNewGroups(UserEntity userEntity, Collection<String> groups, DomainCommand command) { groups.forEach(groupName -> groupDao.findOneByName(groupName).ifPresent(groupEntity -> { if (userCanJoinGroup(userEntity, groupEntity)) { eventBus.publishEvent(new UserJoinedGroupEvent(userEntity.getId(), groupEntity.getId()), command); } })); } private boolean canPerformOperation(DomainCommand command) { //TODO: implement method return true; } private boolean userCanJoinGroup(UserEntity userEntity, GroupEntity groupEntity) { //TODO: implement method return true; } private void sendNotificationEmail(DomainCommand command) { //TODO: implement method } }
package org.neo4j.kernel.impl.store; import org.junit.Rule; import org.junit.Test; import java.io.File; import java.nio.ByteBuffer; import org.neo4j.io.fs.DefaultFileSystemAbstraction; import org.neo4j.io.fs.FileSystemAbstraction; import org.neo4j.io.fs.StoreChannel; import org.neo4j.kernel.impl.store.id.IdGeneratorImpl; import org.neo4j.kernel.impl.store.record.NodeRecord; import org.neo4j.kernel.impl.storemigration.StoreFile; import org.neo4j.kernel.impl.storemigration.StoreFileType; import org.neo4j.logging.NullLogProvider; import org.neo4j.test.PageCacheRule; import org.neo4j.test.TargetDirectory; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.neo4j.kernel.impl.store.StoreFactory.SF_CREATE; import static org.neo4j.kernel.impl.store.StoreFactory.SF_LAZY; import static org.neo4j.kernel.impl.store.id.IdGeneratorImpl.HEADER_SIZE; import static org.neo4j.kernel.impl.store.id.IdGeneratorImpl.markAsSticky; public class FreeIdsAfterRecoveryTest { @Rule public final TargetDirectory.TestDirectory directory = TargetDirectory.testDirForTest( getClass() ); @Rule public final PageCacheRule pageCacheRule = new PageCacheRule(); private final FileSystemAbstraction fs = new DefaultFileSystemAbstraction(); @Test public void shouldCompletelyRebuildIdGeneratorsAfterCrash() throws Exception { // GIVEN StoreFactory storeFactory = new StoreFactory( fs, directory.directory(), pageCacheRule.getPageCache( fs ), NullLogProvider.getInstance() ); long highId; try ( NeoStores stores = storeFactory.openNeoStores( SF_LAZY | SF_CREATE ) ) { // a node store with a "high" node NodeStore nodeStore = stores.getNodeStore(); nodeStore.setHighId( 20 ); nodeStore.updateRecord( node( nodeStore.nextId() ) ); highId = nodeStore.getHighId(); } // populating its .id file with a bunch of ids File nodeIdFile = new File( directory.directory(), StoreFile.NODE_STORE.fileName( StoreFileType.ID ) ); IdGeneratorImpl idGenerator = new IdGeneratorImpl( fs, nodeIdFile, 10, 10_000, false, highId ); for ( long id = 0; id < 15; id++ ) { idGenerator.freeId( id ); } idGenerator.close(); // marking as sticky to simulate a crash try ( StoreChannel channel = fs.open( nodeIdFile, "rw" ) ) { markAsSticky( channel, ByteBuffer.allocate( HEADER_SIZE ) ); } // WHEN try ( NeoStores stores = storeFactory.openNeoStores( SF_LAZY | SF_CREATE ) ) { NodeStore nodeStore = stores.getNodeStore(); assertFalse( nodeStore.getStoreOk() ); // simulating what recovery does nodeStore.deleteIdGenerator(); // recovery happens here... nodeStore.makeStoreOk(); // THEN assertEquals( highId, nodeStore.nextId() ); } } private NodeRecord node( long nextId ) { NodeRecord node = new NodeRecord( nextId ); node.setInUse( true ); return node; } }
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.geom.Path2D; import java.util.Arrays; import java.util.List; import java.util.Objects; import javax.swing.*; public final class MainPanel extends JPanel { private static final String TXT = "***********************"; private static final int LINE_WIDTH = 1; private static final int BI_GAP = 2; private MainPanel() { super(new GridLayout(0, 1)); setBorder(BorderFactory.createEmptyBorder(20, 10, 20, 0)); add(makeBreadcrumbList(0, Color.PINK, Arrays.asList("overlap1:", "0px", TXT))); add(makeBreadcrumbList(5, Color.CYAN, Arrays.asList("overlap2:", "5px", TXT))); add(makeBreadcrumbList(9, Color.ORANGE, Arrays.asList("overlap3:", "9px", TXT))); setPreferredSize(new Dimension(320, 240)); } private static AbstractButton makeButton(String title, Color color, boolean first) { AbstractButton b = new JToggleButton(title) { private final transient ArrowToggleButtonBarCellIcon icon = new ArrowToggleButtonBarCellIcon(); @Override public boolean contains(int x, int y) { Shape s = icon.getShape(); return Objects.nonNull(s) && s.contains(x, y); } @Override public Dimension getPreferredSize() { return new Dimension(icon.getIconWidth(), icon.getIconHeight()); } @Override protected void paintComponent(Graphics g) { icon.paintIcon(this, g, 0, 0); super.paintComponent(g); } }; b.setIcon(new Icon() { @Override public void paintIcon(Component c, Graphics g, int x, int y) { g.setColor(Color.GRAY); g.drawOval(x, y, getIconWidth(), getIconHeight()); } @Override public int getIconWidth() { return 12; } @Override public int getIconHeight() { return 12; } }); b.setContentAreaFilled(false); int th = ArrowToggleButtonBarCellIcon.TH; if (first) { b.setBorder(BorderFactory.createEmptyBorder(0, LINE_WIDTH + BI_GAP, 0, th)); } else { b.setBorder(BorderFactory.createEmptyBorder(0, th + LINE_WIDTH + BI_GAP, 0, th)); } b.setHorizontalAlignment(SwingConstants.LEFT); b.setFocusPainted(false); b.setOpaque(false); b.setBackground(color); return b; } private static Container makeContainer(int overlap) { JPanel p = new JPanel(new FlowLayout(FlowLayout.LEADING, -overlap, 0)) { @Override public boolean isOptimizedDrawingEnabled() { return false; } }; p.setBorder(BorderFactory.createEmptyBorder(0, overlap, 0, 0)); p.setOpaque(false); return p; } private static Component makeBreadcrumbList(int overlap, Color color, List<String> list) { Container p = makeContainer(overlap + LINE_WIDTH); ButtonGroup bg = new ButtonGroup(); boolean f = true; for (String title: list) { AbstractButton b = makeButton(title, color, f); p.add(b); bg.add(b); f = false; } return p; } public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } class ArrowToggleButtonBarCellIcon implements Icon { public static final int TH = 10; // The height of a triangle private static final int HEIGHT = TH * 2 + 1; private static final int WIDTH = 100; private Shape shape; public Shape getShape() { return shape; } protected Shape makeShape(Container parent, Component c, int x, int y) { int w = c.getWidth() - 1; int h = c.getHeight() - 1; double h2 = Math.round(h * .5); double w2 = TH; Path2D p = new Path2D.Double(); p.moveTo(0, 0); p.lineTo(w - w2, 0); p.lineTo(w, h2); p.lineTo(w - w2, h); p.lineTo(0, h); if (c != parent.getComponent(0)) { p.lineTo(w2, h2); } p.closePath(); return AffineTransform.getTranslateInstance(x, y).createTransformedShape(p); } @Override public void paintIcon(Component c, Graphics g, int x, int y) { Container parent = c.getParent(); if (Objects.isNull(parent)) { return; } shape = makeShape(parent, c, x, y); Color bgc = parent.getBackground(); Color borderColor = Color.GRAY.brighter(); if (c instanceof AbstractButton) { ButtonModel m = ((AbstractButton) c).getModel(); if (m.isSelected() || m.isRollover()) { bgc = c.getBackground(); borderColor = Color.GRAY; } } Graphics2D g2 = (Graphics2D) g.create(); g2.setPaint(bgc); g2.fill(shape); g2.setPaint(borderColor); g2.draw(shape); g2.dispose(); } @Override public int getIconWidth() { return WIDTH; } @Override public int getIconHeight() { return HEIGHT; } }
package org.onetwo.plugins.admin.vo; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import lombok.Getter; import lombok.Setter; import org.onetwo.common.tree.AbstractTreeModel; import org.onetwo.common.utils.GuavaUtils; import org.onetwo.common.utils.LangUtils; import org.onetwo.common.utils.StringUtils; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.google.common.collect.Maps; /** * @author wayshall * <br/> */ @SuppressWarnings("serial") @JsonIgnoreProperties({"id", "parent", "parentId", "sort", "level", "index", "leafage", "first", "last"}) public class VueRouterTreeModel extends AbstractTreeModel<VueRouterTreeModel> { @Getter @Setter private String url; private boolean hidden; @Getter @Setter private Map<String, Object> meta = Maps.newHashMap(); public VueRouterTreeModel(String id, String title, String parentId) { super(id, id, parentId); meta.put("title", title); } public String getPath() { String path = (String)getId(); /* String parentId = (String)getParentId(); if(StringUtils.isNotBlank(parentId)) { path = path.substring(parentId.length()+1); } return "/"+path; */ path = "/" + StringUtils.replaceEach(path, "_", "/"); return path; } public String getRedirect() { if(getChildren().isEmpty()) { return null; } return "noredirect"; } public String getComponentViewPath() { if(!getChildren().isEmpty()) { return "Layout"; } // String viewPath = (String) getId(); // viewPath = viewPath.replace('_', '/'); List<String> viewPaths = GuavaUtils.splitAsStream((String) getId(), "_") .map(str->StringUtils.uncapitalize(str)) .collect(Collectors.toList()); String viewPath = StringUtils.join(viewPaths, "/"); viewPath = StringUtils.trimStartWith(viewPath, "/"); return viewPath; } public boolean isHidden() { return hidden; } public void setHidden(boolean hidden) { this.hidden = hidden; } public void setIcon(String icon) { this.meta.put("icon", icon); } public void addMetas(Map<String, Object> meta){ if(LangUtils.isEmpty(meta)){ return ; } if(this.meta == null){ this.meta = Maps.newHashMap(); } this.meta.putAll(meta); } }
package com.bluelinelabs.logansquare.typeconverters; import java.text.DateFormat; /** The default DateTypeConverter implementation. Attempts to parse ISO8601-formatted dates. */ public class DefaultDateConverter extends DateTypeConverter { public DateFormat getDateFormat() { return new DefaultDateFormatter(); } }
package org.opennms.netmgt.config.mock; import java.io.IOException; import java.net.InetAddress; import java.util.Collections; import java.util.Enumeration; import java.util.List; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.exolab.castor.xml.MarshalException; import org.exolab.castor.xml.ValidationException; import org.opennms.netmgt.config.LinkdConfig; import org.opennms.netmgt.config.LinkdConfigManager; import org.opennms.netmgt.config.linkd.LinkdConfiguration; import org.opennms.netmgt.config.linkd.Package; public class MockLinkdConfig implements LinkdConfig { private final ReadWriteLock m_globalLock = new ReentrantReadWriteLock(); private final Lock m_readLock = m_globalLock.readLock(); private final Lock m_writeLock = m_globalLock.writeLock(); @Override public List<InetAddress> getIpList(final Package pkg) { return Collections.emptyList(); } @Override public boolean isInterfaceInPackage(final InetAddress iface, final Package pkg) { return false; } @Override public boolean isInterfaceInPackageRange(final InetAddress iface, final Package pkg) { return false; } @Override public Package getFirstPackageMatch(final InetAddress ipaddr) { return null; } @Override public List<String> getAllPackageMatches(final InetAddress ipAddr) { return Collections.emptyList(); } @Override public boolean isAutoDiscoveryEnabled() { return false; } @Override public boolean isVlanDiscoveryEnabled() { return false; } @Override public Enumeration<Package> enumeratePackage() { final List<Package> list = Collections.emptyList(); return Collections.enumeration(list); } @Override public Package getPackage(final String pkgName) { return null; } @Override public int getThreads() { return 1; } @Override public boolean useIpRouteDiscovery() { return false; } @Override public boolean forceIpRouteDiscoveryOnEthernet() { return false; } @Override public boolean saveRouteTable() { return false; } @Override public boolean useCdpDiscovery() { return false; } @Override public boolean useLldpDiscovery() { return false; } @Override public boolean useBridgeDiscovery() { return false; } @Override public boolean useWifiDiscovery() { return false; } @Override public boolean saveStpNodeTable() { return false; } @Override public boolean saveStpInterfaceTable() { return false; } @Override public long getInitialSleepTime() { return 3000; } @Override public long getSnmpPollInterval() { return 3000; } @Override public long getDiscoveryLinkInterval() { return 3000; } @Override public void update() { } @Override public void save() throws MarshalException, IOException, ValidationException { } @Override public LinkdConfiguration getConfiguration() { return new LinkdConfiguration(); } @Override public String getVlanClassName(final String sysoid) { return null; } @Override public boolean hasClassName(final String sysoid) { return false; } @Override public Lock getReadLock() { return m_readLock; } @Override public Lock getWriteLock() { return m_writeLock; } @Override public boolean hasIpRouteClassName(final String sysoid) { return false; } @Override public String getIpRouteClassName(final String sysoid) { return LinkdConfigManager.DEFAULT_IP_ROUTE_CLASS_NAME; } @Override public String getDefaultIpRouteClassName() { return LinkdConfigManager.DEFAULT_IP_ROUTE_CLASS_NAME; } @Override public void reload() throws IOException, MarshalException, ValidationException { } @Override public boolean useOspfDiscovery() { return false; } @Override public boolean useIsIsDiscovery() { return false; } }
package ru.job4j; /** *Class Calculate 001 1. *@author erokhov *@since 02.12.2016 **/ public class Calculate { /** *Main. * @param args - args. */ public static void main(String[] args) { System.out.println("Hello World"); } }
package org.owasp.dependencycheck; import org.owasp.dependencycheck.Engine; import org.owasp.dependencycheck.reporting.ReportGenerator; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Jeremy Long (jeremy.long@owasp.org) */ public class EngineIntegrationTest { @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() throws Exception { org.owasp.dependencycheck.data.nvdcve.BaseDBTestCase.ensureDBExists(); } @After public void tearDown() { } /** * Test of scan method, of class Engine. * * @throws Exception is thrown when an exception occurs. */ @Test public void testScan() throws Exception { String testClasses = "target/test-classes"; Engine instance = new Engine(); instance.scan(testClasses); assertTrue(instance.getDependencies().size() > 0); instance.analyzeDependencies(); ReportGenerator rg = new ReportGenerator("DependencyCheck", instance.getDependencies(), instance.getAnalyzers()); rg.generateReports("./target/", "ALL"); } }