answer
stringlengths 17
10.2M
|
|---|
package com.alcedomoreno.sirme.web;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Resource;
import org.primefaces.event.CellEditEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.alcedomoreno.sirme.business.data.Address;
import com.alcedomoreno.sirme.business.data.Customer;
import com.alcedomoreno.sirme.business.data.Manager;
import com.alcedomoreno.sirme.business.data.Month.MonthE;
import com.alcedomoreno.sirme.business.data.Report;
import com.alcedomoreno.sirme.business.services.CustomerService;
import com.alcedomoreno.sirme.business.services.OtherService;
import com.alcedomoreno.sirme.business.services.QuestionService;
import com.alcedomoreno.sirme.business.services.UsersService;
import com.alcedomoreno.sirme.business.util.ServiceConstants;
import com.alcedomoreno.sirme.business.util.TransactionException;
import com.alcedomoreno.sirme.business.util.ValidationException;
import com.alcedomoreno.sirme.core.util.MyLogger;
import com.alcedomoreno.sirme.web.excel.CustomerXLSExtract;
import com.alcedomoreno.sirme.web.excel.ManagerDocExtract;
import com.alcedomoreno.sirme.web.schedulers.IPCronService;
import com.alcedomoreno.sirme.web.util.BeanNameUtil;
@Component( BeanNameUtil.SETTINGS_BEAN )
@Scope("session")
public class SettingsBean extends ManagedBean {
// Atributos //
private static final long serialVersionUID = 1L;
private static Logger log = LoggerFactory.getLogger( SettingsBean.class );
private static final String CLASS_NAME = BeanNameUtil.SETTINGS_BEAN;
@Resource( name=BeanNameUtil.APP_BEAN)
private ApplicationBean applicationBean;
@Resource(name = ServiceConstants.CUSTOMER_SERVICE)
private CustomerService customerService;
@Resource(name = ServiceConstants.USER_SERVICE )
private UsersService usersService;
@Resource(name = ServiceConstants.OTHER_SERVICE )
private OtherService otherService;
@Resource(name = ServiceConstants.QUESTION_SERVICE )
private QuestionService questionService;
@Resource( name = "IPDNSCron")
protected IPCronService cronService;
private String newPass1;
private String newPass2;
private String processDir = "C:\\w";
private String processDirManager = "C:\\a";
private String sql;
private List<String> restCalls;
// Fin de los Atributos //
// Constructores //
public SettingsBean(){
MyLogger.info(log, CLASS_NAME, "SettingsBean", "New Instance");
}
// Fin de los Constructores //
// Metodos Publicos //
@Override
public String doInit(){
MyLogger.debug(log, CLASS_NAME, "doInit", "IN");
newPass1 = "";
newPass2 = "";
filter();
MyLogger.debug(log, CLASS_NAME, "doInit", "OUT");
return BeanNameUtil.PAGE_PRINCIPAL_CONFIG;
}
public void filter(){
}
@Override
public String prepareAction(){
MyLogger.debug(log, CLASS_NAME, "prepareAction", "IN", getPageOption());
MyLogger.debug(log, CLASS_NAME, "prepareAction", "OUT",getPageOption());
return BeanNameUtil.PAGE_PRINCIPAL_CONFIG;
}
public void onContactEdit(CellEditEvent event) {
Object oldValue = event.getOldValue();
Object newValue = event.getNewValue();
if(newValue != null && !newValue.equals(oldValue))
applicationBean.sendMessageInfo("clientes.contacto.cambio.titulo", "clientes.contacto.cambio", oldValue.toString(), newValue.toString());
}
@Override
public String save(){
try{
MyLogger.debug(log, CLASS_NAME, "save", "IN");
usersService.updatePassword(getUser().getIdUser(), newPass1, newPass2);
applicationBean.sendMessageInfo("web.operacion.correcta", "Se cambio la contrasena con exito");
MyLogger.debug(log, CLASS_NAME, "save", "OUT");
} catch(ValidationException e){
applicationBean.sendMessageError("web.error.general.validacion", e.getMessage() );
return null;
} catch(TransactionException e){
applicationBean.sendMessageError("web.error.general.transaccion", "No se puede cambiar la contrasena" );
return null;
}
return doInit();
}
@Override
public String update(){
return doInit();
}
@Override
public String delete(){
return doInit();
}
@Override
public String back(){
return BeanNameUtil.PAGE_PRINCIPAL_CONFIG;
}
@Override
public String cancel(){
newPass1 = "";
newPass2 = "";
return BeanNameUtil.PAGE_PRINCIPAL_CONFIG;
}
public void doRestLogin(){
restCalls = applicationBean.getRestLogin();
}
public void doRestPassword(){
restCalls = applicationBean.getRestPassword();
}
public void doRestQuestions(){
restCalls = applicationBean.getRestQuestions();
}
public void doRestAdvices(){
restCalls = applicationBean.getRestAdvices();
}
public void doRestWorks(){
restCalls = applicationBean.getRestWorks();
}
public void process(){
int correctos = 0;
int fallos = 0;
List<String> oks = new ArrayList<String>();
List<String[]> kos = new ArrayList<String[]>();
try{
File dir = new File( processDir );
for (File child : dir.listFiles())
if ( child.isFile() ){
try{
FileInputStream fis = new FileInputStream( child );
Customer customer = CustomerXLSExtract.getInstance().getCustomerFromXLS( fis );
Address address = null;
for ( Address a:customer.getAddress() )
address = a;
address.setCustomer( customer );
boolean oldC = false;
Customer filter = new Customer();
filter.setIdCustomer( 0 );
filter.setCodeCustomer( customer.getCodeCustomer() );
filter = customerService.get( filter );
if ( filter != null )
if ( filter.getCodeCustomer().equalsIgnoreCase( customer.getCodeCustomer() ) ){
oldC = true;
address.setCustomer( filter );
}
List<String> selectedMonths = new ArrayList<String>();
if ( address.getMonths()!=null && !address.getMonths().isEmpty() )
for ( MonthE m:address.getMonths() )
selectedMonths.add( String.valueOf( m.getValue() ) );
address.setMonths( selectedMonths );
if ( !oldC ){
customerService.save( customer );
}
else
customerService.save( address );
correctos++;
oks.add( child.getName() );
child.delete();
MyLogger.debug(log, CLASS_NAME, "process", "OK",child.getPath());
} catch (Exception e){
String errorS = "";
try{
errorS = ((org.hibernate.exception.ConstraintViolationException)((org.springframework.dao.DataIntegrityViolationException)e.getCause()).getCause()).getCause().getMessage();
} catch ( Exception e1 ){
errorS = e.getMessage();
}
MyLogger.debug(log, CLASS_NAME, "process", "KO", child.getPath(),errorS);
fallos++;
String[] ko = new String[]{child.getName(),e.getMessage()};
kos.add( ko );
}
}
} catch ( Exception e){
applicationBean.sendMessageError("web.error.general", "No se puede leer el directorio" );
}
applicationBean.sendMessageInfo("Info", "Proceso finalizado con " + correctos + " OK y " + fallos + " KO.");
System.out.println("Proceso finalizado con " + correctos + " OK y " + fallos + " KO.");
try {
FileWriter fichero = new FileWriter( processDir + "\\ok.txt");
for (String ok:oks)
fichero.write( ok + "\r\n");
fichero.close();
FileWriter fichero2 = new FileWriter( processDir + "\\ko.txt");
for (String[] ko:kos)
fichero2.write( ko[0] + "\t" + ko[1] + "\r\n");
fichero2.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void prepareReports(){
Collection<Report> reports = questionService.getAll();
questionService.getWork( 21 );
questionService.getWork( 20 );
}
public void forceDNS(){
try{
cronService.resetDynDNS();
applicationBean.sendMessageInfo("web.operacion.correcta", "Se actualizo DynDNS con exito");
} catch (Exception e){
applicationBean.sendMessageError("web.error.general.transaccion", "Error actualizando DynDNS" );
}
}
public void resetConnections(){
try{
applicationBean.resetUserAccess();
applicationBean.sendMessageInfo("web.operacion.correcta", "Se resetearon las conexiones con exito");
} catch (Exception e){
applicationBean.sendMessageError("web.error.general.transaccion", "Error reseteando las conexiones" );
}
}
public void launchSql(){
try{
int i = otherService.launchQuery( sql );
applicationBean.sendMessageInfo("web.operacion.correcta", "Se lanzo la query con resultado " + i);
} catch (Exception e){
applicationBean.sendMessageError("web.error.general.transaccion", "Error lanzando la query: ?", e.getMessage() );
}
}
public void processDirManager(){
int correctos = 0;
int fallos = 0;
List<String> oks = new ArrayList<String>();
List<String[]> kos = new ArrayList<String[]>();
try{
File dir = new File( processDirManager );
for (File child : dir.listFiles())
if ( child.isDirectory() )
for (File child2 : child.listFiles()){
if ( child2.isFile() ){
try{
FileInputStream fis = new FileInputStream( child2 );
Manager manager = ManagerDocExtract.getInstance().getCustomerFromDOC( fis );
int id = customerService.save( manager );
manager.setIdManager( id );
if ( manager.getCustomers() != null ){
Iterator<Customer> customIt = manager.getCustomers().iterator();
while( customIt.hasNext() ){
Customer c = customIt.next();
c.setIdCustomer( 0 );
c = customerService.get( c );
if ( c != null )
otherService.launchQuery("UPDATE customers SET idManager = " + id + " WHERE idCustomer = " + c.getIdCustomer() );
}
}
correctos++;
oks.add( child2.getName() );
child2.delete();
MyLogger.debug(log, CLASS_NAME, "process", "OK",child2.getPath());
} catch (Exception e){
String errorS = "";
try{
errorS = ((org.hibernate.exception.ConstraintViolationException)((org.springframework.dao.DataIntegrityViolationException)e.getCause()).getCause()).getCause().getMessage();
} catch ( Exception e1 ){
errorS = e.getMessage();
}
MyLogger.debug(log, CLASS_NAME, "process", "KO", child2.getPath(),errorS);
fallos++;
String[] ko = new String[]{child2.getName(),e.getMessage()};
kos.add( ko );
}
}
}
} catch ( Exception e){
applicationBean.sendMessageError("web.error.general", "No se puede leer el directorio" );
}
applicationBean.sendMessageInfo("Info", "Proceso finalizado con " + correctos + " OK y " + fallos + " KO.");
System.out.println("Proceso finalizado con " + correctos + " OK y " + fallos + " KO.");
try {
FileWriter fichero = new FileWriter( processDirManager + "\\ok.txt");
for (String ok:oks)
fichero.write( ok + "\r\n");
fichero.close();
FileWriter fichero2 = new FileWriter( processDirManager + "\\ko.txt");
for (String[] ko:kos)
fichero2.write( ko[0] + "\t" + ko[1] + "\r\n");
fichero2.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Fin de los Metodos Publicos //
// Metodos Privados //
// Fin de los Metodos Privados //
// Getters y Setters //
public ApplicationBean getApplicationBean() {
return applicationBean;
}
public void setApplicationBean(ApplicationBean applicationBean) {
this.applicationBean = applicationBean;
}
public String getNewPass1() {
return newPass1;
}
public void setNewPass1(String newPass1) {
this.newPass1 = newPass1;
}
public String getNewPass2() {
return newPass2;
}
public void setNewPass2(String newPass2) {
this.newPass2 = newPass2;
}
public String getProcessDir() {
return processDir;
}
public void setProcessDir(String processDir) {
this.processDir = processDir;
}
public String getProcessDirManager() {
return processDirManager;
}
public void setProcessDirManager(String processDirManager) {
this.processDirManager = processDirManager;
}
public String getSql() {
return sql;
}
public void setSql(String sql) {
this.sql = sql;
}
public List<String> getRestCalls() {
return restCalls;
}
public void setRestCalls(List<String> restCalls) {
this.restCalls = restCalls;
}
// Fin de los Getters y Setters //
}
|
package fr.tcpmfa.dataBase;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import fr.tcpmfa.engine.Point;
import fr.tcpmfa.engine.Map;
import fr.tcpmfa.util.Coordinate;
public class DBTDConnexion {
private static String url="jdbc:mysql://localhost/DBTDJava";
private static String root = "root";
private static String password = "";
private java.sql.Connection connection;
private java.sql.Statement statement;
public DBTDConnexion(){
this.connection=null;
this.statement=null;
}
public Boolean open() {
try {
Class.forName("com.mysql.jdbc.Driver");
this.connection = DriverManager.getConnection(DBTDConnexion.url,DBTDConnexion.root,DBTDConnexion.password);
this.statement = this.connection.createStatement();
} catch (ClassNotFoundException e) {
e.printStackTrace();
return false;
} catch (SQLException e) {
e.printStackTrace(); }
return true;
}
public void close(){
try {
this.connection.close();
this.statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void getMap(int ID_Map){
ResultSet info = null;
Coordinate startPoint;
Coordinate endPoint;
ArrayList<Point> liste ;
try {
info = statement.executeQuery("SELECT * FROM map WHERE N_Map="+ID_Map);
info.first();
startPoint=new Coordinate(info.getInt(2), info.getInt(3));
endPoint = new Coordinate(info.getInt(4), info.getInt(5));
info = statement.executeQuery("SELECT * FROM point WHERE N_Map="+ID_Map);
liste=new ArrayList<Point> ();
while(info.next()){
Point point = new Point(info.getInt(2), info.getInt(3));
liste.add(point);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* rcupre un ennemi en fonction de son ID dans la BDD
* @param ID_Ennemy
* @author schouteeten
*/
public void getEnnemy(int ID_Ennemy){
ResultSet info = null;
final int HP;
final int numberDamage;
final int moveSpeed;
final int range;
final String resistanceType;
final int loot;
try {
switch(ID_Ennemy){
case 1:
info = statement.executeQuery("SELECT * FROM Ennemy WHERE N_Map="+ID_Ennemy);
HP = info.getInt(2);
numberDamage=info.getInt(3);
moveSpeed=info.getInt(4);
range=info.getInt(5);
resistanceType=info.getString(6);
loot=info.getInt(7);
break;
case 2:
info = statement.executeQuery("SELECT * FROM Ennemy WHERE N_Map="+ID_Ennemy);
HP = info.getInt(2);
numberDamage=info.getInt(3);
moveSpeed=info.getInt(4);
range=info.getInt(5);
resistanceType=info.getString(6);
loot=info.getInt(7);
break;
case 3:
info = statement.executeQuery("SELECT * FROM Ennemy WHERE N_Map="+ID_Ennemy);
HP = info.getInt(2);
numberDamage=info.getInt(3);
moveSpeed=info.getInt(4);
range=info.getInt(5);
resistanceType=info.getString(6);
loot=info.getInt(7);
break;
case 4:
info = statement.executeQuery("SELECT * FROM Ennemy WHERE N_Map="+ID_Ennemy);
HP = info.getInt(2);
numberDamage=info.getInt(3);
moveSpeed=info.getInt(4);
range=info.getInt(5);
resistanceType=info.getString(6);
loot=info.getInt(7);
break;
case 5:
info = statement.executeQuery("SELECT * FROM Ennemy WHERE N_Map="+ID_Ennemy);
HP = info.getInt(2);
numberDamage=info.getInt(3);
moveSpeed=info.getInt(4);
range=info.getInt(5);
resistanceType=info.getString(6);
loot=info.getInt(7);
break;
default:
System.out.println("erreur");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package edu.wustl.catissuecore.actionForm;
import java.util.List;
import edu.wustl.catissuecore.domainobject.Biohazard;
import edu.wustl.catissuecore.domainobject.CancerResearchGroup;
import edu.wustl.catissuecore.domainobject.CellSpecimenReviewParameters;
import edu.wustl.catissuecore.domainobject.CheckInCheckOutEventParameter;
import edu.wustl.catissuecore.domainobject.CollectionEventParameters;
import edu.wustl.catissuecore.domainobject.CollectionProtocol;
import edu.wustl.catissuecore.domainobject.CollectionProtocolRegistration;
import edu.wustl.catissuecore.domainobject.Department;
import edu.wustl.catissuecore.domainobject.DisposalEventParameters;
import edu.wustl.catissuecore.domainobject.Distribution;
import edu.wustl.catissuecore.domainobject.DistributionProtocol;
import edu.wustl.catissuecore.domainobject.EmbeddedEventParameters;
import edu.wustl.catissuecore.domainobject.FixedEventParameters;
import edu.wustl.catissuecore.domainobject.FluidSpecimenReviewEventParameters;
import edu.wustl.catissuecore.domainobject.FrozenEventParameters;
import edu.wustl.catissuecore.domainobject.Institution;
import edu.wustl.catissuecore.domainobject.MolecularSpecimenReviewParameters;
import edu.wustl.catissuecore.domainobject.Participant;
import edu.wustl.catissuecore.domainobject.ProcedureEventParameters;
import edu.wustl.catissuecore.domainobject.ReceivedEventParameters;
import edu.wustl.catissuecore.domainobject.Site;
import edu.wustl.catissuecore.domainobject.Specimen;
import edu.wustl.catissuecore.domainobject.SpecimenCollectionGroup;
import edu.wustl.catissuecore.domainobject.SpunEventParameters;
import edu.wustl.catissuecore.domainobject.StorageContainer;
import edu.wustl.catissuecore.domainobject.StorageType;
import edu.wustl.catissuecore.domainobject.User;
import edu.wustl.catissuecore.domainobject.ThawEventParameters;
import edu.wustl.catissuecore.domainobject.TransferEventParameters;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.common.actionForm.AbstractActionForm;
/**
* ActionFormFactory is a factory that returns instances of action formbeans
* as per the domain objects.
* @author aniruddha_phadnis
*/
public class ActionFormFactory
{
/**
* Returns the instance of formbean as per given domain object.
* @param object The instance of domain object
* @param operation The operation(Add/Edit) that is to be performed
* @return the instance of formbean.
* @see #setMessageList(List)
*/
public static AbstractActionForm getFormBean(Object object,String operation) throws Exception
{
AbstractActionForm form = null;
if(object instanceof User)
{
form = new UserForm();
}
else if(object instanceof Institution)
{
form = new InstitutionForm();
}
else if(object instanceof Department)
{
form = new DepartmentForm();
}
else if(object instanceof CancerResearchGroup)
{
form = new CancerResearchGroupForm();
}
else if(object instanceof Site)
{
form = new SiteForm();
}
else if(object instanceof StorageType)
{
form = new StorageTypeForm();
}
else if(object instanceof StorageContainer)
{
form = new StorageContainerForm();
}
else if(object instanceof Biohazard)
{
form = new BiohazardForm();
}
else if(object instanceof CollectionProtocol)
{
form = new CollectionProtocolForm();
}
else if(object instanceof DistributionProtocol)
{
form = new DistributionProtocolForm();
}
else if(object instanceof Participant)
{
form = new ParticipantForm();
}
else if(object instanceof CollectionProtocolRegistration)
{
form = new CollectionProtocolRegistrationForm();
}
else if(object instanceof SpecimenCollectionGroup)
{
form = new SpecimenCollectionGroupForm();
}
else if(object instanceof Specimen)
{
if(operation.equals(Constants.EDIT))
{
form = new NewSpecimenForm();
}
else
{
Specimen specimen = (Specimen)object;
if(specimen.getSpecimenCollectionGroup() != null)
{
form = new NewSpecimenForm();
}
else
{
form = new CreateSpecimenForm();
}
}
}
else if(object instanceof Distribution)
{
form = new DistributionForm();
}
else if(object instanceof CellSpecimenReviewParameters)
{
form = new CellSpecimenReviewParametersForm();
}
else if(object instanceof CheckInCheckOutEventParameter)
{
form = new CheckInCheckOutEventParametersForm();
}
else if(object instanceof CollectionEventParameters)
{
form = new CollectionEventParametersForm();
}
else if(object instanceof DisposalEventParameters)
{
form = new DisposalEventParametersForm();
}
else if(object instanceof EmbeddedEventParameters)
{
form = new EmbeddedEventParametersForm();
}
else if(object instanceof FixedEventParameters)
{
form = new FixedEventParametersForm();
}
else if(object instanceof FluidSpecimenReviewEventParameters)
{
form = new FluidSpecimenReviewEventParametersForm();
}
else if(object instanceof FrozenEventParameters)
{
form = new FrozenEventParametersForm();
}
else if(object instanceof MolecularSpecimenReviewParameters)
{
form = new MolecularSpecimenReviewParametersForm();
}
else if(object instanceof ProcedureEventParameters)
{
form = new ProcedureEventParametersForm();
}
else if(object instanceof ReceivedEventParameters)
{
form = new ReceivedEventParametersForm();
}
else if(object instanceof SpunEventParameters)
{
form = new SpunEventParametersForm();
}
else if(object instanceof ThawEventParameters)
{
form = new ThawEventParametersForm();
}
else if(object instanceof TransferEventParameters)
{
form = new TransferEventParametersForm();
}
else
{
throw new Exception("Invalid Object for Add/Edit Operation");
}
return form;
}
}
|
package edu.wustl.catissuecore.bizlogic;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import net.sf.hibernate.HibernateException;
import edu.wustl.catissuecore.domain.Address;
import edu.wustl.catissuecore.domain.Biohazard;
import edu.wustl.catissuecore.domain.CellSpecimen;
import edu.wustl.catissuecore.domain.CollectionEventParameters;
import edu.wustl.catissuecore.domain.DisposalEventParameters;
import edu.wustl.catissuecore.domain.DistributedItem;
import edu.wustl.catissuecore.domain.ExternalIdentifier;
import edu.wustl.catissuecore.domain.FluidSpecimen;
import edu.wustl.catissuecore.domain.MolecularSpecimen;
import edu.wustl.catissuecore.domain.QuantityInCount;
import edu.wustl.catissuecore.domain.QuantityInGram;
import edu.wustl.catissuecore.domain.QuantityInMicrogram;
import edu.wustl.catissuecore.domain.QuantityInMilliliter;
import edu.wustl.catissuecore.domain.ReceivedEventParameters;
import edu.wustl.catissuecore.domain.Specimen;
import edu.wustl.catissuecore.domain.SpecimenCharacteristics;
import edu.wustl.catissuecore.domain.SpecimenCollectionGroup;
import edu.wustl.catissuecore.domain.StorageContainer;
import edu.wustl.catissuecore.domain.TissueSpecimen;
import edu.wustl.catissuecore.integration.IntegrationManager;
import edu.wustl.catissuecore.integration.IntegrationManagerFactory;
import edu.wustl.catissuecore.util.ApiSearchUtil;
import edu.wustl.catissuecore.util.StorageContainerUtil;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.catissuecore.util.global.Utility;
import edu.wustl.common.beans.NameValueBean;
import edu.wustl.common.beans.SessionDataBean;
import edu.wustl.common.cde.CDEManager;
import edu.wustl.common.dao.DAO;
import edu.wustl.common.domain.AbstractDomainObject;
import edu.wustl.common.security.SecurityManager;
import edu.wustl.common.security.exceptions.SMException;
import edu.wustl.common.security.exceptions.UserNotAuthorizedException;
import edu.wustl.common.util.dbManager.DAOException;
import edu.wustl.common.util.global.ApplicationProperties;
import edu.wustl.common.util.global.Validator;
import edu.wustl.common.util.logger.Logger;
/**
* NewSpecimenHDAO is used to add new specimen information into the database using Hibernate.
* @author aniruddha_phadnis
*/
public class NewSpecimenBizLogic extends IntegrationBizLogic
{
/**
* Saves the storageType object in the database.
* @param obj The storageType object to be saved.
* @param session The session in which the object is saved.
* @throws DAOException
*/
protected void insert(Object obj, DAO dao, SessionDataBean sessionDataBean) throws DAOException, UserNotAuthorizedException
{
if (obj instanceof Map)
{
insertMultipleSpecimen((Map) obj, dao, sessionDataBean);
}
else
{
insertSingleSpecimen((Specimen) obj, dao, sessionDataBean, false);
//Inserting authorization data
Specimen specimen = (Specimen) obj;
Set protectionObjects = new HashSet();
protectionObjects.add(specimen);
if (specimen.getSpecimenCharacteristics() != null)
{
protectionObjects.add(specimen.getSpecimenCharacteristics());
}
try
{
SecurityManager.getInstance(this.getClass()).insertAuthorizationData(null, protectionObjects, getDynamicGroups(specimen));
}
catch (SMException e)
{
throw handleSMException(e);
}
}
}
/**
* Insert multiple specimen into the data base.
* @param specimenList
* @param dao
* @param sessionDataBean
* @throws DAOException
* @throws UserNotAuthorizedException
*/
private void insertMultipleSpecimen(Map specimenMap, DAO dao, SessionDataBean sessionDataBean) throws DAOException, UserNotAuthorizedException
{
List specimenList = new ArrayList();
Iterator specimenIterator = specimenMap.keySet().iterator();
while (specimenIterator.hasNext())
{
Specimen specimen = (Specimen) specimenIterator.next();
ApiSearchUtil.setSpecimenDefault(specimen);
//End:- Change for API Search
Long parentSpecimenId = specimen.getId();
specimen.setId(null);
try
{
insertSingleSpecimen(specimen, dao, sessionDataBean, true);
specimenList.add(specimen);
}
catch (DAOException daoException)
{
String message = " (This message is for Specimen number " + parentSpecimenId + ")";
daoException.setSupportingMessage(message);
throw daoException;
}
List derivedSpecimens = (List) specimenMap.get(specimen);
if (derivedSpecimens == null)
{
continue;
}
//insert derived specimens
for (int i = 0; i < derivedSpecimens.size(); i++)
{
Specimen derivedSpecimen = (Specimen) derivedSpecimens.get(i);
derivedSpecimen.setParentSpecimen(specimen);
derivedSpecimen.setSpecimenCollectionGroup(specimen.getSpecimenCollectionGroup());
try
{
insertSingleSpecimen(derivedSpecimen, dao, sessionDataBean, true);
specimenList.add(derivedSpecimen);
}
catch (DAOException daoException)
{
int j = i + 1;
String message = " (This message is for Derived Specimen " + j + " of Parent Specimen number " + parentSpecimenId + ")";
daoException.setSupportingMessage(message);
throw daoException;
}
}
}
//inserting authorization data
Iterator itr = specimenList.iterator();
while(itr.hasNext())
{
Specimen specimen = (Specimen)itr.next();
Set protectionObjects = new HashSet();
protectionObjects.add(specimen);
if (specimen.getSpecimenCharacteristics() != null)
{
protectionObjects.add(specimen.getSpecimenCharacteristics());
}
try
{
SecurityManager.getInstance(this.getClass()).insertAuthorizationData(null, protectionObjects, getDynamicGroups(specimen));
}
catch (SMException e)
{
throw handleSMException(e);
}
}
}
/**
* This method gives the error message.
* This method is overrided for customizing error message
* @param ex - DAOException
* @param obj - Object
* @return - error message string
*/
public String getErrorMessage(DAOException daoException, Object obj, String operation)
{
if (obj instanceof HashMap)
{
obj = new Specimen();
}
String supportingMessage = daoException.getSupportingMessage();
String formatedException = formatException(daoException.getWrapException(), obj, operation);
if (supportingMessage != null && formatedException != null)
{
formatedException += supportingMessage;
}
if (formatedException == null)
{
formatedException = daoException.getMessage();
if (supportingMessage != null)
formatedException += supportingMessage;
}
return formatedException;
}
/**
* Insert single specimen into the data base.
* @param specimen
* @param dao
* @param sessionDataBean
* @param partOfMulipleSpecimen
* @throws DAOException
* @throws UserNotAuthorizedException
*/
private void insertSingleSpecimen(Specimen specimen, DAO dao, SessionDataBean sessionDataBean, boolean partOfMulipleSpecimen)
throws DAOException, UserNotAuthorizedException
{
try
{
ApiSearchUtil.setSpecimenDefault(specimen);
//End:- Change for API Search
//Set protectionObjects = new HashSet();
specimen.setLineage(Constants.NEW_SPECIMEN);
setSpecimenAttributes(dao, specimen, sessionDataBean, partOfMulipleSpecimen);
dao.insert(specimen.getSpecimenCharacteristics(), sessionDataBean, true, true);
dao.insert(specimen, sessionDataBean, true, true);
//protectionObjects.add(specimen);
/*if (specimen.getSpecimenCharacteristics() != null)
{
protectionObjects.add(specimen.getSpecimenCharacteristics());
}*/
Collection externalIdentifierCollection = specimen.getExternalIdentifierCollection();
if (externalIdentifierCollection != null)
{
if (externalIdentifierCollection.isEmpty()) //Dummy entry added for query
{
ExternalIdentifier exId = new ExternalIdentifier();
exId.setName(null);
exId.setValue(null);
externalIdentifierCollection.add(exId);
}
Iterator it = externalIdentifierCollection.iterator();
while (it.hasNext())
{
ExternalIdentifier exId = (ExternalIdentifier) it.next();
exId.setSpecimen(specimen);
dao.insert(exId, sessionDataBean, true, true);
}
}
//Mandar : 17-july-06 : autoevents start
Collection specimenEventsCollection = specimen.getSpecimenEventCollection();
Iterator specimenEventsCollectionIterator = specimenEventsCollection.iterator();
while (specimenEventsCollectionIterator.hasNext())
{
Object eventObject = specimenEventsCollectionIterator.next();
if (eventObject instanceof CollectionEventParameters)
{
CollectionEventParameters collectionEventParameters = (CollectionEventParameters) eventObject;
collectionEventParameters.setSpecimen(specimen);
dao.insert(collectionEventParameters, sessionDataBean, true, true);
}
else if (eventObject instanceof ReceivedEventParameters)
{
ReceivedEventParameters receivedEventParameters = (ReceivedEventParameters) eventObject;
receivedEventParameters.setSpecimen(specimen);
dao.insert(receivedEventParameters, sessionDataBean, true, true);
}
}
//Mandar : 17-july-06 : autoevents end
//Inserting data for Authorization
//SecurityManager.getInstance(this.getClass()).insertAuthorizationData(null, protectionObjects, getDynamicGroups(specimen));
}
catch (SMException e)
{
throw handleSMException(e);
}
}
public void postInsert(Object obj, DAO dao, SessionDataBean sessionDataBean) throws DAOException, UserNotAuthorizedException
{
Map containerMap = null;
try
{
containerMap = StorageContainerUtil.getContainerMapFromCache();
}
catch (Exception e)
{
e.printStackTrace();
}
if (obj instanceof HashMap)
{
HashMap specimenMap = (HashMap) obj;
Iterator specimenIterator = specimenMap.keySet().iterator();
while (specimenIterator.hasNext())
{
Specimen specimen = (Specimen) specimenIterator.next();
updateStorageLocations((TreeMap) containerMap, specimen);
List derivedSpecimens = (List) specimenMap.get(specimen);
if (derivedSpecimens != null)
{
for (int i = 0; i < derivedSpecimens.size(); i++)
{
Specimen derivedSpecimen = (Specimen) derivedSpecimens.get(i);
updateStorageLocations((TreeMap) containerMap, derivedSpecimen);
}
}
}
}
else
{
updateStorageLocations((TreeMap) containerMap, (Specimen) obj);
}
}
void updateStorageLocations(TreeMap containerMap,Specimen specimen)
{
try
{
if (specimen.getStorageContainer() != null)
{
StorageContainerUtil.deleteSinglePositionInContainerMap(specimen.getStorageContainer(), containerMap, specimen
.getPositionDimensionOne().intValue(), specimen.getPositionDimensionTwo().intValue());
}
}
catch (Exception e)
{
}
}
protected String[] getDynamicGroups(AbstractDomainObject obj) throws SMException
{
Specimen specimen = (Specimen) obj;
String[] dynamicGroups = new String[1];
dynamicGroups[0] = SecurityManager.getInstance(this.getClass()).getProtectionGroupByName(specimen.getSpecimenCollectionGroup(),
Constants.getCollectionProtocolPGName(null));
Logger.out.debug("Dynamic Group name: " + dynamicGroups[0]);
return dynamicGroups;
}
protected void chkContainerValidForSpecimen(StorageContainer container, Specimen specimen, DAO dao) throws DAOException
{
boolean aa = container.getHoldsSpecimenClassCollection().contains(specimen.getClassName());
boolean bb = container.getCollectionProtocolCollection().contains(
specimen.getSpecimenCollectionGroup().getCollectionProtocolRegistration().getCollectionProtocol());
if (!container.getHoldsSpecimenClassCollection().contains(specimen.getClassName())
|| (!container.getCollectionProtocolCollection().contains(
specimen.getSpecimenCollectionGroup().getCollectionProtocolRegistration().getCollectionProtocol()) && container
.getCollectionProtocolCollection().size() != 0))
{
throw new DAOException("This Storage Container not valid for Specimen");
}
}
private SpecimenCollectionGroup loadSpecimenCollectionGroup(Long specimenID, DAO dao) throws DAOException
{
//get list of Participant's names
String sourceObjectName = Specimen.class.getName();
String[] selectedColumn = {"specimenCollectionGroup." + Constants.SYSTEM_IDENTIFIER};
String whereColumnName[] = {Constants.SYSTEM_IDENTIFIER};
String whereColumnCondition[] = {"="};
Object whereColumnValue[] = {specimenID};
String joinCondition = Constants.AND_JOIN_CONDITION;
List list = dao.retrieve(sourceObjectName, selectedColumn, whereColumnName, whereColumnCondition, whereColumnValue, joinCondition);
if (!list.isEmpty())
{
Long specimenCollectionGroupId = (Long) list.get(0);
SpecimenCollectionGroup specimenCollectionGroup = new SpecimenCollectionGroup();
specimenCollectionGroup.setId(specimenCollectionGroupId);
return specimenCollectionGroup;
}
return null;
}
private SpecimenCharacteristics loadSpecimenCharacteristics(Long specimenID, DAO dao) throws DAOException
{
//get list of Participant's names
String sourceObjectName = Specimen.class.getName();
String[] selectedColumn = {"specimenCharacteristics." + Constants.SYSTEM_IDENTIFIER};
String whereColumnName[] = {Constants.SYSTEM_IDENTIFIER};
String whereColumnCondition[] = {"="};
Object whereColumnValue[] = {specimenID};
String joinCondition = Constants.AND_JOIN_CONDITION;
List list = dao.retrieve(sourceObjectName, selectedColumn, whereColumnName, whereColumnCondition, whereColumnValue, joinCondition);
if (!list.isEmpty())
{
Long specimenCharacteristicsId = (Long) list.get(0);
SpecimenCharacteristics specimenCharacteristics = new SpecimenCharacteristics();
specimenCharacteristics.setId(specimenCharacteristicsId);
return specimenCharacteristics;
//return (SpecimenCharacteristics)list.get(0);
}
return null;
}
private void setAvailableQuantity(Specimen obj, Specimen oldObj) throws DAOException
{
if (obj instanceof TissueSpecimen)
{
Logger.out.debug("In TissueSpecimen");
TissueSpecimen tissueSpecimenObj = (TissueSpecimen) obj;
TissueSpecimen tissueSpecimenOldObj = (TissueSpecimen) oldObj;
// get new qunatity modifed by user
double newQty = Double.parseDouble(tissueSpecimenObj.getQuantity().toString());//tissueSpecimenObj.getQuantityInGram().doubleValue();
// get old qunatity from database
double oldQty = Double.parseDouble(tissueSpecimenOldObj.getQuantity().toString());//tissueSpecimenOldObj.getQuantityInGram().doubleValue();
Logger.out.debug("New Qty: " + newQty + " Old Qty: " + oldQty);
// get Available qty
double oldAvailableQty = Double.parseDouble(tissueSpecimenOldObj.getAvailableQuantity().toString());//tissueSpecimenOldObj.getAvailableQuantityInGram().doubleValue();
double distQty = 0;
double newAvailableQty = 0;
// Distributed Qty = Old_Qty - Old_Available_Qty
distQty = oldQty - oldAvailableQty;
// New_Available_Qty = New_Qty - Distributed_Qty
newAvailableQty = newQty - distQty;
Logger.out.debug("Dist Qty: " + distQty + " New Available Qty: " + newAvailableQty);
if (newAvailableQty < 0)
{
throw new DAOException("Newly modified Quantity '" + newQty + "' should not be less than current Distributed Quantity '" + distQty
+ "'");
}
else
{
// set new available quantity
tissueSpecimenObj.setAvailableQuantity(new QuantityInGram(newAvailableQty));//tissueSpecimenObj.setAvailableQuantityInGram(new Double(newAvailableQty));
}
}
else if (obj instanceof MolecularSpecimen)
{
Logger.out.debug("In MolecularSpecimen");
MolecularSpecimen molecularSpecimenObj = (MolecularSpecimen) obj;
MolecularSpecimen molecularSpecimenOldObj = (MolecularSpecimen) oldObj;
// get new qunatity modifed by user
double newQty = Double.parseDouble(molecularSpecimenObj.getQuantity().toString());//molecularSpecimenObj.getQuantityInMicrogram().doubleValue();
// get old qunatity from database
double oldQty = Double.parseDouble(molecularSpecimenOldObj.getQuantity().toString());//molecularSpecimenOldObj.getQuantityInMicrogram().doubleValue();
Logger.out.debug("New Qty: " + newQty + " Old Qty: " + oldQty);
// get Available qty
double oldAvailableQty = Double.parseDouble(molecularSpecimenOldObj.getAvailableQuantity().toString());//molecularSpecimenOldObj.getAvailableQuantityInMicrogram().doubleValue();
double distQty = 0;
double newAvailableQty = 0;
// Distributed Qty = Old_Qty - Old_Available_Qty
distQty = oldQty - oldAvailableQty;
// New_Available_Qty = New_Qty - Distributed_Qty
newAvailableQty = newQty - distQty;
Logger.out.debug("Dist Qty: " + distQty + " New Available Qty: " + newAvailableQty);
if (newAvailableQty < 0)
{
throw new DAOException("Newly modified Quantity '" + newQty + "' should not be less than current Distributed Quantity '" + distQty
+ "'");
}
else
{
// set new available quantity
molecularSpecimenObj.setAvailableQuantity(new QuantityInMicrogram(newAvailableQty));//molecularSpecimenObj.setAvailableQuantityInMicrogram(new Double(newAvailableQty));
}
}
else if (obj instanceof CellSpecimen)
{
Logger.out.debug("In CellSpecimen");
CellSpecimen cellSpecimenObj = (CellSpecimen) obj;
CellSpecimen cellSpecimenOldObj = (CellSpecimen) oldObj;
// get new qunatity modifed by user
int newQty = (int) Double.parseDouble(cellSpecimenObj.getQuantity().toString());//cellSpecimenObj.getQuantityInCellCount().intValue();
// get old qunatity from database
int oldQty = (int) Double.parseDouble(cellSpecimenOldObj.getQuantity().toString());//cellSpecimenOldObj.getQuantityInCellCount().intValue();
Logger.out.debug("New Qty: " + newQty + " Old Qty: " + oldQty);
// get Available qty
int oldAvailableQty = (int) Double.parseDouble(cellSpecimenOldObj.getAvailableQuantity().toString());//cellSpecimenOldObj.getAvailableQuantityInCellCount().intValue();
int distQty = 0;
int newAvailableQty = 0;
// Distributed Qty = Old_Qty - Old_Available_Qty
distQty = oldQty - oldAvailableQty;
// New_Available_Qty = New_Qty - Distributed_Qty
newAvailableQty = newQty - distQty;
Logger.out.debug("Dist Qty: " + distQty + " New Available Qty: " + newAvailableQty);
if (newAvailableQty < 0)
{
throw new DAOException("Newly modified Quantity '" + newQty + "' should not be less than current Distributed Quantity '" + distQty
+ "'");
}
else
{
// set new available quantity
cellSpecimenObj.setAvailableQuantity(new QuantityInCount(newAvailableQty));//cellSpecimenObj.setAvailableQuantityInCellCount(new Integer(newAvailableQty));
}
}
else if (obj instanceof FluidSpecimen)
{
Logger.out.debug("In FluidSpecimen");
FluidSpecimen fluidSpecimenObj = (FluidSpecimen) obj;
FluidSpecimen fluidSpecimenOldObj = (FluidSpecimen) oldObj;
// get new qunatity modifed by user
double newQty = Double.parseDouble(fluidSpecimenObj.getQuantity().toString());//fluidSpecimenObj.getQuantityInMilliliter().doubleValue();
// get old qunatity from database
double oldQty = Double.parseDouble(fluidSpecimenOldObj.getQuantity().toString());//fluidSpecimenOldObj.getQuantityInMilliliter().doubleValue();
Logger.out.debug("New Qty: " + newQty + " Old Qty: " + oldQty);
// get Available qty
double oldAvailableQty = Double.parseDouble(fluidSpecimenOldObj.getAvailableQuantity().toString());//fluidSpecimenOldObj.getAvailableQuantityInMilliliter().doubleValue();
double distQty = 0;
double newAvailableQty = 0;
// Distributed Qty = Old_Qty - Old_Available_Qty
distQty = oldQty - oldAvailableQty;
// New_Available_Qty = New_Qty - Distributed_Qty
newAvailableQty = newQty - distQty;
Logger.out.debug("Dist Qty: " + distQty + " New Available Qty: " + newAvailableQty);
if (newAvailableQty < 0)
{
throw new DAOException("Newly modified Quantity '" + newQty + "' should not be less than current Distributed Quantity '" + distQty
+ "'");
}
else
{
fluidSpecimenObj.setAvailableQuantity(new QuantityInMilliliter(newAvailableQty));//fluidSpecimenObj.setAvailableQuantityInMilliliter(new Double(newAvailableQty));
}
}
}
/**
* Updates the persistent object in the database.
* @param obj The object to be updated.
* @param session The session in which the object is saved.
* @throws DAOException
* @throws HibernateException Exception thrown during hibernate operations.
*/
public void update(DAO dao, Object obj, Object oldObj, SessionDataBean sessionDataBean) throws DAOException, UserNotAuthorizedException
{
Specimen specimen = (Specimen) obj;
Specimen specimenOld = (Specimen) oldObj;
ApiSearchUtil.setSpecimenDefault(specimen);
//Added for api Search
if (isStoragePositionChanged(specimenOld, specimen))
{
throw new DAOException("Storage Position should not be changed while updating the specimen");
}
if (!specimenOld.getLineage().equals(specimen.getLineage()))
{
throw new DAOException("Lineage should not be changed while updating the specimen");
}
if (!specimenOld.getClassName().equals(specimen.getClassName()))
{
throw new DAOException("Class should not be changed while updating the specimen");
}
// if(specimenOld.getAvailableQuantity().getValue().longValue() != specimen.getAvailableQuantity().getValue().longValue())
// throw new DAOException("Available Quantity should not be changed while updating the specimen");
//End:- Change for API Search
setAvailableQuantity(specimen, specimenOld);
if (specimen.isParentChanged())
{
//Check whether continer is moved to one of its sub container.
if (isUnderSubSpecimen(specimen, specimen.getParentSpecimen().getId()))
{
throw new DAOException(ApplicationProperties.getValue("errors.specimen.under.subspecimen"));
}
Logger.out.debug("Loading ParentSpecimen: " + specimen.getParentSpecimen().getId());
// check for closed ParentSpecimen
checkStatus(dao, specimen.getParentSpecimen(), "Parent Specimen");
SpecimenCollectionGroup scg = loadSpecimenCollectionGroup(specimen.getParentSpecimen().getId(), dao);
specimen.setSpecimenCollectionGroup(scg);
SpecimenCharacteristics sc = loadSpecimenCharacteristics(specimen.getParentSpecimen().getId(), dao);
if (!Constants.ALIQUOT.equals(specimen.getLineage()))//specimen instanceof OriginalSpecimen)
{
specimen.setSpecimenCharacteristics(sc);
}
}
//check for closed Specimen Collection Group
if (!specimen.getSpecimenCollectionGroup().getId().equals(specimenOld.getSpecimenCollectionGroup().getId()))
checkStatus(dao, specimen.getSpecimenCollectionGroup(), "Specimen Collection Group");
setSpecimenGroupForSubSpecimen(specimen, specimen.getSpecimenCollectionGroup(), specimen.getSpecimenCharacteristics());
if (!Constants.ALIQUOT.equals(specimen.getLineage()))//specimen instanceof OriginalSpecimen)
{
dao.update(specimen.getSpecimenCharacteristics(), sessionDataBean, true, true, false);
}
dao.update(specimen, sessionDataBean, true, false, false);//dao.update(specimen, sessionDataBean, true, true, false);
//Audit of Specimen.
dao.audit(obj, oldObj, sessionDataBean, true);
//Audit of Specimen Characteristics.
dao.audit(specimen.getSpecimenCharacteristics(), specimenOld.getSpecimenCharacteristics(), sessionDataBean, true);
Collection oldExternalIdentifierCollection = specimenOld.getExternalIdentifierCollection();
Collection externalIdentifierCollection = specimen.getExternalIdentifierCollection();
if (externalIdentifierCollection != null)
{
Iterator it = externalIdentifierCollection.iterator();
while (it.hasNext())
{
ExternalIdentifier exId = (ExternalIdentifier) it.next();
exId.setSpecimen(specimen);
dao.update(exId, sessionDataBean, true, true, false);
ExternalIdentifier oldExId = (ExternalIdentifier) getCorrespondingOldObject(oldExternalIdentifierCollection, exId.getId());
dao.audit(exId, oldExId, sessionDataBean, true);
}
}
//Disable functionality
Logger.out.debug("specimen.getActivityStatus() " + specimen.getActivityStatus());
if (specimen.getActivityStatus().equals(Constants.ACTIVITY_STATUS_DISABLED))
{
// check for disabling a specimen
boolean disposalEventPresent = false;
Collection eventCollection = specimen.getSpecimenEventCollection();
Iterator itr = eventCollection.iterator();
while (itr.hasNext())
{
Object eventObject = itr.next();
if (eventObject instanceof DisposalEventParameters)
{
disposalEventPresent = true;
break;
}
}
if (!disposalEventPresent)
{
throw new DAOException(ApplicationProperties.getValue("errors.specimen.not.disabled.no.disposalevent"));
}
setDisableToSubSpecimen(specimen);
Logger.out.debug("specimen.getActivityStatus() " + specimen.getActivityStatus());
Long specimenIDArr[] = new Long[1];
specimenIDArr[0] = specimen.getId();
disableSubSpecimens(dao, specimenIDArr);
}
}
private boolean isUnderSubSpecimen(Specimen specimen, Long parentSpecimenID)
{
if (specimen != null)
{
Iterator iterator = specimen.getChildrenSpecimen().iterator();
while (iterator.hasNext())
{
Specimen childSpecimen = (Specimen) iterator.next();
//Logger.out.debug("SUB CONTINER container "+parentContainerID.longValue()+" "+container.getId().longValue()+" "+(parentContainerID.longValue()==container.getId().longValue()));
if (parentSpecimenID.longValue() == childSpecimen.getId().longValue())
return true;
if (isUnderSubSpecimen(childSpecimen, parentSpecimenID))
return true;
}
}
return false;
}
private void setSpecimenGroupForSubSpecimen(Specimen specimen, SpecimenCollectionGroup specimenCollectionGroup,
SpecimenCharacteristics specimenCharacteristics)
{
if (specimen != null)
{
Logger.out.debug("specimen() " + specimen.getId());
Logger.out.debug("specimen.getChildrenContainerCollection() " + specimen.getChildrenSpecimen().size());
Iterator iterator = specimen.getChildrenSpecimen().iterator();
while (iterator.hasNext())
{
Specimen childSpecimen = (Specimen) iterator.next();
childSpecimen.setSpecimenCollectionGroup(specimenCollectionGroup);
//((OriginalSpecimen)childSpecimen).setSpecimenCharacteristics(specimenCharacteristics);
setSpecimenGroupForSubSpecimen(childSpecimen, specimenCollectionGroup, specimenCharacteristics);
}
}
}
// TODO TO BE REMOVED
private void setDisableToSubSpecimen(Specimen specimen)
{
if (specimen != null)
{
Iterator iterator = specimen.getChildrenSpecimen().iterator();
while (iterator.hasNext())
{
Specimen childSpecimen = (Specimen) iterator.next();
childSpecimen.setActivityStatus(Constants.ACTIVITY_STATUS_DISABLED);
setDisableToSubSpecimen(childSpecimen);
}
}
}
private void setSpecimenAttributes(DAO dao, Specimen specimen, SessionDataBean sessionDataBean, boolean isCollectionGroupName)
throws DAOException, SMException
{
specimen.setActivityStatus(Constants.ACTIVITY_STATUS_ACTIVE);
// set barcode to null in case it is blank
if (specimen.getBarcode() != null && specimen.getBarcode().trim().equals(""))
{
specimen.setBarcode(null);
}
// TODO
//Load & set Specimen Collection Group if present
if (specimen.getSpecimenCollectionGroup() != null)
{
SpecimenCollectionGroup specimenCollectionGroupObj = null;
if (isCollectionGroupName)
{
/*String sourceObjectName = SpecimenCollectionGroup.class.getName();
String[] selectColumnName = {"id"};
String[] whereColumnName = {"name"};
String[] whereColumnCondition = {"="};
Object[] whereColumnValue = {specimen.getSpecimenCollectionGroup().getName()};
String joinCondition = null;
List list = dao.retrieve(sourceObjectName, selectColumnName, whereColumnName, whereColumnCondition, whereColumnValue, joinCondition);
specimenCollectionGroupObj = new SpecimenCollectionGroup();
specimenCollectionGroupObj.setId((Long)list.get(0));*/
List spgList = dao.retrieve(SpecimenCollectionGroup.class.getName(), Constants.NAME, specimen.getSpecimenCollectionGroup().getName());
specimenCollectionGroupObj = (SpecimenCollectionGroup)spgList.get(0);
}
else
{
specimenCollectionGroupObj = new SpecimenCollectionGroup();
specimenCollectionGroupObj.setId(specimen.getSpecimenCollectionGroup().getId());
}
if (specimenCollectionGroupObj != null)
{
/*if (specimenCollectionGroupObj.getActivityStatus().equals(Constants.ACTIVITY_STATUS_CLOSED))
{
throw new DAOException("Specimen Collection Group " + ApplicationProperties.getValue("error.object.closed"));
}*/
checkStatus(dao, specimenCollectionGroupObj,"Specimen Collection Group" );
specimen.setSpecimenCollectionGroup(specimenCollectionGroupObj);
}
}
//Load & set Parent Specimen if present
if (specimen.getParentSpecimen() != null)
{
// Object parentSpecimenObj = dao.retrieve(Specimen.class.getName(), specimen.getParentSpecimen().getId());
// if (parentSpecimenObj != null)
Specimen parentSpecimen = new Specimen();
parentSpecimen.setId(specimen.getParentSpecimen().getId());
// check for closed Parent Specimen
checkStatus(dao, parentSpecimen, "Parent Specimen");
specimen.setLineage(Constants.DERIVED_SPECIMEN);
}
//Load & set Storage Container
if (specimen.getStorageContainer() != null)
{
if (specimen.getStorageContainer().getId() != null)
{
// Object containerObj = dao.retrieve(StorageContainer.class.getName(), specimen.getStorageContainer().getId());
// if (containerObj != null)
// StorageContainer container = (StorageContainer) containerObj;
StorageContainer storageContainerObj = new StorageContainer();
storageContainerObj.setId(specimen.getStorageContainer().getId());
String sourceObjectName = StorageContainer.class.getName();
String[] selectColumnName = {"name"};
String[] whereColumnName = {"id"}; //"storageContainer."+Constants.SYSTEM_IDENTIFIER
String[] whereColumnCondition = {"="};
Object[] whereColumnValue = {specimen.getStorageContainer().getId()};
String joinCondition = null;
List list = dao.retrieve(sourceObjectName, selectColumnName, whereColumnName, whereColumnCondition, whereColumnValue, joinCondition);
if (!list.isEmpty())
{
storageContainerObj.setName((String) list.get(0));
}
// check for closed Storage Container
checkStatus(dao, storageContainerObj, "Storage Container");
StorageContainerBizLogic storageContainerBizLogic = (StorageContainerBizLogic) BizLogicFactory.getInstance().getBizLogic(
Constants.STORAGE_CONTAINER_FORM_ID);
storageContainerBizLogic.checkContainer(dao, storageContainerObj.getId().toString(), specimen.getPositionDimensionOne().toString(),
specimen.getPositionDimensionTwo().toString(), sessionDataBean);
//chkContainerValidForSpecimen(container, specimen,dao);
specimen.setStorageContainer(storageContainerObj);
// else
// throw new DAOException(ApplicationProperties.getValue("errors.storageContainerExist"));
}
}
//Setting the Biohazard Collection
Set set = new HashSet();
Collection biohazardCollection = specimen.getBiohazardCollection();
if (biohazardCollection != null)
{
Iterator it = biohazardCollection.iterator();
while (it.hasNext())
{
Biohazard hazard = (Biohazard) it.next();
Logger.out.debug("hazard.getId() " + hazard.getId());
Object bioObj = dao.retrieve(Biohazard.class.getName(), hazard.getId());
if (bioObj != null)
{
Biohazard hazardObj = (Biohazard) bioObj;
set.add(hazardObj);
}
}
}
specimen.setBiohazardCollection(set);
}
public void disableRelatedObjectsForSpecimenCollectionGroup(DAO dao, Long specimenCollectionGroupArr[]) throws DAOException
{
Logger.out.debug("disableRelatedObjects NewSpecimenBizLogic");
List listOfSpecimenId = super.disableObjects(dao, Specimen.class, "specimenCollectionGroup", "CATISSUE_SPECIMEN",
"SPECIMEN_COLLECTION_GROUP_ID", specimenCollectionGroupArr);
if (!listOfSpecimenId.isEmpty())
{
disableSubSpecimens(dao, Utility.toLongArray(listOfSpecimenId));
}
}
// public void disableRelatedObjectsForStorageContainer(DAO dao, Long storageContainerIdArr[])throws DAOException
// Logger.out.debug("disableRelatedObjectsForStorageContainer NewSpecimenBizLogic");
// List listOfSpecimenId = super.disableObjects(dao, Specimen.class, "storageContainer",
// "CATISSUE_SPECIMEN", "STORAGE_CONTAINER_IDENTIFIER", storageContainerIdArr);
// if(!listOfSpecimenId.isEmpty())
// disableSubSpecimens(dao,Utility.toLongArray(listOfSpecimenId));
private void disableSubSpecimens(DAO dao, Long speIDArr[]) throws DAOException
{
List listOfSubElement = super.disableObjects(dao, Specimen.class, "parentSpecimen", "CATISSUE_SPECIMEN", "PARENT_SPECIMEN_ID", speIDArr);
if (listOfSubElement.isEmpty())
return;
disableSubSpecimens(dao, Utility.toLongArray(listOfSubElement));
}
/**
* @param dao
* @param privilegeName
* @param longs
* @param userId
* @throws DAOException
* @throws SMException
*/
public void assignPrivilegeToRelatedObjectsForSCG(DAO dao, String privilegeName, Long[] specimenCollectionGroupArr, Long userId, String roleId,
boolean assignToUser, boolean assignOperation) throws SMException, DAOException
{
Logger.out.debug("assignPrivilegeToRelatedObjectsForSCG NewSpecimenBizLogic");
List listOfSpecimenId = super.getRelatedObjects(dao, Specimen.class, "specimenCollectionGroup", specimenCollectionGroupArr);
if (!listOfSpecimenId.isEmpty())
{
super.setPrivilege(dao, privilegeName, Specimen.class, Utility.toLongArray(listOfSpecimenId), userId, roleId, assignToUser,
assignOperation);
List specimenCharacteristicsIds = super.getRelatedObjects(dao, Specimen.class, new String[]{"specimenCharacteristics."
+ Constants.SYSTEM_IDENTIFIER}, new String[]{Constants.SYSTEM_IDENTIFIER}, Utility.toLongArray(listOfSpecimenId));
super.setPrivilege(dao, privilegeName, Address.class, Utility.toLongArray(specimenCharacteristicsIds), userId, roleId, assignToUser,
assignOperation);
assignPrivilegeToSubSpecimens(dao, privilegeName, Specimen.class, Utility.toLongArray(listOfSpecimenId), userId, roleId, assignToUser,
assignOperation);
}
}
/**
* @param dao
* @param privilegeName
* @param class1
* @param longs
* @param userId
* @throws DAOException
* @throws SMException
*/
private void assignPrivilegeToSubSpecimens(DAO dao, String privilegeName, Class class1, Long[] speIDArr, Long userId, String roleId,
boolean assignToUser, boolean assignOperation) throws SMException, DAOException
{
List listOfSubElement = super.getRelatedObjects(dao, Specimen.class, "parentSpecimen", speIDArr);
if (listOfSubElement.isEmpty())
return;
super.setPrivilege(dao, privilegeName, Specimen.class, Utility.toLongArray(listOfSubElement), userId, roleId, assignToUser, assignOperation);
List specimenCharacteristicsIds = super.getRelatedObjects(dao, Specimen.class, new String[]{"specimenCharacteristics."
+ Constants.SYSTEM_IDENTIFIER}, new String[]{Constants.SYSTEM_IDENTIFIER}, Utility.toLongArray(listOfSubElement));
super.setPrivilege(dao, privilegeName, Address.class, Utility.toLongArray(specimenCharacteristicsIds), userId, roleId, assignToUser,
assignOperation);
assignPrivilegeToSubSpecimens(dao, privilegeName, Specimen.class, Utility.toLongArray(listOfSubElement), userId, roleId, assignToUser,
assignOperation);
}
public void setPrivilege(DAO dao, String privilegeName, Class objectType, Long[] objectIds, Long userId, String roleId, boolean assignToUser,
boolean assignOperation) throws SMException, DAOException
{
super.setPrivilege(dao, privilegeName, objectType, objectIds, userId, roleId, assignToUser, assignOperation);
List specimenCharacteristicsIds = super.getRelatedObjects(dao, Specimen.class, new String[]{"specimenCharacteristics."
+ Constants.SYSTEM_IDENTIFIER}, new String[]{Constants.SYSTEM_IDENTIFIER}, objectIds);
super.setPrivilege(dao, privilegeName, Address.class, Utility.toLongArray(specimenCharacteristicsIds), userId, roleId, assignToUser,
assignOperation);
assignPrivilegeToSubSpecimens(dao, privilegeName, Specimen.class, objectIds, userId, roleId, assignToUser, assignOperation);
}
// validation code here
/**
* @see edu.wustl.common.bizlogic.IBizLogic#setPrivilege(DAO, String, Class, Long[], Long, String, boolean)
* @param dao
* @param privilegeName
* @param objectIds
* @param userId
* @param roleId
* @param assignToUser
* @throws SMException
* @throws DAOException
*/
public void assignPrivilegeToRelatedObjectsForDistributedItem(DAO dao, String privilegeName, Long[] objectIds, Long userId, String roleId,
boolean assignToUser, boolean assignOperation) throws SMException, DAOException
{
String[] selectColumnNames = {"specimen.id"};
String[] whereColumnNames = {"id"};
List listOfSubElement = super.getRelatedObjects(dao, DistributedItem.class, selectColumnNames, whereColumnNames, objectIds);
if (!listOfSubElement.isEmpty())
{
super.setPrivilege(dao, privilegeName, Specimen.class, Utility.toLongArray(listOfSubElement), userId, roleId, assignToUser,
assignOperation);
}
}
/**
* Overriding the parent class's method to validate the enumerated attribute values
*/
protected boolean validate(Object obj, DAO dao, String operation) throws DAOException
{
boolean result;
if (obj instanceof Map)
{
result = validateMultipleSpecimen((Map) obj, dao, operation);
}
else
{
result = validateSingleSpecimen((Specimen) obj, dao, operation, false);
}
return result;
}
/**
* validates single specimen.
*/
private boolean validateSingleSpecimen(Specimen specimen, DAO dao, String operation, boolean partOfMulipleSpecimen) throws DAOException
{
//Added by Ashish
//Logger.out.debug("Start-Inside validate method of specimen bizlogic");
if (specimen == null)
{
throw new DAOException(ApplicationProperties.getValue("domain.object.null.err.msg", "Specimen"));
}
Validator validator = new Validator();
if (specimen.getSpecimenCollectionGroup() == null || specimen.getSpecimenCollectionGroup().getId() == null
|| specimen.getSpecimenCollectionGroup().getId().equals("-1"))
{
String message = ApplicationProperties.getValue("specimen.specimenCollectionGroup");
throw new DAOException(ApplicationProperties.getValue("errors.item.required", message));
}
if (specimen.getParentSpecimen() != null
&& (specimen.getParentSpecimen().getId() == null || validator.isEmpty(specimen.getParentSpecimen().getId().toString())))
{
String message = ApplicationProperties.getValue("createSpecimen.parent");
throw new DAOException(ApplicationProperties.getValue("errors.item.required", message));
}
if (validator.isEmpty(specimen.getLabel()))
{
String message = ApplicationProperties.getValue("specimen.label");
throw new DAOException(ApplicationProperties.getValue("errors.item.required", message));
}
if (validator.isEmpty(specimen.getClassName()))
{
String message = ApplicationProperties.getValue("specimen.type");
throw new DAOException(ApplicationProperties.getValue("errors.item.required", message));
}
if (validator.isEmpty(specimen.getType()))
{
String message = ApplicationProperties.getValue("specimen.subType");
throw new DAOException(ApplicationProperties.getValue("errors.item.required", message));
}
if (specimen.getStorageContainer() != null && specimen.getStorageContainer().getId() == null)
{
String message = ApplicationProperties.getValue("specimen.subType");
throw new DAOException(ApplicationProperties.getValue("errors.invalid", message));
}
if (specimen.getSpecimenEventCollection() != null)
{
Iterator specimenEventCollectionIterator = specimen.getSpecimenEventCollection().iterator();
while (specimenEventCollectionIterator.hasNext())
{
//CollectionEvent validation.
Object eventObject = specimenEventCollectionIterator.next();
if (eventObject instanceof CollectionEventParameters)
{
CollectionEventParameters collectionEventParameters = (CollectionEventParameters) eventObject;
collectionEventParameters.getUser();
if (collectionEventParameters.getUser() == null || collectionEventParameters.getUser().getId() == null)
{
String message = ApplicationProperties.getValue("specimen.collection.event.user");
throw new DAOException(ApplicationProperties.getValue("errors.item.required", message));
}
if (!validator.checkDate(Utility.parseDateToString(collectionEventParameters.getTimestamp(), Constants.DATE_PATTERN_MM_DD_YYYY)))
{
String message = ApplicationProperties.getValue("specimen.collection.event.date");
throw new DAOException(ApplicationProperties.getValue("errors.item.required", message));
}
// checks the collectionProcedure
if (!validator.isValidOption(collectionEventParameters.getCollectionProcedure()))
{
String message = ApplicationProperties.getValue("collectioneventparameters.collectionprocedure");
throw new DAOException(ApplicationProperties.getValue("errors.item.required", message));
}
List procedureList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_COLLECTION_PROCEDURE, null);
if (!Validator.isEnumeratedValue(procedureList, collectionEventParameters.getCollectionProcedure()))
{
throw new DAOException(ApplicationProperties.getValue("events.collectionProcedure.errMsg"));
}
if (!validator.isValidOption(collectionEventParameters.getContainer()))
{
String message = ApplicationProperties.getValue("collectioneventparameters.container");
throw new DAOException(ApplicationProperties.getValue("errors.item.required", message));
}
List containerList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_CONTAINER, null);
if (!Validator.isEnumeratedValue(containerList, collectionEventParameters.getContainer()))
{
throw new DAOException(ApplicationProperties.getValue("events.container.errMsg"));
}
}
//ReceivedEvent validation
else if (eventObject instanceof ReceivedEventParameters)
{
ReceivedEventParameters receivedEventParameters = (ReceivedEventParameters) eventObject;
if (receivedEventParameters.getUser() == null || receivedEventParameters.getUser().getId() == null)
{
String message = ApplicationProperties.getValue("specimen.recieved.event.user");
throw new DAOException(ApplicationProperties.getValue("errors.item.required", message));
}
if (!validator.checkDate(Utility.parseDateToString(receivedEventParameters.getTimestamp(), Constants.DATE_PATTERN_MM_DD_YYYY)))
{
String message = ApplicationProperties.getValue("specimen.recieved.event.date");
throw new DAOException(ApplicationProperties.getValue("errors.item.required", message));
}
// checks the collectionProcedure
if (!validator.isValidOption(receivedEventParameters.getReceivedQuality()))
{
String message = ApplicationProperties.getValue("collectioneventparameters.receivedquality");
throw new DAOException(ApplicationProperties.getValue("errors.item.required", message));
}
List qualityList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_RECEIVED_QUALITY, null);
if (!Validator.isEnumeratedValue(qualityList, receivedEventParameters.getReceivedQuality()))
{
throw new DAOException(ApplicationProperties.getValue("events.receivedQuality.errMsg"));
}
}
}
}
//Validations for Biohazard Add-More Block
Collection bioHazardCollection = specimen.getBiohazardCollection();
Biohazard biohazard = null;
if (bioHazardCollection != null && !bioHazardCollection.isEmpty())
{
Iterator itr = bioHazardCollection.iterator();
while (itr.hasNext())
{
biohazard = (Biohazard) itr.next();
if (!validator.isValidOption(biohazard.getType()))
{
String message = ApplicationProperties.getValue("newSpecimen.msg");
throw new DAOException(ApplicationProperties.getValue("errors.newSpecimen.biohazard.missing", message));
}
if (biohazard.getId() == null)
{
String message = ApplicationProperties.getValue("newSpecimen.msg");
throw new DAOException(ApplicationProperties.getValue("errors.newSpecimen.biohazard.missing", message));
}
}
}
//validations for external identifiers
Collection extIdentifierCollection = specimen.getExternalIdentifierCollection();
ExternalIdentifier extIdentifier = null;
if (extIdentifierCollection != null && !extIdentifierCollection.isEmpty())
{
Iterator itr = extIdentifierCollection.iterator();
while (itr.hasNext())
{
extIdentifier = (ExternalIdentifier) itr.next();
if (validator.isEmpty(extIdentifier.getName()))
{
String message = ApplicationProperties.getValue("specimen.msg");
throw new DAOException(ApplicationProperties.getValue("errors.specimen.externalIdentifier.missing", message));
}
if (validator.isEmpty(extIdentifier.getValue()))
{
String message = ApplicationProperties.getValue("specimen.msg");
throw new DAOException(ApplicationProperties.getValue("errors.specimen.externalIdentifier.missing", message));
}
}
}
//End Ashish
if (Constants.ALIQUOT.equals(specimen.getLineage()))
{
//return true;
}
validateFields(specimen, dao, operation, partOfMulipleSpecimen);
List specimenClassList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_SPECIMEN_CLASS, null);
String specimenClass = Utility.getSpecimenClassName(specimen);
if (!Validator.isEnumeratedValue(specimenClassList, specimenClass))
{
throw new DAOException(ApplicationProperties.getValue("protocol.class.errMsg"));
}
if (!Validator.isEnumeratedValue(Utility.getSpecimenTypes(specimenClass), specimen.getType()))
{
throw new DAOException(ApplicationProperties.getValue("protocol.type.errMsg"));
}
SpecimenCharacteristics characters = specimen.getSpecimenCharacteristics();
if (characters == null)
{
throw new DAOException(ApplicationProperties.getValue("specimen.characteristics.errMsg"));
}
else
{
if (specimen.getSpecimenCollectionGroup() != null)
{
// NameValueBean undefinedVal = new NameValueBean(Constants.UNDEFINED,Constants.UNDEFINED);
List tissueSiteList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_TISSUE_SITE, null);
if (!Validator.isEnumeratedValue(tissueSiteList, characters.getTissueSite()))
{
throw new DAOException(ApplicationProperties.getValue("protocol.tissueSite.errMsg"));
}
// NameValueBean unknownVal = new NameValueBean(Constants.UNKNOWN,Constants.UNKNOWN);
List tissueSideList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_TISSUE_SIDE, null);
if (!Validator.isEnumeratedValue(tissueSideList, characters.getTissueSide()))
{
throw new DAOException(ApplicationProperties.getValue("specimen.tissueSide.errMsg"));
}
List pathologicalStatusList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_PATHOLOGICAL_STATUS, null);
if (!Validator.isEnumeratedValue(pathologicalStatusList, specimen.getPathologicalStatus()))
{
throw new DAOException(ApplicationProperties.getValue("protocol.pathologyStatus.errMsg"));
}
}
}
if (operation.equals(Constants.ADD))
{
if (!specimen.getAvailable().booleanValue())
{
throw new DAOException(ApplicationProperties.getValue("specimen.available.errMsg"));
}
if (!Constants.ACTIVITY_STATUS_ACTIVE.equals(specimen.getActivityStatus()))
{
throw new DAOException(ApplicationProperties.getValue("activityStatus.active.errMsg"));
}
}
else
{
if (!Validator.isEnumeratedValue(Constants.ACTIVITY_STATUS_VALUES, specimen.getActivityStatus()))
{
throw new DAOException(ApplicationProperties.getValue("activityStatus.errMsg"));
}
}
//Logger.out.debug("End-Inside validate method of specimen bizlogic");
return true;
}
private void validateFields(Specimen specimen, DAO dao, String operation, boolean partOfMulipleSpecimen) throws DAOException
{
Validator validator = new Validator();
if (partOfMulipleSpecimen)
{
if (specimen.getSpecimenCollectionGroup() == null || validator.isEmpty(specimen.getSpecimenCollectionGroup().getName()))
{
String quantityString = ApplicationProperties.getValue("specimen.specimenCollectionGroup");
throw new DAOException(ApplicationProperties.getValue("errors.item.required", quantityString));
}
List spgList = dao.retrieve(SpecimenCollectionGroup.class.getName(), Constants.NAME, specimen.getSpecimenCollectionGroup().getName());
if (spgList.size() == 0)
{
throw new DAOException(ApplicationProperties.getValue("errors.item.unknown", "Specimen Collection Group "
+ specimen.getSpecimenCollectionGroup().getName()));
}
}
if (validator.isEmpty(specimen.getLabel()))
{
String labelString = ApplicationProperties.getValue("specimen.label");
throw new DAOException(ApplicationProperties.getValue("errors.item.required", labelString));
}
if (specimen.getQuantity() == null || specimen.getQuantity().getValue() == null)
{
String quantityString = ApplicationProperties.getValue("specimen.quantity");
throw new DAOException(ApplicationProperties.getValue("errors.item.required", quantityString));
}
/**
* If specimen is virtually located, then in that case storage container is being set null explicitly in Specimen
* domain object.Hence to avoid NullPointerException here check null of container is required.
* @author jitendra_agrawal
*/
if (specimen.getStorageContainer() != null)
{
Long storageContainerId = specimen.getStorageContainer().getId();
Integer xPos = specimen.getPositionDimensionOne();
Integer yPos = specimen.getPositionDimensionTwo();
if (storageContainerId == null || xPos == null || yPos == null || xPos.intValue() < 0 || yPos.intValue() < 0)
{
throw new DAOException(ApplicationProperties.getValue("errors.item.format", ApplicationProperties
.getValue("specimen.positionInStorageContainer")));
}
}
}
/**
* validates multiple specimen. Internally it for each specimen it innvokes validateSingleSpecimen.
* @throws DAOException
* @throws DAOException
*/
private boolean validateMultipleSpecimen(Map specimenMap, DAO dao, String operation) throws DAOException
{
populateStorageLocations(dao, specimenMap);
Iterator specimenIterator = specimenMap.keySet().iterator();
boolean result = true;
while (specimenIterator.hasNext() && result == true)
{
Specimen specimen = (Specimen) specimenIterator.next();
//validate single specimen
/* if (specimenCollectionGroup != null)
{
if (specimenCollectionGroup.getActivityStatus().equals(Constants.ACTIVITY_STATUS_CLOSED))
{
throw new DAOException("Specimen Collection Group " + ApplicationProperties.getValue("error.object.closed"));
}
specimen.setSpecimenCollectionGroup(specimenCollectionGroup);
}
List spgList = dao.retrieve(SpecimenCollectionGroup.class.getName(), Constants.NAME, specimen.getSpecimenCollectionGroup().getName());
if(spgList!=null && !spgList.isEmpty())
{
specimenCollectionGroup = (SpecimenCollectionGroup) spgList.get(0);
}
else if(specimen.getParentSpecimen()!=null)
{
List spList = dao.retrieve(Specimen.class.getName(), Constants.SYSTEM_LABEL, specimen.getParentSpecimen().getLabel());
if (spList != null && !spList.isEmpty())
{
Specimen sp = (Specimen) spList.get(0);
specimenCollectionGroup = sp.getSpecimenCollectionGroup();
}
} */
// TODO uncomment code for label, performance
try
{
result = validateSingleSpecimen(specimen, dao, operation, true);
}
catch (DAOException daoException)
{
String message = daoException.getMessage();
message += " (This message is for Specimen number " + specimen.getId() + ")";
daoException.setMessage(message);
throw daoException;
}
List derivedSpecimens = (List) specimenMap.get(specimen);
if (derivedSpecimens == null)
{
continue;
}
//validate derived specimens
for (int i = 0; i < derivedSpecimens.size(); i++)
{
Specimen derivedSpecimen = (Specimen) derivedSpecimens.get(i);
derivedSpecimen.setSpecimenCharacteristics(specimen.getSpecimenCharacteristics());
derivedSpecimen.setSpecimenCollectionGroup(specimen.getSpecimenCollectionGroup());
derivedSpecimen.setPathologicalStatus(specimen.getPathologicalStatus());
try
{
result = validateSingleSpecimen(derivedSpecimen, dao, operation, false);
}
catch (DAOException daoException)
{
int j = i + 1;
String message = daoException.getMessage();
message += " (This message is for Derived Specimen " + j + " of Parent Specimen number " + specimen.getId() + ")";
daoException.setMessage(message);
throw daoException;
}
if (!result)
{
break;
}
}
}
return result;
}
/**
*
* Start --> Code added for auto populating storage locations in case of multiple specimen
*/
/**
* This method populates SCG Id and storage locations for Multiple Specimen
* @param dao
* @param specimenMap
* @throws DAOException
*/
private void populateStorageLocations(DAO dao, Map specimenMap) throws DAOException
{
final String saperator = "$";
Map tempSpecimenMap = new HashMap();
Iterator specimenIterator = specimenMap.keySet().iterator();
while (specimenIterator.hasNext())
{
Specimen specimen = (Specimen) specimenIterator.next();
//validate single specimen
SpecimenCollectionGroup specimenCollectionGroup = null;
if (specimen.getSpecimenCollectionGroup() != null)
{
String[] selectColumnName = {"id", "collectionProtocolRegistration.id"};
String[] whereColumnName = {Constants.NAME};
String[] whereColumnCondition = {"="};
String[] whereColumnValue = {specimen.getSpecimenCollectionGroup().getName()};
List spCollGroupList = dao.retrieve(SpecimenCollectionGroup.class.getName(), selectColumnName, whereColumnName, whereColumnCondition,
whereColumnValue, null);
// TODO test
if (!spCollGroupList.isEmpty())
{
Object idList[] = (Object[]) spCollGroupList.get(0);
Long scgId = (Long) idList[0];
long cpId = ((Long) idList[1]).longValue();
specimen.getSpecimenCollectionGroup().setId(scgId);
if (specimen.getStorageContainer() == null)
{
List tempListOfSpecimen = (ArrayList) tempSpecimenMap.get(cpId + saperator + specimen.getClassName());
if (tempListOfSpecimen == null)
{
tempListOfSpecimen = new ArrayList();
}
int i = 0;
for (; i < tempListOfSpecimen.size(); i++)
{
Specimen sp = (Specimen) tempListOfSpecimen.get(i);
if (specimen.getId().longValue() < sp.getId().longValue())
break;
}
tempListOfSpecimen.add(i, specimen);
tempSpecimenMap.put(cpId + saperator + specimen.getClassName(), tempListOfSpecimen);
}
}
}
}
Iterator keyIterator = tempSpecimenMap.keySet().iterator();
while (keyIterator.hasNext())
{
String key = (String) keyIterator.next();
StorageContainerBizLogic scbizLogic = (StorageContainerBizLogic) BizLogicFactory.getInstance().getBizLogic(
Constants.STORAGE_CONTAINER_FORM_ID);
String split[] = key.split("[$]");
Map containerMap = scbizLogic.getAllocatedContaienrMapForSpecimen((Long.parseLong(split[0])), split[1], 0, "", false);
List listOfSpecimens = (ArrayList) tempSpecimenMap.get(key);
allocatePositionToSpecimensList(specimenMap, listOfSpecimens, containerMap);
}
}
/**
* This function gets the default positions for list of specimens
* @param specimenMap
* @param listOfSpecimens
* @param containerMap
*/
private void allocatePositionToSpecimensList(Map specimenMap, List listOfSpecimens, Map containerMap)
{
Iterator iterator = containerMap.keySet().iterator();
int i = 0;
while (iterator.hasNext())
{
NameValueBean nvb = (NameValueBean) iterator.next();
Map tempMap = (Map) containerMap.get(nvb);
if (tempMap.size() > 0)
{
boolean result = false;
for (; i < listOfSpecimens.size(); i++)
{
Specimen tempSpecimen = (Specimen) listOfSpecimens.get(i);
result = allocatePositionToSingleSpecimen(specimenMap, tempSpecimen, tempMap, nvb);
if (result == false)
break;
}
if (result == true)
break;
}
}
}
/**
* This function gets the default position specimen,the position should not be used by any other specimen in specimenMap
* @param specimenMap
* @param tempSpecimen
* @param tempMap
* @param nvb
* @return
*/
private boolean allocatePositionToSingleSpecimen(Map specimenMap, Specimen tempSpecimen, Map tempMap, NameValueBean nvbForContainer)
{
Iterator itr = tempMap.keySet().iterator();
String containerId = nvbForContainer.getValue(), xPos, yPos;
while (itr.hasNext())
{
NameValueBean nvb = (NameValueBean) itr.next();
xPos = nvb.getValue();
List list = (List) tempMap.get(nvb);
for (int i = 0; i < list.size(); i++)
{
nvb = (NameValueBean) list.get(i);
yPos = nvb.getValue();
boolean result = checkPositionValidForSpecimen(containerId, xPos, yPos, specimenMap);
if (result == true)
{
StorageContainer tempStorageContainer = new StorageContainer();
tempStorageContainer.setId(new Long(Long.parseLong(containerId)));
tempSpecimen.setPositionDimensionOne(new Integer(Integer.parseInt(xPos)));
tempSpecimen.setPositionDimensionTwo(new Integer(Integer.parseInt(yPos)));
tempSpecimen.setStorageContainer(tempStorageContainer);
return true;
}
}
}
return false;
}
/**
* This method checks whether the given parameters match with parameters in specimen Map
* @param containerId
* @param pos
* @param pos2
* @param specimenMap
* @return
*/
private boolean checkPositionValidForSpecimen(String containerId, String xpos, String ypos, Map specimenMap)
{
Iterator specimenIterator = specimenMap.keySet().iterator();
while (specimenIterator.hasNext())
{
Specimen specimen = (Specimen) specimenIterator.next();
boolean matchFound = checkMatchingPosition(containerId, xpos, ypos, specimen);
if (matchFound == true)
return false;
List derivedSpecimens = (List) specimenMap.get(specimen);
if (derivedSpecimens != null)
{
for (int i = 0; i < derivedSpecimens.size(); i++)
{
Specimen derivedSpecimen = (Specimen) derivedSpecimens.get(i);
matchFound = checkMatchingPosition(containerId, xpos, ypos, derivedSpecimen);
if (matchFound == true)
return false;
}
}
}
return true;
}
/**
* This method checks whether the given parameters match with parameters of the specimen
* @param containerId
* @param pos
* @param pos2
* @param specimen
* @return
*/
private boolean checkMatchingPosition(String containerId, String xpos, String ypos, Specimen specimen)
{
String storageContainerId = "";
if (specimen.getStorageContainer() != null && specimen.getStorageContainer().getId() != null)
storageContainerId += specimen.getStorageContainer().getId();
else
return false;
String pos1 = specimen.getPositionDimensionOne() + "";
String pos2 = specimen.getPositionDimensionTwo() + "";
if (storageContainerId.equals(containerId) && xpos.equals(pos1) && ypos.equals(pos2))
return true;
return false;
}
/**
*
* End --> Code added for auto populating storage locations in case of multiple specimen
*/
/* This function checks whether the storage position of a specimen is changed or not
* & returns the status accordingly.
*/
private boolean isStoragePositionChanged(Specimen oldSpecimen, Specimen newSpecimen)
{
StorageContainer oldContainer = oldSpecimen.getStorageContainer();
StorageContainer newContainer = newSpecimen.getStorageContainer();
//Added for api: Jitendra
if ((oldContainer == null && newContainer != null) || (oldContainer != null && newContainer == null))
{
return true;
}
if (oldContainer != null && newContainer != null)
{
if (oldContainer.getId().longValue() == newContainer.getId().longValue())
{
if (oldSpecimen.getPositionDimensionOne().intValue() == newSpecimen.getPositionDimensionOne().intValue())
{
if (oldSpecimen.getPositionDimensionTwo().intValue() == newSpecimen.getPositionDimensionTwo().intValue())
{
return false;
}
else
{
return true;
}
}
else
{
return true;
}
}
else
{
return true;
}
}
else
{
return false;
}
}
/**
* This method fetches linked data from integrated application i.e. CAE/caTies.
*/
public List getLinkedAppData(Long id, String applicationID)
{
Logger.out.debug("In getIntegrationData() of SpecimenBizLogic ");
Logger.out.debug("ApplicationName in getIntegrationData() of SCGBizLogic==>" + applicationID);
long identifiedPathologyReportId = 0;
try
{
//JDBC call to get matching identifier from database
Class.forName("org.gjt.mm.mysql.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/catissuecore", "catissue_core", "catissue_core");
Statement stmt = connection.createStatement();
String specimenCollectionGroupQuery = "select SPECIMEN_COLLECTION_GROUP_ID from CATISSUE_SPECIMEN where IDENTIFIER=" + id;
ResultSet specimenCollectionGroupResultSet = stmt.executeQuery(specimenCollectionGroupQuery);
long specimenCollectionGroupId = 0;
while (specimenCollectionGroupResultSet.next())
{
specimenCollectionGroupId = specimenCollectionGroupResultSet.getLong(1);
break;
}
Logger.out.debug("SpecimenCollectionGroupId==>" + specimenCollectionGroupId);
if (specimenCollectionGroupId == 0)
{
List exception = new ArrayList();
exception.add("SpecimenCollectionGroupId is not available for Specimen");
return exception;
}
String clinicalReportQuery = "select CLINICAL_REPORT_ID from CATISSUE_SPECIMEN_COLL_GROUP where IDENTIFIER=" + specimenCollectionGroupId;
ResultSet clinicalReportResultSet = stmt.executeQuery(clinicalReportQuery);
long clinicalReportId = 0;
while (clinicalReportResultSet.next())
{
clinicalReportId = clinicalReportResultSet.getLong(1);
break;
}
Logger.out.debug("ClinicalReportId==>" + clinicalReportId);
clinicalReportResultSet.close();
if (clinicalReportId == 0)
{
List exception = new ArrayList();
exception.add("ClinicalReportId is not available for SpecimenCollectionGroup");
return exception;
}
String identifiedPathologyReportIdQuery = "select IDENTIFIER from CATISSUE_IDENTIFIED_PATHOLOGY_REPORT where CLINICAL_REPORT_ID="
+ clinicalReportId;
ResultSet identifiedPathologyReportResultSet = stmt.executeQuery(identifiedPathologyReportIdQuery);
while (identifiedPathologyReportResultSet.next())
{
identifiedPathologyReportId = identifiedPathologyReportResultSet.getLong(1);
break;
}
Logger.out.debug("IdentifiedPathologyReportId==>" + identifiedPathologyReportId);
identifiedPathologyReportResultSet.close();
if (identifiedPathologyReportId == 0)
{
List exception = new ArrayList();
exception.add("IdentifiedPathologyReportId is not available for linked ClinicalReportId");
return exception;
}
stmt.close();
connection.close();
}
catch (Exception e)
{
Logger.out.debug("JDBC Exception==>" + e.getMessage());
}
IntegrationManager integrationManager = IntegrationManagerFactory.getIntegrationManager(applicationID);
return integrationManager.getLinkedAppData(new Specimen(), new Long(identifiedPathologyReportId));
}
public String getPageToShow()
{
return new String();
}
public List getMatchingObjects()
{
return new ArrayList();
}
}
|
package gui;
import java.awt.AWTEvent;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.util.Map;
import javax.swing.Timer;
public class RepeatingReleasedEventsFixer implements AWTEventListener {
private final Map<Integer, ReleasedAction> _map = new HashMap<>();
public void install() {
Toolkit.getDefaultToolkit().addAWTEventListener(this, AWTEvent.KEY_EVENT_MASK);
}
public void remove() {
Toolkit.getDefaultToolkit().removeAWTEventListener(this);
}
@Override
public void eventDispatched(AWTEvent event) {
assert event instanceof KeyEvent : "Shall only listen to KeyEvents, so no other events shall come here";
assert assertEDT(); // REMEMBER THAT THIS IS SINGLE THREADED, so no need for synch.
// ?: Is this one of our synthetic RELEASED events?
if (event instanceof Reposted) {
// -> Yes, so we shalln't process it again.
return;
}
// ?: KEY_TYPED event? (We're only interested in KEY_PRESSED and KEY_RELEASED).
if (event.getID() == KeyEvent.KEY_TYPED) {
// -> Yes, TYPED, don't process.
return;
}
final KeyEvent keyEvent = (KeyEvent) event;
// ?: Is this already consumed?
// (Note how events are passed on to all AWTEventListeners even though a previous one consumed it)
if (keyEvent.isConsumed()) {
return;
}
// ?: Is this RELEASED? (the problem we're trying to fix!)
if (keyEvent.getID() == KeyEvent.KEY_RELEASED) {
// -> Yes, so stick in wait
/**
* Really just wait until "immediately", as the point is that the subsequent PRESSED shall already have been
* posted on the event queue, and shall thus be the direct next event no matter which events are posted
* afterwards. The code with the ReleasedAction handles if the Timer thread actually fires the action due to
* lags, by cancelling the action itself upon the PRESSED.
*/
final Timer timer = new Timer(2, null);
ReleasedAction action = new ReleasedAction(keyEvent, timer);
timer.addActionListener(action);
timer.start();
_map.put(Integer.valueOf(keyEvent.getKeyCode()), action);
// Consume the original
keyEvent.consume();
}
else if (keyEvent.getID() == KeyEvent.KEY_PRESSED) {
// Remember that this is single threaded (EDT), so we can't have races.
ReleasedAction action = _map.remove(Integer.valueOf(keyEvent.getKeyCode()));
// ?: Do we have a corresponding RELEASED waiting?
if (action != null) {
// -> Yes, so dump it
action.cancel();
}
// System.out.println("PRESSED: [" + keyEvent + "]");
}
else {
throw new AssertionError("All IDs should be covered.");
}
}
/**
* The ActionListener that posts the RELEASED {@link RepostedKeyEvent} if the {@link Timer} times out (and hence the
* repeat-action was over).
*/
private class ReleasedAction implements ActionListener {
private final KeyEvent _originalKeyEvent;
private Timer _timer;
ReleasedAction(KeyEvent originalReleased, Timer timer) {
_timer = timer;
_originalKeyEvent = originalReleased;
}
void cancel() {
assert assertEDT();
_timer.stop();
_timer = null;
_map.remove(Integer.valueOf(_originalKeyEvent.getKeyCode()));
}
@Override
public void actionPerformed(ActionEvent e) {
assert assertEDT();
// ?: Are we already cancelled?
// (Judging by Timer and TimerQueue code, we can theoretically be raced to be posted onto EDT by TimerQueue,
// due to some lag, unfair scheduling)
if (_timer == null) {
// -> Yes, so don't post the new RELEASED event.
return;
}
// Stop Timer and clean.
cancel();
// Creating new KeyEvent (we've consumed the original).
KeyEvent newEvent = new RepostedKeyEvent((Component) _originalKeyEvent.getSource(),
_originalKeyEvent.getID(), _originalKeyEvent.getWhen(), _originalKeyEvent.getModifiers(),
_originalKeyEvent.getKeyCode(), _originalKeyEvent.getKeyChar(), _originalKeyEvent.getKeyLocation());
// Posting to EventQueue.
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(newEvent);
// System.out.println("Posted synthetic RELEASED [" + newEvent + "].");
}
}
/**
* Marker interface that denotes that the {@link KeyEvent} in question is reposted from some
* {@link AWTEventListener}, including this. It denotes that the event shall not be "hack processed" by this class
* again. (The problem is that it is not possible to state "inject this event from this point in the pipeline" - one
* have to inject it to the event queue directly, thus it will come through this {@link AWTEventListener} too.
*/
public interface Reposted {
// marker
}
/**
* Dead simple extension of {@link KeyEvent} that implements {@link Reposted}.
*/
@SuppressWarnings("serial")
public static class RepostedKeyEvent extends KeyEvent implements Reposted {
public RepostedKeyEvent(Component source, int id,
long when, int modifiers, int keyCode, char keyChar, int keyLocation) {
super(source, id, when, modifiers, keyCode, keyChar, keyLocation);
}
}
private static boolean assertEDT() {
if (!EventQueue.isDispatchThread()) {
throw new AssertionError("Not EDT, but [" + Thread.currentThread() + "].");
}
return true;
}
}
|
package org.glob3.mobile.specific;
import org.glob3.mobile.generated.IIntBuffer;
import com.google.gwt.core.client.JavaScriptObject;
public class IntBuffer_WebGL
extends
IIntBuffer {
private final JavaScriptObject _buffer;
private int _timestamp = 0;
public IntBuffer_WebGL(final JavaScriptObject data) {
_buffer = jsCreateBuffer(data);
}
public IntBuffer_WebGL(final int size) {
_buffer = jsCreateBuffer(size);
}
IntBuffer_WebGL(final byte[] data) {
// TODO needed??
throw new RuntimeException("ByteBuffer_WebGL(final byte[] data) IS NOT IMPLEMENTED");
}
@Override
public int size() {
return jsSize();
}
@Override
public int timestamp() {
return _timestamp;
}
@Override
public int get(final int i) {
return jsGet(i);
}
@Override
public void put(final int i,
final int value) {
jsPut(i, value);
}
public JavaScriptObject getBuffer() {
return _buffer;
}
private void incTimestamp() {
_timestamp++;
}
//TODO _CHANGED_TO_UINT16;
private native JavaScriptObject jsCreateBuffer(final JavaScriptObject data) /*-{
return new Uint16Array(data);
}-*/;
private native JavaScriptObject jsCreateBuffer(final int size) /*-{
return new Uint16Array(size);
}-*/;
private native int jsSize() /*-{
return this.@org.glob3.mobile.specific.IntBuffer_WebGL::_buffer.length;
}-*/;
private native byte jsGet(int i) /*-{
this.@org.glob3.mobile.specific.IntBuffer_WebGL::_buffer[i];
}-*/;
private native void jsPut(int i,
int value) /*-{
if (value < 0 || value > 65535) {
alert("EXCEDING SHORT RANGE IN UINT16 JAVASCRIPT BUFFER");
}
var thisInstance = this;
if (thisInstance.@org.glob3.mobile.specific.IntBuffer_WebGL::_buffer[i] != value) {
thisInstance.@org.glob3.mobile.specific.IntBuffer_WebGL::_buffer[i] = value;
thisInstance.@org.glob3.mobile.specific.IntBuffer_WebGL::incTimestamp()();
}
}-*/;
}
|
package io.flutter.view;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.ui.JBColor;
import com.intellij.ui.JBSplitter;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.JBPanel;
import com.intellij.ui.components.panels.VerticalLayout;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import io.flutter.inspector.FrameRenderingDisplay;
import io.flutter.inspector.HeapDisplay;
import io.flutter.perf.FlutterWidgetPerfManager;
import io.flutter.perf.PerfMetric;
import io.flutter.perf.PerfReportKind;
import io.flutter.run.FlutterLaunchMode;
import io.flutter.run.daemon.FlutterApp;
import io.flutter.server.vmService.FlutterFramesMonitor;
import io.flutter.server.vmService.ServiceExtensions;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class InspectorPerfTab extends JBPanel implements InspectorTabPanel {
/**
* Tracking widget repaints may confuse users so we disable it by default currently.
*/
private static final boolean ENABLE_TRACK_REPAINTS = false;
private static final boolean SHOW_MEMORY_PANEL = false;
private static final NumberFormat fpsFormat = new DecimalFormat();
static {
fpsFormat.setMinimumFractionDigits(1);
fpsFormat.setMaximumFractionDigits(1);
}
private final Disposable parentDisposable;
private final @NotNull FlutterApp app;
private final BoolServiceExtensionCheckbox showPerfOverlay;
private final BoolServiceExtensionCheckbox showRepaintRainbow;
private final ToolWindow toolWindow;
private JPanel rebuildStatsPanel;
private WidgetPerfSummaryView perfSummaryView;
private JCheckBox trackRebuildsCheckbox;
private JCheckBox trackRepaintsCheckbox;
private JBSplitter treeSplitter;
private boolean lastUseSplitter = false;
private float lastSplitterProportion = 0.5f;
private JPanel perfSummaryContainer;
private JPanel perfSummaryPlaceholder;
private JComponent currentSummaryView;
InspectorPerfTab(Disposable parentDisposable, @NotNull FlutterApp app, ToolWindow toolWindow) {
this.app = app;
this.toolWindow = toolWindow;
this.parentDisposable = parentDisposable;
final FlutterWidgetPerfManager widgetPerfManager = FlutterWidgetPerfManager.getInstance(app.getProject());
showPerfOverlay = new BoolServiceExtensionCheckbox(app, ServiceExtensions.performanceOverlay, "");
showRepaintRainbow = new BoolServiceExtensionCheckbox(app, ServiceExtensions.repaintRainbow, "");
buildUI();
trackRebuildsCheckbox.setSelected(widgetPerfManager.isTrackRebuildWidgets());
if (ENABLE_TRACK_REPAINTS) {
trackRepaintsCheckbox.setSelected(widgetPerfManager.isTrackRepaintWidgets());
}
app.hasServiceExtension(ServiceExtensions.trackRebuildWidgets.getExtension(), trackRebuildsCheckbox::setEnabled, parentDisposable);
if (ENABLE_TRACK_REPAINTS) {
app.hasServiceExtension(ServiceExtensions.trackRepaintWidgets.getExtension(), trackRepaintsCheckbox::setEnabled, parentDisposable);
}
trackRebuildsCheckbox.addChangeListener((l) -> {
setTrackRebuildWidgets(trackRebuildsCheckbox.isSelected());
updateShowPerfSummaryView();
});
if (ENABLE_TRACK_REPAINTS) {
trackRepaintsCheckbox.addChangeListener((l) -> {
setTrackRepaintWidgets(trackRepaintsCheckbox.isSelected());
updateShowPerfSummaryView();
});
}
}
void updateShowPerfSummaryView() {
final boolean show = getShowPerfTable();
final boolean firstRender = currentSummaryView == null;
final JComponent summaryView = show ? perfSummaryView : perfSummaryPlaceholder;
if (summaryView != currentSummaryView) {
if (currentSummaryView != null) {
perfSummaryContainer.remove(currentSummaryView);
}
currentSummaryView = summaryView;
perfSummaryContainer.add(summaryView, BorderLayout.CENTER);
perfSummaryContainer.revalidate();
perfSummaryContainer.repaint();
}
}
boolean getShowPerfTable() {
final FlutterWidgetPerfManager widgetPerfManager = FlutterWidgetPerfManager.getInstance(app.getProject());
return widgetPerfManager.isTrackRebuildWidgets() || widgetPerfManager.isTrackRepaintWidgets();
}
private void buildUI() {
setLayout(new BorderLayout(0, 8));
setBorder(JBUI.Borders.empty(3));
// We have to set the minimum size to make "Split Mode" work well.
// Otherwise, this tab will require the majority of the IntelliJ window
// width largely due to the long warning message about running in debug
// mode.
setMinimumSize(new Dimension(0, 0));
// Header
final JPanel footer = new JPanel(new VerticalLayout(0));
footer.add(new JSeparator());
final JPanel labels = new JPanel(new BorderLayout(6, 0));
labels.setBorder(JBUI.Borders.empty(0, 8));
final JLabel runModeLabel = new JBLabel("Run mode: " + app.getLaunchMode());
runModeLabel.setVerticalAlignment(SwingConstants.TOP);
labels.add(
runModeLabel,
BorderLayout.WEST
);
footer.add(labels);
if (app.getLaunchMode() == FlutterLaunchMode.DEBUG) {
final JBLabel label =
new JBLabel("<html><body>(note: debug mode frame rendering times are not indicative of release mode performance)</body></html>");
label.setForeground(JBColor.RED);
labels.add(label, BorderLayout.CENTER);
}
treeSplitter = new JBSplitter(false, "io.flutter.view.InspectorPerfTab", lastSplitterProportion);
add(treeSplitter, BorderLayout.CENTER);
// FPS
assert app.getVMServiceManager() != null;
final FlutterFramesMonitor flutterFramesMonitor = app.getVMServiceManager().getFlutterFramesMonitor();
final JBLabel fpsLabel = new JBLabel(" ", SwingConstants.CENTER);
fpsLabel.setForeground(UIUtil.getLabelDisabledForeground());
final FlutterFramesMonitor.Listener listener = event -> {
fpsLabel.setText(fpsFormat.format(flutterFramesMonitor.getFPS()) + " frames per second");
SwingUtilities.invokeLater(fpsLabel::repaint);
};
flutterFramesMonitor.addListener(listener);
Disposer.register(parentDisposable, () -> flutterFramesMonitor.removeListener(listener));
fpsLabel.setBorder(JBUI.Borders.empty(0, 5));
// Frame Rendering
final JPanel frameRenderingPanel = new JPanel(new BorderLayout());
final JPanel frameRenderingDisplay = FrameRenderingDisplay.createJPanelView(parentDisposable, app);
frameRenderingPanel.add(fpsLabel, BorderLayout.NORTH);
frameRenderingPanel.add(frameRenderingDisplay, BorderLayout.CENTER);
frameRenderingPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Frame rendering time"));
// Memory
JPanel memoryPanel = null;
if (SHOW_MEMORY_PANEL) {
memoryPanel = new JPanel(new BorderLayout());
final JPanel heapDisplay = HeapDisplay.createJPanelView(parentDisposable, app);
memoryPanel.add(heapDisplay, BorderLayout.CENTER);
memoryPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Memory usage"));
}
// Performance settings
final JPanel perfSettings = new JPanel(new VerticalLayout(5));
perfSettings.add(showPerfOverlay.getComponent());
perfSettings.add(showRepaintRainbow.getComponent());
perfSettings.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Framework settings"));
final JBPanel generalPerfPanel = new JBPanel(new VerticalLayout(5));
generalPerfPanel.add(perfSettings);
generalPerfPanel.add(frameRenderingPanel);
final JBPanel leftColumn = new JBPanel(new BorderLayout());
leftColumn.add(ScrollPaneFactory.createScrollPane(generalPerfPanel), BorderLayout.CENTER);
leftColumn.add(footer, BorderLayout.SOUTH);
if (memoryPanel != null) {
generalPerfPanel.add(memoryPanel);
}
Disposer.register(parentDisposable, treeSplitter::dispose);
treeSplitter.setFirstComponent(leftColumn);
rebuildStatsPanel = new JPanel(new BorderLayout(0, 5));
// rebuild stats
perfSummaryContainer = new JPanel(new BorderLayout());
currentSummaryView = null;
perfSummaryPlaceholder = new JPanel(new BorderLayout());
perfSummaryPlaceholder.add(
ScrollPaneFactory.createScrollPane(
new JBLabel(
"<html><body style='padding-left:25px; padding-right:25px;'>" +
"<p>" +
"Widget rebuild information tells you what widgets have been " +
"recently rebuilt on your current screen and in the source file you're " +
"viewing." +
"</p>" +
"<br>" +
"<p>" +
"It also provides you with relevant performance advices based on the " +
"behavior of your UI." +
"</p>" +
"</body></html>"
),
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
)
);
perfSummaryContainer.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Rebuild stats"));
final JPanel perfViewSettings = new JPanel(new VerticalLayout(5));
trackRebuildsCheckbox = new JCheckBox("Show widget rebuild information");
trackRebuildsCheckbox.setHorizontalAlignment(JLabel.LEFT);
trackRebuildsCheckbox.setToolTipText(
"<html><body><p><b>This profiler identifies widgets that are rebuilt when the UI changes.</b></p>" +
"<br>" +
"<p>Look for the indicators on the left margin of the code editor<br>and a list of the top rebuilt widgets in this window.</p>" +
"</body></html>");
perfViewSettings.add(trackRebuildsCheckbox);
if (ENABLE_TRACK_REPAINTS) {
trackRepaintsCheckbox = new JCheckBox("Show widget repaint information");
perfViewSettings.add(trackRepaintsCheckbox);
}
perfViewSettings.add(new JSeparator());
perfSummaryView = new WidgetPerfSummaryView(parentDisposable, app, PerfMetric.lastFrame, PerfReportKind.rebuild);
perfSummaryContainer.add(perfViewSettings, BorderLayout.NORTH);
updateShowPerfSummaryView();
rebuildStatsPanel.add(perfSummaryContainer, BorderLayout.CENTER);
// perf tips
final JPanel perfTipsPanel = perfSummaryView.getWidgetPerfTipsPanel();
rebuildStatsPanel.add(perfTipsPanel, BorderLayout.SOUTH);
perfTipsPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Performance tips"));
perfTipsPanel.setVisible(false);
treeSplitter.setHonorComponentsMinimumSize(false);
treeSplitter.setSecondComponent(rebuildStatsPanel);
toolWindow.getComponent().addComponentListener(new ComponentListener() {
@Override
public void componentResized(ComponentEvent e) {
layoutUiOnResize();
}
@Override
public void componentMoved(ComponentEvent e) {
}
@Override
public void componentShown(ComponentEvent e) {
layoutUiOnResize();
}
@Override
public void componentHidden(ComponentEvent e) {
}
});
layoutUiOnResize();
}
private void layoutUiOnResize() {
final int windowWidth = toolWindow.getComponent().getWidth();
final int windowHeight = toolWindow.getComponent().getHeight();
final double aspectRatio = (double)windowWidth / (double)windowHeight;
final boolean vertical = aspectRatio < 1.4 && windowWidth < 500;
if (vertical != treeSplitter.getOrientation()) {
treeSplitter.setOrientation(vertical);
}
}
private void setTrackRebuildWidgets(boolean selected) {
final FlutterWidgetPerfManager widgetPerfManager = FlutterWidgetPerfManager.getInstance(app.getProject());
widgetPerfManager.setTrackRebuildWidgets(selected);
// Update default so next app launched will match the existing setting.
FlutterWidgetPerfManager.trackRebuildWidgetsDefault = selected;
}
private void setTrackRepaintWidgets(boolean selected) {
final FlutterWidgetPerfManager widgetPerfManager = FlutterWidgetPerfManager.getInstance(app.getProject());
widgetPerfManager.setTrackRepaintWidgets(selected);
// Update default so next app launched will match the existing setting.
FlutterWidgetPerfManager.trackRepaintWidgetsDefault = selected;
}
@Override
public void setVisibleToUser(boolean visible) {
assert app.getVMServiceManager() != null;
perfSummaryView.setVisibleToUser(visible);
if (visible) {
app.getVMServiceManager().addPollingClient();
}
else {
app.getVMServiceManager().removePollingClient();
}
}
}
|
package jade.content.schema;
import jade.content.onto.*;
import jade.content.abs.*;
import java.util.Hashtable;
import java.util.Vector;
import java.util.Enumeration;
/**
* @author Federico Bergenti - Universita` di Parma
*/
public abstract class ObjectSchema {
private class AttributeDescriptor {
private String name = null;
private ObjectSchema schema = null;
private int cardinality = 0;
/**
* Constructor declaration
*
* @param name
* @param schema
* @param cardinality
*
*/
private AttributeDescriptor(String name, ObjectSchema schema,
int cardinality) {
this.name = name;
this.schema = schema;
this.cardinality = cardinality;
}
}
public static final int MANDATORY = 0;
public static final int OPTIONAL = 1;
private Hashtable attributeDescriptors = new Hashtable();
private Vector baseSchemas = new Vector();
private String typeName = null;
/**
* Constructor
*
* @param typeName
*
*/
protected ObjectSchema(String typeName) {
this.typeName = typeName;
}
/**
* Add an attribute to the schema.
*
* @param name name of the attribute.
* @param elementSchema schema of the attribute.
* @param cardinality cardinality, i.e., optional or mandatory
*
*/
protected void addAttribute(String name, ObjectSchema elementSchema,
int cardinality) {
attributeDescriptors.put(name.toUpperCase(),
new AttributeDescriptor(name, elementSchema,
cardinality));
}
/**
* Add an attribute to the schema.
*
* @param name name of the attribute.
* @param elementSchema schema of the attribute.
*
*/
protected void addAttribute(String name, ObjectSchema elementSchema) {
addAttribute(name, elementSchema, MANDATORY);
}
/**
* Adds a base schema.
*
* @param base the base schema.
*
*/
protected void addBaseSchema(ObjectSchema base) {
baseSchemas.addElement(base);
}
private void getAttributeDescriptorNames(Vector v) {
for (Enumeration e = baseSchemas.elements(); e.hasMoreElements(); ) {
ObjectSchema base = (ObjectSchema) e.nextElement();
base.getAttributeDescriptorNames(v);
}
for (Enumeration e = attributeDescriptors.keys();
e.hasMoreElements(); ) {
v.addElement(e.nextElement());
}
}
/**
* Returns the names of all attributes.
*
* @return the names of all attributes.
*
*/
public String[] getAttributeNames() {
Vector allAttributeDescriptors = new Vector();
getAttributeDescriptorNames(allAttributeDescriptors);
String[] ret = new String[allAttributeDescriptors.size()];
int counter = 0;
for (Enumeration e = allAttributeDescriptors.elements();
e.hasMoreElements(); ) {
ret[counter++] = (String) e.nextElement();
}
return ret;
}
/**
* Is the attribute <code>name</code> mandatory?
*
* @param name name of the attribute.
*
* @return <code>true</code> if the attribute is mandatory.
*
* @throws OntologyException
*
*/
public boolean isMandatory(String name) throws OntologyException {
name = name.toUpperCase();
AttributeDescriptor ad =
(AttributeDescriptor) attributeDescriptors.get(name);
if (ad == null) {
for (Enumeration e = baseSchemas.elements();
e.hasMoreElements(); ) {
try {
ObjectSchema base = (ObjectSchema) e.nextElement();
return base.isMandatory(name);
}
catch (OntologyException oe) {}
}
throw new OntologyException("No element named: " + name);
}
return (ad.cardinality == MANDATORY);
}
/**
* Is <code>name</code> an attribute?
*
* @param name name to test.
*
* @return <code>true</code> if <code>name</code> is an attribute.
*
* @throws OntologyException
*
*/
public boolean isAttribute(String name) throws OntologyException {
name = name.toUpperCase();
AttributeDescriptor ad =
(AttributeDescriptor) attributeDescriptors.get(name);
if (ad != null) {
return true;
}
for (Enumeration e = baseSchemas.elements(); e.hasMoreElements(); ) {
ObjectSchema base = (ObjectSchema) e.nextElement();
if (base.isAttribute(name)) {
return true;
}
}
return false;
}
/**
* Retrieves an attribute's schema.
*
* @param name name of the attribute.
*
* @return the schema of attribute <code>name</code>
*
* @throws OntologyException
*
*/
public ObjectSchema getAttributeSchema(String name)
throws OntologyException {
name = name.toUpperCase();
AttributeDescriptor ad =
(AttributeDescriptor) attributeDescriptors.get(name);
if (ad == null) {
for (Enumeration e = baseSchemas.elements();
e.hasMoreElements(); ) {
try {
ObjectSchema base = (ObjectSchema) e.nextElement();
return base.getAttributeSchema(name);
}
catch (OntologyException oe) {}
}
throw new OntologyException("No element named: " + name);
}
return ad.schema;
}
/**
* Retrieves the name of the type of this schema.
*
* @return the name of the type.
*
*/
public String getTypeName() {
return typeName;
}
/**
* Creates a new instance.
*
* @return the new instance.
*
*/
public abstract AbsObject newInstance();
}
|
package ViewManager;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import client.client.Client;
public class CommitLogReader {
BufferedReader br;
static TaskDistributor td;
static RandomAccessFile raf;
static ViewManagerController vmc;
static String fileName = "logs//output.log";
static long readPtr;
public CommitLogReader() {
try {
raf = new RandomAccessFile(fileName, "rw");
br = new BufferedReader(new FileReader("logs//output.log"));
readPtr = -1;
td = new TaskDistributor();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/*public void read() {
Client.connectToCluster("192.168.56.101");
String raw;
try {
raw = br.readLine();
while (raw != null) {
String[] splitRaw = raw.split(" - ");
String jsonString = splitRaw[1];
JSONObject json = (JSONObject) new JSONParser()
.parse(jsonString);
String type = json.get("type").toString();
String table = json.get("table").toString();
if (table.contains("groupby")) {
if (type.equalsIgnoreCase("insert")||type.equalsIgnoreCase("update")){
vmc.decideGroupBy(json,table);
}
}else if (table.contains("preagg_agg")) {
if (type.equalsIgnoreCase("insert")||type.equalsIgnoreCase("update")){
vmc.decidePreagg(json,table);
}
} else {
if (table.contains("RJ_")) {
if (type.equalsIgnoreCase("insert")){
JSONObject data = (JSONObject) json.get("data");
String bufferString = data.get("stream").toString();
Stream s = Serialize.deserializeStream(bufferString);
if(s.isDeleteOperation())
vmc.propagateDeleteRJ(json);
else
vmc.propagateRJ(json);
}
} else {
if (type.equals("insert")) {
vmc.update(json);
}
if (type.equals("update")) {
vmc.update(json);
}
if (type.equals("delete-row")) {
vmc.cascadeDelete(json, true);
}
}
}
raw = br.readLine();
}
Client.getClusterInstance().close();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}*/
public static void main(String[] args) {
CommitLogReader cmr = new CommitLogReader();
// monitor a single file
TimerTask task = new FileWatcher(new File(fileName)) {
protected void onChange(File file) {
readCL();
}
};
Timer timer = new Timer();
timer.schedule(task,new Date(),1000);
}
private static void readCL() {
System.out.println("on change");
String raw;
int counter = 0;
try {
if(readPtr==-1){
raw = raf.readLine();
readPtr = raf.getFilePointer();
counter++;
}else{
raf.seek(readPtr);
raw = raf.readLine();
readPtr = raf.getFilePointer();
counter++;
}
while (raw != null) {
String[] splitRaw = raw.split(" - ");
String jsonString = splitRaw[1];
JSONObject json = (JSONObject) new JSONParser().parse(jsonString);
String type = json.get("type").toString();
String table = json.get("table").toString();
System.out.println(table);
td.processRequest(json,type,table);
System.out.println("back");
if(counter<10){
raw = raf.readLine();
readPtr = raf.getFilePointer();
}else{
raw = null;
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
public void closeCLREader(){
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
Client.getClusterInstance().close();
}
}
|
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
package opennlp.common.xml;
import org.jdom.*;
import java.util.*;
public class XmlUtils {
/**
* Returns all of the children with the given tag name. This method stops
* recursing under elements that match the <code>name</code> argument.
*/
public static List getChildrenNested (Element e, String name) {
List elements = new ArrayList();
List children = e.getChildren();
for (Iterator i=children.iterator(); i.hasNext(); ) {
Element c = (Element)i.next();
if (c.getName().equals("name")) {
elements.add(c);
}
else {
elements.addAll(getChildrenNested(c, name));
}
}
return elements;
}
/**
* Returns the text content of all children with the given tag name.
*/
public static String getChildTextNested (Element e, String name) {
StringBuffer sb = new StringBuffer();
List children = e.getChildren();
if (e.getName().equals(name)) {
sb.append(e.getText());
if (children.size() > 0)
sb.append(' ');
}
for (Iterator i=children.iterator(); i.hasNext(); )
sb.append(getChildTextNested((Element)i.next(), name)).append(' ');
return sb.toString();
}
/**
* Returns the text content of all children with the given tag name.
*/
public static String getAllTextNested (Element e) {
StringBuffer sb = new StringBuffer();
sb.append(e.getText());
List children = e.getChildren();
if (children.size() > 0)
sb.append(' ');
for (Iterator i=children.iterator(); i.hasNext(); )
sb.append(getAllTextNested((Element)i.next())).append(' ');
return sb.toString();
}
/**
* Make a regular string into suitable PCDATA.
*
* @param s The string which may contain special XML characters.
*/
public static String filt2XML(String s) {
StringBuffer input = new StringBuffer(s);
StringBuffer output = new StringBuffer(input.length());
for(int i=0; i<input.length(); i++) {
char c = input.charAt(i);
switch(c) {
case '<': output.append("<"); break;
case '>': output.append(">"); break;
case '&': output.append("&"); break;
case '\'': output.append("'"); break;
case '"': output.append("""); break;
default: output.append(c);
}
}
return output.toString();
}
}
|
package org.jdesktop.swingx;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.print.PrinterException;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.regex.Pattern;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.DefaultCellEditor;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JViewport;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.TableModelEvent;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import org.jdesktop.swingx.action.BoundAction;
import org.jdesktop.swingx.decorator.ComponentAdapter;
import org.jdesktop.swingx.decorator.FilterPipeline;
import org.jdesktop.swingx.decorator.HighlighterPipeline;
import org.jdesktop.swingx.decorator.PipelineEvent;
import org.jdesktop.swingx.decorator.PipelineListener;
import org.jdesktop.swingx.decorator.Sorter;
import org.jdesktop.swingx.icon.ColumnControlIcon;
import org.jdesktop.swingx.plaf.JXTableAddon;
import org.jdesktop.swingx.plaf.LookAndFeelAddons;
import org.jdesktop.swingx.table.ColumnControlButton;
import org.jdesktop.swingx.table.ColumnFactory;
import org.jdesktop.swingx.table.DefaultTableColumnModelExt;
import org.jdesktop.swingx.table.TableColumnExt;
import org.jdesktop.swingx.table.TableColumnModelExt;
/**
* <p>A JXTable is a JTable with built-in support for row sorting, filtering, and highlighting, column visibility
* and a special popup control on the column header for quick access to table configuration.
* You can instantiate a JXTable just as you would a JTable, using a TableModel. However, a JXTable automatically
* wraps TableColumns inside a TableColumnExt instance. TableColumnExt supports visibility, sortability, and
* prototype values for column sizing, none of which are available in TableColumn. You can retrieve the TableColumnExt
* instance for a column using {@link #getColumnExt(Object)} or {@link #getColumnExt(int colnumber)}.
*
* <p>A JXTable is, by default, sortable by clicking on column headers; each subsequent click on a header reverses
* the order of the sort, and a sort arrow icon is automatically drawn on the header. Sorting can be disabled using
* {@link #setSortable(boolean)}. Sorting on columns is handled by a Sorter instance which contains a Comparator
* used to compare values in two rows of a column. You can replace the Comparator for a given column by using
* <code>getColumnExt("column").getSorter().setComparator(customComparator)</code>
*
* <p>Columns can be hidden or shown by setting the visible property on the TableColumnExt using
* {@link TableColumnExt#setVisible(boolean)}. Columns can also be shown or hidden from the column control popup.
*
* <p>The column control popup is triggered by an icon drawn to the far right of the column headers, above the
* table's scrollbar (when installed in a JScrollPane). The popup allows the user to select which columns should
* be shown or hidden, as well as to pack columns and turn on horizontal scrolling. To show or hide the column control,
* use the {@link #setColumnControlVisible(boolean show)} method.
*
* <p>Rows can be filtered from a JXTable using a Filter class and a FilterPipeline. One assigns a FilterPipeline to
* the table using {@link #setFilters(FilterPipeline)}. Filtering hides, but does not delete or permanently remove rows
* from a JXTable. Filters are used to provide sorting to the table--rows are not removed, but the table is made
* to believe rows in the model are in a sorted order.
*
* <p>One can automatically highlight certain rows in a JXTable by attaching Highlighters in the
* {@link #setHighlighters(HighlighterPipeline)} method. An example would be a Highlighter that colors alternate
* rows in the table for readability; AlternateRowHighlighter does this. Again, like Filters, Highlighters can
* be chained together in a HighlighterPipeline to achieve more interesting effects.
*
* <p>You can resize all columns, selected columns, or a single column using the methods like {@link #packAll()}.
* Packing combines several other aspects of a JXTable. If horizontal scrolling is enabled using
* {@link #setHorizontalScrollEnabled(boolean)}, then the scrollpane will allow the table to scroll right-left, and
* columns will be sized to their preferred size. To control the preferred sizing of a column, you can provide
* a prototype value for the column in the TableColumnExt using {@link TableColumnExt#setPrototypeValue(Object)}.
* The prototype is used as an indicator of the preferred size of the column. This can be useful if some data in
* a given column is very long, but where the resize algorithm would normally not pick this up.
*
* <p>Last, you can also provide searches on a JXTable using the search methods.
*
* @author Ramesh Gupta
* @author Amy Fowler
* @author Mark Davidson
* @author Jeanette Winzenburg
*/
public class JXTable extends JTable implements Searchable {
/** Constant string for horizontal scroll actions, used in JXTable's Action Map. */
public static final String HORIZONTALSCROLL_ACTION_COMMAND = ColumnControlButton.COLUMN_CONTROL_MARKER + "horizontalScroll";
/** Constant string for packing all columns, used in JXTable's Action Map. */
public static final String PACKALL_ACTION_COMMAND = ColumnControlButton.COLUMN_CONTROL_MARKER + "packAll";
/** Constant string for packing selected columns, used in JXTable's Action Map. */
public static final String PACKSELECTED_ACTION_COMMAND = ColumnControlButton.COLUMN_CONTROL_MARKER + "packSelected";
/** TODO */
public static final String UIPREFIX = "JXTable.";
static {
// Hack: make sure the resource bundle is loaded
LookAndFeelAddons.contribute(new JXTableAddon());
}
public static boolean TRACE = false;
/** The sorter attached to this table for the column currently being sorted. */
protected Sorter sorter = null;
/** The FilterPipeline for the table. */
protected FilterPipeline filters = null;
/** The HighlighterPipeline for the table. */
protected HighlighterPipeline highlighters = null;
// MUST ALWAYS ACCESS dataAdapter through accessor method!!!
private final ComponentAdapter dataAdapter = new TableAdapter(this);
private boolean sortable = false;
private int visibleRowCount = 18;
/**
* flag to indicate if the column control is visible.
*/
private boolean columnControlVisible;
/**
* A button that allows the user to select which columns to display, and
* which to hide
*/
private JComponent columnControlButton;
/**
* ScrollPane's original vertical scroll policy.
* If the columnControl is visible the policy is set to
* ALWAYS.
*/
private int verticalScrollPolicy;
/**
* Mouse/Motion/Listener keeping track of mouse moved in
* cell coordinates.
*/
private RolloverProducer rolloverProducer;
/**
* RolloverController: listens to cell over events and
* repaints entered/exited rows.
*/
private LinkController linkController;
private int oldAutoResizeMode;
protected boolean isXTableRowHeightSet;
/** Instantiates a JXTable with a default table model, no data. */
public JXTable() {
init();
}
/**
* Instantiates a JXTable with a specific table model.
* @param dm The model to use.
*/
public JXTable(TableModel dm) {
super(dm);
init();
}
/**
* Instantiates a JXTable with a specific table model.
* @param dm The model to use.
*/
public JXTable(TableModel dm, TableColumnModel cm) {
super(dm, cm);
init();
}
/**
* Instantiates a JXTable with a specific table model, column model, and selection model.
* @param dm The table model to use.
* @param cm The colomn model to use.
* @param sm The list selection model to use.
*/
public JXTable(TableModel dm, TableColumnModel cm, ListSelectionModel sm) {
super(dm, cm, sm);
init();
}
/**
* Instantiates a JXTable for a given number of columns and rows.
* @param numRows Count of rows to accomodate.
* @param numColumns Count of columns to accomodate.
*/
public JXTable(int numRows, int numColumns) {
super(numRows, numColumns);
init();
}
/**
* Instantiates a JXTable with data in a vector or rows and column names.
* @param rowData Row data, as a Vector of Objects.
* @param columnNames Column names, as a Vector of Strings.
*/
public JXTable(Vector rowData, Vector columnNames) {
super(rowData, columnNames);
init();
}
/**
* Instantiates a JXTable with data in a array or rows and column names.
* @param rowData Row data, as a two-dimensional Array of Objects (by row, for column).
* @param columnNames Column names, as a Array of Strings.
*/
public JXTable(Object[][] rowData, Object[] columnNames) {
super(rowData, columnNames);
init();
}
/** Initializes the table for use. */
protected void init() {
setSortable(true);
// Register the actions that this class can handle.
ActionMap map = getActionMap();
map.put("print", new Actions("print"));
map.put("find", new Actions("find"));
map.put(PACKALL_ACTION_COMMAND, createPackAllAction());//new Actions("packAll"));
map.put(PACKSELECTED_ACTION_COMMAND, createPackSelectedAction());//new Actions("packSelected"));
map.put(HORIZONTALSCROLL_ACTION_COMMAND, createHorizontalScrollAction());
updateRowHeightUI(false);
}
/** Creates an Action for horizontal scrolling. */
private Action createHorizontalScrollAction() {
String actionName = getUIString(HORIZONTALSCROLL_ACTION_COMMAND);
BoundAction action = new BoundAction(actionName, HORIZONTALSCROLL_ACTION_COMMAND);
action.setStateAction();
action.registerCallback(this, "setHorizontalScrollEnabled");
action.setSelected(isHorizontalScrollEnabled());
return action;
}
private String getUIString(String key) {
String text = UIManager.getString(UIPREFIX + key);
return text != null ? text : key;
}
/** Creates an Action for packing selected columns. */
private Action createPackSelectedAction() {
String text = getUIString(PACKSELECTED_ACTION_COMMAND);
BoundAction action = new BoundAction(text, PACKSELECTED_ACTION_COMMAND);
action.registerCallback(this, "packSelected");
action.setEnabled(getSelectedColumnCount() > 0);
return action;
}
/** Creates an Action for packing all columns. */
private Action createPackAllAction() {
String text = getUIString(PACKALL_ACTION_COMMAND);
BoundAction action = new BoundAction(text, PACKALL_ACTION_COMMAND);
action.registerCallback(this, "packAll");
return action;
}
/**
* This resizes all columns to fit the viewport; if horizontal scrolling
* is enabled, all columns will get their preferred width. This can be
* triggered by the "packAll" BoundAction on the table as well.
*/
public void packAll() {
packTable(getDefaultPackMargin());
}
/**
* This resizes selected columns to fit the viewport; if horizontal scrolling
* is enabled, selected columns will get their preferred width. This can be
* triggered by the "packSelected" BoundAction on the table as well.
*/
public void packSelected() {
int selected = getSelectedColumn();
if (selected >= 0) {
packColumn(selected, getDefaultPackMargin());
}
}
/**
* Controls horizontal scrolling in the viewport, and works in coordination
* with column sizing.
*
* @param enabled If true, the scrollpane will allow the table to scroll
* horizontally, and columns will resize to their preferred width. If false,
* columns will resize to fit the viewport.
*/
public void setHorizontalScrollEnabled(boolean enabled) {
if (enabled == (isHorizontalScrollEnabled())) return;
if (enabled) {
oldAutoResizeMode = getAutoResizeMode();
setAutoResizeMode(AUTO_RESIZE_OFF);
} else {
setAutoResizeMode(oldAutoResizeMode);
}
}
/** Returns the current setting for horizontal scrolling. */
private boolean isHorizontalScrollEnabled() {
return getAutoResizeMode() == AUTO_RESIZE_OFF;
}
/** Returns the default margin for packing columns. */
private int getDefaultPackMargin() {
return 4;
}
/** Notifies the table that a new column has been selected. */
public void columnSelectionChanged(ListSelectionEvent e) {
super.columnSelectionChanged(e);
if (e.getValueIsAdjusting()) return;
Action packSelected = getActionMap().get(PACKSELECTED_ACTION_COMMAND);
if ((packSelected != null)) {// && (e.getSource() instanceof ListSelectionModel)){
packSelected.setEnabled(!((ListSelectionModel) e.getSource()).isSelectionEmpty());
}
}
public void setAutoResizeMode(int mode) {
super.setAutoResizeMode(mode);
Action packSelected = getActionMap().get(HORIZONTALSCROLL_ACTION_COMMAND);
if (packSelected instanceof BoundAction) {
((BoundAction) packSelected).setSelected(isHorizontalScrollEnabled());
}
}
/**
* Property to enable/disable rollover support. This can be enabled
* to show "live" rollover behaviour, f.i. the cursor over LinkModel cells.
* Default is disabled. If using a RolloverHighlighter on the table,
* this should be set to true.
*
* @param rolloverEnabled
*/
public void setRolloverEnabled(boolean rolloverEnabled) {
boolean old = isRolloverEnabled();
if (rolloverEnabled == old) return;
if (rolloverEnabled) {
rolloverProducer = new RolloverProducer();
addMouseListener(rolloverProducer);
addMouseMotionListener(rolloverProducer);
linkController = new LinkController();
addPropertyChangeListener(linkController);
} else {
removeMouseListener(rolloverProducer);
removeMouseMotionListener(rolloverProducer);
rolloverProducer = null;
removePropertyChangeListener(linkController);
linkController = null;
}
firePropertyChange("rolloverEnabled", old, isRolloverEnabled());
}
/**
* Returns the rolloverEnabled property.
* @return <code>true</code> if rollover is enabled
*/
public boolean isRolloverEnabled() {
return rolloverProducer != null;
}
/**
* If the default editor for LinkModel.class is of type
* LinkRenderer enables link visiting with the given linkVisitor.
* As a side-effect the rollover property is set to true.
*
* @param linkVisitor
*/
public void setDefaultLinkVisitor(ActionListener linkVisitor) {
TableCellEditor renderer = getDefaultEditor(LinkModel.class);
if (renderer instanceof LinkRenderer) {
((LinkRenderer) renderer).setVisitingDelegate(linkVisitor);
}
setRolloverEnabled(true);
}
/**
* overridden to addionally configure the upper right corner
* of an enclosing scrollpane with the ColumnControl.
*/
protected void configureEnclosingScrollPane() {
super.configureEnclosingScrollPane();
configureColumnControl();
configureViewportBackground();
}
/**
* set's the viewports background to this.background.
* PENDING: need to repeat on background changes to this!
*
*/
protected void configureViewportBackground() {
Container p = getParent();
if (p instanceof JViewport) {
p.setBackground(getBackground());
}
}
/**
* configure the upper right corner of an enclosing scrollpane
* with/o the ColumnControl, depending on setting of
* columnControl visibility flag.
*
* PENDING: should choose corner depending on
* component orientation.
*/
private void configureColumnControl() {
Container p = getParent();
if (p instanceof JViewport) {
Container gp = p.getParent();
if (gp instanceof JScrollPane) {
JScrollPane scrollPane = (JScrollPane)gp;
// Make certain we are the viewPort's view and not, for
// example, the rowHeaderView of the scrollPane -
// an implementor of fixed columns might do this.
JViewport viewport = scrollPane.getViewport();
if (viewport == null || viewport.getView() != this) {
return;
}
if (isColumnControlVisible()) {
verticalScrollPolicy = scrollPane.getVerticalScrollBarPolicy();
scrollPane.setCorner(JScrollPane.UPPER_RIGHT_CORNER, getColumnControl());
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
} else {
scrollPane.setVerticalScrollBarPolicy(verticalScrollPolicy == 0 ?
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED : verticalScrollPolicy);
try {
scrollPane.setCorner(JScrollPane.UPPER_RIGHT_CORNER, null);
}
catch (Exception ex) {
// Ignore spurious exception thrown by JScrollPane. This is a Swing bug!
}
}
}
}
}
/**
* returns visibility flag of column control. <p>
*
* Note: if the table is not inside a JScrollPane
* the column control is not shown even if this returns true.
* In this case it's the responsibility of the client code
* to actually show it.
*
* @return
*/
public boolean isColumnControlVisible() {
return columnControlVisible;
}
/**
* returns the component for column control.
* @return
*/
public JComponent getColumnControl() {
if (columnControlButton == null) {
columnControlButton = new ColumnControlButton(this, new ColumnControlIcon());
}
return columnControlButton;
}
/**
* bound property to flag visibility state of column control.
* @param showColumnControl
*/
public void setColumnControlVisible(boolean showColumnControl) {
boolean old = columnControlVisible;
this.columnControlVisible = showColumnControl;
// JW: hacking issue #38(swingx) to initially add all columns
if (showColumnControl) {
getColumnControl();
}
configureColumnControl();
firePropertyChange("columnControlVisible", old, columnControlVisible);
}
/**
* Returns a new instance of the default renderer for the specified class.
* This differs from <code>getDefaultRenderer()</code> in that it returns a <b>new</b>
* instance each time so that the renderer may be set and customized on
* a particular column.
*
* @param columnClass Class of value being rendered
* @return TableCellRenderer instance which renders values of the specified type
*/
public TableCellRenderer getNewDefaultRenderer(Class columnClass) {
TableCellRenderer renderer = getDefaultRenderer(columnClass);
if (renderer != null) {
try {
return (TableCellRenderer) renderer.getClass().newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
private void setLazyValue(Hashtable h, Class c, String s) {
h.put(c, new UIDefaults.ProxyLazyValue(s));
}
private void setLazyRenderer(Class c, String s) {
setLazyValue(defaultRenderersByColumnClass, c, s);
}
private void setLazyEditor(Class c, String s) {
setLazyValue(defaultEditorsByColumnClass, c, s);
}
protected void createDefaultEditors() {
super.createDefaultEditors();
setLazyEditor(LinkModel.class, "org.jdesktop.swingx.LinkRenderer");
}
/**
* Creates default cell renderers for objects, numbers, doubles, dates,
* booleans, icons, and links.
*
*/
protected void createDefaultRenderers() {
// super.createDefaultRenderers();
// This duplicates JTable's functionality in order to make the renderers
// available in getNewDefaultRenderer(); If JTable's renderers either
// were public, or it provided a factory for *new* renderers, this would
// not be needed
defaultRenderersByColumnClass = new UIDefaults();
// Objects
setLazyRenderer(Object.class,
"javax.swing.table.DefaultTableCellRenderer");
// Numbers
setLazyRenderer(Number.class, "org.jdesktop.swingx.JXTable$NumberRenderer");
// Doubles and Floats
setLazyRenderer(Float.class, "org.jdesktop.swingx.JXTable$DoubleRenderer");
setLazyRenderer(Double.class, "org.jdesktop.swingx.JXTable$DoubleRenderer");
// Dates
setLazyRenderer(Date.class, "org.jdesktop.swingx.JXTable$DateRenderer");
// Icons and ImageIcons
setLazyRenderer(Icon.class, "org.jdesktop.swingx.JXTable$IconRenderer");
setLazyRenderer(ImageIcon.class, "org.jdesktop.swingx.JXTable$IconRenderer");
// Booleans
setLazyRenderer(Boolean.class, "org.jdesktop.swingx.JXTable$BooleanRenderer");
// Other
setLazyRenderer(LinkModel.class, "org.jdesktop.swingx.LinkRenderer");
}
/**
* bug fix: super doesn't update all renderers/editors.
*/
public void updateUI() {
super.updateUI();
// JW PENDING: update columnControl
if (columnControlButton != null) {
columnControlButton.updateUI();
}
for (Enumeration defaultEditors= defaultEditorsByColumnClass.elements(); defaultEditors.hasMoreElements();) {
updateEditorUI(defaultEditors.nextElement());
}
for (Enumeration defaultRenderers = defaultRenderersByColumnClass.elements();defaultRenderers.hasMoreElements();) {
updateRendererUI(defaultRenderers.nextElement());
}
Enumeration columns = getColumnModel().getColumns();
if (getColumnModel() instanceof TableColumnModelExt) {
columns = Collections.enumeration(((TableColumnModelExt) getColumnModel()).getAllColumns());
}
while (columns.hasMoreElements()) {
TableColumn column = (TableColumn) columns.nextElement();
updateEditorUI(column.getCellEditor());
updateRendererUI(column.getCellRenderer());
updateRendererUI(column.getHeaderRenderer());
}
updateRowHeightUI(true);
configureViewportBackground();
}
private void updateRowHeightUI(boolean respectRowSetFlag) {
if (respectRowSetFlag && isXTableRowHeightSet) return;
int minimumSize = getFont().getSize() + 6;
int uiSize = UIManager.getInt(UIPREFIX + "rowHeight");
setRowHeight(Math.max(minimumSize, uiSize != 0 ? uiSize : 18));
isXTableRowHeightSet = false;
}
/** Changes the row height for all rows in the table. */
public void setRowHeight(int rowHeight) {
super.setRowHeight(rowHeight);
if (rowHeight > 0) {
isXTableRowHeightSet = true;
}
}
/**
* this is a Hack: does not set the isXTableRowHeight flag.
* @param rowHeight
*/
// protected void setRowHeightInternally(int rowHeight) {
// super.setRowHeight(rowHeight);
private void updateEditorUI(Object value) {
// maybe null or proxyValue
if (!(value instanceof TableCellEditor)) return;
// super handled this
if ((value instanceof JComponent) || (value instanceof DefaultCellEditor)) return;
// custom editors might balk about fake rows/columns
try {
Component comp = ((TableCellEditor) value).getTableCellEditorComponent(this, null, false, -1, -1);
if (comp instanceof JComponent) {
((JComponent) comp).updateUI();
}
} catch (Exception e) {
// ignore - can't do anything
}
}
private void updateRendererUI(Object value) {
// maybe null or proxyValue
if (!(value instanceof TableCellRenderer)) return;
// super handled this
if (value instanceof JComponent) return;
// custom editors might balk about fake rows/columns
try {
Component comp = ((TableCellRenderer) value).getTableCellRendererComponent(this, null, false, false, -1, -1);
if (comp instanceof JComponent) {
((JComponent) comp).updateUI();
}
} catch (Exception e) {
// ignore - can't do anything
}
}
/**
* A small class which dispatches actions.
* TODO: Is there a way that we can make this static?
* JW: I hate those if constructs... we are in OO-land!
*/
private class Actions extends UIAction {
Actions(String name) {
super(name);
}
public void actionPerformed(ActionEvent evt) {
if ("print".equals(getName())) {
try {
print();
}
catch (PrinterException ex) {
//REMIND(aim): should invoke pluggable application error handler
ex.printStackTrace();
}
}
else if ("find".equals(getName())) {
find();
}
// else if (PACKALL_ACTION_COMMAND.equals(getName())) {
// packAll();
// } else if (PACKSELECTED_ACTION_COMMAND.equals(getName())) {
// packSelected();
}
}
/** The JXFindDialog we open on find() */
private JXFindDialog dialog = null;
private boolean automaticSortDisabled;
/** Listens for changes from the filters. */
private PipelineListener pipelineListener;
/** Listens for changes from the highlighters. */
private ChangeListener highlighterChangeListener;
/** the factory to use for column creation and configuration. */
private ColumnFactory columnFactory;
/** Opens the JXFindDialog for the table. */
private void find() {
if (dialog == null) {
dialog = new JXFindDialog(this);
}
dialog.setVisible(true);
}
/**
* Sets "sortable" property indicating whether or not this table
* supports sortable columns. If <code>sortable</code> is <code>true</code>
* then sorting will be enabled on all columns whose <code>sortable</code>
* property is <code>true</code>. If <code>sortable</code> is <code>false</code>
* then sorting will be disabled for all columns, regardless of each column's
* individual <code>sorting</code> property. The default is <code>true</code>.
* @see TableColumnExt#isSortable()
* @param sortable boolean indicating whether or not this table supports
* sortable columns
*/
public void setSortable(boolean sortable) {
if (sortable == isSortable()) return;
this.sortable = sortable;
firePropertyChange("sortable", !sortable, sortable);
//JW @todo: this is a hack!
if (sorter != null) {
updateOnFilterContentChanged();
}
}
/** Returns true if the table is sortable. */
public boolean isSortable() {
return sortable;
}
// public void setAutomaticSort(boolean automaticEnabled) {
// this.automaticSortDisabled = !automaticEnabled;
// public boolean isAutomaticSort() {
// return !automaticSortDisabled;
public void tableChanged(TableModelEvent e) {
Selection selection = new Selection(this);
if (filters != null) {
filters.flush(); // will call contentsChanged()
}
else if (sorter != null) {
sorter.refresh();
// if (isAutomaticSort()) {
// sorter.refresh();
}
super.tableChanged(e);
restoreSelection(selection);
}
protected void updateOnFilterContentChanged() {
removeSorter();
clearSelection();
// Force private rowModel in JTable to null;
boolean heightSet = isXTableRowHeightSet;
setRowHeight(getRowHeight()); // Ugly!
isXTableRowHeightSet = heightSet;
revalidate();
repaint();
}
/** returns the listener for changes in filters. */
protected PipelineListener getFilterPipelineListener() {
if (pipelineListener == null) {
pipelineListener = createPipelineListener();
}
return pipelineListener;
}
/** creates the listener for changes in filters. */
protected PipelineListener createPipelineListener() {
PipelineListener l = new PipelineListener() {
public void contentsChanged(PipelineEvent e) {
updateOnFilterContentChanged();
}
};
return l;
}
/** Returns the row count in the table; if filters are applied, this is the filtered row count. */
@Override
public int getRowCount() {
// RG: If there are no filters, call superclass version rather than accessing model directly
return filters == null ? super.getRowCount() : filters.getOutputSize();
}
/**
* workaround bug in JTable.
* (Bug Parade ID #6291631 - negative y is mapped to row 0).
*/
public int rowAtPoint(Point point) {
if (point.y < 0) return -1;
return super.rowAtPoint(point);
}
public boolean isHierarchical(int column) {
return false;
}
/**
* Convert row index from view coordinates to model coordinates
* accounting for the presence of sorters and filters.
*
* @param row row index in view coordinates
* @return row index in model coordinates
*/
public int convertRowIndexToModel(int row) {
if (sorter == null) {
if (filters == null) {
return row;
}
else {
// delegate conversion to the filters pipeline
return filters.convertRowIndexToModel(row);
}
}
else {
// after performing its own conversion, the sorter
// delegates the conversion to the filters pipeline, if any
return sorter.convertRowIndexToModel(row);
}
}
/**
* Convert row index from model coordinates to view coordinates
* accounting for the presence of sorters and filters.
*
* @param row row index in model coordinates
* @return row index in view coordinates
*/
public int convertRowIndexToView(int row) {
if (sorter == null) {
if (filters == null) {
return row;
}
else {
// delegate conversion to the filters pipeline
return filters.convertRowIndexToView(row);
}
}
else {
// before performing its own conversion, the sorter
// delegates the conversion to the filters pipeline, if any
return sorter.convertRowIndexToView(row);
}
}
/**
* {@inheritDoc}
*/
public Object getValueAt(int row, int column) {
if (sorter == null) { // have interactive sorter?
if (filters == null) { // have filter pipeline?
// superclass will call convertColumnIndexToModel
return super.getValueAt(row, column); // unsorted, unfiltered
}
else { // filtered
return filters.getValueAt(row, convertColumnIndexToModel(column));
}
}
else { // interactively sorted, and potentially filtered
return sorter.getValueAt(row, convertColumnIndexToModel(column));
}
}
/**
* {@inheritDoc}
*/
public void setValueAt(Object aValue, int row, int column) {
if (sorter == null) {
if (filters == null) {
super.setValueAt(aValue, row, column);
}
else {
filters.setValueAt(aValue, row, convertColumnIndexToModel(column));
}
}
else {
sorter.setValueAt(aValue, row, convertColumnIndexToModel(column));
}
}
/**
* {@inheritDoc}
*/
public boolean isCellEditable(int row, int column) {
if (sorter == null) {
if (filters == null) {
return super.isCellEditable(row, column);
}
else {
return filters.isCellEditable(row, convertColumnIndexToModel(column));
}
}
else {
return sorter.isCellEditable(row, convertColumnIndexToModel(column));
}
}
/**
* {@inheritDoc}
*/
public void setModel(TableModel newModel) {
//JW: need to clear here because super.setModel
// calls tableChanged...
// fixing #173
clearSelection();
super.setModel(newModel);
use(filters);
}
protected JTableHeader createDefaultTableHeader() {
return new JXTableHeader(columnModel);
}
protected TableColumnModel createDefaultColumnModel() {
return new DefaultTableColumnModelExt();
}
private void restoreSelection(Selection selection) {
clearSelection(); // call overridden version
// RG: calculate rowCount once, not inside a loop
final int rowCount = getModel().getRowCount();
for (int i = 0; i < selection.selected.length; i++) {
// JW: make sure we convert valid row indices (in model coordinates) only
// fix
int selected = selection.selected[i];
if ((selected != selection.lead) && (selected < rowCount)) {
int index = convertRowIndexToView(selection.selected[i]);
selectionModel.addSelectionInterval(index, index);
}
}
// JW: make sure we convert valid row indices (in model coordinates) only
// fix
if ((selection.lead >= 0) && (selection.lead < rowCount)) {
selection.lead = convertRowIndexToView(selection.lead);
selectionModel.addSelectionInterval(selection.lead, selection.lead);
}
}
/** Returns the FilterPipeline for the table, null if none. */
public FilterPipeline getFilters() {
return filters;
}
/**
* setModel() and setFilters() may be called in either order.
*
* @param pipeline
*/
private void use(FilterPipeline pipeline) {
if (pipeline != null) {
// check JW: adding listener multiple times (after setModel)?
if (initialUse(pipeline)) {
pipeline.addPipelineListener(getFilterPipelineListener());
pipeline.assign(getComponentAdapter());
}
pipeline.flush();
}
}
/**
*
* @param pipeline must be != null
* @return true is not yet used in this JXTable, false otherwise
*/
private boolean initialUse(FilterPipeline pipeline) {
if (pipelineListener == null) return true;
PipelineListener[] l = pipeline.getPipelineListeners();
for (int i = 0; i < l.length; i++) {
if (pipelineListener.equals(l[i])) return false;
}
return true;
}
/** Sets the FilterPipeline for filtering table rows. */
public void setFilters(FilterPipeline pipeline) {
unsetFilters();
doSetFilters(pipeline);
}
private void unsetFilters() {
if (filters == null) return;
// fix#125: cleanup old filters
filters.removePipelineListener(pipelineListener);
// hacking around -
//brute force update of sorter by removing
pipelineListener.contentsChanged(null);
}
private void doSetFilters(FilterPipeline pipeline) {
filters = pipeline;
use(filters);
}
/** Returns the HighlighterPipeline assigned to the table, null if none. */
public HighlighterPipeline getHighlighters() {
return highlighters;
}
/** Assigns a HighlighterPipeline to the table.
* bound property.
*/
public void setHighlighters(HighlighterPipeline pipeline) {
HighlighterPipeline old = getHighlighters();
if (old != null) {
old.removeChangeListener(getHighlighterChangeListener());
}
highlighters = pipeline;
if (highlighters != null) {
highlighters.addChangeListener(getHighlighterChangeListener());
}
firePropertyChange("highlighters", old, getHighlighters());
}
/**
* returns the ChangeListener to use with highlighters.
* Creates one if necessary.
* @return != null
*/
private ChangeListener getHighlighterChangeListener() {
if (highlighterChangeListener == null) {
highlighterChangeListener = new ChangeListener() {
public void stateChanged(ChangeEvent e) {
repaint();
}
};
}
return highlighterChangeListener;
}
private void removeSorter() {
// // fixing #167: remove from pipeline
// // moved to refreshSorter
// if (sorter != null) {
// sorter.interpose(null, getComponentAdapter(), null);
sorter = null;
getTableHeader().repaint();
}
/*
* Used by headerListener
*/
protected void resetSorter() {
if (sorter != null) {
Selection selection = new Selection(this);
removeSorter();
restoreSelection(selection);
}
}
private Sorter refreshSorter(int columnIndex) {
TableColumn col = getColumnModel().getColumn(columnIndex);
if (col instanceof TableColumnExt) {
TableColumnExt column = (TableColumnExt) col;
Sorter newSorter = column.getSorter();
if (newSorter != null) {
// JW: hacking around #167: un-assign from filters
// this should be done somewhere else!
newSorter.interpose(null, getComponentAdapter(), null);
// filter pipeline may be null!
newSorter.interpose(filters, getComponentAdapter(), sorter); // refresh
return newSorter;
}
}
return sorter;
}
/*
* Used by headerListener
*/
protected void setSorter(int columnIndex) {
if (!isSortable()) return;
Selection selection = new Selection(this);
if (sorter == null) {
sorter = refreshSorter(columnIndex); // create and refresh
}
else {
int modelColumnIndex = convertColumnIndexToModel(columnIndex);
if (sorter.getColumnIndex() == modelColumnIndex) {
sorter.toggle();
}
else {
sorter = refreshSorter(columnIndex); // create and refresh
}
}
restoreSelection(selection);
}
/*
* Used by ColumnHeaderRenderer.getTableCellRendererComponent()
*/
public Sorter getSorter(int columnIndex) {
return sorter == null ? null :
sorter.getColumnIndex() == convertColumnIndexToModel(columnIndex) ?
sorter : null;
}
/**
* Remove all columns
*/
protected void removeColumns() {
/** @todo promote this method to superclass, and
* change createDefaultColumnsFromModel() to call this method */
TableColumnModel cm = getColumnModel();
while (cm.getColumnCount() > 0) {
cm.removeColumn(cm.getColumn(0));
}
}
/**
* returns a list of all visible TableColumns.
*
* @return
*/
public List getColumns() {
return getColumns(false); /** @todo Implement this */
}
/**
* returns a list of TableColumns including hidden if the parameter
* is set to true.
*
* @param includeHidden
* @return
*/
public List getColumns(boolean includeHidden) {
TableColumnModel columnModel = getColumnModel();
if (columnModel instanceof TableColumnModelExt) {
return ((TableColumnModelExt) columnModel).getColumns(includeHidden);
}
return Collections.list(getColumnModel().getColumns());
}
/**
* reorders the columns in the sequence given array.
* Logical names that do not correspond to any column in the
* model will be ignored.
* Columns with logical names not contained are added at the end.
* @param columnNames array of logical column names
*/
public void setColumnSequence(Object[] identifiers) {
List columns = getColumns(true);
Map map = new HashMap();
for (Iterator iter = columns.iterator(); iter.hasNext();) {
// PENDING: handle duplicates...
TableColumn column = (TableColumn) iter.next();
map.put(column.getIdentifier(), column);
getColumnModel().removeColumn(column);
}
for (int i = 0; i < identifiers.length; i++) {
TableColumn column = (TableColumn) map.get(identifiers[i]);
if (column != null) {
getColumnModel().addColumn(column);
columns.remove(column);
}
}
for (Iterator iter = columns.iterator(); iter.hasNext();) {
// PENDING: handle duplicates...
TableColumn column = (TableColumn) iter.next();
getColumnModel().addColumn(column);
}
}
public TableColumnExt getColumnExt(Object identifier) {
return (TableColumnExt)super.getColumn(identifier);
}
public TableColumnExt getColumnExt(int viewColumnIndex) {
return (TableColumnExt) getColumnModel().getColumn(viewColumnIndex);
}
public void createDefaultColumnsFromModel() {
TableModel model = getModel();
if (model != null) {
// Create new columns from the data model info
// Note: it's critical to create the new columns before
// deleting the old ones. Why?
int modelColumnCount = model.getColumnCount();
TableColumn newColumns[] = new TableColumn[modelColumnCount];
for (int i = 0; i < newColumns.length; i++) {
newColumns[i] = createAndConfigureColumn(model, i);
}
// Remove any current columns
TableColumnModel columnModel = getColumnModel();
while (columnModel.getColumnCount() > 0) {
columnModel.removeColumn(columnModel.getColumn(0));
}
// Now add the new columns to the column model
for (int i = 0; i < newColumns.length; i++) {
addColumn(newColumns[i]);
}
}
}
protected TableColumn createAndConfigureColumn(TableModel model, int modelColumn) {
// TableColumn column = createColumn(modelColumn);
// if (model instanceof MetaDataProvider) {
// MetaDataProvider provider = (MetaDataProvider) model;
// MetaData metaData = provider.getMetaData(provider.getFieldNames()[modelColumn]);
// configureColumn(column, metaData);
// column.setHeaderValue(model.getColumnName(modelColumn));
return getColumnFactory().createAndConfigureTableColumn(model, modelColumn);
}
private ColumnFactory getColumnFactory() {
if (columnFactory == null) {
columnFactory = ColumnFactory.getInstance();
}
return columnFactory;
}
// /**
// * set column properties from MetaData. <p>
// * Experimental, will be moved somewhere else when
// * going for a data-unaware swingx layer.<p>
// *
// * Note: the column must not be assumed to be already
// * added to the columnModel nor to have any relation
// * to the current tableModel!.
// *
// * @param column
// * @param metaData
// */
// public void configureColumn(TableColumn column, MetaData metaData) {
// column.setIdentifier(metaData.getName());
// column.setHeaderValue(metaData.getLabel());
// if (column instanceof TableColumnExt) {
// TableColumnExt columnExt = (TableColumnExt) column;
// if (metaData.getElementClass() == String.class) {
//// if (metaData.getDisplayWidth() > 0) {
//// StringBuffer buf = new StringBuffer(metaData.getDisplayWidth());
//// for (int i = 0; i < metaData.getDisplayWidth(); i++) {
//// buf.append("r");
//// columnExt.setPrototypeValue(buf.toString());
// columnExt.putClientProperty(TableColumnExt.SORTER_COMPARATOR,
// Collator.getInstance());
// /**
// * Returns the default table model object, which is
// * a <code>DefaultTableModel</code>. A subclass can override this
// * method to return a different table model object.
// *
// * @return the default table model object
// * @see DefaultTableColumnModelExt
// */
// protected TableModel createDefaultDataModel() {
// return new DefaultTableModelExt();
/**
* Returns the margin between columns.
*
* @return the margin between columns
*/
public int getColumnMargin() {
return getColumnModel().getColumnMargin();
}
/**
* Sets the margin between columns.
*
* @param value margin between columns; must be greater than or equal to zero.
*/
public void setColumnMargin(int value) {
getColumnModel().setColumnMargin(value);
}
/**
* Returns the selection mode used by this table's selection model.
*
* @return the selection mode used by this table's selection model
*/
public int getSelectionMode() {
return getSelectionModel().getSelectionMode();
}
/**
* Returns the decorated <code>Component</code> used as a stamp to render
* the specified cell. Overrides superclass version to provide support for
* cell decorators.
*
* @param renderer the <code>TableCellRenderer</code> to prepare
* @param row the row of the cell to render, where 0 is the first row
* @param column the column of the cell to render, where 0 is the first column
* @return the decorated <code>Component</code> used as a stamp to render the specified cell
* @see org.jdesktop.swingx.decorator.Highlighter
*/
public Component prepareRenderer(TableCellRenderer renderer, int row,
int column) {
Component stamp = super.prepareRenderer(renderer, row, column);
if (highlighters == null) {
return stamp; // no need to decorate renderer with highlighters
}
else {
// MUST ALWAYS ACCESS dataAdapter through accessor method!!!
ComponentAdapter adapter = getComponentAdapter();
adapter.row = row;
adapter.column = column;
return highlighters.apply(stamp, adapter);
}
}
protected ComponentAdapter getComponentAdapter() {
// MUST ALWAYS ACCESS dataAdapter through accessor method!!!
return dataAdapter;
}
/**
* Performs a search across the table using String that represents a regex pattern;
* {@link java.util.regex.Pattern}. All columns and all rows are searched; the row id
* of the first match is returned.
*/
public int search(String searchString) {
return search(searchString, -1);
}
/**
* Performs a search on a column using String that represents a regex pattern;
* {@link java.util.regex.Pattern}. The specified column searched; the row id
* of the first match is returned.
*/
public int search(String searchString, int columnIndex) {
Pattern pattern = null;
if (searchString != null) {
return search(Pattern.compile(searchString, 0), columnIndex);
}
return -1;
}
/**
* Performs a search across the table using a {@link java.util.regex.Pattern}.
* All columns and all rows are searched; the row id
* of the first match is returned.
*/
public int search(Pattern pattern) {
return search(pattern, -1);
}
/**
* Performs a search across the table using a {@link java.util.regex.Pattern}.
* starting at a given row. All columns and all rows are searched; the row id
* of the first match is returned.
*/
public int search(Pattern pattern, int startIndex) {
return search(pattern, startIndex, false);
}
// Save the last column with the match.
private int lastCol = 0;
/**
* Performs a search across the table using a {@link java.util.regex.Pattern}.
* starting at a given row. All columns and all rows are searched; the row id
* of the first match is returned.
*
* @param startIndex row to start search
* @param backwards whether to start at the last row and search up to the first.
* @return row with a match.
*/
public int search(Pattern pattern, int startIndex, boolean backwards) {
if (pattern == null) {
lastCol = 0;
return -1;
}
int rows = getRowCount();
int endCol = getColumnCount();
int matchRow = -1;
if (backwards == true) {
if (startIndex < 0)
startIndex = rows;
int startRow = startIndex - 1;
for (int r = startRow; r >= 0 && matchRow == -1; r
for (int c = endCol - 1; c >= 0; c
Object value = getValueAt(r, c);
if ((value != null) &&
// JW: differs from PatternHighlighter/Filter
pattern.matcher(value.toString()).find()) {
// pattern.matcher(value.toString()).matches()) {
changeSelection(r, c, false, false);
matchRow = r;
lastCol = c;
break; // No need to search other columns
}
}
if (matchRow == -1) {
lastCol = endCol;
}
}
} else {
int startRow = startIndex + 1;
for (int r = startRow; r < rows && matchRow == -1; r++) {
for (int c = lastCol; c < endCol; c++) {
Object value = getValueAt(r, c);
if ((value != null) &&
// JW: differs from PatternHighlighter/Filter
pattern.matcher(value.toString()).find()) {
// pattern.matcher(value.toString()).matches()) {
changeSelection(r, c, false, false);
matchRow = r;
lastCol = c;
break; // No need to search other columns
}
}
if (matchRow == -1) {
lastCol = 0;
}
}
}
if (matchRow != -1) {
Object viewport = getParent();
if (viewport instanceof JViewport) {
Rectangle rect = getCellRect(getSelectedRow(), 0, true);
Point pt = ((JViewport) viewport).getViewPosition();
rect.setLocation(rect.x - pt.x, rect.y - pt.y);
((JViewport) viewport).scrollRectToVisible(rect);
}
}
return matchRow;
}
// public int search(Pattern pattern, int startIndex, boolean backwards) {
// if (pattern == null) {
// lastCol = 0;
// return -1;
// int rows = getRowCount();
// int endCol = getColumnCount();
// int startRow = startIndex + 1;
// int matchRow = -1;
// if (backwards == true) {
// for (int r = startRow; r >= 0 && matchRow == -1; r--) {
// for (int c = endCol; c >= 0; c--) {
// Object value = getValueAt(r, c);
// if ( (value != null) &&
// pattern.matcher(value.toString()).find()) {
// changeSelection(r, c, false, false);
// matchRow = r;
// lastCol = c;
// break; // No need to search other columns
// if (matchRow == -1) {
// lastCol = endCol;
// else {
// for (int r = startRow; r < rows && matchRow == -1; r++) {
// for (int c = lastCol; c < endCol; c++) {
// Object value = getValueAt(r, c);
// if ( (value != null) &&
// pattern.matcher(value.toString()).find()) {
// changeSelection(r, c, false, false);
// matchRow = r;
// lastCol = c;
// break; // No need to search other columns
// if (matchRow == -1) {
// lastCol = 0;
// if (matchRow != -1) {
// Object viewport = getParent();
// if (viewport instanceof JViewport) {
// Rectangle rect = getCellRect(getSelectedRow(), 0, true);
// Point pt = ( (JViewport) viewport).getViewPosition();
// rect.setLocation(rect.x - pt.x, rect.y - pt.y);
// ( (JViewport) viewport).scrollRectToVisible(rect);
// return matchRow;
public void setVisibleRowCount(int visibleRowCount) {
this.visibleRowCount = visibleRowCount;
}
public int getVisibleRowCount() {
return visibleRowCount;
}
public Dimension getPreferredScrollableViewportSize() {
Dimension prefSize = super.getPreferredScrollableViewportSize();
// JTable hardcodes this to 450 X 400, so we'll calculate it
// based on the preferred widths of the columns and the
// visibleRowCount property instead...
if (prefSize.getWidth() == 450 && prefSize.getHeight() == 400) {
TableColumnModel columnModel = getColumnModel();
int columnCount = columnModel.getColumnCount();
int w = 0;
for (int i = 0; i < columnCount; i++) {
TableColumn column = columnModel.getColumn(i);
initializeColumnPreferredWidth(column);
w += column.getPreferredWidth();
}
prefSize.width = w;
JTableHeader header = getTableHeader();
//remind(aim): height is still off...???
int rowCount = getVisibleRowCount();
prefSize.height = rowCount * getRowHeight() +
(header != null? header.getPreferredSize().height : 0);
setPreferredScrollableViewportSize(prefSize);
}
return prefSize;
}
/**
* Packs all the columns to their optimal size. Works best with
* auto resizing turned off.
*
* Contributed by M. Hillary (Issue #60)
*
* @param margin the margin to apply to each column.
*/
public void packTable(int margin) {
for (int c = 0; c < getColumnCount(); c++)
packColumn(c, margin, -1 );
}
/**
* Packs an indivudal column in the table.
* Contributed by M. Hillary (Issue #60)
*
* @param column
* The Column index to pack in View Coordinates
* @param margin
* The Margin to apply to the column width.
*/
public void packColumn(int column, int margin) {
packColumn(column, margin, -1);
}
/**
* Packs an indivual column in the table to less than or equal to the
* maximum witdth. If maximun is -1 then the column is made as wide
* as it needs.
* Contributed by M. Hillary (Issue #60)
*
* @param column The Column index to pack in View Coordinates
* @param margin The margin to apply to the column
* @param max The maximum width the column can be resized to. -1 mean any size.
*/
public void packColumn(int column, int margin, int max) {
getColumnFactory().packColumn(this, getColumnExt(column), margin, max);
}
/**
* Initialize the preferredWidth of the specified column based on the
* column's prototypeValue property. If the column is not an
* instance of <code>TableColumnExt</code> or prototypeValue is <code>null</code>
* then the preferredWidth is left unmodified.
* @see org.jdesktop.swingx.table.TableColumnExt#setPrototypeValue
* @param column TableColumn object representing view column
*/
protected void initializeColumnPreferredWidth(TableColumn column) {
if (column instanceof TableColumnExt) {
getColumnFactory().configureColumnWidths(this, (TableColumnExt) column);
}
}
protected static class TableAdapter extends ComponentAdapter {
private final JXTable table;
/**
* Constructs a <code>TableDataAdapter</code> for the specified
* target component.
*
* @param component the target component
*/
public TableAdapter(JXTable component) {
super(component);
table = component;
}
/**
* Typesafe accessor for the target component.
*
* @return the target component as a {@link javax.swing.JTable}
*/
public JXTable getTable() {
return table;
}
/**
* {@inheritDoc}
*/
public boolean hasFocus() {
boolean rowIsLead = (table.getSelectionModel().
getLeadSelectionIndex() == row);
boolean colIsLead =
(table.getColumnModel().getSelectionModel().
getLeadSelectionIndex() ==
column);
return table.isFocusOwner() && (rowIsLead && colIsLead);
}
public String getColumnName(int columnIndex) {
TableColumnModel columnModel = table.getColumnModel();
if (columnModel == null){
return "Column " + columnIndex;
}
TableColumn column = columnModel.getColumn(columnIndex);
return column == null ? "" : column.getHeaderValue().toString();
}
public int getColumnCount() {
return table.getModel().getColumnCount();
}
public int getRowCount() {
return table.getModel().getRowCount();
}
/**
* {@inheritDoc}
*/
public Object getValueAt(int row, int column) {
// RG: eliminate superfluous back-and-forth conversions
return table.getModel().getValueAt(row, column);
}
public Object getFilteredValueAt(int row, int column) {
return table.getValueAt(row, column); // in view coordinates
}
public void setValueAt(Object aValue, int row, int column) {
// RG: eliminate superfluous back-and-forth conversions
table.getModel().setValueAt(aValue, row, column);
}
public boolean isCellEditable(int row, int column) {
// RG: eliminate superfluous back-and-forth conversions
return table.getModel().isCellEditable(row, column);
}
/**
* {@inheritDoc}
*/
public boolean isSelected() {
return table.isCellSelected(row, column);
}
/**
* {@inheritDoc}
*/
public int modelToView(int columnIndex) {
return table.convertColumnIndexToView(columnIndex);
}
/**
* {@inheritDoc}
*/
public int viewToModel(int columnIndex) {
return table.convertColumnIndexToModel(columnIndex);
}
public String getColumnIdentifier(int columnIndex) {
Object identifier = table.getColumnExt(columnIndex).getIdentifier();
return identifier != null ? identifier.toString() : null;
}
}
private static class Selection {
protected final int[] selected; // used ONLY within save/restoreSelection();
protected int lead = -1;
protected Selection(JXTable table) {
selected = table.getSelectedRows(); // in view coordinates
for (int i = 0; i < selected.length; i++) {
selected[i] = table.convertRowIndexToModel(selected[i]); // model coordinates
}
if (selected.length > 0) {
// convert lead selection index to model coordinates
lead = table.convertRowIndexToModel(
table.getSelectionModel().getLeadSelectionIndex());
}
}
}
/*
* Default Type-based Renderers:
* JTable's default table cell renderer classes are private and
* JTable:getDefaultRenderer() returns a *shared* cell renderer instance,
* thus there is no way for us to instantiate a new instance of one of its
* default renderers. So, we must replicate the default renderer classes
* here so that we can instantiate them when we need to create renderers
* to be set on specific columns.
*/
public static class NumberRenderer extends DefaultTableCellRenderer {
public NumberRenderer() {
super();
setHorizontalAlignment(JLabel.RIGHT);
}
}
public static class DoubleRenderer extends NumberRenderer {
NumberFormat formatter;
public DoubleRenderer() {
super();
}
public void setValue(Object value) {
if (formatter == null) {
formatter = NumberFormat.getInstance();
}
setText( (value == null) ? "" : formatter.format(value));
}
}
public static class DateRenderer extends DefaultTableCellRenderer {
DateFormat formatter;
public DateRenderer() {
super();
}
public void setValue(Object value) {
if (formatter == null) {
formatter = DateFormat.getDateInstance();
}
setText( (value == null) ? "" : formatter.format(value));
}
}
public static class IconRenderer extends DefaultTableCellRenderer {
public IconRenderer() {
super();
setHorizontalAlignment(JLabel.CENTER);
}
public void setValue(Object value) {
setIcon( (value instanceof Icon) ? (Icon) value : null);
}
}
public static class BooleanRenderer extends JCheckBox
implements TableCellRenderer {
public BooleanRenderer() {
super();
setHorizontalAlignment(JLabel.CENTER);
}
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (isSelected) {
setForeground(table.getSelectionForeground());
super.setBackground(table.getSelectionBackground());
}
else {
setForeground(table.getForeground());
setBackground(table.getBackground());
}
setSelected( (value != null && ( (Boolean) value).booleanValue()));
return this;
}
}
// /**
// * Renders a LinkModel type the link in the table column
// */
// public static class LinkRenderer extends DefaultTableCellRenderer {
// // Should have a way of setting these statically
// private static Color colorLive = new Color(0, 0, 238);
// private static Color colorVisited = new Color(82, 24, 139);
// public void setValue(Object value) {
// if (value != null && value instanceof LinkModel) {
// LinkModel link = (LinkModel) value;
// setText(link.getText());
// setToolTipText(link.getURL().toString());
// if (link.getVisited()) {
// setForeground(colorVisited);
// else {
// setForeground(colorLive);
// else {
// super.setValue(value != null ? value.toString() : "");
// public void paintComponent(Graphics g) {
// super.paintComponent(g);
// if (!getText().equals("")) {
// // Render an underline. A really smart person
// // would actually render an underline font but
// // that's too much for my little brain.
// Rectangle rect = PaintUtils.getTextBounds(g, this);
// FontMetrics fm = g.getFontMetrics();
// int descent = fm.getDescent();
// //REMIND(aim): should we be basing the underline on
// //the font's baseline instead of the text bounds?
// g.drawLine(rect.x, (rect.y + rect.height) - descent + 1,
// rect.x + rect.width,
// (rect.y + rect.height) - descent + 1);
}
|
package org.jdesktop.swingx;
import java.awt.Color;
import java.awt.Component;
import java.awt.ComponentOrientation;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.print.PrinterException;
import java.beans.PropertyChangeEvent;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.DefaultCellEditor;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JViewport;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
import javax.swing.SizeSequence;
import javax.swing.SwingUtilities;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.TableColumnModelEvent;
import javax.swing.event.TableModelEvent;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import org.jdesktop.swingx.action.BoundAction;
import org.jdesktop.swingx.decorator.ComponentAdapter;
import org.jdesktop.swingx.decorator.FilterPipeline;
import org.jdesktop.swingx.decorator.Highlighter;
import org.jdesktop.swingx.decorator.HighlighterPipeline;
import org.jdesktop.swingx.decorator.PatternHighlighter;
import org.jdesktop.swingx.decorator.PipelineEvent;
import org.jdesktop.swingx.decorator.PipelineListener;
import org.jdesktop.swingx.decorator.ResetDTCRColorHighlighter;
import org.jdesktop.swingx.decorator.SearchHighlighter;
import org.jdesktop.swingx.decorator.SelectionMapper;
import org.jdesktop.swingx.decorator.SizeSequenceMapper;
import org.jdesktop.swingx.decorator.SortController;
import org.jdesktop.swingx.decorator.SortKey;
import org.jdesktop.swingx.decorator.SortOrder;
import org.jdesktop.swingx.event.TableColumnModelExtListener;
import org.jdesktop.swingx.icon.ColumnControlIcon;
import org.jdesktop.swingx.plaf.LookAndFeelAddons;
import org.jdesktop.swingx.table.ColumnControlButton;
import org.jdesktop.swingx.table.ColumnFactory;
import org.jdesktop.swingx.table.DefaultTableColumnModelExt;
import org.jdesktop.swingx.table.TableColumnExt;
import org.jdesktop.swingx.table.TableColumnModelExt;
/**
* <p>
* A JXTable is a JTable with built-in support for row sorting, filtering, and
* highlighting, column visibility and a special popup control on the column
* header for quick access to table configuration. You can instantiate a JXTable
* just as you would a JTable, using a TableModel. However, a JXTable
* automatically wraps TableColumns inside a TableColumnExt instance.
* TableColumnExt supports visibility, sortability, and prototype values for
* column sizing, none of which are available in TableColumn. You can retrieve
* the TableColumnExt instance for a column using {@link #getColumnExt(Object)}
* or {@link #getColumnExt(int colnumber)}.
*
* <p>
* A JXTable is, by default, sortable by clicking on column headers; each
* subsequent click on a header reverses the order of the sort, and a sort arrow
* icon is automatically drawn on the header. Sorting can be disabled using
* {@link #setSortable(boolean)}. Sorting on columns is handled by a Sorter
* instance which contains a Comparator used to compare values in two rows of a
* column. You can replace the Comparator for a given column by using
* <code>getColumnExt("column").setComparator(customComparator)</code>
*
* <p>
* Columns can be hidden or shown by setting the visible property on the
* TableColumnExt using {@link TableColumnExt#setVisible(boolean)}. Columns can
* also be shown or hidden from the column control popup.
*
* <p>
* The column control popup is triggered by an icon drawn to the far right of
* the column headers, above the table's scrollbar (when installed in a
* JScrollPane). The popup allows the user to select which columns should be
* shown or hidden, as well as to pack columns and turn on horizontal scrolling.
* To show or hide the column control, use the
* {@link #setColumnControlVisible(boolean show)}method.
*
* <p>
* Rows can be filtered from a JXTable using a Filter class and a
* FilterPipeline. One assigns a FilterPipeline to the table using
* {@link #setFilters(FilterPipeline)}. Filtering hides, but does not delete or
* permanently remove rows from a JXTable. Filters are used to provide sorting
* to the table--rows are not removed, but the table is made to believe rows in
* the model are in a sorted order.
*
* <p>
* One can automatically highlight certain rows in a JXTable by attaching
* Highlighters in the {@link #setHighlighters(HighlighterPipeline)}method. An
* example would be a Highlighter that colors alternate rows in the table for
* readability; AlternateRowHighlighter does this. Again, like Filters,
* Highlighters can be chained together in a HighlighterPipeline to achieve more
* interesting effects.
*
* <p>
* You can resize all columns, selected columns, or a single column using the
* methods like {@link #packAll()}. Packing combines several other aspects of a
* JXTable. If horizontal scrolling is enabled using
* {@link #setHorizontalScrollEnabled(boolean)}, then the scrollpane will allow
* the table to scroll right-left, and columns will be sized to their preferred
* size. To control the preferred sizing of a column, you can provide a
* prototype value for the column in the TableColumnExt using
* {@link TableColumnExt#setPrototypeValue(Object)}. The prototype is used as
* an indicator of the preferred size of the column. This can be useful if some
* data in a given column is very long, but where the resize algorithm would
* normally not pick this up.
*
* <p>
* JXTable guarantees to delegate creation and configuration of TableColumnExt
* to a ColumnFactory. By default, the application-wide shared ColumnFactory is used.
* You can install a custom ColumnFactory, either application-wide by
* {@link ColumnFactory#setInstance(ColumnFactory)} or per table instance by
* {@link #setColumnFactory(ColumnFactory)}.
*
* <p>
* Last, you can also provide searches on a JXTable using the Searchable property.
*
* <p>
* Keys/Actions registered with this component:
*
* <ul>
* <li> "find" - open an appropriate search widget for searching cell content. The
* default action registeres itself with the SearchFactory as search target.
* <li> "print" - print the table
* <li> {@link JXTable#HORIZONTALSCROLL_ACTION_COMMAND} - toggle the horizontal scrollbar
* <li> {@link JXTable#PACKSELECTED_ACTION_COMMAND} - resize the selected column to fit the widest
* cell content
* <li> {@link JXTable#PACKALL_ACTION_COMMAND} - resize all columns to fit the widest
* cell content in each column
*
* </ul>
*
* <p>
* Key bindings.
*
* <ul>
* <li> "control F" - bound to actionKey "find".
* </ul>
*
* <p>
* Client Properties.
*
* <ul>
* <li> {@link JXTable#MATCH_HIGHLIGHTER} - set to Boolean.TRUE to
* use a SearchHighlighter to mark a cell as matching.
* </ul>
*
* @author Ramesh Gupta
* @author Amy Fowler
* @author Mark Davidson
* @author Jeanette Winzenburg
*/
public class JXTable extends JTable
// implements TableColumnModelExtListener
{
private static final Logger LOG = Logger.getLogger(JXTable.class.getName());
// public static final int AUTO_RESIZE_INTELLI_OFF = -1;
/**
* Constant string for horizontal scroll actions, used in JXTable's Action
* Map.
*/
public static final String HORIZONTALSCROLL_ACTION_COMMAND =
ColumnControlButton.COLUMN_CONTROL_MARKER + "horizontalScroll";
/** Constant string for packing all columns, used in JXTable's Action Map. */
public static final String PACKALL_ACTION_COMMAND =
ColumnControlButton.COLUMN_CONTROL_MARKER + "packAll";
/**
* Constant string for packing selected columns, used in JXTable's Action
* Map.
*/
public static final String PACKSELECTED_ACTION_COMMAND =
ColumnControlButton.COLUMN_CONTROL_MARKER + "packSelected";
/** The prefix marker to find component related properties in the resourcebundle. */
public static final String UIPREFIX = "JXTable.";
/** key for client property to use SearchHighlighter as match marker. */
public static final String MATCH_HIGHLIGHTER = AbstractSearchable.MATCH_HIGHLIGHTER;
static {
// Hack: make sure the resource bundle is loaded
LookAndFeelAddons.getAddon();
}
/** The FilterPipeline for the table. */
protected FilterPipeline filters;
/** The HighlighterPipeline for the table. */
protected HighlighterPipeline highlighters;
/**
* The Highlighter used to hack around DefaultTableCellRenderer's color memory.
*/
protected Highlighter resetDefaultTableCellRendererHighlighter;
/** The ComponentAdapter for model data access. */
protected ComponentAdapter dataAdapter;
/** The handler for mapping view/model coordinates of row selection. */
private SelectionMapper selectionMapper;
/** flag to indicate if table is interactively sortable. */
private boolean sortable;
/** future - enable/disable autosort on cell updates not used */
// private boolean automaticSortDisabled;
/** Listens for changes from the filters. */
private PipelineListener pipelineListener;
/** Listens for changes from the highlighters. */
private ChangeListener highlighterChangeListener;
/** the factory to use for column creation and configuration. */
private ColumnFactory columnFactory;
/** The default number of visible rows (in a ScrollPane). */
private int visibleRowCount = 18;
private SizeSequenceMapper rowModelMapper;
private Field rowModelField;
private boolean rowHeightEnabled;
/**
* flag to indicate if the column control is visible.
*/
private boolean columnControlVisible;
/**
* ScrollPane's original vertical scroll policy. If the columnControl is
* visible the policy is set to ALWAYS.
*/
private int verticalScrollPolicy;
/**
* A button that allows the user to select which columns to display, and
* which to hide
*/
private JComponent columnControlButton;
/**
* Mouse/Motion/Listener keeping track of mouse moved in cell coordinates.
*/
private RolloverProducer rolloverProducer;
/**
* RolloverController: listens to cell over events and repaints
* entered/exited rows.
*/
private TableRolloverController linkController;
/** field to store the autoResizeMode while interactively setting
* horizontal scrollbar to visible.
*/
private int oldAutoResizeMode;
/** temporary hack: rowheight will be internally adjusted to font size
* on instantiation and in updateUI if
* the height has not been set explicitly by the application.
*/
protected boolean isXTableRowHeightSet;
protected Searchable searchable;
/** property to control the tracksViewportHeight behaviour. */
private boolean fillsViewportHeight;
/** internal flag to control the tracksViewportWidth behaviour. */
private boolean ensureFillsViewportWidth;
private boolean editable;
private boolean expandsToViewportWidthEnabled;
private boolean dockedOnExpand;
private boolean intelliMode;
private boolean inLayout;
/** Instantiates a JXTable with a default table model, no data. */
public JXTable() {
init();
}
/**
* Instantiates a JXTable with a specific table model.
*
* @param dm
* The model to use.
*/
public JXTable(TableModel dm) {
super(dm);
init();
}
/**
* Instantiates a JXTable with a specific table model.
*
* @param dm
* The model to use.
*/
public JXTable(TableModel dm, TableColumnModel cm) {
super(dm, cm);
init();
}
/**
* Instantiates a JXTable with a specific table model, column model, and
* selection model.
*
* @param dm
* The table model to use.
* @param cm
* The colomn model to use.
* @param sm
* The list selection model to use.
*/
public JXTable(TableModel dm, TableColumnModel cm, ListSelectionModel sm) {
super(dm, cm, sm);
init();
}
/**
* Instantiates a JXTable for a given number of columns and rows.
*
* @param numRows
* Count of rows to accomodate.
* @param numColumns
* Count of columns to accomodate.
*/
public JXTable(int numRows, int numColumns) {
super(numRows, numColumns);
init();
}
/**
* Instantiates a JXTable with data in a vector or rows and column names.
*
* @param rowData
* Row data, as a Vector of Objects.
* @param columnNames
* Column names, as a Vector of Strings.
*/
public JXTable(Vector rowData, Vector columnNames) {
super(rowData, columnNames);
init();
}
/**
* Instantiates a JXTable with data in a array or rows and column names.
*
* @param rowData
* Row data, as a two-dimensional Array of Objects (by row, for
* column).
* @param columnNames
* Column names, as a Array of Strings.
*/
public JXTable(Object[][] rowData, Object[] columnNames) {
super(rowData, columnNames);
init();
}
/**
* Initializes the table for use.
*
*/
/*
* PENDING JW: this method should be private!
*
*/
protected void init() {
setEditable(true);
setSortable(true);
setRolloverEnabled(true);
setTerminateEditOnFocusLost(true);
// guarantee getFilters() to return != null
setFilters(null);
initActionsAndBindings();
// instantiate row height depending on font size
updateRowHeightUI(false);
setFillsViewportHeight(true);
}
/**
* Property to enable/disable rollover support. This can be enabled to show
* "live" rollover behaviour, f.i. the cursor over LinkModel cells. Default
* is enabled. If rollover effects are not used, this property should be
* disabled.
*
* @param rolloverEnabled
*/
public void setRolloverEnabled(boolean rolloverEnabled) {
boolean old = isRolloverEnabled();
if (rolloverEnabled == old)
return;
if (rolloverEnabled) {
rolloverProducer = createRolloverProducer();
addMouseListener(rolloverProducer);
addMouseMotionListener(rolloverProducer);
getLinkController().install(this);
} else {
removeMouseListener(rolloverProducer);
removeMouseMotionListener(rolloverProducer);
rolloverProducer = null;
getLinkController().release();
}
firePropertyChange("rolloverEnabled", old, isRolloverEnabled());
}
protected TableRolloverController getLinkController() {
if (linkController == null) {
linkController = createLinkController();
}
return linkController;
}
protected TableRolloverController createLinkController() {
return new TableRolloverController();
}
/**
* creates and returns the RolloverProducer to use.
*
* @return <code>RolloverProducer</code>
*/
protected RolloverProducer createRolloverProducer() {
RolloverProducer r = new RolloverProducer() {
protected void updateRolloverPoint(JComponent component,
Point mousePoint) {
JTable table = (JTable) component;
int col = table.columnAtPoint(mousePoint);
int row = table.rowAtPoint(mousePoint);
if ((col < 0) || (row < 0)) {
row = -1;
col = -1;
}
rollover.x = col;
rollover.y = row;
}
};
return r;
}
/**
* Returns the rolloverEnabled property.
*
* @return <code>true</code> if rollover is enabled
*/
public boolean isRolloverEnabled() {
return rolloverProducer != null;
}
/**
* listens to rollover properties.
* Repaints effected component regions.
* Updates link cursor.
*
* @author Jeanette Winzenburg
*/
public static class TableRolloverController<T extends JTable> extends RolloverController<T> {
private Cursor oldCursor;
protected void rollover(Point oldLocation, Point newLocation) {
if (oldLocation != null) {
Rectangle r = component.getCellRect(oldLocation.y, oldLocation.x, false);
r.x = 0;
r.width = component.getWidth();
component.repaint(r);
}
if (newLocation != null) {
Rectangle r = component.getCellRect(newLocation.y, newLocation.x, false);
r.x = 0;
r.width = component.getWidth();
component.repaint(r);
}
setRolloverCursor(newLocation);
}
/**
* overridden to return false if cell editable.
*/
@Override
protected boolean isClickable(Point location) {
return super.isClickable(location) && !component.isCellEditable(location.y, location.x);
}
protected RolloverRenderer getRolloverRenderer(Point location, boolean prepare) {
TableCellRenderer renderer = component.getCellRenderer(location.y, location.x);
RolloverRenderer rollover = renderer instanceof RolloverRenderer ?
(RolloverRenderer) renderer : null;
if ((rollover != null) && !rollover.isEnabled()) {
rollover = null;
}
if ((rollover != null) && prepare) {
component.prepareRenderer(renderer, location.y, location.x);
}
return rollover;
}
private void setRolloverCursor(Point location) {
if (hasRollover(location)) {
if (oldCursor == null) {
oldCursor = component.getCursor();
component.setCursor(Cursor
.getPredefinedCursor(Cursor.HAND_CURSOR));
}
} else {
if (oldCursor != null) {
component.setCursor(oldCursor);
oldCursor = null;
}
}
}
protected Point getFocusedCell() {
int leadRow = component.getSelectionModel()
.getLeadSelectionIndex();
int leadColumn = component.getColumnModel().getSelectionModel()
.getLeadSelectionIndex();
return new Point(leadColumn, leadRow);
}
}
/**
* overridden to addionally configure the upper right corner of an enclosing
* scrollpane with the ColumnControl.
*/
@Override
protected void configureEnclosingScrollPane() {
super.configureEnclosingScrollPane();
configureColumnControl();
// configureViewportBackground();
}
/**
* set's the viewports background to this.background.<p>
*
* PENDING: need to
* repeat on background changes to this!
* @deprecated no longer used - replaced by fillsViewportHeight
*
*/
protected void configureViewportBackground() {
Container p = getParent();
if (p instanceof JViewport) {
p.setBackground(getBackground());
}
}
/**
* configure the upper right corner of an enclosing scrollpane with/o the
* ColumnControl, depending on setting of columnControl visibility flag.<p>
*
* PENDING: should choose corner depending on component orientation.
*/
private void configureColumnControl() {
Container p = getParent();
if (p instanceof JViewport) {
Container gp = p.getParent();
if (gp instanceof JScrollPane) {
JScrollPane scrollPane = (JScrollPane) gp;
// Make certain we are the viewPort's view and not, for
// example, the rowHeaderView of the scrollPane -
// an implementor of fixed columns might do this.
JViewport viewport = scrollPane.getViewport();
if (viewport == null || viewport.getView() != this) {
return;
}
if (isColumnControlVisible()) {
verticalScrollPolicy = scrollPane
.getVerticalScrollBarPolicy();
scrollPane.setCorner(JScrollPane.UPPER_TRAILING_CORNER,
getColumnControl());
scrollPane
.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
} else {
if (verticalScrollPolicy != 0) {
// Fix #155-swingx: reset only if we had force always before
// PENDING: JW - doesn't cope with dynamically changing the policy
// shouldn't be much of a problem because doesn't happen too often??
scrollPane.setVerticalScrollBarPolicy(verticalScrollPolicy);
}
try {
scrollPane.setCorner(JScrollPane.UPPER_TRAILING_CORNER,
null);
} catch (Exception ex) {
// Ignore spurious exception thrown by JScrollPane. This
// is a Swing bug!
}
}
}
}
}
/**
* Hack around core swing JScrollPane bug: can't cope with
* corners when changing component orientation at runtime.
* overridden to re-configure the columnControl.
*/
@Override
public void setComponentOrientation(ComponentOrientation o) {
super.setComponentOrientation(o);
configureColumnControl();
}
/**
* returns visibility flag of column control.
* <p>
*
* Note: if the table is not inside a JScrollPane the column control is not
* shown even if this returns true. In this case it's the responsibility of
* the client code to actually show it.
*
* @return true if the column is visible, false otherwise
*/
public boolean isColumnControlVisible() {
return columnControlVisible;
}
/**
* Lazily creates and returns the component use as column control.
*
* @return component for column control, guaranteed to be != null.
* @see #setColumnControl(JComponent)
*/
public JComponent getColumnControl() {
if (columnControlButton == null) {
columnControlButton = createDefaultColumnControl();
}
return columnControlButton;
}
/**
* Sets the columnControl and updates the scrollpane, if any.
* If the given component is null, sets and uses the default columnControl.
* <p>
* NOTE: from the table's perspective, the columnControl is simply a
* JComponent to add to and keep in the trailing corner of the JScrollPane (if any).
* It's up to developers to configure the concrete control as needed.
* <p>
* PENDING JW: release old column control? who's responsible?
* Could implement CCB.autoRelease()?
*
* @param columnControl the JComponent to use as columnControl.
*/
public void setColumnControl(JComponent columnControl) {
JComponent old = columnControlButton;
this.columnControlButton = columnControl;
configureColumnControl();
firePropertyChange("columnControl", old, getColumnControl());
}
/**
* Factory method to create the default ColumnControl used by this table.
* Here: a ColumnControlButton configured
* with this and the default ColumnControlIcon
*
* @return the default ColumnControl.
*/
protected JComponent createDefaultColumnControl() {
return new ColumnControlButton(this, new ColumnControlIcon());
}
/**
* bound property to flag visibility state of column control.
*
* @param showColumnControl
*/
public void setColumnControlVisible(boolean showColumnControl) {
boolean old = columnControlVisible;
this.columnControlVisible = showColumnControl;
configureColumnControl();
firePropertyChange("columnControlVisible", old, columnControlVisible);
}
/**
* A small class which dispatches actions. TODO: Is there a way that we can
* make this static? JW: I hate those if constructs... we are in OO-land!
*/
private class Actions extends UIAction {
Actions(String name) {
super(name);
}
public void actionPerformed(ActionEvent evt) {
if ("print".equals(getName())) {
try {
print();
} catch (PrinterException ex) {
// REMIND(aim): should invoke pluggable application error
// handler
LOG.log(Level.WARNING, "", ex);
}
} else if ("find".equals(getName())) {
find();
}
}
}
private void initActionsAndBindings() {
// Register the actions that this class can handle.
ActionMap map = getActionMap();
map.put("print", new Actions("print"));
map.put("find", new Actions("find"));
map.put(PACKALL_ACTION_COMMAND, createPackAllAction());
map.put(PACKSELECTED_ACTION_COMMAND, createPackSelectedAction());
map.put(HORIZONTALSCROLL_ACTION_COMMAND, createHorizontalScrollAction());
// JW: this should be handled by the LF!
KeyStroke findStroke = KeyStroke.getKeyStroke("control F");
getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(findStroke, "find");
}
/** Creates an Action for horizontal scrolling. */
private Action createHorizontalScrollAction() {
String actionName = getUIString(HORIZONTALSCROLL_ACTION_COMMAND);
BoundAction action = new BoundAction(actionName,
HORIZONTALSCROLL_ACTION_COMMAND);
action.setStateAction();
action.registerCallback(this, "setHorizontalScrollEnabled");
action.setSelected(isHorizontalScrollEnabled());
return action;
}
private String getUIString(String key) {
String text = UIManager.getString(UIPREFIX + key);
return text != null ? text : key;
}
/** Creates an Action for packing selected columns. */
private Action createPackSelectedAction() {
String text = getUIString(PACKSELECTED_ACTION_COMMAND);
BoundAction action = new BoundAction(text, PACKSELECTED_ACTION_COMMAND);
action.registerCallback(this, "packSelected");
action.setEnabled(getSelectedColumnCount() > 0);
return action;
}
/** Creates an Action for packing all columns. */
private Action createPackAllAction() {
String text = getUIString(PACKALL_ACTION_COMMAND);
BoundAction action = new BoundAction(text, PACKALL_ACTION_COMMAND);
action.registerCallback(this, "packAll");
return action;
}
/**
* This resizes all columns to fit the viewport; if horizontal scrolling is
* enabled, all columns will get their preferred width. This can be
* triggered by the "packAll" BoundAction on the table as well.
*/
public void packAll() {
packTable(-1);
expandToViewportWidth();
}
/**
* This resizes selected columns to fit the viewport; if horizontal
* scrolling is enabled, selected columns will get their preferred width.
* This can be triggered by the "packSelected" BoundAction on the table as
* well.
*/
public void packSelected() {
int selected = getColumnModel().getSelectionModel().getLeadSelectionIndex();
if (selected >= 0) {
packColumn(selected, -1);
}
}
/** Notifies the table that a new column has been selected.
* overridden to update the enabled state of the packSelected
* action.
*/
@Override
public void columnSelectionChanged(ListSelectionEvent e) {
super.columnSelectionChanged(e);
if (e.getValueIsAdjusting())
return;
Action packSelected = getActionMap().get(PACKSELECTED_ACTION_COMMAND);
if ((packSelected != null)) {
packSelected.setEnabled(!((ListSelectionModel) e.getSource())
.isSelectionEmpty());
}
}
/**
* Controls horizontal scrolling in the viewport, and works in coordination
* with column sizing.
*
* @param enabled
* If true, the scrollpane will allow the table to scroll
* horizontally, and columns will resize to their preferred
* width. If false, columns will resize to fit the viewport.
*/
public void setHorizontalScrollEnabled(boolean enabled) {
if (enabled == (isHorizontalScrollEnabled()))
return;
if (enabled) {
oldAutoResizeMode = getAutoResizeMode();
intelliMode = true;
setAutoResizeMode(AUTO_RESIZE_OFF);
} else {
intelliMode = false;
setAutoResizeMode(oldAutoResizeMode);
}
}
/** Returns the current setting for horizontal scrolling. */
protected boolean isHorizontalScrollEnabled() {
return getAutoResizeMode() == AUTO_RESIZE_OFF;
}
/**
* overridden to update the show horizontal scrollbar action's
* selected state.
*/
@Override
public void setAutoResizeMode(int mode) {
if ((mode == AUTO_RESIZE_OFF) && (getAutoResizeMode() != mode)) {
ensureFillsViewportWidth = true;
}
if (mode != AUTO_RESIZE_OFF) {
oldAutoResizeMode = mode;
}
super.setAutoResizeMode(mode);
Action showHorizontal = getActionMap().get(
HORIZONTALSCROLL_ACTION_COMMAND);
if (showHorizontal instanceof BoundAction) {
((BoundAction) showHorizontal)
.setSelected(isHorizontalScrollEnabled());
}
}
/**
* Make the table fill the entire viewport if necessary.
* "necessary" might be true if the isHorizontalScrollEnabled()
* and the table's preferred width is less than the
* parent's width (usually the viewport). <p>
*
* Does nothing if !expandsToViewportWidthEnabled which is
* the default. <p>
*
* Note: this feature is very experimental - that's why there
* is a dedicated (probably?) temporary property to control
* the enablement.
*
*/
public void expandToViewportWidth() {
if (!isExpandsToViewportWidthEnabled()) return;
ensureFillsViewportWidth = true;
revalidate();
}
/**
* overridden to support auto-expand to parent's width if
* enabled and necessary.
*/
@Override
public boolean getScrollableTracksViewportWidth() {
boolean shouldTrack = super.getScrollableTracksViewportWidth();
// TODO jw remove all expandsToViewport
if (isExpandsToViewportWidthEnabled() &&
ensureFillsViewportWidth && isHorizontalScrollEnabled()) {
return hasExcessWidth();
}
if (intelliMode) {
return hasExcessWidth();
}
return shouldTrack;
}
/**
* overridden to support auto-expand to parent's width if enabled and
* necessary.
*/
@Override
public void doLayout() {
int resizeMode = getAutoResizeMode();
// fool super...
if (intelliMode && hasRealizedParent() && hasExcessWidth()) {
autoResizeMode = oldAutoResizeMode;
}
inLayout = true;
super.doLayout();
inLayout = false;
autoResizeMode = resizeMode;
// TODO jw - remove everything related to the expandToViewport ...
if (!isExpandsToViewportWidthEnabled()) return;
if (ensureFillsViewportWidth && (getWidth() > 0) && (getParent() != null)
&& (getParent().getWidth() > 0)) {
// JW: initially this flag was introduced to prevent
// an endless loop when doing the layout ...
// doesn't seem to be a problem any longer
// if commented, then the right edge of the table sticks to the
// border of the viewport on increasing the viewport width
// (that's because it's effectively always on)
// on decreasing the scrollbar appears
// if reset to false increasing the viewport width leaves
// doesn't increase the table width - to fit again an explicit
// expandToWidth is needed.
if (!isDockedOnExpandWidth()) {
ensureFillsViewportWidth = false;
}
for (Enumeration enumeration = getColumnModel().getColumns(); enumeration
.hasMoreElements();) {
TableColumn c = (TableColumn) enumeration.nextElement();
c.setPreferredWidth(c.getWidth());
}
revalidate();
}
}
private boolean hasRealizedParent() {
return (getWidth() > 0) && (getParent() != null)
&& (getParent().getWidth() > 0);
}
private boolean hasExcessWidth() {
return getPreferredSize().width < getParent().getWidth();
}
@Override
public void columnMarginChanged(ChangeEvent e) {
if (isEditing()) {
removeEditor();
}
TableColumn resizingColumn = getResizingColumn();
// Need to do this here, before the parent's
// layout manager calls getPreferredSize().
if (resizingColumn != null && autoResizeMode == AUTO_RESIZE_OFF && !inLayout) {
resizingColumn.setPreferredWidth(resizingColumn.getWidth());
}
resizeAndRepaint();
}
private TableColumn getResizingColumn() {
return (tableHeader == null) ? null
: tableHeader.getResizingColumn();
}
/**
* Sets the expandsToViewportWidth property. If enabled, the table
* can be expanded to viewport width if isHorizontalScrollEnabled.
* The expansion (if enabled) is done automatically after
* in createColumnsFromModel() and in packAll(),
* in all other cases client code must do so explicitly.
*
* The default value is false.
*
*
* PENDING other candidate contexts for auto-expand?
*
* @param enabled boolean indicating whether the table
* should auto-expand columns to fit the viewport width.
*/
public void setExpandsToViewportWidthEnabled(boolean enabled) {
boolean old = isExpandsToViewportWidthEnabled();
if (old == enabled) return;
expandsToViewportWidthEnabled= enabled;
firePropertyChange("expandsToViewportWidthEnabled", old, isExpandsToViewportWidthEnabled());
expandToViewportWidth();
}
/**
*
* @return a boolean property indicating whether the table
* should auto-expand columns to fit the viewport width.
*/
protected boolean isExpandsToViewportWidthEnabled() {
return expandsToViewportWidthEnabled;
}
/**
*
* @param docked boolean to indicate whether the table width should
* be kept docked to the right viewport boundary on expanding the
* viewport's width.
*/
public void setDockedOnExpandWidth(boolean docked) {
boolean old = isDockedOnExpandWidth();
if (old == docked) return;
this.dockedOnExpand = docked;
expandToViewportWidth();
firePropertyChange("dockeOnExpandWidth", old, isDockedOnExpandWidth());
}
/**
*
* @return boolean to indicate docking state on viewport expansion.
*/
protected boolean isDockedOnExpandWidth() {
return dockedOnExpand;
}
/**
* Set flag to control JXTable's scrollableTracksViewportHeight
* property.
* If true the table's height will be always at least as large as the
* containing (viewport?) parent, if false the table's height will be
* independent of parent's height.
*
*/
public void setFillsViewportHeight(boolean fillsViewportHeight) {
if (fillsViewportHeight == getFillsViewportHeight()) return;
boolean old = getFillsViewportHeight();
this.fillsViewportHeight = fillsViewportHeight;
firePropertyChange("fillsViewportHeight", old, getFillsViewportHeight());
revalidate();
}
/**
* Returns the flag to control JXTable scrollableTracksViewportHeight
* property.
* If true the table's height will be always at least as large as the
* containing (viewport?) parent, if false the table's height will be
* independent of parent's height.
*
* @return true if the table's height will always be at least as large
* as the containing parent, false if it is independent
*/
public boolean getFillsViewportHeight() {
return fillsViewportHeight;
}
/**
* Overridden to control the tracksHeight property depending on
* fillsViewportHeight and relative size to containing parent (viewport?).
*
* @return true if the control flag is true and the containing viewport
* height > prefHeight, else returns false.
*
*/
@Override
public boolean getScrollableTracksViewportHeight() {
return getFillsViewportHeight()
&& getParent() instanceof JViewport
&& (((JViewport)getParent()).getHeight() > getPreferredSize().height);
}
/**
* Returns the row count in the table; if filters are applied, this is the
* filtered row count.
*/
@Override
public int getRowCount() {
// RG: If there are no filters, call superclass version rather than
// accessing model directly
return filters == null ?
super.getRowCount() : filters.getOutputSize();
}
public boolean isHierarchical(int column) {
return false;
}
/**
* Convert row index from view coordinates to model coordinates accounting
* for the presence of sorters and filters.
*
* @param row
* row index in view coordinates
* @return row index in model coordinates
*/
public int convertRowIndexToModel(int row) {
return getFilters().convertRowIndexToModel(row);
}
/**
* Convert row index from model coordinates to view coordinates accounting
* for the presence of sorters and filters.
*
* @param row
* row index in model coordinates
* @return row index in view coordinates
*/
public int convertRowIndexToView(int row) {
return getFilters().convertRowIndexToView(row);
}
/**
* Overridden to account for row index mapping.
* {@inheritDoc}
*/
@Override
public Object getValueAt(int row, int column) {
return getModel().getValueAt(convertRowIndexToModel(row),
convertColumnIndexToModel(column));
}
/**
* Overridden to account for row index mapping. This implementation
* respects {@link #isCellEditable(int, int)} as documented in
* {@link JTable#isCellEditable(int, int)}: it has no effect if
* the cell is not editable.
*
* {@inheritDoc}
*/
@Override
public void setValueAt(Object aValue, int row, int column) {
if (!isCellEditable(row, column)) return;
getModel().setValueAt(aValue, convertRowIndexToModel(row),
convertColumnIndexToModel(column));
}
/**
* Overridden to account for row index mapping and to respect
* both {@link #isEditable()} and {@link TableColumnExt#isEditable()} property.
*
* {@inheritDoc}
*/
@Override
public boolean isCellEditable(int row, int column) {
if (!isEditable()) return false;
boolean editable = getModel().isCellEditable(convertRowIndexToModel(row),
convertColumnIndexToModel(column));
if (editable) {
TableColumnExt tableColumn = getColumnExt(column);
if (tableColumn != null) {
editable = editable && tableColumn.isEditable();
}
}
return editable;
}
/**
* Overridden to update selectionMapper
*/
@Override
public void setSelectionModel(ListSelectionModel newModel) {
super.setSelectionModel(newModel);
getSelectionMapper().setViewSelectionModel(getSelectionModel());
}
/**
* {@inheritDoc}
*/
@Override
public void setModel(TableModel newModel) {
// JW: need to look here? is done in tableChanged as well.
getSelectionMapper().lock();
super.setModel(newModel);
}
/**
* additionally updates filtered state.
* {@inheritDoc}
*/
@Override
public void tableChanged(TableModelEvent e) {
if (getSelectionModel().getValueIsAdjusting()) {
// this may happen if the uidelegate/editor changed selection
// and adjusting state
// before firing a editingStopped
// need to enforce update of model selection
getSelectionModel().setValueIsAdjusting(false);
}
// JW: make SelectionMapper deaf ... super doesn't know about row
// mapping and sets rowSelection in model coordinates
// causing complete confusion.
getSelectionMapper().lock();
super.tableChanged(e);
updateSelectionAndRowModel(e);
use(filters);
}
/**
* reset model selection coordinates in SelectionMapper after
* model events.
*
* @param e
*/
private void updateSelectionAndRowModel(TableModelEvent e) {
// JW: c&p from JTable
if (e.getType() == TableModelEvent.INSERT) {
int start = e.getFirstRow();
int end = e.getLastRow();
if (start < 0) {
start = 0;
}
if (end < 0) {
end = getModel().getRowCount() - 1;
}
// Adjust the selectionMapper to account for the new rows.
int length = end - start + 1;
getSelectionMapper().insertIndexInterval(start, length, true);
getRowModelMapper().insertIndexInterval(start, length, getRowHeight());
} else if (e.getType() == TableModelEvent.DELETE) {
int start = e.getFirstRow();
int end = e.getLastRow();
if (start < 0) {
start = 0;
}
if (end < 0) {
end = getModel().getRowCount() - 1;
}
int deletedCount = end - start + 1;
// Adjust the selectionMapper to account for the new rows
getSelectionMapper().removeIndexInterval(start, end);
getRowModelMapper().removeIndexInterval(start, deletedCount);
} else if (isDataChanged(e) || isStructureChanged(e)) {
// JW fixing part of #172 - trying to adjust lead/anchor to valid
// indices (at least in model coordinates) after super's default clearSelection
// in dataChanged/structureChanged.
hackLeadAnchor(e);
getSelectionMapper().clearModelSelection();
getRowModelMapper().clearModelSizes();
updateViewSizeSequence();
}
// nothing to do on TableEvent.updated
}
private boolean isDataChanged(TableModelEvent e) {
return e.getType() == TableModelEvent.UPDATE &&
e.getFirstRow() == 0 &&
e.getLastRow() == Integer.MAX_VALUE;
}
private boolean isStructureChanged(TableModelEvent e) {
return e == null || e.getFirstRow() == TableModelEvent.HEADER_ROW;
}
/**
* Trying to hack around #172-swingx: lead/anchor of row selection model
* is not adjusted to valid (not even model indices!) in the
* usual clearSelection after dataChanged/structureChanged.
*
* Note: as of jdk1.5U6 the anchor/lead of the view selectionModel is
* unconditionally set to -1 after data/structureChanged.
*
* @param e
*/
private void hackLeadAnchor(TableModelEvent e) {
int lead = getSelectionModel().getLeadSelectionIndex();
int anchor = getSelectionModel().getAnchorSelectionIndex();
int lastRow = getModel().getRowCount() - 1;
if ((lead > lastRow) || (anchor > lastRow)) {
lead = anchor = lastRow;
getSelectionModel().setAnchorSelectionIndex(lead);
getSelectionModel().setLeadSelectionIndex(lead);
}
}
/**
* Called if individual row height mapping need to be updated.
* This implementation guards against unnessary access of
* super's private rowModel field.
*/
protected void updateViewSizeSequence() {
SizeSequence sizeSequence = null;
if (isRowHeightEnabled()) {
sizeSequence = getSuperRowModel();
}
getRowModelMapper().setViewSizeSequence(sizeSequence, getRowHeight());
}
/**
* temporaryly exposed for testing...
* @return <code>SelectionMapper</code>
*/
protected SelectionMapper getSelectionMapper() {
if (selectionMapper == null) {
selectionMapper = new SelectionMapper(filters, getSelectionModel());
}
return selectionMapper;
}
/** Returns the FilterPipeline for the table. */
public FilterPipeline getFilters() {
// PENDING: this is guaranteed to be != null because
// init calls setFilters(null) which enforces an empty
// pipeline
return filters;
}
/**
* setModel() and setFilters() may be called in either order.
*
* @param pipeline
*/
private void use(FilterPipeline pipeline) {
if (pipeline != null) {
// check JW: adding listener multiple times (after setModel)?
if (initialUse(pipeline)) {
pipeline.addPipelineListener(getFilterPipelineListener());
pipeline.assign(getComponentAdapter());
} else {
pipeline.flush();
}
}
}
/**
* @return true is not yet used in this JXTable, false otherwise
*/
private boolean initialUse(FilterPipeline pipeline) {
if (pipelineListener == null) return true;
PipelineListener[] l = pipeline.getPipelineListeners();
for (int i = 0; i < l.length; i++) {
if (pipelineListener.equals(l[i]))
return false;
}
return true;
}
/**
* Sets the FilterPipeline for filtering table rows, maybe null
* to remove all previously applied filters.
*
* Note: the current "interactive" sortState is preserved (by
* internally copying the old sortKeys to the new pipeline, if any).
*
* @param pipeline the <code>FilterPipeline</code> to use, null removes
* all filters.
*/
public void setFilters(FilterPipeline pipeline) {
FilterPipeline old = getFilters();
List<? extends SortKey> sortKeys = null;
if (old != null) {
old.removePipelineListener(pipelineListener);
sortKeys = old.getSortController().getSortKeys();
}
if (pipeline == null) {
pipeline = new FilterPipeline();
}
filters = pipeline;
filters.getSortController().setSortKeys(sortKeys);
// #173-swingx
use(filters);
getRowModelMapper().setFilters(filters);
getSelectionMapper().setFilters(filters);
}
/** returns the listener for changes in filters. */
protected PipelineListener getFilterPipelineListener() {
if (pipelineListener == null) {
pipelineListener = createPipelineListener();
}
return pipelineListener;
}
/** creates the listener for changes in filters. */
protected PipelineListener createPipelineListener() {
PipelineListener l = new PipelineListener() {
public void contentsChanged(PipelineEvent e) {
updateOnFilterContentChanged();
}
};
return l;
}
/**
* method called on change notification from filterpipeline.
*/
protected void updateOnFilterContentChanged() {
revalidate();
repaint();
}
/**
* Sets "sortable" property indicating whether or not this table
* supports sortable columns. If <code>sortable</code> is
* <code>true</code> then sorting will be enabled on all columns whose
* <code>sortable</code> property is <code>true</code>. If
* <code>sortable</code> is <code>false</code> then sorting will be
* disabled for all columns, regardless of each column's individual
* <code>sorting</code> property. The default is <code>true</code>.
*
* @see TableColumnExt#isSortable()
* @param sortable
* boolean indicating whether or not this table supports sortable
* columns
*/
public void setSortable(boolean sortable) {
if (sortable == isSortable())
return;
this.sortable = sortable;
if (!isSortable()) resetSortOrder();
firePropertyChange("sortable", !sortable, sortable);
}
/**
* Returns the table's sortable property.
*
* @return true if the table is sortable.
*/
public boolean isSortable() {
return sortable;
}
/**
* Removes the interactive sorter.
* Used by headerListener.
*
*/
public void resetSortOrder() {
// JW PENDING: think about notification instead of manual repaint.
SortController controller = getSortController();
if (controller != null) {
controller.setSortKeys(null);
}
if (getTableHeader() != null) {
getTableHeader().repaint();
}
}
/**
*
* Toggles the sort order of the column at columnIndex.
* <p>
* The exact behaviour is defined by the SortController's
* toggleSortOrder implementation. Typically a unsorted
* column is sorted in ascending order, a sorted column's
* order is reversed.
* <p>
* Respects the tableColumnExt's sortable and comparator
* properties: routes the column's comparator to the SortController
* and does nothing if !isSortable(column).
* <p>
*
* PRE: 0 <= columnIndex < getColumnCount()
*
* @param columnIndex the columnIndex in view coordinates.
*
*/
public void toggleSortOrder(int columnIndex) {
if (!isSortable(columnIndex))
return;
SortController controller = getSortController();
if (controller != null) {
TableColumnExt columnExt = getColumnExt(columnIndex);
controller.toggleSortOrder(convertColumnIndexToModel(columnIndex),
columnExt != null ? columnExt.getComparator() : null);
}
}
/**
* Decides if the column at columnIndex can be interactively sorted.
* <p>
* Here: true if both this table and the column sortable property is
* enabled, false otherwise.
*
* @param columnIndex column in view coordinates
* @return boolean indicating whether or not the column is sortable
* in this table.
*/
protected boolean isSortable(int columnIndex) {
boolean sortable = isSortable();
TableColumnExt tableColumnExt = getColumnExt(columnIndex);
if (tableColumnExt != null) {
sortable = sortable && tableColumnExt.isSortable();
}
return sortable;
}
/**
* Sorts the table by the given column using SortOrder.
*
*
* Respects the tableColumnExt's sortable and comparator
* properties: routes the column's comparator to the SortController
* and does nothing if !isSortable(column).
* <p>
*
* PRE: 0 <= columnIndex < getColumnCount()
* <p>
*
*
* @param columnIndex the column index in view coordinates.
* @param sortOrder the sort order to use. If null or SortOrder.UNSORTED,
* this method has the same effect as resetSortOrder();
*
*/
public void setSortOrder(int columnIndex, SortOrder sortOrder) {
if ((sortOrder == null) || !sortOrder.isSorted()) {
resetSortOrder();
return;
}
if (!isSortable(columnIndex)) return;
SortController sortController = getSortController();
if (sortController != null) {
TableColumnExt columnExt = getColumnExt(columnIndex);
SortKey sortKey = new SortKey(sortOrder,
convertColumnIndexToModel(columnIndex),
columnExt != null ? columnExt.getComparator() : null);
sortController.setSortKeys(Collections.singletonList(sortKey));
}
}
/**
* Returns the SortOrder of the given column.
*
* @param columnIndex the column index in view coordinates.
* @return the interactive sorter's SortOrder if matches the column
* or SortOrder.UNSORTED
*/
public SortOrder getSortOrder(int columnIndex) {
SortController sortController = getSortController();
if (sortController == null) return SortOrder.UNSORTED;
SortKey sortKey = SortKey.getFirstSortKeyForColumn(sortController.getSortKeys(),
convertColumnIndexToModel(columnIndex));
return sortKey != null ? sortKey.getSortOrder() : SortOrder.UNSORTED;
}
/**
*
* Toggles the sort order of the column with identifier.
* <p>
* The exact behaviour is defined by the SortController's
* toggleSortOrder implementation. Typically a unsorted
* column is sorted in ascending order, a sorted column's
* order is reversed.
* <p>
* Respects the tableColumnExt's sortable and comparator
* properties: routes the column's comparator to the SortController
* and does nothing if !isSortable(column).
* <p>
*
* PENDING: JW - define the behaviour if the identifier is not found.
* This can happen if either there's no column at all with the identifier
* or if there's no column of type TableColumnExt.
* Currently does nothing, that is does not change sort state.
*
* @param identifier the column identifier.
*
*/
public void toggleSortOrder(Object identifier) {
if (!isSortable(identifier))
return;
SortController controller = getSortController();
if (controller != null) {
TableColumnExt columnExt = getColumnExt(identifier);
if (columnExt == null) return;
controller.toggleSortOrder(columnExt.getModelIndex(),
columnExt.getComparator());
}
}
/**
* Sorts the table by the given column using the SortOrder.
*
*
* Respects the tableColumnExt's sortable and comparator
* properties: routes the column's comparator to the SortController
* and does nothing if !isSortable(column).
* <p>
*
* PENDING: JW - define the behaviour if the identifier is not found.
* This can happen if either there's no column at all with the identifier
* or if there's no column of type TableColumnExt.
* Currently does nothing, that is does not change sort state.
*
* @param identifier the column's identifier.
* @param sortOrder the sort order to use. If null or SortOrder.UNSORTED,
* this method has the same effect as resetSortOrder();
*
*/
public void setSortOrder(Object identifier, SortOrder sortOrder) {
if ((sortOrder == null) || !sortOrder.isSorted()) {
resetSortOrder();
return;
}
if (!isSortable(identifier)) return;
SortController sortController = getSortController();
if (sortController != null) {
TableColumnExt columnExt = getColumnExt(identifier);
if (columnExt == null) return;
SortKey sortKey = new SortKey(sortOrder,
columnExt.getModelIndex(),
columnExt.getComparator());
sortController.setSortKeys(Collections.singletonList(sortKey));
}
}
/**
* Returns the SortOrder of the given column.
*
* PENDING: JW - define the behaviour if the identifier is not found.
* This can happen if either there's no column at all with the identifier
* or if there's no column of type TableColumnExt.
* Currently returns SortOrder.UNSORTED.
*
* @param identifier the column's identifier.
* @return the interactive sorter's SortOrder if matches the column
* or SortOrder.UNSORTED
*/
public SortOrder getSortOrder(Object identifier) {
SortController sortController = getSortController();
if (sortController == null) return SortOrder.UNSORTED;
TableColumnExt columnExt = getColumnExt(identifier);
if (columnExt == null) return SortOrder.UNSORTED;
int modelIndex = columnExt.getModelIndex();
SortKey sortKey = SortKey.getFirstSortKeyForColumn(sortController.getSortKeys(),
modelIndex);
return sortKey != null ? sortKey.getSortOrder() : SortOrder.UNSORTED;
}
/**
* Decides if the column with identifier can be interactively sorted.
* <p>
* Here: true if both this table and the column sortable property is
* enabled, false otherwise.
*
* @param identifier the column's identifier
* @return boolean indicating whether or not the column is sortable
* in this table.
*/
protected boolean isSortable(Object identifier) {
boolean sortable = isSortable();
TableColumnExt tableColumnExt = getColumnExt(identifier);
if (tableColumnExt != null) {
sortable = sortable && tableColumnExt.isSortable();
}
return sortable;
}
/**
* returns the currently active SortController. Can be null
* on the very first call after instantiation.
* @return the currently active <code>SortController</code> may be null
*/
protected SortController getSortController() {
// // this check is for the sake of the very first call after instantiation
if (filters == null) return null;
return getFilters().getSortController();
}
/**
*
* @return the currently interactively sorted TableColumn or null
* if there is not sorter active or if the sorted column index
* does not correspond to any column in the TableColumnModel.
*/
public TableColumn getSortedColumn() {
// bloody hack: get primary SortKey and
// check if there's a column with it available
SortController controller = getSortController();
if (controller != null) {
SortKey sortKey = SortKey.getFirstSortingKey(controller.getSortKeys());
if (sortKey != null) {
int sorterColumn = sortKey.getColumn();
List<TableColumn> columns = getColumns(true);
for (Iterator<TableColumn> iter = columns.iterator(); iter.hasNext();) {
TableColumn column = iter.next();
if (column.getModelIndex() == sorterColumn) {
return column;
}
}
}
}
return null;
}
/**
* overridden to remove the interactive sorter if the
* sorted column is no longer contained in the ColumnModel.
*/
@Override
public void columnRemoved(TableColumnModelEvent e) {
// JW - old problem: need access to removed column
// to get hold of removed modelIndex
// to remove interactive sorter if any
// no way
// int modelIndex = convertColumnIndexToModel(e.getFromIndex());
updateSorterAfterColumnRemoved();
super.columnRemoved(e);
}
/**
* guarantee that the interactive sorter is removed if its column
* is removed.
*
*/
private void updateSorterAfterColumnRemoved() {
TableColumn sortedColumn = getSortedColumn();
if (sortedColumn == null) {
resetSortOrder();
}
}
/**
* Remove all columns, make sure to include hidden.
*
*/
protected void removeColumns() {
/**
* TODO: promote this method to superclass, and change
* createDefaultColumnsFromModel() to call this method
*/
List<TableColumn> columns = getColumns(true);
for (Iterator<TableColumn> iter = columns.iterator(); iter.hasNext();) {
getColumnModel().removeColumn(iter.next());
}
}
/**
* returns a list of all visible TableColumns.
*
* @return list of all the visible <code>TableColumns</code>
*/
public List<TableColumn> getColumns() {
return Collections.list(getColumnModel().getColumns());
}
/**
* returns a list of TableColumns including hidden if the parameter is set
* to true.
*
* @param includeHidden
* @return list of <code>TableColumns</code> including hidden columns if
* specified
*/
public List<TableColumn> getColumns(boolean includeHidden) {
if (getColumnModel() instanceof TableColumnModelExt) {
return ((TableColumnModelExt) getColumnModel())
.getColumns(includeHidden);
}
return getColumns();
}
/**
* returns the number of TableColumns including hidden if the parameter is set
* to true.
*
* @param includeHidden
* @return number of <code>TableColumns</code> including hidden columns
* if specified
*/
public int getColumnCount(boolean includeHidden) {
if (getColumnModel() instanceof TableColumnModelExt) {
return ((TableColumnModelExt) getColumnModel())
.getColumnCount(includeHidden);
}
return getColumnCount();
}
/**
* reorders the columns in the sequence given array. Logical names that do
* not correspond to any column in the model will be ignored. Columns with
* logical names not contained are added at the end.
*
* @param identifiers
* array of logical column names
*/
public void setColumnSequence(Object[] identifiers) {
List columns = getColumns(true);
Map map = new HashMap();
for (Iterator iter = columns.iterator(); iter.hasNext();) {
// PENDING: handle duplicate identifiers ...
TableColumn column = (TableColumn) iter.next();
map.put(column.getIdentifier(), column);
getColumnModel().removeColumn(column);
}
for (int i = 0; i < identifiers.length; i++) {
TableColumn column = (TableColumn) map.get(identifiers[i]);
if (column != null) {
getColumnModel().addColumn(column);
columns.remove(column);
}
}
for (Iterator iter = columns.iterator(); iter.hasNext();) {
TableColumn column = (TableColumn) iter.next();
getColumnModel().addColumn(column);
}
}
/**
* Returns the <code>TableColumnExt</code> object for the column in the
* table whose identifier is equal to <code>identifier</code>, when
* compared using <code>equals</code>. The returned TableColumn is
* guaranteed to be part of the current ColumnModel but may be hidden, that
* is
*
* <pre> <code>
* TableColumnExt column = table.getColumnExt(id);
* if (column != null) {
* int viewIndex = table.convertColumnIndexToView(column.getModelIndex());
* assertEquals(column.isVisible(), viewIndex >= 0);
* }
* </code> </pre>
*
* @param identifier
* the identifier object
*
* @return the <code>TableColumnExt</code> object that matches the
* identifier or null if none is found.
*/
public TableColumnExt getColumnExt(Object identifier) {
if (getColumnModel() instanceof TableColumnModelExt) {
return ((TableColumnModelExt) getColumnModel())
.getColumnExt(identifier);
} else {
// PENDING: not tested!
try {
TableColumn column = getColumn(identifier);
if (column instanceof TableColumnExt) {
return (TableColumnExt) column;
}
} catch (Exception e) {
// TODO: handle exception
}
}
return null;
}
/**
* Returns the <code>TableColumnExt</code> object for the column in the
* table whose column index is equal to <code>viewColumnIndex</code> or
* null if the column is not of type <code>TableColumnExt</code>
*
* @param viewColumnIndex
* index of the column with the object in question
*
* @return the <code>TableColumnExt</code> object that matches the column
* index
* @throws ArrayIndexOutOfBoundsException if viewColumnIndex out of allowed range.
*/
public TableColumnExt getColumnExt(int viewColumnIndex) {
TableColumn column = getColumn(viewColumnIndex);
if (column instanceof TableColumnExt) {
return (TableColumnExt) column;
}
return null;
}
public TableColumn getColumn(int viewColumnIndex) {
return getColumnModel().getColumn(viewColumnIndex);
}
@Override
public void createDefaultColumnsFromModel() {
TableModel model = getModel();
if (model != null) {
// Create new columns from the data model info
// Note: it's critical to create the new columns before
// deleting the old ones. Why?
// JW PENDING: the reason is somewhere in the early forums - search!
int modelColumnCount = model.getColumnCount();
TableColumn newColumns[] = new TableColumn[modelColumnCount];
for (int i = 0; i < newColumns.length; i++) {
newColumns[i] = createAndConfigureColumn(model, i);
}
// Remove any current columns
removeColumns();
// Now add the new columns to the column model
for (int i = 0; i < newColumns.length; i++) {
addColumn(newColumns[i]);
}
}
expandToViewportWidth();
}
protected TableColumn createAndConfigureColumn(TableModel model,
int modelColumn) {
return getColumnFactory().createAndConfigureTableColumn(model,
modelColumn);
}
/**
*
* @see #setColumnFactory(ColumnFactory)
* @return the columnFactory to use for column creation and
* configuration.
*/
protected ColumnFactory getColumnFactory() {
/*
* TODO JW: think about implications of not/ copying the reference
* to the shared instance into the table's field? Better
* access the getInstance() on each call? We are on single thread
* anyway...
* Furthermore, we don't expect the instance to change often, typically
* it is configured on startup. So we don't really have to worry about
* changes which would destabilize column state?
*/
if (columnFactory == null) {
return ColumnFactory.getInstance();
// columnFactory = ColumnFactory.getInstance();
}
return columnFactory;
}
/**
* Set's the ColumnFactory to use for column creation and
* configuration. The default value is the shared application
* ColumnFactory.
*
* TODO auto-configure columns on set? or add public table api to
* do so? Mostly, this is meant to be done once in the lifetime
* of the table, preferably before a model is set ... overshoot?
*
* @param columnFactory the factory to use, null indicates
* to use the shared application ColumnFactory.
*/
public void setColumnFactory(ColumnFactory columnFactory) {
ColumnFactory old = getColumnFactory();
this.columnFactory = columnFactory;
firePropertyChange("columnFactory", old, getColumnFactory());
}
/**
* Returns the margin between columns.
*
* @return the margin between columns
*/
public int getColumnMargin() {
return getColumnModel().getColumnMargin();
}
/**
* Sets the margin between columns.
*
* @param value
* margin between columns; must be greater than or equal to zero.
*/
public void setColumnMargin(int value) {
getColumnModel().setColumnMargin(value);
}
/**
* Returns the selection mode used by this table's selection model.
*
* @return the selection mode used by this table's selection model
*/
public int getSelectionMode() {
return getSelectionModel().getSelectionMode();
}
/** Opens the find widget for the table. */
private void find() {
SearchFactory.getInstance().showFindInput(this, getSearchable());
}
/**
*
* @return a not-null Searchable for this editor.
*/
public Searchable getSearchable() {
if (searchable == null) {
searchable = new TableSearchable();
}
return searchable;
}
/**
* sets the Searchable for this editor. If null, a default
* searchable will be used.
*
* @param searchable
*/
public void setSearchable(Searchable searchable) {
this.searchable = searchable;
}
public class TableSearchable extends AbstractSearchable {
private SearchHighlighter searchHighlighter;
protected void findMatchAndUpdateState(Pattern pattern, int startRow,
boolean backwards) {
SearchResult matchRow = null;
if (backwards) {
// CHECK: off-one end still needed?
// Probably not - the findXX don't have side-effects any longer
// hmmm... still needed: even without side-effects we need to
// guarantee calling the notfound update at the very end of the
// loop.
for (int r = startRow; r >= -1 && matchRow == null; r
matchRow = findMatchBackwardsInRow(pattern, r);
updateState(matchRow);
}
} else {
for (int r = startRow; r <= getSize() && matchRow == null; r++) {
matchRow = findMatchForwardInRow(pattern, r);
updateState(matchRow);
}
}
// KEEP - JW: Needed to update if loop wasn't entered!
// the alternative is to go one off in the loop. Hmm - which is
// preferable?
// updateState(matchRow);
}
/**
* called if sameRowIndex && !hasEqualRegEx. Matches the cell at
* row/lastFoundColumn against the pattern. PRE: lastFoundColumn valid.
*
* @param pattern
* @param row
* @return an appropriate <code>SearchResult</code> if matching or null
*/
protected SearchResult findExtendedMatch(Pattern pattern, int row) {
return findMatchAt(pattern, row, lastSearchResult.foundColumn);
}
/**
* Searches forward through columns of the given row. Starts at
* lastFoundColumn or first column if lastFoundColumn < 0. returns an
* appropriate SearchResult if a matching cell is found in this row or
* null if no match is found. A row index out off range results in a
* no-match.
*
* @param pattern
* @param row
* the row to search
* @return an appropriate <code>SearchResult</code> if a matching cell
* is found in this row or null if no match is found
*/
private SearchResult findMatchForwardInRow(Pattern pattern, int row) {
int startColumn = (lastSearchResult.foundColumn < 0) ? 0 : lastSearchResult.foundColumn;
if (isValidIndex(row)) {
for (int column = startColumn; column < getColumnCount(); column++) {
SearchResult result = findMatchAt(pattern, row, column);
if (result != null)
return result;
}
}
return null;
}
/**
* Searches forward through columns of the given row. Starts at
* lastFoundColumn or first column if lastFoundColumn < 0. returns an
* appropriate SearchResult if a matching cell is found in this row or
* null if no match is found. A row index out off range results in a
* no-match.
*
* @param pattern
* @param row
* the row to search
* @return an appropriate <code>SearchResult</code> if a matching cell is found
* in this row or null if no match is found
*/
private SearchResult findMatchBackwardsInRow(Pattern pattern, int row) {
int startColumn = (lastSearchResult.foundColumn < 0) ? getColumnCount() - 1
: lastSearchResult.foundColumn;
if (isValidIndex(row)) {
for (int column = startColumn; column >= 0; column
SearchResult result = findMatchAt(pattern, row, column);
if (result != null)
return result;
}
}
return null;
}
/**
* Matches the cell content at row/col against the given Pattern.
* Returns an appropriate SearchResult if matching or null if no
* matching
*
* @param pattern
* @param row
* a valid row index in view coordinates
* @param column
* a valid column index in view coordinates
* @return an appropriate <code>SearchResult</code> if matching or null
*/
protected SearchResult findMatchAt(Pattern pattern, int row, int column) {
Object value = getValueAt(row, column);
if (value != null) {
Matcher matcher = pattern.matcher(value.toString());
if (matcher.find()) {
return createSearchResult(matcher, row, column);
}
}
return null;
}
/**
* Called if startIndex is different from last search, reset the column
* to -1 and make sure a backwards/forwards search starts at last/first
* row, respectively.
*
* @param startIndex
* @param backwards
* @return adjusted <code>startIndex</code>
*/
@Override
protected int adjustStartPosition(int startIndex, boolean backwards) {
lastSearchResult.foundColumn = -1;
return super.adjustStartPosition(startIndex, backwards);
}
/**
* Moves the internal start for matching as appropriate and returns the
* new startIndex to use. Called if search was messaged with the same
* startIndex as previously.
*
* @param startRow
* @param backwards
* @return new start index to use
*/
@Override
protected int moveStartPosition(int startRow, boolean backwards) {
if (backwards) {
lastSearchResult.foundColumn
if (lastSearchResult.foundColumn < 0) {
startRow
}
} else {
lastSearchResult.foundColumn++;
if (lastSearchResult.foundColumn >= getColumnCount()) {
lastSearchResult.foundColumn = -1;
startRow++;
}
}
return startRow;
}
/**
* Checks if the startIndex is a candidate for trying a re-match.
*
*
* @param startIndex
* @return true if the startIndex should be re-matched, false if not.
*/
@Override
protected boolean isEqualStartIndex(final int startIndex) {
return super.isEqualStartIndex(startIndex)
&& isValidColumn(lastSearchResult.foundColumn);
}
/**
* checks if row is in range: 0 <= row < getRowCount().
*
* @param column
* @return true if the column is in range, false otherwise
*/
private boolean isValidColumn(int column) {
return column >= 0 && column < getColumnCount();
}
protected int getSize() {
return getRowCount();
}
protected void moveMatchMarker() {
int row = lastSearchResult.foundRow;
int column = lastSearchResult.foundColumn;
Pattern pattern = lastSearchResult.pattern;
if ((row < 0) || (column < 0)) {
if (markByHighlighter()) {
getSearchHighlighter().setPattern(null);
}
return;
}
if (markByHighlighter()) {
Rectangle cellRect = getCellRect(row, column, true);
if (cellRect != null) {
scrollRectToVisible(cellRect);
}
ensureInsertedSearchHighlighters();
// TODO (JW) - cleanup SearchHighlighter state management
getSearchHighlighter().setPattern(pattern);
int modelColumn = convertColumnIndexToModel(column);
getSearchHighlighter().setHighlightCell(row, modelColumn);
} else { // use selection
changeSelection(row, column, false, false);
if (!getAutoscrolls()) {
// scrolling not handled by moving selection
Rectangle cellRect = getCellRect(row, column, true);
if (cellRect != null) {
scrollRectToVisible(cellRect);
}
}
}
}
private boolean markByHighlighter() {
return Boolean.TRUE.equals(getClientProperty(MATCH_HIGHLIGHTER));
}
private SearchHighlighter getSearchHighlighter() {
if (searchHighlighter == null) {
searchHighlighter = createSearchHighlighter();
}
return searchHighlighter;
}
private void ensureInsertedSearchHighlighters() {
if (getHighlighters() == null) {
setHighlighters(new HighlighterPipeline(
new Highlighter[] { getSearchHighlighter() }));
} else if (!isInPipeline(getSearchHighlighter())) {
getHighlighters().addHighlighter(getSearchHighlighter());
}
}
private boolean isInPipeline(PatternHighlighter searchHighlighter) {
Highlighter[] inPipeline = getHighlighters().getHighlighters();
if ((inPipeline.length > 0) &&
(searchHighlighter.equals(inPipeline[inPipeline.length -1]))) {
return true;
}
getHighlighters().removeHighlighter(searchHighlighter);
return false;
}
protected SearchHighlighter createSearchHighlighter() {
return new SearchHighlighter();
}
}
/**
* Scrolls vertically to make the given row visible.
* This might not have any effect if the table isn't contained
* in a JViewport. <p>
*
* Note: this method has no precondition as it internally uses
* getCellRect which is lenient to off-range coordinates.
*
* @param row the view row index of the cell
*/
public void scrollRowToVisible(int row) {
Rectangle cellRect = getCellRect(row, 0, false);
Rectangle visibleRect = getVisibleRect();
cellRect.x = visibleRect.x;
cellRect.width = visibleRect.width;
scrollRectToVisible(cellRect);
}
/**
* Scrolls horizontally to make the given column visible.
* This might not have any effect if the table isn't contained
* in a JViewport. <p>
*
* Note: this method has no precondition as it internally uses
* getCellRect which is lenient to off-range coordinates.
*
* @param column the view column index of the cell
*/
public void scrollColumnToVisible(int column) {
Rectangle cellRect = getCellRect(0, column, false);
Rectangle visibleRect = getVisibleRect();
cellRect.y = visibleRect.y;
cellRect.height = visibleRect.height;
scrollRectToVisible(cellRect);
}
/**
* Scrolls to make the cell at row and column visible.
* This might not have any effect if the table isn't contained
* in a JViewport.<p>
*
* Note: this method has no precondition as it internally uses
* getCellRect which is lenient to off-range coordinates.
*
* @param row the view row index of the cell
* @param column the view column index of the cell
*/
public void scrollCellToVisible(int row, int column) {
Rectangle cellRect = getCellRect(row, column, false);
scrollRectToVisible(cellRect);
}
public void setVisibleRowCount(int visibleRowCount) {
this.visibleRowCount = visibleRowCount;
}
public int getVisibleRowCount() {
return visibleRowCount;
}
@Override
public Dimension getPreferredScrollableViewportSize() {
Dimension prefSize = super.getPreferredScrollableViewportSize();
// JTable hardcodes this to 450 X 400, so we'll calculate it
// based on the preferred widths of the columns and the
// visibleRowCount property instead...
if (prefSize.getWidth() == 450 && prefSize.getHeight() == 400) {
TableColumnModel columnModel = getColumnModel();
int columnCount = columnModel.getColumnCount();
int w = 0;
for (int i = 0; i < columnCount; i++) {
TableColumn column = columnModel.getColumn(i);
initializeColumnPreferredWidth(column);
w += column.getPreferredWidth();
}
prefSize.width = w;
JTableHeader header = getTableHeader();
// remind(aim): height is still off...???
int rowCount = getVisibleRowCount();
prefSize.height = rowCount * getRowHeight()
+ (header != null ? header.getPreferredSize().height : 0);
setPreferredScrollableViewportSize(prefSize);
}
return prefSize;
}
/**
* Packs all the columns to their optimal size. Works best with auto
* resizing turned off.
*
* Contributed by M. Hillary (Issue #60)
*
* @param margin
* the margin to apply to each column.
*/
public void packTable(int margin) {
for (int c = 0; c < getColumnCount(); c++)
packColumn(c, margin, -1);
}
/**
* Packs an indivudal column in the table. Contributed by M. Hillary (Issue
* #60)
*
* @param column
* The Column index to pack in View Coordinates
* @param margin
* The Margin to apply to the column width.
*/
public void packColumn(int column, int margin) {
packColumn(column, margin, -1);
}
/**
* Packs an indivual column in the table to less than or equal to the
* maximum witdth. If maximun is -1 then the column is made as wide as it
* needs. Contributed by M. Hillary (Issue #60)
*
* @param column
* The Column index to pack in View Coordinates
* @param margin
* The margin to apply to the column
* @param max
* The maximum width the column can be resized to. -1 mean any
* size.
*/
public void packColumn(int column, int margin, int max) {
getColumnFactory().packColumn(this, getColumnExt(column), margin, max);
}
/**
* Initialize the preferredWidth of the specified column based on the
* column's prototypeValue property. If the column is not an instance of
* <code>TableColumnExt</code> or prototypeValue is <code>null</code>
* then the preferredWidth is left unmodified.
*
* @see org.jdesktop.swingx.table.TableColumnExt#setPrototypeValue
* @param column
* TableColumn object representing view column
*/
protected void initializeColumnPreferredWidth(TableColumn column) {
if (column instanceof TableColumnExt) {
getColumnFactory().configureColumnWidths(this,
(TableColumnExt) column);
}
}
/**
* @return the unconfigured ComponentAdapter.
*/
protected ComponentAdapter getComponentAdapter() {
if (dataAdapter == null) {
dataAdapter = new TableAdapter(this);
}
return dataAdapter;
}
/**
* Convenience to access a configured ComponentAdapter.
*
* @param row the row index in view coordinates.
* @param column the column index in view coordinates.
* @return the configured ComponentAdapter.
*/
protected ComponentAdapter getComponentAdapter(int row, int column) {
ComponentAdapter adapter = getComponentAdapter();
adapter.row = row;
adapter.column = column;
return adapter;
}
protected static class TableAdapter extends ComponentAdapter {
private final JXTable table;
/**
* Constructs a <code>TableDataAdapter</code> for the specified target
* component.
*
* @param component
* the target component
*/
public TableAdapter(JXTable component) {
super(component);
table = component;
}
/**
* Typesafe accessor for the target component.
*
* @return the target component as a {@link javax.swing.JTable}
*/
public JXTable getTable() {
return table;
}
public String getColumnName(int columnIndex) {
TableColumn column = getColumnByModelIndex(columnIndex);
return column == null ? "" : column.getHeaderValue().toString();
}
protected TableColumn getColumnByModelIndex(int modelColumn) {
List columns = table.getColumns(true);
for (Iterator iter = columns.iterator(); iter.hasNext();) {
TableColumn column = (TableColumn) iter.next();
if (column.getModelIndex() == modelColumn) {
return column;
}
}
return null;
}
public String getColumnIdentifier(int columnIndex) {
TableColumn column = getColumnByModelIndex(columnIndex);
Object identifier = column != null ? column.getIdentifier() : null;
return identifier != null ? identifier.toString() : null;
}
@Override
public int getColumnCount() {
return table.getModel().getColumnCount();
}
@Override
public int getRowCount() {
return table.getModel().getRowCount();
}
/**
* {@inheritDoc}
*/
public Object getValueAt(int row, int column) {
return table.getModel().getValueAt(row, column);
}
public void setValueAt(Object aValue, int row, int column) {
table.getModel().setValueAt(aValue, row, column);
}
public boolean isCellEditable(int row, int column) {
return table.getModel().isCellEditable(row, column);
}
@Override
public boolean isTestable(int column) {
return getColumnByModelIndex(column) != null;
}
public Object getFilteredValueAt(int row, int column) {
return getValueAt(table.convertRowIndexToModel(row), column);
// return table.getValueAt(row, modelToView(column)); // in view coordinates
}
/**
* {@inheritDoc}
*/
public boolean isSelected() {
return table.isCellSelected(row, column);
}
/**
* {@inheritDoc}
*/
public boolean hasFocus() {
boolean rowIsLead = (table.getSelectionModel()
.getLeadSelectionIndex() == row);
boolean colIsLead = (table.getColumnModel().getSelectionModel()
.getLeadSelectionIndex() == column);
return table.isFocusOwner() && (rowIsLead && colIsLead);
}
/**
* {@inheritDoc}
*/
@Override
public int modelToView(int columnIndex) {
return table.convertColumnIndexToView(columnIndex);
}
/**
* {@inheritDoc}
*/
@Override
public int viewToModel(int columnIndex) {
return table.convertColumnIndexToModel(columnIndex);
}
}
/** Returns the HighlighterPipeline assigned to the table, null if none. */
public HighlighterPipeline getHighlighters() {
return highlighters;
}
/**
* Assigns a HighlighterPipeline to the table, maybe null to
* remove all Highlighters. bound property.
*
* @param pipeline the HighlighterPipeline to use for renderer
* decoration.
*/
public void setHighlighters(HighlighterPipeline pipeline) {
HighlighterPipeline old = getHighlighters();
if (old != null) {
old.removeChangeListener(getHighlighterChangeListener());
}
highlighters = pipeline;
if (highlighters != null) {
highlighters.addChangeListener(getHighlighterChangeListener());
}
firePropertyChange("highlighters", old, getHighlighters());
repaint();
}
/**
* Adds a Highlighter.
*
* If the HighlighterPipeline returned from getHighlighters() is null, creates
* and sets a new pipeline containing the given Highlighter. Else, appends
* the Highlighter to the end of the pipeline.
*
* @param highlighter the Highlighter to add - must not be null.
* @throws NullPointerException if highlighter is null.
*/
public void addHighlighter(Highlighter highlighter) {
HighlighterPipeline pipeline = getHighlighters();
if (pipeline == null) {
setHighlighters(new HighlighterPipeline(new Highlighter[] {highlighter}));
} else {
pipeline.addHighlighter(highlighter);
}
}
/**
* Removes the Highlighter.
*
* Does nothing if the HighlighterPipeline is null or does not contain
* the given Highlighter.
*
* @param highlighter the highlighter to remove.
*/
public void removeHighlighter(Highlighter highlighter) {
if ((getHighlighters() == null)) return;
getHighlighters().removeHighlighter(highlighter);
}
/**
* returns the ChangeListener to use with highlighters. Creates one if
* necessary.
*
* @return != null
*/
protected ChangeListener getHighlighterChangeListener() {
if (highlighterChangeListener == null) {
highlighterChangeListener = new ChangeListener() {
public void stateChanged(ChangeEvent e) {
repaint();
}
};
}
return highlighterChangeListener;
}
public Component prepareRenderer(TableCellRenderer renderer, int row,
int column) {
Component stamp = super.prepareRenderer(renderer, row, column);
// #145-swingx: default renderers don't respect componentOrientation.
adjustComponentOrientation(stamp);
// #258-swingx: hacking around DefaultTableCellRenderer color memory.
resetDefaultTableCellRendererColors(stamp, row, column);
if (highlighters == null) {
return stamp; // no need to decorate renderer with highlighters
} else {
return highlighters.apply(stamp, getComponentAdapter(row, column));
}
}
/**
* Method to hack around #258-swingx: apply a specialized Highlighter
* to force reset the color "memory" of DefaultTableCellRenderer.
* This is called for each renderer in {@link #prepareRenderer} after
* calling super, but before applying the HighlighterPipeline. Subclasses
* which are sure to solve the problem at the core (that is in
* a well-behaved DefaultTableCellRenderer) should override this method
* to do nothing.
*
* @param renderer the <code>TableCellRenderer</code> to hack
* @param row the row of the cell to render
* @param column the column index of the cell to render
*/
protected void resetDefaultTableCellRendererColors(Component renderer, int row, int column) {
ComponentAdapter adapter = getComponentAdapter(row, column);
if (resetDefaultTableCellRendererHighlighter == null) {
resetDefaultTableCellRendererHighlighter = new ResetDTCRColorHighlighter();
}
// hacking around DefaultTableCellRenderer color memory.
resetDefaultTableCellRendererHighlighter.highlight(renderer, adapter);
}
/**
* Overridden to adjust the editor's component orientation if
* appropriate.
*/
@Override
public Component prepareEditor(TableCellEditor editor, int row, int column) {
Component comp = super.prepareEditor(editor, row, column);
adjustComponentOrientation(comp);
return comp;
}
/**
* adjusts the Component's orientation to JXTable's CO if appropriate.
* Here: always.
*
* @param stamp
*/
protected void adjustComponentOrientation(Component stamp) {
if (stamp.getComponentOrientation().equals(getComponentOrientation())) return;
stamp.applyComponentOrientation(getComponentOrientation());
}
/**
* Returns a new instance of the default renderer for the specified class.
* This differs from <code>getDefaultRenderer()</code> in that it returns
* a <b>new </b> instance each time so that the renderer may be set and
* customized on a particular column.
*
* PENDING: must not return null!
*
* @param columnClass
* Class of value being rendered
* @return TableCellRenderer instance which renders values of the specified
* type
*/
public TableCellRenderer getNewDefaultRenderer(Class columnClass) {
TableCellRenderer renderer = getDefaultRenderer(columnClass);
if (renderer != null) {
try {
return (TableCellRenderer) renderer.getClass().newInstance();
} catch (Exception e) {
LOG.fine("could not create renderer for " + columnClass);
}
}
return null;
}
/**
* Creates default cell renderers for objects, numbers, doubles, dates,
* booleans, icons, and links.
* THINK: delegate to TableCellRenderers?
* Overridden so we can act as factory for renderers plus hacking around
* huge memory consumption of UIDefaults (see #6345050 in core Bug parade)
*
*/
@Override
protected void createDefaultRenderers() {
// super.createDefaultRenderers();
// This duplicates JTable's functionality in order to make the renderers
// available in getNewDefaultRenderer(); If JTable's renderers either
// were public, or it provided a factory for *new* renderers, this would
// not be needed
// hack around #6345050 - new UIDefaults()
// is created with a huge initialCapacity
// giving a dummy key/value array as parameter reduces that capacity
// to length/2.
Object[] dummies = new Object[] {
1, 0,
2, 0,
3, 0,
4, 0,
5, 0,
6, 0,
7, 0,
8, 0,
9, 0,
10, 0,
};
defaultRenderersByColumnClass = new UIDefaults(dummies);
defaultRenderersByColumnClass.clear();
// defaultRenderersByColumnClass = new UIDefaults();
// Objects
setLazyRenderer(Object.class,
"javax.swing.table.DefaultTableCellRenderer");
// Numbers
setLazyRenderer(Number.class,
"org.jdesktop.swingx.JXTable$NumberRenderer");
// Doubles and Floats
setLazyRenderer(Float.class,
"org.jdesktop.swingx.JXTable$DoubleRenderer");
setLazyRenderer(Double.class,
"org.jdesktop.swingx.JXTable$DoubleRenderer");
// Dates
setLazyRenderer(Date.class, "org.jdesktop.swingx.JXTable$DateRenderer");
// Icons and ImageIcons
setLazyRenderer(Icon.class, "org.jdesktop.swingx.JXTable$IconRenderer");
setLazyRenderer(ImageIcon.class,
"org.jdesktop.swingx.JXTable$IconRenderer");
// Booleans
setLazyRenderer(Boolean.class,
"org.jdesktop.swingx.JXTable$BooleanRenderer");
// Other
// setLazyRenderer(LinkModel.class, "org.jdesktop.swingx.LinkRenderer");
}
private void setLazyValue(Hashtable h, Class c, String s) {
h.put(c, new UIDefaults.ProxyLazyValue(s));
}
private void setLazyRenderer(Class c, String s) {
setLazyValue(defaultRenderersByColumnClass, c, s);
}
private void setLazyEditor(Class c, String s) {
setLazyValue(defaultEditorsByColumnClass, c, s);
}
/*
* Default Type-based Renderers: JTable's default table cell renderer
* classes are private and JTable:getDefaultRenderer() returns a *shared*
* cell renderer instance, thus there is no way for us to instantiate a new
* instance of one of its default renderers. So, we must replicate the
* default renderer classes here so that we can instantiate them when we
* need to create renderers to be set on specific columns.
*/
public static class NumberRenderer extends DefaultTableCellRenderer {
public NumberRenderer() {
super();
setHorizontalAlignment(JLabel.TRAILING);
}
}
public static class DoubleRenderer extends NumberRenderer {
private final NumberFormat formatter;
public DoubleRenderer() {
this(null);
}
public DoubleRenderer(NumberFormat formatter) {
if (formatter == null) {
formatter = NumberFormat.getInstance();
}
this.formatter = formatter;
}
public void setValue(Object value) {
setText((value == null) ? "" : formatter.format(value));
}
}
public static class DateRenderer extends DefaultTableCellRenderer {
private final DateFormat formatter;
public DateRenderer() {
this(null);
}
public DateRenderer(DateFormat formatter) {
if (formatter == null) {
formatter = DateFormat.getDateInstance();
}
this.formatter = formatter;
}
public void setValue(Object value) {
setText((value == null) ? "" : formatter.format(value));
}
}
public static class IconRenderer extends DefaultTableCellRenderer {
public IconRenderer() {
super();
setHorizontalAlignment(JLabel.CENTER);
}
public void setValue(Object value) {
setIcon((value instanceof Icon) ? (Icon) value : null);
}
}
/*
* re- c&p'd from 1.5 JTable.
*/
public static class BooleanRenderer extends JCheckBox implements // , UIResource
TableCellRenderer {
private static final Border noFocusBorder = new EmptyBorder(1, 1, 1, 1);
public BooleanRenderer() {
super();
setHorizontalAlignment(JLabel.CENTER);
setBorderPainted(true);
}
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
if (isSelected) {
setForeground(table.getSelectionForeground());
super.setBackground(table.getSelectionBackground());
} else {
setForeground(table.getForeground());
setBackground(table.getBackground());
}
setSelected((value != null && ((Boolean) value).booleanValue()));
if (hasFocus) {
setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
} else {
setBorder(noFocusBorder);
}
return this;
}
}
/**
* Creates default cell editors for objects, numbers, and boolean values.
* Overridden to hacking around
* huge memory consumption of UIDefaults (see #6345050 in core Bug parade)
* @see DefaultCellEditor
*/
@Override
protected void createDefaultEditors() {
Object[] dummies = new Object[] {
1, 0,
2, 0,
3, 0,
4, 0,
5, 0,
6, 0,
7, 0,
8, 0,
9, 0,
10, 0,
};
defaultEditorsByColumnClass = new UIDefaults(dummies);
defaultEditorsByColumnClass.clear();
// defaultEditorsByColumnClass = new UIDefaults();
// Objects
setLazyEditor(Object.class, "org.jdesktop.swingx.JXTable$GenericEditor");
// Numbers
setLazyEditor(Number.class, "org.jdesktop.swingx.JXTable$NumberEditor");
// Booleans
setLazyEditor(Boolean.class, "org.jdesktop.swingx.JXTable$BooleanEditor");
// setLazyEditor(LinkModel.class, "org.jdesktop.swingx.LinkRenderer");
}
/**
* Default Editors
*/
public static class GenericEditor extends DefaultCellEditor {
Class[] argTypes = new Class[]{String.class};
java.lang.reflect.Constructor constructor;
Object value;
public GenericEditor() {
super(new JTextField());
getComponent().setName("Table.editor");
}
public boolean stopCellEditing() {
String s = (String)super.getCellEditorValue();
// Here we are dealing with the case where a user
// has deleted the string value in a cell, possibly
// after a failed validation. Return null, so that
// they have the option to replace the value with
// null or use escape to restore the original.
// For Strings, return "" for backward compatibility.
if ("".equals(s)) {
if (constructor.getDeclaringClass() == String.class) {
value = s;
}
super.stopCellEditing();
}
try {
value = constructor.newInstance(new Object[]{s});
}
catch (Exception e) {
((JComponent)getComponent()).setBorder(new LineBorder(Color.red));
return false;
}
return super.stopCellEditing();
}
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected,
int row, int column) {
this.value = null;
((JComponent)getComponent()).setBorder(new LineBorder(Color.black));
try {
Class type = table.getColumnClass(column);
// Since our obligation is to produce a value which is
// assignable for the required type it is OK to use the
// String constructor for columns which are declared
// to contain Objects. A String is an Object.
if (type == Object.class) {
type = String.class;
}
constructor = type.getConstructor(argTypes);
}
catch (Exception e) {
return null;
}
return super.getTableCellEditorComponent(table, value, isSelected, row, column);
}
public Object getCellEditorValue() {
return value;
}
}
public static class NumberEditor extends GenericEditor {
public NumberEditor() {
((JTextField)getComponent()).setHorizontalAlignment(JTextField.RIGHT);
}
}
public static class BooleanEditor extends DefaultCellEditor {
public BooleanEditor() {
super(new JCheckBox());
JCheckBox checkBox = (JCheckBox)getComponent();
checkBox.setHorizontalAlignment(JCheckBox.CENTER);
}
}
/**
* @return boolean to indicate if the table is editable.
*/
public boolean isEditable() {
return editable;
}
/**
* Sets the editable property. If false, all cells are not editable.
*
*
* @param editable the flag to indicate if the table is editable.
*/
public void setEditable(boolean editable) {
boolean old = isEditable();
this.editable = editable;
firePropertyChange("editable", old, isEditable());
}
/**
* @return boolean to indicate whether an ongoing edit should be terminated
* if the focus is moved to somewhere outside of the table.
* @see #setTerminateEditOnFocusLost(boolean)
*/
public boolean isTerminateEditOnFocusLost() {
return Boolean.TRUE.equals(getClientProperty("terminateEditOnFocusLost"));
}
/**
* Sets the property to determine whether an ongoing edit should be terminated
* if the focus is moved to somewhere outside of the table. If true, terminates
* the edit, does nothing otherwise. The exact behaviour is implemented in
* <code>JTable.CellEditorRemover</code>: "outside" is interpreted to be on a component
* which is not under the table hierarchy but inside the same toplevel window,
* "terminate" does so in any case, first tries to stop the edit, if that's unsuccess
* cancels the edit.
*
* The default value is true.
*
* @param terminate the flag to determine whether or not to terminate the edit
*/
public void setTerminateEditOnFocusLost(boolean terminate) {
// JW: we can leave the propertyChange notification to the
// putClientProperty - the key and method name are the same
putClientProperty("terminateEditOnFocusLost", terminate);
}
/**
*
* @return boolean to indicate whether a keyStroke should try to
* start editing.
* @see #setAutoStartEditOnKeyStroke(boolean)
*/
public boolean isAutoStartEditOnKeyStroke() {
return !Boolean.FALSE.equals(getClientProperty("JTable.autoStartsEdit"));
}
/**
* Sets the autoStartsEdit property. If true, keystrokes are passed-on to
* the cellEditor of the lead cell to let it decide whether to start an edit.
* <p>
* The default value is true.
*
* @param autoStart boolean to determine whether a keyStroke should
* try to start editing.
*/
public void setAutoStartEditOnKeyStroke(boolean autoStart) {
boolean old = isAutoStartEditOnKeyStroke();
// JW: we have to take over propertyChange notification
// because the key and method name are different.
// As a consequence, there are two events fired: one for
// the client prop and one for this method.
putClientProperty("JTable.autoStartsEdit", autoStart);
firePropertyChange("autoStartEditOnKeyStroke", old, isAutoStartEditOnKeyStroke());
}
/**
* bug fix: super doesn't update all renderers/editors.
*/
@Override
public void updateUI() {
super.updateUI();
if (columnControlButton != null) {
columnControlButton.updateUI();
}
for (Enumeration defaultEditors = defaultEditorsByColumnClass
.elements(); defaultEditors.hasMoreElements();) {
updateEditorUI(defaultEditors.nextElement());
}
for (Enumeration defaultRenderers = defaultRenderersByColumnClass
.elements(); defaultRenderers.hasMoreElements();) {
updateRendererUI(defaultRenderers.nextElement());
}
List columns = getColumns(true);
for (Iterator iter = columns.iterator(); iter.hasNext();) {
TableColumn column = (TableColumn) iter.next();
updateEditorUI(column.getCellEditor());
updateRendererUI(column.getCellRenderer());
updateRendererUI(column.getHeaderRenderer());
}
updateRowHeightUI(true);
updateHighlighters();
configureViewportBackground();
}
/**
* Updates highlighter after ui changes.
*
*/
protected void updateHighlighters() {
if (getHighlighters() == null) return;
getHighlighters().updateUI();
}
/**
* internal (unsucessful?) hack to try and set rowHeight to something more
* pleasing then the default. Tries to measure the font and/or ask the
* UIManager for a default value.
*
* The underlying problem is that raw types can't implement
* UIResource.
*/
private void updateRowHeightUI(boolean respectRowSetFlag) {
if (respectRowSetFlag && isXTableRowHeightSet)
return;
int minimumSize = getFont().getSize() + 6;
int uiSize = UIManager.getInt(UIPREFIX + "rowHeight");
setRowHeight(Math.max(minimumSize, uiSize != 0 ? uiSize : 18));
isXTableRowHeightSet = false;
}
/**
* Overriden to keep view/model coordinates of SizeSequence in synch.
* @inheritDoc
*/
public void setRowHeight(int rowHeight) {
super.setRowHeight(rowHeight);
if (rowHeight > 0) {
isXTableRowHeightSet = true;
}
updateViewSizeSequence();
}
/**
* Overriden to keep view/model coordinates of SizeSequence in synch.
* Does nothing #isRowHeightEnabled is false.
*
* @see #isRowHeightEnabled()
* @inheritDoc
*/
@Override
public void setRowHeight(int row, int rowHeight) {
if (!isRowHeightEnabled()) return;
super.setRowHeight(row, rowHeight);
updateViewSizeSequence();
resizeAndRepaint();
}
/**
* sets enabled state of individual rowHeight support. The default
* is false.
* Enabling the support envolves reflective access
* to super's private field rowModel which may fail due to security
* issues. If failing the support is not enabled.
*
* PENDING: should we throw an Exception if the enabled fails?
* Or silently fail - depends on runtime context,
* can't do anything about it.
*
* @param enabled a boolean to indicate whether per-row heights should
* be enabled.
*/
public void setRowHeightEnabled(boolean enabled) {
boolean old = isRowHeightEnabled();
if (old == enabled) return;
if (enabled && !canEnableRowHeight()) return;
rowHeightEnabled = enabled;
if (!enabled) {
adminSetRowHeight(getRowHeight());
}
firePropertyChange("rowHeightEnabled", old, rowHeightEnabled);
}
/**
*
* @return a boolean to indicate whether individual row height
* support is enabled.
* @see #isRowHeightEnabled()
*/
public boolean isRowHeightEnabled() {
return rowHeightEnabled;
}
private boolean canEnableRowHeight() {
return getRowModelField() != null;
}
private SizeSequence getSuperRowModel() {
try {
Field field = getRowModelField();
if (field != null) {
return (SizeSequence) field.get(this);
}
} catch (SecurityException e) {
LOG.fine("cannot use reflection " +
" - expected behaviour in sandbox");
} catch (IllegalArgumentException e) {
LOG.fine("problem while accessing super's private field - private api changed?");
} catch (IllegalAccessException e) {
LOG.fine("cannot access private field " +
" - expected behaviour in sandbox. " +
"Could be program logic running wild in unrestricted contexts");
}
return null;
}
/**
* @return <code>Field</code>
*/
private Field getRowModelField() {
if (rowModelField == null) {
try {
rowModelField = JTable.class.getDeclaredField("rowModel");
rowModelField.setAccessible(true);
} catch (SecurityException e) {
rowModelField = null;
LOG.fine("cannot access JTable private field rowModel " +
"- expected behaviour in sandbox");
} catch (NoSuchFieldException e) {
LOG.fine("problem while accessing super's private field" +
" - private api changed?");
}
}
return rowModelField;
}
/**
*
* @return <code>SizeSequenceMapper</code>
*/
protected SizeSequenceMapper getRowModelMapper() {
if (rowModelMapper == null) {
rowModelMapper = new SizeSequenceMapper(filters);
}
return rowModelMapper;
}
/**
* calling setRowHeight for internal reasons.
* Keeps the isXTableRowHeight unchanged.
*/
protected void adminSetRowHeight(int rowHeight) {
boolean heightSet = isXTableRowHeightSet;
setRowHeight(rowHeight);
isXTableRowHeightSet = heightSet;
}
private void updateEditorUI(Object value) {
// maybe null or proxyValue
if (!(value instanceof TableCellEditor))
return;
// super handled this
if ((value instanceof JComponent)
|| (value instanceof DefaultCellEditor))
return;
// custom editors might balk about fake rows/columns
try {
Component comp = ((TableCellEditor) value)
.getTableCellEditorComponent(this, null, false, -1, -1);
if (comp instanceof JComponent) {
((JComponent) comp).updateUI();
}
} catch (Exception e) {
// ignore - can't do anything
}
}
private void updateRendererUI(Object value) {
// maybe null or proxyValue
if (!(value instanceof TableCellRenderer))
return;
// super handled this
if (value instanceof JComponent)
return;
// custom editors might balk about fake rows/columns
try {
Component comp = ((TableCellRenderer) value)
.getTableCellRendererComponent(this, null, false, false,
-1, -1);
if (comp instanceof JComponent) {
((JComponent) comp).updateUI();
}
} catch (Exception e) {
// ignore - can't do anything
}
}
/**
* workaround bug in JTable. (Bug Parade ID #6291631 - negative y is mapped
* to row 0).
*/
public int rowAtPoint(Point point) {
if (point.y < 0)
return -1;
return super.rowAtPoint(point);
}
protected JTableHeader createDefaultTableHeader() {
return new JXTableHeader(columnModel);
}
protected TableColumnModel createDefaultColumnModel() {
return new DefaultTableColumnModelExt();
}
}
|
package fi.hu.cs.titokone;
import fi.hu.cs.ttk91.*;
import java.util.*;
/** This class represents the processor. It can be told to run for one
command cycle at a time. */
public class Processor implements TTK91Cpu {
private static final String INVALID_OPCODE_MESSAGE = "Invalid operation code";
private static final String ADDRESS_OUT_OF_BOUNDS_MESSAGE = "Memory address out of bounds";
private static final String BAD_ACCESS_MODE_MESSAGE = "Invalid memory addressing mode";
private static final String BRACNH_BAD_ACCESS_MODE_MESSAGE = "Invalid memory access mode in branching command";
private static final String STORE_BAD_ACCESS_MODE_MESSAGE = "Invalid memory access mode in STORE";
private static final String NO_KDB_DATA_MESSAGE = "No keyboard data available";
private static final String NO_STDIN_DATA_MESSAGE = "No standard input data available";
private static final String INVALID_DEVICE_MESSAGE = "Invalid device number";
private static final String INTEGER_OVERFLOW_MESSAGE = "Integer overflow";
private static final String DIVISION_BY_ZERO_MESSAGE = "Division by zero";
private static final int CRT = 0;
private static final int KBD = 1;
private static final int STDIN = 6;
private static final int STDOUT = 7;
/** This field represents the memory of computer. */
private RandomAccessMemory ram;
/** This field represents the registers of computer. */
private Registers regs;
/** Is program running. */
private int status = TTK91Cpu.STATUS_SVC_SD;
/** Rundebugger */
private RunDebugger runDebugger = new RunDebugger();
/**
state register array.
index:
0 - greater
1 - equal
2 - less
3 - arithmetic overflow
4 - divide by zero
5 - unknown instruction
6 - forbidden memory access
7 - device interrupt
8 - supervisor call
9 - priviledged mode
10 - interrupts disabled
*/
private boolean[] sr = new boolean[11];
/** The stdinData and kbdData fields stores buffer data to be read with
the IN operation. When the data has been read, the field should be
set to be null. */
private Integer stdinData=null, kbdData=null;
/** Creates new processor, memory and registers.
Processor state, program counter get initial values
@param memsize creates new computer with given size of memory.
Proper values are power of two (from 512 to 64k). */
public Processor(int memsize){
ram = new RandomAccessMemory (memsize);
regs = new Registers();
}
/** Returns the memory attached to the processor. */
public TTK91Memory getMemory() {
return ram;
}
/** Returns the value of given registerID. The index numbers
are available from the TTK91CPU interface.
@param registerID Identifying number of the register.
@return Value of given register. Inproper value returns -1. */
public int getValueOf(int registerID) {
return regs.getRegister (registerID);
}
/** Returns queried memory line.
@param row Number of the row in processor's memory.
@return Queried memory line. */
public MemoryLine getMemoryLine (int row) {
return ram.getMemoryLine (row);
}
/** Method returns the current value of Processor. Status values
are available from the TTK91CPU interface.
@return Current status of the Processor. */
public int getStatus() {
return status;
}
/** Method erases memorylines from memory. Memory will be filled
with 0-lines. */
public void eraseMemory() {
ram = new RandomAccessMemory (ram.getSize());
}
public void memoryInput(int rowNumber, MemoryLine inputLine)
throws TTK91AddressOutOfBounds {
try {
ram.setMemoryLine(rowNumber, inputLine);
} catch (ArrayIndexOutOfBoundsException e) {
throw new TTK91AddressOutOfBounds();
}
}
/** This method adds a line of keyboard data to a buffer the Processor
can read it from during its next command cycle (or previous cycle
repeated).
@param kbdInput An int to be "read from the keyboard". */
public void keyboardInput(int kbdInput) {
kbdData = new Integer (kbdInput);
}
/** This method adds a line of stdin data to a buffer the Processor
can read it from during its next command cycle (or previous cycle
repeated).
@param stdinInput An int to be "read from STDIN (file)". */
public void stdinInput(int stdinInput) {
stdinData = new Integer (stdinInput);
}
public RunInfo runInit(int initSP, int initFP) {
// TODO RunInfo-olion generointi
status = TTK91Cpu.STATUS_STILL_RUNNING;
regs.setRegister (TTK91Cpu.CU_PC, 0);
regs.setRegister (TTK91Cpu.CU_PC_CURRENT, 0);
regs.setRegister (TTK91Cpu.REG_SP, initSP);
regs.setRegister (TTK91Cpu.REG_FP, initFP);
ram.setCodeAreaLength (initFP+1);
ram.setDataAreaLength (ram.getSize() -(initFP+1));
return null;
}
public RunInfo runLine() throws TTK91RuntimeException{
if (status != TTK91Cpu.STATUS_STILL_RUNNING) return null;
try {
// get PC
int PC = regs.getRegister (TTK91Cpu.CU_PC);
// fetch the next command to IR from memory and increase PC
MemoryLine IR = ram.getMemoryLine(PC);
runDebugger.cycleStart (IR.getSymbolic(), PC, regs.getRegister (TTK91Cpu.REG_SP), regs.getRegister (TTK91Cpu.REG_FP));
regs.setRegister (TTK91Cpu.CU_IR, IR.getBinary());
regs.setRegister (TTK91Cpu.CU_PC, PC+1);
// cut up the command in IR
int opcode = IR.getBinary() >>> 24; // operation code
int Rj = ((IR.getBinary()&0xE00000) >>> 21) + TTK91Cpu.REG_R0; // first operand (register 0..7)
int M = (IR.getBinary()&0x180000) >>> 19; // memory addressing mode
int Ri = ((IR.getBinary()&0x070000) >>> 16) + TTK91Cpu.REG_R0; // index register
int ADDR = IR.getBinary()&0xFFFF; // address
runDebugger.runCommand (opcode, Rj, regs.getRegister (Rj),
Ri, regs.getRegister(Ri), ADDR, M,
opcode + ":" + (Rj-TTK91Cpu.REG_R0) + ":" + M + ":" + (Ri-TTK91Cpu.REG_R0) + ":" + ADDR);
// fetch parameter from memory
if (Ri != TTK91Cpu.REG_R0) ADDR += regs.getRegister (Ri); // add indexing register Ri
int param = ADDR; // constant value
if (M == 1) param = ram.getValue(ADDR); // one memory fetch
if (M == 2) param = ram.getValue (ram.getValue(ADDR)); // two memory fetches
// run the command
if (M == 3) {
status = TTK91Cpu.STATUS_ABNORMAL_EXIT;
throw new TTK91BadAccessMode(new Message(Processor.BAD_ACCESS_MODE_MESSAGE).toString());
}
if (opcode == 0) nop();
else if (opcode >= 1 && opcode <= 4) transfer (opcode, Rj, M, ADDR, param);
else if (opcode >= 17 && opcode <= 27) alu (opcode, Rj, param);
else if (opcode == 31) comp (Rj, param);
else if (opcode >= 32 && opcode <= 44) branch (opcode, Rj, M, ADDR, param);
else if (opcode >= 49 && opcode <= 50) subr (opcode, Rj, ADDR, param);
else if (opcode >= 51 && opcode <= 54) stack (opcode, Rj, Ri, param);
else if (opcode == 112) svc (Rj, param);
else {
status = TTK91Cpu.STATUS_ABNORMAL_EXIT;
throw new TTK91InvalidOpCode(new Message(Processor.INVALID_OPCODE_MESSAGE).toString());
}
} catch (ArrayIndexOutOfBoundsException e) {
status = TTK91Cpu.STATUS_ABNORMAL_EXIT;
throw new TTK91AddressOutOfBounds(new Message(Processor.ADDRESS_OUT_OF_BOUNDS_MESSAGE).toString());
}
// update PC_CURRENT
regs.setRegister (TTK91Cpu.CU_PC_CURRENT, regs.getRegister (TTK91Cpu.CU_PC));
// give registers to runDebugger
Integer[] registers = new Integer[8];
for (int i=0; i < registers.length; i++)
registers[i] = new Integer (regs.getRegister (i + TTK91Cpu.REG_R0));
runDebugger.setRegisters (registers);
return runDebugger.cycleEnd();
}
/** Transfer-operations. */
private void transfer(int opcode, int Rj, int M, int ADDR, int param)
throws TTK91BadAccessMode, TTK91AddressOutOfBounds, TTK91NoKbdData, TTK91NoStdInData, TTK91InvalidDevice {
runDebugger.setOperationType (RunDebugger.DATA_TRANSFER_OPERATION);
switch (opcode) {
case 1 : // STORE
if (M == 2) {
status = TTK91Cpu.STATUS_ABNORMAL_EXIT;
throw new TTK91BadAccessMode(new Message (Processor.STORE_BAD_ACCESS_MODE_MESSAGE).toString());
}
if (M == 0) writeToMemory (ADDR, regs.getRegister(Rj));
if (M == 1) writeToMemory (ram.getValue (ADDR), regs.getRegister(Rj));
break;
case 2 : // LOAD
regs.setRegister (Rj, param);
break;
case 3 :
switch (param) {
case KBD : // Keyboard
if (kbdData == null) {
regs.setRegister (TTK91Cpu.CU_PC, regs.getRegister (TTK91Cpu.CU_PC) -1); // reverse this command
throw new TTK91NoKbdData(new Message (Processor.NO_KDB_DATA_MESSAGE).toString());
}
regs.setRegister (Rj, kbdData.intValue());
runDebugger.setIN (param, kbdData.intValue());
kbdData = null;
break;
case STDIN : // Standard input file
if (stdinData == null) {
regs.setRegister (TTK91Cpu.CU_PC, regs.getRegister (TTK91Cpu.CU_PC) -1); // reverse this command
throw new TTK91NoStdInData(new Message (Processor.NO_STDIN_DATA_MESSAGE).toString());
}
regs.setRegister (Rj, stdinData.intValue());
runDebugger.setIN (param, stdinData.intValue());
stdinData = null;
break;
default :
status = TTK91Cpu.STATUS_ABNORMAL_EXIT;
throw new TTK91InvalidDevice(new Message (Processor.INVALID_DEVICE_MESSAGE).toString());
}
break;
case 4 : // OUT
if (param != CRT && param != STDOUT) {
status = TTK91Cpu.STATUS_ABNORMAL_EXIT;
throw new TTK91InvalidDevice(new Message (Processor.INVALID_DEVICE_MESSAGE).toString());
}
runDebugger.setOUT (param, regs.getRegister(Rj));
break;
}
}
/** ALU-operations.
@return Result of the ALU-operation. */
private void alu(int opcode, int Rj, int param)
throws TTK91IntegerOverflow, TTK91DivisionByZero {
runDebugger.setOperationType (RunDebugger.ALU_OPERATION);
long n;
switch (opcode) {
case 17 : // ADD
n = (long)regs.getRegister (Rj) - (long)param;
if (isOverflow (n)) {
status = TTK91Cpu.STATUS_ABNORMAL_EXIT;
throw new TTK91IntegerOverflow(new Message (Processor.INTEGER_OVERFLOW_MESSAGE).toString());
}
regs.setRegister (Rj, (int)n);
break;
case 18 : // SUB
n = (long)regs.getRegister (Rj) - (long)param;
if (isOverflow (n)) {
status = TTK91Cpu.STATUS_ABNORMAL_EXIT;
throw new TTK91IntegerOverflow(new Message (Processor.INTEGER_OVERFLOW_MESSAGE).toString());
}
regs.setRegister (Rj, (int)n);
break;
case 19 : // MUL
n = (long)regs.getRegister (Rj) * (long)param;
if (isOverflow (n)) {
status = TTK91Cpu.STATUS_ABNORMAL_EXIT;
throw new TTK91IntegerOverflow(new Message (Processor.INTEGER_OVERFLOW_MESSAGE).toString());
}
regs.setRegister (Rj, (int)n);
break;
case 20 : // DIV
if (param == 0) {
status = TTK91Cpu.STATUS_ABNORMAL_EXIT;
throw new TTK91DivisionByZero(new Message (Processor.DIVISION_BY_ZERO_MESSAGE).toString());
}
regs.setRegister (Rj, regs.getRegister (Rj) / param);
break;
case 21 : // MOD
if (param == 0) {
status = TTK91Cpu.STATUS_ABNORMAL_EXIT;
throw new TTK91DivisionByZero(new Message (Processor.DIVISION_BY_ZERO_MESSAGE).toString());
}
regs.setRegister (Rj, regs.getRegister (Rj) % param);
break;
case 22 : // AND
regs.setRegister (Rj, regs.getRegister (Rj) & param);
break;
case 23 :
regs.setRegister (Rj, regs.getRegister (Rj) | param);
break;
case 24 : // XOR
regs.setRegister (Rj, regs.getRegister (Rj) ^ param);
break;
case 25 : // SHL
regs.setRegister (Rj, regs.getRegister(Rj) << param);
break;
case 26 : // SHR
regs.setRegister (Rj, regs.getRegister(Rj) >>> param);
break;
case 27 : // SHRA
regs.setRegister (Rj, regs.getRegister(Rj) >> param);
break;
}
runDebugger.setALUResult (regs.getRegister (Rj));
}
/** Compare-method manipulates status register.
@param Rj First value to compare (register index).
@param param Second value. */
private void comp(int Rj, int param) {
// COMP
runDebugger.setOperationType (RunDebugger.COMP_OPERATION);
if (regs.getRegister (Rj) > param) {
sr[0] = true;
sr[1] = false;
sr[2] = false;
runDebugger.setCompareResult (0);
}
else if (regs.getRegister (Rj) < param) {
sr[0] = false;
sr[1] = false;
sr[2] = true;
runDebugger.setCompareResult (2);
}
else {
sr[0] = false;
sr[1] = true;
sr[2] = false;
runDebugger.setCompareResult (1);
}
}
/** Branching. */
private void branch(int opcode, int Rj, int M, int ADDR, int param)
throws TTK91BadAccessMode {
runDebugger.setOperationType (RunDebugger.BRANCH_OPERATION);
if (M == 2) {
status = TTK91Cpu.STATUS_ABNORMAL_EXIT;
throw new TTK91BadAccessMode(new Message (Processor.BRACNH_BAD_ACCESS_MODE_MESSAGE).toString());
}
switch (opcode) {
case 32 : // JUMP
regs.setRegister (TTK91Cpu.CU_PC, param);
break;
case 33 : // JNEG
if (regs.getRegister (Rj) < 0) regs.setRegister (TTK91Cpu.CU_PC, param);
break;
case 34 : // JZER
if (regs.getRegister (Rj) == 0) regs.setRegister (TTK91Cpu.CU_PC, param);
break;
case 35 : // JPOS
if (regs.getRegister (Rj) > 0) regs.setRegister (TTK91Cpu.CU_PC, param);
break;
case 36 : // JNNEG
if (regs.getRegister (Rj) >= 0) regs.setRegister (TTK91Cpu.CU_PC, param);
break;
case 37 : // JNZER
if (regs.getRegister (Rj) != 0) regs.setRegister (TTK91Cpu.CU_PC, param);
break;
case 38 : // JNPOS
if (regs.getRegister (Rj) <= 0) regs.setRegister (TTK91Cpu.CU_PC, param);
break;
case 39 : // JLES
if (sr[2]) regs.setRegister (TTK91Cpu.CU_PC, param);
break;
case 40 : // JEQU
if (sr[1]) regs.setRegister (TTK91Cpu.CU_PC, param);
break;
case 41 : // JGRE
if (sr[0]) regs.setRegister (TTK91Cpu.CU_PC, param);
break;
case 42 : // JNLES
if (sr[1] || sr[0]) regs.setRegister (TTK91Cpu.CU_PC, param);
break;
case 43 : // JNEQU
if (sr[2] || sr[0]) regs.setRegister (TTK91Cpu.CU_PC, param);
break;
case 44 : // JNGRE
if (sr[2] || sr[1]) regs.setRegister (TTK91Cpu.CU_PC, param);
break;
}
}
/** Stack. */
private void stack(int opcode, int Rj, int Ri, int param)
throws TTK91AddressOutOfBounds {
runDebugger.setOperationType (RunDebugger.STACK_OPERATION);
switch (opcode) {
case 51 : // PUSH
regs.setRegister (Rj, regs.getRegister(Rj) +1);
writeToMemory (regs.getRegister(Rj), param);
break;
case 52 : // POP
regs.setRegister (Ri, ram.getValue (regs.getRegister(Rj)));
regs.setRegister (Rj, regs.getRegister(Rj) -1);
break;
case 53 : // PUSHR
stack(51, Rj, Ri, regs.getRegister (TTK91Cpu.REG_R0)); // PUSH R0
stack(51, Rj, Ri, regs.getRegister (TTK91Cpu.REG_R1)); // PUSH R1
stack(51, Rj, Ri, regs.getRegister (TTK91Cpu.REG_R2)); // PUSH R2
stack(51, Rj, Ri, regs.getRegister (TTK91Cpu.REG_R3)); // PUSH R3
stack(51, Rj, Ri, regs.getRegister (TTK91Cpu.REG_R4)); // PUSH R4
stack(51, Rj, Ri, regs.getRegister (TTK91Cpu.REG_R5)); // PUSH R5
stack(51, Rj, Ri, regs.getRegister (TTK91Cpu.REG_R6)); // PUSH R6
break;
case 54 : // POPR
stack(52, Rj, regs.getRegister (TTK91Cpu.REG_R6), param); // POP R6
stack(52, Rj, regs.getRegister (TTK91Cpu.REG_R5), param); // POP R5
stack(52, Rj, regs.getRegister (TTK91Cpu.REG_R4), param); // POP R4
stack(52, Rj, regs.getRegister (TTK91Cpu.REG_R3), param); // POP R3
stack(52, Rj, regs.getRegister (TTK91Cpu.REG_R2), param); // POP R2
stack(52, Rj, regs.getRegister (TTK91Cpu.REG_R1), param); // POP R1
stack(52, Rj, regs.getRegister (TTK91Cpu.REG_R0), param); // POP R0
break;
}
}
/** Subroutine. */
private void subr(int opcode, int Rj, int ADDR, int param)
throws TTK91AddressOutOfBounds {
runDebugger.setOperationType (RunDebugger.SUB_OPERATION);
int sp;
switch (opcode) {
case 49 : // CALL
// push PC and FP to stack (Rj is stack pointer)
sp = regs.getRegister (Rj);
writeToMemory (++sp, regs.getRegister (TTK91Cpu.CU_PC));
writeToMemory (++sp, regs.getRegister (TTK91Cpu.REG_FP));
// update stack and frame pointers
regs.setRegister (Rj, sp);
regs.setRegister (TTK91Cpu.REG_FP, sp);
// set PC
regs.setRegister (TTK91Cpu.CU_PC, ADDR);
break;
case 50 : // EXIT
// pop FP and PC from stack (Rj is stack pointer)
sp = regs.getRegister (Rj);
regs.setRegister (TTK91Cpu.REG_FP, ram.getValue (sp
regs.setRegister (TTK91Cpu.CU_PC, ram.getValue (sp
// decrease number of parameters from stack
regs.setRegister (Rj, sp -param);
break;
}
}
/** Supervisor call. */
private void svc(int Rj, int param)
throws TTK91AddressOutOfBounds, TTK91NoKbdData {
runDebugger.setSVCOperation (param);
Calendar calendar;
// make CALL operation to supervisor
subr(49, Rj, -1, param);
switch (param) {
case 11 : // HALT
runDebugger.setOperationType (RunDebugger.SVC_OPERATION);
status = TTK91Cpu.STATUS_SVC_SD;
break;
case 12 : // READ
if (kbdData == null) {
subr (50, Rj, 0, 1); // EXIT from SVC(READ)
runDebugger.setOperationType (RunDebugger.SVC_OPERATION);
regs.setRegister (TTK91Cpu.CU_PC, regs.getRegister (TTK91Cpu.CU_PC) -1); // reverse this command
throw new TTK91NoKbdData(new Message (Processor.NO_KDB_DATA_MESSAGE).toString());
}
writeToMemory (ram.getValue (regs.getRegister(TTK91Cpu.REG_FP) -2), kbdData.intValue());
kbdData = null;
subr (50, Rj, 0, 1); // EXIT from SVC(READ)
break;
case 13 : // WRITE
runDebugger.setOUT (CRT, ram.getValue (regs.getRegister(TTK91Cpu.REG_FP) -2));
subr (50, Rj, 0, 1); // EXIT from SVC(WRITE)
break;
case 14 : // TIME
calendar = new GregorianCalendar();
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
writeToMemory (ram.getValue (regs.getRegister(TTK91Cpu.REG_FP) -2), second);
writeToMemory (ram.getValue (regs.getRegister(TTK91Cpu.REG_FP) -3), minute);
writeToMemory (ram.getValue (regs.getRegister(TTK91Cpu.REG_FP) -4), hour);
subr (50, Rj, 0, 3); // EXIT from SVC(TIME)
break;
case 15 : // DATE
calendar = new GregorianCalendar();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int date = calendar.get(Calendar.DATE);
writeToMemory (ram.getValue (regs.getRegister(TTK91Cpu.REG_FP) -2), date);
writeToMemory (ram.getValue (regs.getRegister(TTK91Cpu.REG_FP) -3), month);
writeToMemory (ram.getValue (regs.getRegister(TTK91Cpu.REG_FP) -4), year);
subr (50, Rj, 0, 3); // EXIT from SVC(DATE)
break;
}
runDebugger.setOperationType (RunDebugger.SVC_OPERATION);
}
private void nop() {
runDebugger.setOperationType (RunDebugger.NO_OPERATION);
}
private void writeToMemory (int row, int value) {
MemoryLine memoryLine;
// if write is to code area checks if given value has symbolic presentation
if (row < ram.getCodeAreaSize())
memoryLine = new MemoryLine (value, new BinaryInterpreter().binaryToString(value));
else
memoryLine = new MemoryLine (value, null);
ram.setMemoryLine (row, memoryLine);
runDebugger.addChangedMemoryLine (row, memoryLine);
}
/** Tests if given long value is acceptable int value. */
private boolean isOverflow (long value) {
return (value > (long)Integer.MAX_VALUE || value < (long)Integer.MIN_VALUE);
}
}
|
package dr.inference.model;
import dr.inference.loggers.LogColumn;
import dr.inference.loggers.NumberColumn;
public class AdaptableSizeFastMatrixParameter extends FastMatrixParameter {
public AdaptableSizeFastMatrixParameter(String id, int rowDimension, int colDimension, int maxRow, int maxCol, double startingValue, boolean lowerTriangle) {
super(id, maxRow, maxCol, startingValue);
if(maxRow < rowDimension){
throw new RuntimeException("Row Dimension: " + rowDimension + ", is greater than Max Row Dimension: " + maxRow + " in " + getParameterName());
}
if(maxCol < colDimension){
throw new RuntimeException("Column Dimension: " + colDimension + ", is greater than Max Column Dimension: " + columnDimension + " in " + getParameterName());
}
this.rowDimension = rowDimension;
this.columnDimension = colDimension;
this.maxRow = maxRow;
this.maxCol = maxCol;
this.storedColumnDimension = rowDimension;
this.storedColumnDimension = columnDimension;
this.lowerTriangle = lowerTriangle;
}
public void setRowDimension(int rowDimension){
int oldRowDimension = this.rowDimension;
this.rowDimension = rowDimension;
if(rowDimension > oldRowDimension)
fireParameterChangedEvent(-1, ChangeType.ADDED);
else
fireParameterChangedEvent(-1, ChangeType.REMOVED);
}
public void setColumnDimension(int columnDimension){
int oldColumnDimension = this.columnDimension;
this.columnDimension = columnDimension;
if(columnDimension > oldColumnDimension)
fireParameterChangedEvent(-1, ChangeType.ADDED);
else
fireParameterChangedEvent(-1, ChangeType.REMOVED);
}
@Override
protected void storeValues(){
super.storeValues();
storedRowDimension = rowDimension;
storedColumnDimension = columnDimension;
}
protected void restoreValues(){
super.restoreValues();
rowDimension = storedRowDimension;
columnDimension = storedColumnDimension;
}
public int getRowDimension(){
return rowDimension;
}
public int getColumnDimension(){
return columnDimension;
}
public int getDimension(){
return rowDimension * columnDimension;
}
public int getMaxRowDimension(){return maxRow;}
public int getMaxColumnDimension(){return maxCol;}
public void setParameterValue(int index, double value) {
int row = index % rowDimension;
int col = index / rowDimension;
if (row >= col || !lowerTriangle){
super.setParameterValueQuietly(row, col, value);
fireParameterChangedEvent(index, ChangeType.VALUE_CHANGED);
}
}
public void setParameterValue(int row, int column, double value){
if(row >= column || !lowerTriangle){
super.setParameterValueQuietly(row, column, value);
fireParameterChangedEvent(getRowDimension() * column + row, ChangeType.VALUE_CHANGED);
}
}
public void setParameterValueQuietly(int index, double value){
int row = index % rowDimension;
int col = index / rowDimension;
if(row >= col || !lowerTriangle) {
super.setParameterValueQuietly(row, col, value);
}
}
public void setParameterValueQuietly(int row, int column, double value){
if(row >= column || !lowerTriangle){
super.setParameterValueQuietly(row, column, value);
}
}
public double getParameterValue(int index){
int row = index % rowDimension;
int col = index / rowDimension;
if(row >= col || !lowerTriangle) {
return super.getParameterValue(row, col);
}
else return 0;
}
public double getParameterValue(int row, int col){
if(row >= col || !lowerTriangle) {
return super.getParameterValue(row, col);
}
else return 0;
}
public double[] getParameterValues(){
double[] answer = new double[getDimension()];
for (int i = 0; i < getDimension(); i++) {
answer[i]= getParameterValue(i);
}
return answer;
}
int rowDimension;
int columnDimension;
int storedRowDimension;
int storedColumnDimension;
int maxRow;
int maxCol;
boolean lowerTriangle;
public LogColumn[] getColumns(){
LogColumn[] bigMatrixColumn = new ASFMPColumn[1];
bigMatrixColumn[0] = new ASFMPColumn(getParameterName());
return bigMatrixColumn;
}
private class ASFMPColumn extends NumberColumn {
public ASFMPColumn(String label) {
super(label);
}
protected String getFormattedValue(){
String fullMatrix = "{";
for (int i = 0; i <getRowDimension() ; i++) {
fullMatrix += " { ";
for (int j = 0; j < getColumnDimension(); j++) {
fullMatrix += formatValue(getParameterValue(i,j));
if(j != getColumnDimension() - 1){
fullMatrix += ", ";
}
}
if(i == getRowDimension()-1)
fullMatrix += " } ";
else
fullMatrix += " },";
}
fullMatrix += "}";
return fullMatrix;
}
@Override
public double getDoubleValue() {
return 0;
}
}
}
|
package edu.ucsb.cs56.projects.games.poker;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import org.junit.Test;
/**
* Test class for CompareHands, to test if winning hands are judged correctly
*
*@author Gregory Whiter
*@version CS56, Fall 2016
*@see CompareHands
*/
public class CompareHandsTest{
Card twoDiamond = new Card(2,"D");
Card twoHeart = new Card(2,"H");
Card twoClub = new Card(2,"C");
Card twoSpade = new Card(2,"S");
Card threeDiamond = new Card(3,"D");
Card threeHeart = new Card(3,"H");
Card threeClub = new Card(3,"C");
Card threeSpade = new Card(3,"S");
Card fourDiamond = new Card(4,"D");
Card fourHeart = new Card(4,"H");
Card fourClub = new Card(4,"C");
Card fourSpade = new Card(4,"S");
Card fiveDiamond = new Card(5,"D");
Card fiveHeart = new Card(5,"H");
Card fiveClub = new Card(5,"C");
Card fiveSpade = new Card(5,"S");
Card sixDiamond = new Card(6,"D");
Card sixHeart = new Card(6,"H");
Card sixClub = new Card(6,"C");
Card sixSpade = new Card(6,"S");
Card sevenDiamond = new Card(7,"D");
Card sevenHeart = new Card(7,"H");
Card sevenClub = new Card(7,"C");
Card sevenSpade = new Card(7,"S");
Card eightDiamond = new Card(8,"D");
Card eightHeart = new Card(8,"H");
Card eightClub = new Card(8,"C");
Card eightSpade = new Card(8,"S");
Card nineDiamond = new Card(9,"D");
Card nineHeart = new Card(9,"H");
Card nineClub = new Card(9,"C");
Card nineSpade = new Card(9,"S");
Card tenDiamond = new Card(10,"D");
Card tenHeart = new Card(10,"H");
Card tenClub = new Card(10,"C");
Card tenSpade = new Card(10,"S");
Card jackDiamond = new Card(11,"D");
Card jackHeart = new Card(11,"H");
Card jackClub = new Card(11,"C");
Card jackSpade = new Card(11,"S"); // JACK
Card queenDiamond = new Card(12,"D");
Card queenHeart = new Card(12,"H");
Card queenClub = new Card(12,"C");
Card queenSpade = new Card(12,"S"); // QUEEN
Card kingDiamond = new Card(13,"D");
Card kingHeart = new Card(13,"H");
Card kingClub = new Card(13,"C");
Card kingSpade = new Card(13,"S"); // KING
Card aceDiamond = new Card(14,"D");
Card aceHeart = new Card(14,"H");
Card aceClub = new Card(14,"C");
Card aceSpade = new Card(14,"S"); // ACE
Player player1, player2;
ArrayList<Player> players = new ArrayList<Player>(2);
TableCards table;
Hand hand1, hand2;
CompareHands comparingHands;
ArrayList<Card> cardHand = new ArrayList<Card>(); //Player cards + table cards
/** test hand with one pair wins over ace high hand */
@Test
public void testisOnePairWins(){
table = new TableCards(fiveSpade, twoHeart, kingClub, nineDiamond, jackHeart);
hand1 = new Hand(fiveDiamond, sixSpade);
player1 = new User(hand1);
hand2 = new Hand(aceSpade, sixHeart);
player2 = new User(hand2);
players.add(player1);
players.add(player2);
comparingHands = new CompareHands(players, table);
assertEquals(0, comparingHands.compareHands());
}
/** test hand with one pair loses to hand with straight */
@Test
public void testisOnePairLoses(){
table = new TableCards(fiveSpade, twoHeart, kingClub, nineDiamond, jackHeart);
hand1 = new Hand(fiveDiamond, sixSpade);
player1 = new User(hand1);
hand2 = new Hand(queenSpade, tenHeart);
player2 = new User(hand2);
players.add(player1);
players.add(player2);
comparingHands = new CompareHands(players, table);
assertEquals(1, comparingHands.compareHands());
}
/** test two pair wins against one pair */
@Test
public void testisTwoPairWins(){
table = new TableCards(threeSpade, threeDiamond, sevenHeart, queenClub, fiveClub);
hand1 = new Hand(fiveDiamond, jackSpade);
player1 = new User(hand1);
hand2 = new Hand(aceHeart, tenSpade);
player2 = new User(hand2);
players.add(player1);
players.add(player2);
comparingHands = new CompareHands(players, table);
assertEquals(0, comparingHands.compareHands());
assertEquals("Two Pair beats Pair!", comparingHands.compareMessage());
}
/** test two pair loses against straight */
@Test
public void testisTwoPairLoses(){
table = new TableCards(threeSpade, threeDiamond, sevenHeart, queenClub, fiveClub);
hand1 = new Hand(fiveDiamond, jackSpade);
player1 = new User(hand1);
hand2 = new Hand(fourHeart, sixSpade);
player2 = new User(hand2);
players.add(player1);
players.add(player2);
comparingHands = new CompareHands(players, table);
assertEquals(1, comparingHands.compareHands());
assertEquals("Straight beats Two Pair!", comparingHands.compareMessage());
}
/** test three of a kind wins against one pair */
@Test
public void testisThreeOfAKindWins(){
table = new TableCards(fiveSpade, twoSpade, kingSpade, fiveClub, jackSpade);
hand1 = new Hand(fiveDiamond, eightHeart);
player1 = new User(hand1);
hand2 = new Hand(fourHeart, sixClub);
player2 = new User(hand2);
players.add(player1);
players.add(player2);
comparingHands = new CompareHands(players, table);
assertEquals(0, comparingHands.compareHands());
assertEquals("Three of a Kind beats Pair!", comparingHands.compareMessage());
}
/** test three of a kind loses against flush */
@Test
public void testisThreeOfAKindLoses(){
table = new TableCards(fiveSpade, twoSpade, kingSpade, fiveClub, jackSpade);
hand1 = new Hand(fiveDiamond, eightHeart);
player1 = new User(hand1);
hand2 = new Hand(fourSpade, sixClub);
player2 = new User(hand2);
players.add(player1);
players.add(player2);
comparingHands = new CompareHands(players, table);
assertEquals(1, comparingHands.compareHands());
}
/** test straight wins against three of a kind */
@Test
public void testisStraightWins(){
table = new TableCards(aceSpade, twoHeart, sevenHeart, threeDiamond, jackHeart);
hand1 = new Hand(fourSpade, fiveSpade);
player1 = new User(hand1);
hand2 = new Hand(sevenDiamond, sevenClub);
player2 = new User(hand2);
players.add(player1);
players.add(player2);
comparingHands = new CompareHands(players, table);
assertEquals(0, comparingHands.compareHands());
}
/** test straight loses against flush */
@Test
public void testisStraightLoses(){
table = new TableCards(fiveSpade, twoHeart, sevenHeart, threeDiamond, jackHeart);
hand1 = new Hand(fourDiamond, aceSpade);
player1 = new User(hand1);
hand2 = new Hand(tenHeart, kingHeart);
player2 = new User(hand2);
players.add(player1);
players.add(player2);
comparingHands = new CompareHands(players, table);
assertEquals(1, comparingHands.compareHands());
}
/** test flush wins against straight */
@Test
public void testisFlushWins(){
table = new TableCards(fiveDiamond, twoHeart, eightSpade, nineSpade, jackSpade);
hand1 = new Hand(fourSpade, kingSpade);
player1 = new User(hand1);
hand2 = new Hand(tenSpade, queenDiamond);
player2 = new User(hand2);
players.add(player1);
players.add(player2);
comparingHands = new CompareHands(players, table);
assertEquals(0, comparingHands.compareHands());
}
/** test flush loses to straight flush */
@Test
public void testisFlushLoses(){
table = new TableCards(twoDiamond, fiveSpade, threeSpade, fourSpade, jackSpade);
hand1 = new Hand(fourSpade, kingSpade);
player1 = new User(hand1);
hand2 = new Hand(aceSpade, twoSpade);
player2 = new User(hand2);
players.add(player1);
players.add(player2);
comparingHands = new CompareHands(players, table);
assertEquals(1, comparingHands.compareHands());
}
/** test full house wins against flush */
@Test
public void testisFullHouseWins(){
table = new TableCards(twoSpade,twoHeart,eightHeart,nineDiamond,jackHeart);
hand1 = new Hand(twoDiamond, eightClub);
player1 = new User(hand1);
hand2 = new Hand(tenHeart, fiveHeart);
player2 = new User(hand2);
players.add(player1);
players.add(player2);
comparingHands = new CompareHands(players, table);
assertEquals(0, comparingHands.compareHands());
}
/** test full house loses against four of a kind */
@Test
public void testisFullHouseLoses(){
table = new TableCards(twoSpade,twoHeart,eightHeart,eightClub,jackHeart);
hand1 = new Hand(twoDiamond, jackSpade);
player1 = new User(hand1);
hand2 = new Hand(eightSpade, eightDiamond);
player2 = new User(hand2);
players.add(player1);
players.add(player2);
comparingHands = new CompareHands(players, table);
assertEquals(1, comparingHands.compareHands());
}
/** test four of a kind wins against three of a kind */
@Test
public void testisFourOfAKindWins(){
table = new TableCards(aceSpade,aceHeart,tenHeart,threeClub,jackHeart);
hand1 = new Hand(aceDiamond, aceClub);
player1 = new User(hand1);
hand2 = new Hand(threeSpade, threeDiamond);
player2 = new User(hand2);
players.add(player1);
players.add(player2);
comparingHands = new CompareHands(players, table);
assertEquals(0, comparingHands.compareHands());
}
/** test four of a kind loses to straight flush */
@Test
public void testisFourOfAKindLoses(){
table = new TableCards(aceSpade, aceHeart, threeSpade, fourSpade, jackDiamond);
hand1 = new Hand(aceDiamond, aceClub);
player1 = new User(hand1);
hand2 = new Hand(twoSpade, fiveSpade);
player2 = new User(hand2);
players.add(player1);
players.add(player2);
comparingHands = new CompareHands(players, table);
assertEquals(1, comparingHands.compareHands());
}
/** test straight flush wins against full house */
@Test
public void testisStraightFlushWins(){
table = new TableCards(jackClub, threeDiamond, fourDiamond, fiveDiamond, jackHeart);
hand1 = new Hand(aceClub, twoClub);
player1 = new User(hand1);
hand2 = new Hand(fourDiamond, jackSpade);
player2 = new User(hand2);
players.add(player1);
players.add(player2);
comparingHands = new CompareHands(players, table);
assertEquals(0, comparingHands.compareHands());
}
/** test close case of two pair of 3's and 10's beats two pair of 3's and 5's */
@Test
public void testLowerTwoPairLoses() {
table = new TableCards(threeSpade, threeDiamond, sevenHeart, queenClub, jackClub);
hand1 = new Hand(tenDiamond, tenSpade);
player1 = new User(hand1);
hand2 = new Hand(fiveHeart, fiveSpade);
player2 = new User(hand2);
players.add(player1);
players.add(player2);
comparingHands = new CompareHands(players, table);
//For now, counts as a tie
assertEquals(-1, comparingHands.compareHands());
}
/** test case where players have the same hand */
@Test
public void testTie(){
table = new TableCards(aceSpade, threeDiamond, sevenHeart, queenClub, jackClub);
hand1 = new Hand(tenDiamond, tenSpade);
player1 = new User(hand1);
hand2 = new Hand(tenHeart, tenClub);
player2 = new User(hand2);
players.add(player1);
players.add(player2);
comparingHands = new CompareHands(players, table);
assertEquals(-1, comparingHands.compareHands());
}
/** test lowest ranking straightflush wins against straight */
@Test
public void testStraightFlushWinsAgain(){
table = new TableCards(aceSpade, twoSpade, threeSpade, fourSpade, jackHeart);
hand1 = new Hand(fiveSpade, kingHeart);
player1 = new User(hand1);
hand2 = new Hand(fiveHeart, kingDiamond);
player2 = new User(hand2);
players.add(player1);
players.add(player2);
comparingHands = new CompareHands(players, table);
assertEquals(0, comparingHands.compareHands());
}
/** test straight wins against two pairs */
@Test
public void testStraightWinsAgain(){
table = new TableCards(fiveSpade, fourSpade, threeSpade, twoSpade, jackHeart);
hand1 = new Hand(aceHeart, kingHeart);
player1 = new User(hand1);
hand2 = new Hand(fourHeart, jackDiamond);
player2 = new User(hand2);
players.add(player1);
players.add(player2);
comparingHands = new CompareHands(players, table);
assertEquals(0, comparingHands.compareHands());
}
/** test straight wins against pair when table has duplicate values */
@Test
public void testStraightDuplicateWins() {
table = new TableCards(aceSpade, fourSpade, threeSpade, twoSpade, jackHeart);
hand1 = new Hand(aceHeart, kingHeart);
player1 = new User(hand1);
hand2 = new Hand(fourHeart, sevenDiamond);
player2 = new User(hand2);
players.add(player1);
players.add(player2);
comparingHands = new CompareHands(players, table);
assertEquals(0, comparingHands.compareHands());
}
/** test straight flush wins against lower straight flush */
@Test
public void testStraightFlushBeatsStraightFlush() {
table = new TableCards(eightHeart, nineHeart, tenHeart, fiveClub, twoSpade);
hand1 = new Hand(jackHeart, queenHeart);
player1 = new User(hand1);
hand2 = new Hand(sevenHeart, jackHeart);
player2 = new User(hand2);
players.add(player1);
players.add(player2);
comparingHands = new CompareHands(players, table);
//for now counts as a tie
assertEquals(-1, comparingHands.compareHands());
}
/** test four of a kind wins against lower four of a kind */
@Test
public void testFourOfAKBeatsFourOfAK() {
table = new TableCards(eightHeart, nineHeart, eightDiamond, nineClub, twoSpade);
hand1 = new Hand(eightSpade, eightClub);
player1 = new User(hand1);
hand2 = new Hand(nineDiamond, nineHeart);
player2 = new User(hand2);
players.add(player1);
players.add(player2);
comparingHands = new CompareHands(players, table);
//for now counts as a tie
assertEquals(-1, comparingHands.compareHands());
}
/** test full house wins against lower full house */
@Test
public void testFullHouseBeatsFullHouse() {
table = new TableCards(twoSpade, twoHeart, eightHeart, eightDiamond, jackHeart);
hand1 = new Hand(twoDiamond, jackClub);
player1 = new User(hand1);
hand2 = new Hand(eightClub, jackSpade);
player2 = new User(hand2);
players.add(player1);
players.add(player2);
comparingHands = new CompareHands(players, table);
//for now counts as a tie
assertEquals(-1, comparingHands.compareHands());
}
/** test flush wins against lower flush */
@Test
public void testFlushBeatsFlush() {
table = new TableCards(twoSpade,twoHeart,eightHeart,nineDiamond,jackHeart);
hand1 = new Hand(threeHeart, tenHeart);
player1 = new User(hand1);
hand2 = new Hand(queenHeart, fiveHeart);
player2 = new User(hand2);
players.add(player1);
players.add(player2);
comparingHands = new CompareHands(players, table);
//for now counts as a tie
assertEquals(-1, comparingHands.compareHands());
}
/** test straight wins against lower straight */
@Test
public void testStraightBeatsStraight() {
table = new TableCards(fourHeart, fiveSpade, sixClub, eightSpade, twoDiamond);
hand1 = new Hand(sevenHeart, nineHeart);
player1 = new User(hand1);
hand2 = new Hand(threeClub, sevenClub);
player2 = new User(hand2);
players.add(player1);
players.add(player2);
comparingHands = new CompareHands(players, table);
//For now, counts as a tie
assertEquals(-1, comparingHands.compareHands());
}
/** test three of a kind wins against lower three of a kind */
@Test
public void testThreeOfAKBeatsThreeOfAK() {
table = new TableCards(fourSpade, tenDiamond, threeHeart, sixDiamond, fourClub);
hand1 = new Hand(tenHeart, tenSpade);
player1 = new User(hand1);
hand2 = new Hand(fourHeart, sevenDiamond);
player2 = new User(hand2);
players.add(player1);
players.add(player2);
comparingHands = new CompareHands(players, table);
//For now, counts as a tie
assertEquals(-1, comparingHands.compareHands());
}
/** Test two pair wins against lower two pair */
@Test
public void testTwoPairBeatsTwoPair() {
table = new TableCards(fourSpade, tenDiamond, threeHeart, sixDiamond, fourClub);
hand1 = new Hand(aceHeart, tenSpade);
player1 = new User(hand1);
hand2 = new Hand(sixHeart, sevenDiamond);
player2 = new User(hand2);
players.add(player1);
players.add(player2);
comparingHands = new CompareHands(players, table);
//For now, counts as a tie
assertEquals(-1, comparingHands.compareHands());
}
/** Test pair wins against lower pair */
@Test
public void pairBeatsPair() {
table = new TableCards(sevenClub, tenDiamond, threeHeart, sixDiamond, fourClub);
hand1 = new Hand(aceHeart, tenSpade);
player1 = new User(hand1);
hand2 = new Hand(twoHeart, sevenDiamond);
player2 = new User(hand2);
players.add(player1);
players.add(player2);
comparingHands = new CompareHands(players, table);
//For now, counts as a tie
assertEquals(-1, comparingHands.compareHands());
}
/** Test player with higher card wins when no actual hands are able to be made */
@Test
public void testHighCardBeatsLowerCard() {
table = new TableCards(sevenClub, tenDiamond, threeHeart, sixDiamond, fourClub);
hand1 = new Hand(aceHeart, twoSpade);
player1 = new User(hand1);
hand2 = new Hand(nineHeart, jackDiamond);
player2 = new User(hand2);
players.add(player1);
players.add(player2);
comparingHands = new CompareHands(players, table);
//For now, counts as a tie
assertEquals(-1, comparingHands.compareHands());
}
}
|
package eu.ydp.empiria.player.client.module.math;
import java.util.List;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.dom.client.Style.Overflow;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HasWidgets;
import eu.ydp.empiria.player.client.PlayerGinjector;
import eu.ydp.empiria.player.client.components.ExListBoxChangeListener;
import eu.ydp.empiria.player.client.module.Factory;
import eu.ydp.empiria.player.client.module.ModuleJsSocketFactory;
import eu.ydp.empiria.player.client.module.OneViewInteractionModuleBase;
import eu.ydp.empiria.player.client.module.binding.BindingGroupIdentifier;
import eu.ydp.empiria.player.client.module.binding.DefaultBindingGroupIdentifier;
import eu.ydp.empiria.player.client.resources.StyleNameConstants;
import eu.ydp.empiria.player.client.util.events.bus.EventsBus;
import eu.ydp.empiria.player.client.util.events.player.PlayerEvent;
import eu.ydp.empiria.player.client.util.events.player.PlayerEventHandler;
import eu.ydp.empiria.player.client.util.events.player.PlayerEventTypes;
public class MathModule extends OneViewInteractionModuleBase implements Factory<MathModule> {
protected AbsolutePanel outerPanel;
protected FlowPanel mainPanel;
protected AbsolutePanel listBoxesLayer;
private final EventsBus eventsBus = PlayerGinjector.INSTANCE.getEventsBus();
protected List<MathGap> gaps;
protected BindingGroupIdentifier widthBindingIdentifier;
protected boolean showingAnswer = false;
protected boolean markingAnswer = false;
protected boolean locked = false;
protected StyleNameConstants styleNames = PlayerGinjector.INSTANCE.getStyleNameConstants();
private MathModuleHelper helper;
@Override
public void installViews(List<HasWidgets> placeholders) {
eventsBus.addHandler(PlayerEvent.getType(PlayerEventTypes.BEFORE_FLOW), new PlayerEventHandler() {
@Override
public void onPlayerEvent(PlayerEvent event) {
if(event.getType()==PlayerEventTypes.BEFORE_FLOW){
updateResponse(false);
}
}
});
outerPanel = new AbsolutePanel();
outerPanel.getElement().getStyle().setOverflow(Overflow.VISIBLE);
outerPanel.setStyleName(styleNames.QP_MATHINTERACTION());
mainPanel = new FlowPanel();
mainPanel.setStyleName(styleNames.QP_MATHINTERACTION_INNER());
outerPanel.add(mainPanel, 0, 0);
applyIdAndClassToView(mainPanel);
placeholders.get(0).add(outerPanel);
if (getModuleElement().hasAttribute("widthBindingGroup")){
widthBindingIdentifier = new DefaultBindingGroupIdentifier(getModuleElement().getAttribute("widthBindingGroup"));
}
helper = new MathModuleHelper(getModuleElement(), getModuleSocket(), getResponse(), this);
helper.initStyles();
helper.initGapsProperties();
gaps = helper.initGaps();
initGapListeners();
}
@Override
public void onBodyLoad() {
}
@Override
public void onBodyUnload() {
}
@Override
public void onSetUp() {
listBoxesLayer = new AbsolutePanel();
listBoxesLayer.getElement().getStyle().setOverflow(Overflow.VISIBLE);
listBoxesLayer.setStyleName(styleNames.QP_MATHINTERACTION_GAPS());
outerPanel.add(listBoxesLayer);
helper.placeGaps(listBoxesLayer);
updateResponse(false);
}
private void initGapListeners(){
for (MathGap gap : gaps){
if (gap instanceof TextEntryGap){
((TextEntryGap)gap).getTextBox().addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
updateResponse(true);
}
});
} else if (gap instanceof InlineChoiceGap){
((InlineChoiceGap)gap).getListBox().setChangeListener(new ExListBoxChangeListener() {
@Override
public void onChange() {
updateResponse(true);
}
});
}
}
}
@Override
public void onStart() {
helper.calculateActualSizes();
helper.setSizes();
helper.initMath(mainPanel);
listBoxesLayer.setWidth(mainPanel.getOffsetWidth() + "px");
listBoxesLayer.setHeight(mainPanel.getOffsetHeight() + "px");
helper.positionGaps(listBoxesLayer);
}
@Override
public void onClose() {
}
@Override
public void markAnswers(boolean mark) {
if (mark && !markingAnswer){
List<Boolean> evaluation = getModuleSocket().evaluateResponse(getResponse());
for (int i = 0 ; i < evaluation.size() && i < gaps.size() ; i ++){
if ("".equals( getResponse().values.get(i)) ){
gaps.get(i).mark(false, false);
} else if (evaluation.get(i)){
gaps.get(i).mark(true, false);
} else {
gaps.get(i).mark(false, true);
}
}
} else if (!mark && markingAnswer){
for (int i = 0 ; i < gaps.size() ; i ++){
gaps.get(i).unmark();
}
}
markingAnswer = mark;
}
@Override
public void showCorrectAnswers(boolean show) {
if (show && !showingAnswer){
for (int i = 0 ; i < getResponse().correctAnswers.getResponseValuesCount() ; i ++){
gaps.get(i).setValue( getResponse().correctAnswers.getResponseValue(i).getAnswers().get(0) );
}
} else if (!show && showingAnswer){
for (int i = 0 ; i < getResponse().values.size() ; i ++){
gaps.get(i).setValue( getResponse().values.get(i) );
}
}
showingAnswer = show;
}
@Override
public void lock(boolean lock) {
locked = lock;
for (int i = 0 ; i < gaps.size() ; i ++){
gaps.get(i).setEnabled(!lock);
}
}
@Override
public void reset() {
for (int i = 0 ; i < gaps.size() ; i ++){
gaps.get(i).reset();
gaps.get(i).unmark();
}
updateResponse(false);
}
@Override
public JSONArray getState() {
JSONArray arr = new JSONArray();
for (int i = 0 ; i < getResponse().values.size() ; i ++){
JSONString val = new JSONString(getResponse().values.get(i));
arr.set(i, val);
}
return arr;
}
@Override
public void setState(JSONArray newState) {
if (newState.isArray() != null){
for (int i = 0 ; i < gaps.size() ; i ++){
gaps.get(i).setValue(newState.get(i).isString().stringValue());
}
}
updateResponse(false);
}
@Override
public JavaScriptObject getJsSocket() {
return ModuleJsSocketFactory.createSocketObject(this);
}
private void updateResponse(boolean userInteract){
if (showingAnswer) {
return;
}
if (getResponse() != null){
getResponse().values.clear();
for (int i = 0 ; i < gaps.size() ; i ++){
getResponse().values.add( gaps.get(i).getValue() );
}
fireStateChanged(userInteract);
}
}
@Override
public MathModule getNewInstance() {
return new MathModule();
}
}
|
package org.herac.tuxguitar.util;
public class TGSynchronizer {
private static TGSynchronizer instance;
private TGSynchronizerController controller;
private TGSynchronizer(){
super();
}
public static TGSynchronizer instance(){
if (instance == null) {
synchronized (TGSynchronizer.class) {
instance = new TGSynchronizer();
}
}
return instance;
}
public void addRunnable(TGRunnable runnable) throws Throwable {
TGSynchronizerTask task = new TGSynchronizerTask(runnable);
this.controller.excecute(task);
if(task.getThrowable() != null){
throw task.getThrowable();
}
}
public void setController(TGSynchronizerController controller){
this.controller = controller;
}
public class TGSynchronizerTask{
private long threadId;
private Throwable throwable;
private TGRunnable runnable;
public TGSynchronizerTask(TGRunnable runnable){
this.threadId = Thread.currentThread().getId();
this.runnable = runnable;
this.throwable = null;
}
public Throwable getThrowable(){
return this.throwable;
}
public long getThreadId(){
return this.threadId;
}
public void run(){
try{
this.runnable.run();
}catch(Throwable throwable){
this.throwable = throwable;
}
}
}
public interface TGRunnable {
public void run() throws Throwable;
}
public interface TGSynchronizerController{
public void excecute(TGSynchronizerTask task);
}
}
|
// -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import javax.swing.*;
public final class MainPanel extends JPanel {
private MainPanel() {
super(new BorderLayout());
UIManager.put("TabbedPane.tabInsets", new Insets(1, 4, 0, 4));
UIManager.put("TabbedPane.selectedTabPadInsets", new Insets(1, 1, 1, 1));
UIManager.put("TabbedPane.tabAreaInsets", new Insets(3, 2, 0, 2));
UIManager.put("TabbedPane.selectedLabelShift", 0);
UIManager.put("TabbedPane.labelShift", 0);
JTabbedPane tabs = new UnderlineFocusTabbedPane();
tabs.addTab("JTree", new ColorIcon(Color.RED), new JScrollPane(new JTree()));
tabs.addTab("JTextArea", new ColorIcon(Color.GREEN), new JScrollPane(new JTextArea()));
tabs.addTab("JTable", new ColorIcon(Color.BLUE), new JScrollPane(new JTable(8, 3)));
tabs.addTab("JSplitPane", new ColorIcon(Color.ORANGE), new JScrollPane(new JSplitPane()));
tabs.setSelectedIndex(-1);
EventQueue.invokeLater(() -> tabs.setSelectedIndex(0));
add(tabs);
setPreferredSize(new Dimension(320, 240));
}
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 UnderlineFocusTabbedPane extends JTabbedPane {
private static final Color ALPHA_ZERO = new Color(0x0, true);
private static final Color SELECTION_COLOR = new Color(0x00_AA_FF);
protected UnderlineFocusTabbedPane() {
super();
}
@Override public void updateUI() {
UIManager.put("TabbedPane.focus", new Color(0x0, true));
super.updateUI();
// if (getUI() instanceof WindowsTabbedPaneUI) {
// setUI(new WindowsTabbedPaneUI() {
// @Override protected void paintFocusIndicator(Graphics g, int tabPlacement, Rectangle[] rects, int tabIndex, Rectangle iconRect, Rectangle textRect, boolean isSelected) {
// super.paintFocusIndicator(
// g, tabPlacement, rects, tabIndex, iconRect, textRect, false);
// } else {
// setUI(new BasicTabbedPaneUI() {
// @Override protected void paintFocusIndicator(Graphics g, int tabPlacement, Rectangle[] rects, int tabIndex, Rectangle iconRect, Rectangle textRect, boolean isSelected) {
// super.paintFocusIndicator(
// g, tabPlacement, rects, tabIndex, iconRect, textRect, false);
addChangeListener(e -> {
JTabbedPane tabbedPane = (JTabbedPane) e.getSource();
if (tabbedPane.getTabCount() <= 0) {
return;
}
int idx = tabbedPane.getSelectedIndex();
for (int i = 0; i < tabbedPane.getTabCount(); i++) {
Component c = tabbedPane.getTabComponentAt(i);
if (c instanceof JComponent) {
Color color = i == idx ? SELECTION_COLOR : ALPHA_ZERO;
((JComponent) c).setBorder(BorderFactory.createMatteBorder(0, 0, 3, 0, color));
}
}
});
}
@Override public void insertTab(String title, Icon icon, Component component, String tip, int index) {
super.insertTab(title, icon, component, tip, index);
JLabel label = new JLabel(title, icon, SwingConstants.CENTER);
setTabComponentAt(index, label);
}
}
class ColorIcon implements Icon {
private final Color color;
protected ColorIcon(Color color) {
this.color = color;
}
@Override public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2 = (Graphics2D) g.create();
g2.translate(x, y);
g2.setPaint(color);
g2.fillRect(1, 1, getIconWidth() - 3, getIconHeight() - 3);
g2.dispose();
}
@Override public int getIconWidth() {
return 16;
}
@Override public int getIconHeight() {
return 16;
}
}
|
package edu.wustl.query.annotations.xmi;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import javax.jmi.model.ModelPackage;
import javax.jmi.model.MofPackage;
import javax.jmi.xmi.XmiReader;
import org.netbeans.api.mdr.MDRManager;
import org.netbeans.api.mdr.MDRepository;
import org.omg.uml.UmlPackage;
import org.openide.util.Lookup;
import edu.common.dynamicextensions.bizlogic.BizLogicFactory;
import edu.common.dynamicextensions.domain.AbstractMetadata;
import edu.common.dynamicextensions.domaininterface.EntityInterface;
import edu.common.dynamicextensions.domaininterface.userinterface.ContainerInterface;
import edu.common.dynamicextensions.exception.DynamicExtensionsSystemException;
import edu.common.dynamicextensions.xmi.XMIUtilities;
import edu.common.dynamicextensions.xmi.importer.XMIImportProcessor;
import edu.wustl.common.bizlogic.DefaultBizLogic;
import edu.wustl.common.util.logger.Logger;
import edu.wustl.query.bizlogic.AnnotationUtil;
import edu.wustl.query.util.global.Constants;
/**
* @author ashish_gupta
*
*/
public class ImportXmi
{
// name of a UML extent (instance of UML metamodel) that the UML models will be loaded into
private static final String UML_INSTANCE = "UMLInstance";
// name of a MOF extent that will contain definition of UML metamodel
private static final String UML_MM = "UML";
// repository
private static MDRepository rep;
// UML extent
private static UmlPackage uml;
// XMI reader
private static XmiReader reader;
/**
* @param args
*/
public static void main(String[] args)
{
Logger.configure("");
FileInputStream fileInputStream = null;
try
{
//validate(args);
//Ist parameter is fileName
// Fully qualified Name of the xmi file to be imported
String fileName = "cider.xmi";
String hookEntity = "none";
if (args.length > 0)
{
fileName = args[0];
hookEntity = args[1];
}
//"C://Documents and Settings//ashish_gupta//Desktop//XMLs//caTissueCore_1.4_Edited.xmi";
File file = new File(fileName);
Logger.out.info("
Logger.out.info("Filename = " + file.getAbsolutePath());
Logger.out.info("Hook Entity = " + hookEntity);
String packageName = "";
//String conditionRecordObjectCsvFileName = "";
String pathCsvFileName = "";
int indexOfExtension = file.getName().lastIndexOf(".");
String domainModelName = "";
if (indexOfExtension == -1)
{
domainModelName = file.getName();
}
else
{
domainModelName = file.getName().substring(0, indexOfExtension);
}
Logger.out.info("Name of the file = " + domainModelName);
Logger.out.info("\n
// get the default repository
rep = MDRManager.getDefault().getDefaultRepository();
// create an XMIReader
reader = Lookup.getDefault().lookup(XmiReader.class);
init();
fileInputStream = new FileInputStream(file);
// start a read-only transaction
rep.beginTrans(true);
// read the document
reader.read(fileInputStream, null, uml);
pathCsvFileName = "cider.csv";
if (args.length > 2)
{
pathCsvFileName = args[2];
}
packageName = "edu.wustl.cider.domain.discritdata";
if (args.length > 3)
{
packageName = args[3];
}
/*if (args.length > 4)
{
conditionRecordObjectCsvFileName = args[4];
}*/
if (("").equals(packageName))
{
throw new Exception(
"Package name is mandatory parameter. If no package is present please specify 'Default'.");
}
/**
* This code is commented out by Baljeet.....As it was related to something Collection Protocol
*/
/*List<Long> conditionObjectIds = new ArrayList<Long>();
if(!conditionRecordObjectCsvFileName.equals(""))
{
List<String> conditionObjectNames = readFile(conditionRecordObjectCsvFileName);
for(String conditionObjName :conditionObjectNames)
{
System.out.println("conditionObjName = " + conditionObjName);
Long cpId =(Long) getObjectIdentifier(conditionObjName,CollectionProtocol.class.getName(),Constants.TITLE);
if(cpId == null)
{
throw new DynamicExtensionsSystemException("Specified Collection Protocol does not exist.");
}
conditionObjectIds.add(cpId);
}
}*/
//EntityInterface staticEntity = null;
if (!hookEntity.equalsIgnoreCase(AnnotationConstants.NONE))
{
DefaultBizLogic defaultBizLogic = BizLogicFactory.getDefaultBizLogic();
List staticEntityList = defaultBizLogic.retrieve(AbstractMetadata.class.getName(),
Constants.NAME, hookEntity);
if (staticEntityList == null || staticEntityList.isEmpty())
{
throw new DynamicExtensionsSystemException(
"Please enter correct Hook Entity name.");
}
//staticEntity = (EntityInterface) staticEntityList.get(0);
}
boolean isEntityGroupSystemGenerated = false;
boolean isCreateTable = false;
// this variable indicates that the import xmi is run only to store the metaData
// not to create the tables
//Baljeet........
// if(hookEntity.equalsIgnoreCase(AnnotationConstants.NONE))
// isEntityGroupSystemGenerated = true;
List<String> containerNames = readFile(pathCsvFileName);
XMIImportProcessor xmiImportProcessor = new XMIImportProcessor();
List<ContainerInterface> mainContainerList = xmiImportProcessor.processXmi(uml,
domainModelName, packageName, containerNames, isEntityGroupSystemGenerated,isCreateTable);
boolean isEditedXmi = xmiImportProcessor.isEditedXmi;
Logger.out.info("\n
Logger.out.info("Package name = " + packageName);
Logger.out.info("isEditedXmi = " + isEditedXmi);
Logger.out.info("Forms have been created !!!!");
Logger.out.info("Associating with hook entity.");
Logger.out.info("\n
//List<ContainerInterface> mainContainerList = getMainContainerList(pathCsvFileName,entityNameVsContainers);
if (!hookEntity.equalsIgnoreCase(AnnotationConstants.NONE))
{//Integrating with hook entity
/**
* Commneted out by baljeet as for Query , we will be having no hooked Entity, so this condition will never be executed
*/
//associateHookEntity(mainContainerList,conditionObjectIds,staticEntity,isEditedXmi);
}
else
{
Set<PathObject> processedPathList = new HashSet<PathObject>();
for (ContainerInterface mainContainer : mainContainerList)
{
AnnotationUtil.addQueryPathsForAllAssociatedEntities(
((EntityInterface) mainContainer.getAbstractEntity()), null, null,
null, processedPathList);
}
}
Logger.out.info("
}
catch (Exception e)
{
Logger.out.info("Fatal error reading XMI.");
Logger.out.info("
Logger.out.info(e.getMessage(),e);
Logger.out.info("\n
}
finally
{
// release the transaction
rep.endTrans();
MDRManager.getDefault().shutdownAll();
try
{
fileInputStream.close();
}
catch (IOException io)
{
Logger.out.debug("Error. Specified file does not exist.");
}
XMIUtilities.cleanUpRepository();
}
}
*//*
/**
* @param args
* @throws Exception
private static void validate(String[] args) throws Exception
{
if (args.length == 0)
{
throw new Exception("Please Specify the file name to be imported");
}
if (args.length < 2)
{
throw new Exception("Please Specify the hook entity name");
}
if (args.length < 3)
{
throw new Exception("Please Specify the main container csv file name");
}
if (args.length < 4)
{
throw new Exception("Please Specify the name of the Package to be imported");
}
}*/
/**
* @param path
* @param entityNameVsContainers
* @return
* @throws IOException
*/
// private static List<ContainerInterface> getMainContainerList(String path,Map<String, List<ContainerInterface>> entityNameVsContainers) throws IOException
// List<ContainerInterface> mainContainerList = getContainerObjectList(containerNames,entityNameVsContainers);
// return mainContainerList;
/**
* @param path
* @return
* @throws IOException
*/
private static List<String> readFile(String path) throws IOException
{
List<String> containerNames = new ArrayList<String>();
File file = new File(path);
BufferedReader bufRdr = new BufferedReader(new FileReader(file));
String line = null;
//read each line of text file
while ((line = bufRdr.readLine()) != null)
{
StringTokenizer tokens = new StringTokenizer(line, ",");
while (tokens.hasMoreTokens())
{
//get next token and store it in the array
containerNames.add(tokens.nextToken());
}
}
return containerNames;
}
private static void init() throws Exception
{
uml = (UmlPackage) rep.getExtent(UML_INSTANCE);
if (uml == null)
{
// UML extent does not exist -> create it (note that in case one want's to instantiate
// a metamodel other than MOF, they need to provide the second parameter of the createExtent
// method which indicates the metamodel package that should be instantiated)
uml = (UmlPackage) rep.createExtent(UML_INSTANCE, getUmlPackage());
}
}
/** Finds "UML" package -> this is the topmost package of UML metamodel - that's the
* package that needs to be instantiated in order to create a UML extent
*/
private static MofPackage getUmlPackage() throws Exception
{
// get the MOF extent containing definition of UML metamodel
ModelPackage umlMM = (ModelPackage) rep.getExtent(UML_MM);
if (umlMM == null)
{
// it is not present -> create it
umlMM = (ModelPackage) rep.createExtent(UML_MM);
}
// find package named "UML" in this extent
MofPackage result = getUmlPackage(umlMM);
if (result == null)
{
// it cannot be found -> UML metamodel is not loaded -> load it from XMI
reader.read(UmlPackage.class.getResource("resources/01-02-15_Diff.xml").toString(),
umlMM);
// try to find the "UML" package again
result = getUmlPackage(umlMM);
}
return result;
}
/** Finds "UML" package in a given extent
* @param umlMM MOF extent that should be searched for "UML" package.
*/
private static MofPackage getUmlPackage(ModelPackage umlMM)
{
// iterate through all instances of package
for (Iterator it = umlMM.getMofPackage().refAllOfClass().iterator(); it.hasNext();)
{
MofPackage pkg = (MofPackage) it.next();
Logger.out.info("\n\nName = " + pkg.getName());
// is the package topmost and is it named "UML"?
if (pkg.getContainer() == null && "UML".equals(pkg.getName()))
{
// yes -> return it
return pkg;
}
}
// a topmost package named "UML" could not be found
return null;
}
/**
* @throws DAOException
* @throws DynamicExtensionsSystemException
* @throws UserNotAuthorizedException
* @throws BizLogicException
* @throws DynamicExtensionsApplicationException
*
*/
/*private static void associateHookEntity(List<ContainerInterface> mainContainerList,
List<Long> conditionObjectIds, EntityInterface staticEntity, boolean isEditedXmi)
throws DAOException, DynamicExtensionsSystemException, BizLogicException,
UserNotAuthorizedException, DynamicExtensionsApplicationException
{
Object typeId = getObjectIdentifier("edu.wustl.catissuecore.domain.CollectionProtocol",
AbstractMetadata.class.getName(), Constants.NAME);
DefaultBizLogic defaultBizLogic = BizLogicFactory.getDefaultBizLogic();
//Set<String> keySet = entityNameVsContainers.keySet();
// for(String key : keySet)
for (ContainerInterface container : mainContainerList)
{
// List<ContainerInterface> containerList = entityNameVsContainers.get(key);
// ContainerInterface container = containerList.get(0);
if (isEditedXmi)
{//Retrieve entity map
List<EntityMap> entityMapList = defaultBizLogic.retrieve(EntityMap.class.getName(),
"containerId", container.getId());
if (entityMapList != null && entityMapList.size() > 0)
{
EntityMap entityMap = entityMapList.get(0);
if (conditionObjectIds != null)
{
editConditions(entityMap, conditionObjectIds, typeId);
}
AnnotationBizLogic annotation = new AnnotationBizLogic();
annotation.updateEntityMap(entityMap);
}
else
{//Create new Entity Map
createIntegrationObjects(container, staticEntity, conditionObjectIds, typeId);
}
}
else
{//Create new Entity Map
createIntegrationObjects(container, staticEntity, conditionObjectIds, typeId);
}
}
}*/
/**
* @param entityMap
* @param clinicalStudyId
* @param typeId
* @throws DynamicExtensionsSystemException
* @throws DAOException
*/
/*private static void editConditions(EntityMap entityMap, List<Long> conditionObjectIds,
Object typeId) throws DynamicExtensionsSystemException, DAOException
{
Collection<FormContext> formContextColl = entityMap.getFormContextCollection();
for (FormContext formContext : formContextColl)
{
Collection<EntityMapCondition> entityMapCondColl = formContext
.getEntityMapConditionCollection();
for (Long collectionProtocolId : conditionObjectIds)
{
int temp = 0;
for (EntityMapCondition condition : entityMapCondColl)
{
if (condition.getStaticRecordId().compareTo(collectionProtocolId) == 0)
{
temp++;
break;
}
}
if (temp == 0)
{
EntityMapCondition entityMapCondition = getEntityMapCondition(formContext,
collectionProtocolId, typeId);
entityMapCondColl.add(entityMapCondition);
}
}
formContext.setEntityMapConditionCollection(entityMapCondColl);
}
}*/
/**
* @param container
* @param staticEntity
* @param clinicalStudyId
* @param typeId
* @throws DynamicExtensionsSystemException
* @throws DAOException
* @throws BizLogicException
* @throws UserNotAuthorizedException
* @throws DynamicExtensionsApplicationException
*/
/*private static void createIntegrationObjects(ContainerInterface container,
EntityInterface staticEntity, List<Long> conditionObjectIds, Object typeId)
throws DynamicExtensionsSystemException, DAOException, BizLogicException,
UserNotAuthorizedException, DynamicExtensionsApplicationException
{
EntityMap entityMap = getEntityMap(container, staticEntity.getId());
Collection<FormContext> formContextColl = getFormContext(entityMap, conditionObjectIds,
typeId);
entityMap.setFormContextCollection(formContextColl);
AnnotationBizLogic annotation = new AnnotationBizLogic();
annotation.insert(entityMap, Constants.HIBERNATE_DAO);
AnnotationUtil.addAssociation(staticEntity.getId(), container.getId(), true);
}*/
/**
* @param entityMap
* @param collectionProtocolName
* @param typeId
* @return
* @throws DynamicExtensionsSystemException
* @throws DAOException
*/
/*private static Collection<FormContext> getFormContext(EntityMap entityMap,
List<Long> conditionObjectIds, Object typeId) throws DynamicExtensionsSystemException,
DAOException
{
Collection<FormContext> formContextColl = new HashSet<FormContext>();
FormContext formContext = new FormContext();
formContext.setEntityMap(entityMap);
Collection<EntityMapCondition> entityMapConditionColl = new HashSet<EntityMapCondition>();
if (conditionObjectIds != null)
{
for (Long cpId : conditionObjectIds)
{
entityMapConditionColl.add(getEntityMapCondition(formContext, cpId, typeId));
}
}
formContext.setEntityMapConditionCollection(entityMapConditionColl);
formContextColl.add(formContext);
return formContextColl;
}*/
/**
* @param formContext
* @param collectionProtocolName
* @param typeId
* @return
* @throws DynamicExtensionsSystemException
* @throws DAOException
*/
*//**
*//*
*//**
*//*
/*private static EntityMapCondition getEntityMapCondition(FormContext formContext,
Long conditionObjectId, Object typeId) throws DynamicExtensionsSystemException,
DAOException
{
// Collection<EntityMapCondition> entityMapCondColl = new HashSet<EntityMapCondition>();
// for(Long cpId : conditionObjectIds)
// {
EntityMapCondition entityMapCondition = new EntityMapCondition();
entityMapCondition.setStaticRecordId((conditionObjectId));
entityMapCondition.setTypeId(((Long) typeId));
entityMapCondition.setFormContext(formContext);
// entityMapCondColl.add(entityMapCondition);
// }
return entityMapCondition;
}
* @param container
* @param hookEntityName
* @return
* @throws DAOException
* @throws DynamicExtensionsSystemException
private static EntityMap getEntityMap(ContainerInterface container, Object staticEntityId)
throws DAOException, DynamicExtensionsSystemException
{
EntityMap entityMap = new EntityMap();
entityMap.setContainerId(container.getId());
entityMap.setCreatedBy("");
entityMap.setCreatedDate(new Date());
entityMap.setLinkStatus(AnnotationConstants.STATUS_ATTACHED);
entityMap.setStaticEntityId(((Long) staticEntityId));
return entityMap;
}
* @param hookEntityName
* @return
* @throws DAOException
private static Object getObjectIdentifier(String whereColumnValue, String selectObjName,
String whereColumnName) throws DAOException
{
DefaultBizLogic defaultBizLogic = BizLogicFactory.getDefaultBizLogic();
String[] selectColName = {Constants.SYSTEM_IDENTIFIER};
String[] whereColName = {whereColumnName};
Object[] whereColValue = {whereColumnValue};
String[] whereColCondition = {Constants.Equals};
String joinCondition = Constants.AND_JOIN_CONDITION;
List id = defaultBizLogic.retrieve(selectObjName, selectColName, whereColName,
whereColCondition, whereColValue, joinCondition);
Object object = null;
if (id != null && id.size() > 0)
{
object = id.get(0);
}
return object;
}*/
}
|
package de.aima13.whoami.support;
import java.io.File;
import java.sql.*;
public class DataSourceManager {
private Connection dbConnection = null;
public DataSourceManager(File sqliteDatabase) throws ClassNotFoundException, SQLException {
Class.forName("org.sqlite.JDBC");
dbConnection = DriverManager.getConnection
("jdbc:sqlite:" + sqliteDatabase.getAbsolutePath());
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
if (!dbConnection.isClosed() && dbConnection != null) {
dbConnection.close();
}
} catch (SQLException e) {
}
}
});
}
/**
* Zur Abfrage, ob Verbindung noch offen ist bzw von null verschieden.
* @return Boolean, der angibt ob die Verbindung zustande gekommen ist, bzw. noch offen ist.
*/
public boolean isConnected(){
try {
return !dbConnection.isClosed();
} catch (SQLException e) {
return false;
}
}
public ResultSet querySqlStatement(String statement) throws SQLException {
Statement s = dbConnection.createStatement();
ResultSet rs = s.executeQuery(statement);
return rs;
}
public void closeConnection() {
try {
if (!dbConnection.isClosed() && dbConnection != null) {
dbConnection.close();
}
} catch (SQLException e) {
}
}
}
|
package de.aima13.whoami.support;
import java.io.File;
import java.sql.*;
public class DataSourceManager {
private Connection dbConnection = null;
public DataSourceManager(File sqliteDatabase) throws ClassNotFoundException, SQLException {
Class.forName("org.sqlite.JDBC");
dbConnection = DriverManager.getConnection
("jdbc:sqlite:" + sqliteDatabase.getAbsolutePath());
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
if (!dbConnection.isClosed() && dbConnection != null) {
dbConnection.close();
}
} catch (SQLException e) {
}
}
});
}
public boolean isConnected(){
try {
return !dbConnection.isClosed();
} catch (SQLException e) {
return false;
}
}
public ResultSet querySqlStatement(String statement) throws SQLException {
Statement s = dbConnection.createStatement();
ResultSet rs = s.executeQuery(statement);
return rs;
}
public void closeConnection() {
try {
if (!dbConnection.isClosed() && dbConnection != null) {
dbConnection.close();
}
} catch (SQLException e) {
}
}
}
|
package aima.gui.fx.demo.search;
import aima.core.environment.nqueens.AttackingPairsHeuristic;
import aima.core.environment.nqueens.NQueensBoard;
import aima.core.environment.nqueens.NQueensBoard.Config;
import aima.core.search.framework.Metrics;
import aima.core.search.framework.qsearch.GraphSearch;
import aima.core.search.framework.qsearch.TreeSearch;
import aima.core.search.informed.AStarSearch;
import aima.core.search.informed.GreedyBestFirstSearch;
import aima.core.search.uninformed.BreadthFirstSearch;
import aima.core.search.uninformed.DepthFirstSearch;
import aima.core.search.uninformed.IterativeDeepeningSearch;
import aima.gui.fx.framework.IntegrableApplication;
import aima.gui.fx.framework.Parameter;
import aima.gui.fx.framework.SimulationPaneBuilder;
import aima.gui.fx.framework.SimulationPaneCtrl;
import aima.gui.fx.views.NQueensViewCtrl;
import javafx.application.Platform;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import java.util.Arrays;
/**
* Integrable application which demonstrates how different search strategies
* solve the N-Queens problem.
*
* @author Ruediger Lunde
*
*/
public class NQueensSearchApp extends IntegrableApplication {
public static void main(String[] args) {
launch(args);
}
public final static String PARAM_STRATEGY = "strategy";
public final static String PARAM_BOARD_SIZE = "boardSize";
public final static String PARAM_INIT_CONFIG = "initConfig";
private NQueensViewCtrl stateViewCtrl;
private SimulationPaneCtrl simPaneCtrl;
private NQueensSearchProg experiment;
public NQueensSearchApp() {
experiment = new NQueensSearchProg();
experiment.addProgressTracer(this::updateStateView);
}
@Override
public String getTitle() {
return "N-Queens Search App";
}
/**
* Defines state view, parameters, and call-back functions and calls the
* simulation pane builder to create layout and controller objects.
*/
@Override
public Pane createRootPane() {
BorderPane root = new BorderPane();
StackPane stateView = new StackPane();
stateViewCtrl = new NQueensViewCtrl(stateView);
Parameter[] params = createParameters();
SimulationPaneBuilder builder = new SimulationPaneBuilder();
builder.defineParameters(params);
builder.defineStateView(stateView);
builder.defineInitMethod(this::initialize);
builder.defineSimMethod(this::simulate);
simPaneCtrl = builder.getResultFor(root);
simPaneCtrl.setParam(SimulationPaneCtrl.PARAM_SIM_SPEED, 1);
return root;
}
protected Parameter[] createParameters() {
Parameter p1 = new Parameter(PARAM_STRATEGY,
"Depth-First Search (incremental)", "Breadth-First Search (incremental)",
"Iterative Deepening Search",
"Greedy Best-First Search (attacking pair heuristic)", "A* search (attacking pair heuristic)",
"Hill Climbing", "Simulated Annealing", "Genetic Algorithm");
Parameter p2 = new Parameter(PARAM_BOARD_SIZE, 4, 8, 16, 32, 64);
p2.setDefaultValueIndex(1);
Parameter p3 = new Parameter(PARAM_INIT_CONFIG, "FirstRow", "Random");
p3.setDependency(PARAM_STRATEGY, "Iterative Deepening Search",
"Greedy Best-First Search (attacking pair heuristic)", "A* search (attacking pair heuristic)",
"Hill Climbing", "Simulated Annealing", "Genetic Algorithm");
return new Parameter[] {p1, p2, p3};
}
/** Displays the initialized board on the state view. */
@Override
public void initialize() {
experiment.setBoardSize(simPaneCtrl.getParamAsInt(PARAM_BOARD_SIZE));
Object strategy = simPaneCtrl.getParamValue(PARAM_STRATEGY);
Config config;
if (Arrays.asList("Depth-First Search (incremental)", "Breadth-First Search (incremental)", "Genetic Algorithm")
.contains(strategy))
config = Config.EMPTY;
else if (simPaneCtrl.getParamValue(PARAM_INIT_CONFIG).equals("Random"))
config = Config.QUEEN_IN_EVERY_COL;
else
config = Config.QUEENS_IN_FIRST_ROW;
experiment.initExperiment(config);
stateViewCtrl.update(experiment.getBoard());
}
@Override
public void finalize() {
simPaneCtrl.cancelSimulation();
}
/** Starts the experiment. */
public void simulate() {
Object strategy = simPaneCtrl.getParamValue(PARAM_STRATEGY);
if (strategy.equals("Depth-First Search (incremental)"))
experiment.startExperiment(new DepthFirstSearch(new TreeSearch()));
else if (strategy.equals("Breadth-First Search (incremental)"))
experiment.startExperiment(new BreadthFirstSearch(new TreeSearch()));
else if (strategy.equals("Iterative Deepening Search"))
experiment.startExperiment(new IterativeDeepeningSearch());
else if (strategy.equals("Greedy Best-First Search (attacking pair heuristic)"))
experiment.startExperiment(new GreedyBestFirstSearch(new GraphSearch(), new AttackingPairsHeuristic()));
else if (strategy.equals("A* search (attacking pair heuristic)"))
experiment.startExperiment(new AStarSearch(new GraphSearch(), new AttackingPairsHeuristic()));
else if (strategy.equals("Hill Climbing"))
experiment.startHillClimbingExperiment();
else if (strategy.equals("Simulated Annealing"))
experiment.startSimulatedAnnealingExperiment();
else if (strategy.equals("Genetic Algorithm"))
experiment.startGenAlgoExperiment(simPaneCtrl.getParamValue(PARAM_INIT_CONFIG).equals("Random"));
}
/**
* Caution: While the background thread should be slowed down, updates of
* the GUI have to be done in the GUI thread!
*/
private void updateStateView(NQueensBoard board, Metrics metrics) {
Platform.runLater(() -> updateStateViewLater(board, metrics));
simPaneCtrl.waitAfterStep();
}
/**
* Must be called by the GUI thread!
*/
private void updateStateViewLater(NQueensBoard board, Metrics metrics) {
stateViewCtrl.update(board);
simPaneCtrl.setStatus(metrics.toString());
}
}
|
package ca.codybanman.AstroidEscape.android;
import android.annotation.SuppressLint;
import android.app.ActionBar.LayoutParams;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import ca.codybanman.AEHelpers.IActivityRequestHandler;
import ca.codybanman.AstroidEscape.AEGame;
import ca.codybanman.GameServices.ActionResolver;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.facebook.AppEventsLogger;
import com.facebook.UiLifecycleHelper;
import com.facebook.widget.FacebookDialog;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.games.Games;
import com.google.example.games.basegameutils.GameHelper;
import com.google.example.games.basegameutils.GameHelper.GameHelperListener;
@SuppressLint("HandlerLeak")
public class AndroidLauncher extends AndroidApplication implements
IActivityRequestHandler, GameHelperListener, ActionResolver {
private GameHelper gameHelper;
private UiLifecycleHelper uiHelper;
private final int SHOW_ADS = 1;
private final int HIDE_ADS = 0;
protected Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SHOW_ADS: {
adView.setVisibility(View.VISIBLE);
break;
}
case HIDE_ADS: {
adView.setVisibility(View.INVISIBLE);
break;
}
}
}
};
AdView adView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
cfg.useGLSurfaceView20API18 = true;
cfg.useAccelerometer = false;
cfg.useCompass = false;
RelativeLayout layout = new RelativeLayout(this);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
View gameView = initializeForView(new AEGame(this, this), cfg);
if (gameHelper == null) {
gameHelper = new GameHelper(this, GameHelper.CLIENT_GAMES);
gameHelper.enableDebugLog(true);
}
gameHelper.setup(this);
uiHelper = new UiLifecycleHelper(this, null);
uiHelper.onCreate(savedInstanceState);
adView = new AdView(this);
adView.setAdSize(AdSize.SMART_BANNER);
adView.setAdUnitId("ca-app-pub-7512999237077002/4617342779");
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("D4514AFD171EE7ABDD56A1FEA2B2D9AF").build();
adView.setId(12345); // this is an arbitrary id, allows for relative
// positioning in createGameView()
RelativeLayout.LayoutParams adParams = new RelativeLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM,
RelativeLayout.TRUE);
adParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
adView.setLayoutParams(adParams);
adView.setBackgroundColor(Color.argb(1, 23, 23, 23));
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
params.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
params.addRule(RelativeLayout.BELOW, adView.getId());
gameView.setLayoutParams(params);
layout.addView(gameView);
layout.addView(adView, adParams);
setContentView(layout);
adView.loadAd(adRequest);
adView.resume();
}
@Override
public void onResume() {
super.onResume();
AppEventsLogger.activateApp(this, "1441691276089861");
uiHelper.onResume();
}
@Override
public void onStart() {
super.onStart();
EasyTracker.getInstance(this).activityStart(this); // Add this method.
gameHelper.onStart(this);
}
@Override
public void onStop() {
super.onStop();
EasyTracker.getInstance(this).activityStop(this); // Add this method.
gameHelper.onStop();
uiHelper.onStop();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
gameHelper.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data,
new FacebookDialog.Callback() {
@Override
public void onError(FacebookDialog.PendingCall pendingCall,
Exception error, Bundle data) {
Log.e("Activity",
String.format("Error: %s", error.toString()));
}
@Override
public void onComplete(
FacebookDialog.PendingCall pendingCall, Bundle data) {
Log.i("Activity", "Success!");
}
});
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
@Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
@Override
public void showAds(boolean show) {
handler.sendEmptyMessage(show ? SHOW_ADS : HIDE_ADS);
}
@Override
public boolean getSignedInGPGS() {
return gameHelper.isSignedIn();
}
@Override
public void loginGPGS() {
try {
runOnUiThread(new Runnable() {
public void run() {
gameHelper.beginUserInitiatedSignIn();
System.out.println("Login G+");
}
});
} catch (final Exception ex) {
System.out.println("Sign in failure");
}
}
@Override
public void submitScoreGPGS(int score) {
Games.Leaderboards.submitScore(gameHelper.getApiClient(),
"CgkIuZDUg8cCEAIQAQ", score);
}
@Override
public void unlockAchievementGPGS(String achievementId) {
Games.Achievements.unlock(gameHelper.getApiClient(), achievementId);
}
@Override
public void getLeaderboardGPGS() {
this.startActivityForResult(
Games.Leaderboards.getLeaderboardIntent(
gameHelper.getApiClient(), "CgkIuZDUg8cCEAIQAQ"),
15453525);
}
@Override
public void getAchievementsGPGS() {
startActivityForResult(
Games.Achievements.getAchievementsIntent(gameHelper
.getApiClient()), 15154545);
}
@Override
public void signIn() {
// TODO Auto-generated method stub
}
@Override
public void onSignInFailed() {
// TODO Auto-generated method stub
}
@Override
public void onSignInSucceeded() {
// TODO Auto-generated method stub
}
@Override
public void postToFacebook(double scores) {
int num = (int) (100 * scores);
float score = ((float) (num)) / 100;
if (FacebookDialog.canPresentShareDialog(getApplicationContext(),
FacebookDialog.ShareDialogFeature.SHARE_DIALOG)) {
// Publish the post using the Share Dialog
FacebookDialog shareDialog = new FacebookDialog.ShareDialogBuilder(
this)
.setName("I just scored " + score + " on Asteroid Escape!")
.setCaption("Asteroid Escape - (play.google.com)")
.setDescription("Can you do better?")
.setPicture("http://s28.postimg.org/qtkhsp07t/ae_launcher.png")
.setLink(
"https://play.google.com/store/apps/details?id=ca.codybanman.AstroidEscape")
.build();
uiHelper.trackPendingDialogCall(shareDialog.present());
} else {
// Fallback. For example, publish the post using the Feed Dialog
}
}
}
|
package at.irian.ankor.akka;
import akka.actor.Props;
import akka.actor.UntypedActor;
import at.irian.ankor.session.ModelSession;
import at.irian.ankor.event.ModelEvent;
import at.irian.ankor.event.dispatch.DispatchThreadChecker;
import at.irian.ankor.event.dispatch.EventDispatcher;
import at.irian.ankor.event.dispatch.SimpleEventDispatcher;
/**
* @author Manfred Geiler
*/
public class ModelSessionActor extends UntypedActor {
private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(ModelSessionActor.class);
public static Props props(ModelSession modelSession) {
return Props.create(ModelSessionActor.class, modelSession);
}
public static String name(ModelSession modelSession) {
return "ankor_" + modelSession.getId();
}
private final EventDispatcher eventDispatcher;
private final DispatchThreadChecker dispatchThreadChecker;
public ModelSessionActor(ModelSession modelSession) {
this.eventDispatcher = new SimpleEventDispatcher(modelSession.getEventListeners());
this.dispatchThreadChecker = new DispatchThreadChecker(modelSession);
}
@Override
public void onReceive(Object msg) throws Exception {
LOG.debug("{} received {}", self(), msg);
if (msg instanceof ModelEvent) {
handleEvent((ModelEvent) msg);
} else {
unhandled(msg);
}
}
private void handleEvent(ModelEvent event) {
boolean registered = dispatchThreadChecker.registerCurrentThread();
try {
eventDispatcher.dispatch(event);
} finally {
if (registered) {
dispatchThreadChecker.clear();
}
}
}
}
|
package org.anyline.jdbc.config.db;
import org.anyline.jdbc.config.db.SQL.COMPARE_TYPE;
import org.anyline.jdbc.config.db.impl.SQLVariableImpl;
import org.anyline.util.BasicUtil;
public class SQLHelper {
public static SQLVariable buildVariable(int signType, String all, String prefix, String fullKey, String afterChar){
int varType = -1;
COMPARE_TYPE compare = SQL.COMPARE_TYPE.EQUAL;
if(null == afterChar){
afterChar = "";
}
SQLVariable var = new SQLVariableImpl();
String key = null;
if(signType ==1){
key = fullKey.replace(":", "");
}else if(signType ==2){
key = fullKey.replace("$", "").replace("{", "").replace("}", "");
}
if(fullKey.startsWith("$") || fullKey.startsWith("::")){
// AND CD = ${CD}
// AND CD = ::CD
varType = SQLVariable.VAR_TYPE_REPLACE;
}else if("'".equals(afterChar)){
// AND CD = '{CD}'
// AND CD = ':CD'
varType = SQLVariable.VAR_TYPE_KEY_REPLACE;
}else if(prefix.endsWith("%") || afterChar.startsWith("%")){
//AND CD LIKE '%{CD}%'
//AND CD LIKE '%:CD%'
varType = SQLVariable.VAR_TYPE_KEY;
if(prefix.endsWith("%") && afterChar.startsWith("%")){
compare = SQL.COMPARE_TYPE.LIKE;
}else if(prefix.endsWith("%")){
compare = SQL.COMPARE_TYPE.LIKE_PREFIX;
}else if(afterChar.startsWith("%")){
compare = SQL.COMPARE_TYPE.LIKE_SUBFIX;
}
}else{
varType = SQLVariable.VAR_TYPE_KEY;
if(prefix.equalsIgnoreCase("IN") || prefix.equalsIgnoreCase("IN(")){
//AND CD IN({CD})
compare = SQL.COMPARE_TYPE.IN;
}
}
var.setSignType(signType);
var.setKey(key);
var.setType(varType);
var.setCompare(compare);
return var;
}
public static SQL.COMPARE_TYPE parseCompare(int code){
for (COMPARE_TYPE type : COMPARE_TYPE.values()) {
if(type.getCode() == code){
return type;
}
}
return null;
}
public static SQL.COMPARE_TYPE parseCompare(String code){
if(BasicUtil.isEmpty(code)){
return null;
}
for (COMPARE_TYPE type : COMPARE_TYPE.values()) {
if(code.equals(type.getCode()+"")){
return type;
}
}
return null;
}
}
|
package org.anyline.jdbc.util;
import org.anyline.jdbc.config.db.SQLAdapter;
import org.anyline.jdbc.ds.DataSourceHolder;
import org.anyline.util.SpringContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Repository;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Repository
public class SQLAdapterUtil {
private static ConcurrentHashMap<String, SQLAdapter> adapters= new ConcurrentHashMap<>();
@Autowired(required = false)
public void setAdapters(Map<String, SQLAdapter> map){
for (SQLAdapter adapter:map.values()){
adapters.put(adapter.type().getCode(), adapter);
}
}
private static SQLAdapter defaultAdapter = null; //adapter
public static SQLAdapter getAdapter(JdbcTemplate jdbc){
if(null != defaultAdapter){
return defaultAdapter;
}
if(adapters.size() ==1){
defaultAdapter = adapters.values().iterator().next();
return defaultAdapter;
}
SQLAdapter adapter = null;
SQLAdapter.DB_TYPE type = DataSourceHolder.dialect();
if(null != type){
adapter = getAdapter(type.getName());
if(null != adapter){
return adapter;
}
}
DataSource ds = null;
Connection con = null;
try {
if(null != jdbc){
ds = jdbc.getDataSource();
con = DataSourceUtils.getConnection(ds);
String name = con.getMetaData().getDatabaseProductName().toLowerCase().replace(" ", "");
name += con.getMetaData().getURL().toLowerCase();
//url
adapter = getAdapter(name);
}
if(null == adapter){
adapter = SpringContextUtil.getBean(SQLAdapter.class);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
if(!DataSourceUtils.isConnectionTransactional(con, ds)){
DataSourceUtils.releaseConnection(con, ds);
}
}
return adapter;
}
private static SQLAdapter getAdapter(String name){
SQLAdapter adapter = null;
adapter = adapters.get(name);
if(null != adapter){
return adapter;
}
if(name.contains("mysql")){
adapter = adapters.get(SQLAdapter.DB_TYPE.MYSQL.getCode());
}else if(name.contains("mssql") || name.contains("sqlserver")){
adapter = adapters.get(SQLAdapter.DB_TYPE.MSSQL.getCode());
}else if(name.contains("oracle")){
adapter = adapters.get(SQLAdapter.DB_TYPE.ORACLE.getCode());
}else if(name.contains("postgresql")){
adapter = adapters.get(SQLAdapter.DB_TYPE.PostgreSQL.getCode());
}
else if(name.contains("clickhouse")){
adapter = adapters.get(SQLAdapter.DB_TYPE.ClickHouse.getCode());
}else if(name.contains("db2")){
adapter = adapters.get(SQLAdapter.DB_TYPE.DB2.getCode());
}else if(name.contains("derby")){
adapter = adapters.get(SQLAdapter.DB_TYPE.Derby.getCode());
}else if(name.contains("dmdbms")){
adapter = adapters.get(SQLAdapter.DB_TYPE.DM.getCode());
}else if(name.contains("hgdb") || name.contains("highgo")){
adapter = adapters.get(SQLAdapter.DB_TYPE.HighGo.getCode());
}else if(name.contains("kingbase")){
adapter = adapters.get(SQLAdapter.DB_TYPE.KingBase.getCode());
}else if(name.contains("oceanbase")){
adapter = adapters.get(SQLAdapter.DB_TYPE.OceanBase.getCode());
}else if(name.contains("polardb")){
adapter = adapters.get(SQLAdapter.DB_TYPE.PolarDB.getCode());
}else if(name.contains("sqlite")){
adapter = adapters.get(SQLAdapter.DB_TYPE.SQLite.getCode());
}else if(name.contains(":h2:")){
adapter = adapters.get(SQLAdapter.DB_TYPE.H2.getCode());
}else if(name.contains("hsqldb")){
adapter = adapters.get(SQLAdapter.DB_TYPE.HSQLDB.getCode());
}else if(name.contains("taos")){
adapter = adapters.get(SQLAdapter.DB_TYPE.TDengine.getCode());
}else if(name.contains("neo4j")){
adapter = adapters.get(SQLAdapter.DB_TYPE.Neo4j.getCode());
}
adapters.put(name, adapter);
return adapter;
}
}
|
package net.signalr.client.transport;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import net.signalr.client.util.TimeProvider;
import net.signalr.client.util.concurrent.Schedulable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Represents the transport monitor.
*/
final class TransportMonitor implements Schedulable, TransportListener {
/**
* The private logger.
*/
private static final Logger logger = LoggerFactory.getLogger(TransportMonitor.class);
/**
* The transport manager.
*/
private final TransportManager _manager;
/**
* The time provider.
*/
private final TimeProvider _timeProvider;
/**
* The lost timeout in milliseconds.
*/
private final long _lostTimeout;
/**
* The slow timeout in milliseconds.
*/
private final long _slowTimeout;
/**
* The last heartbeat time in milliseconds.
*/
private final AtomicLong _lastHeartbeatTime;
/**
* The transport status.
*/
private Status _status;
/**
* Initializes a new instance of the {@link TransportMonitor} class.
*
* @param timeProvider The time provider.
* @param manager The transport manager.
* @param timeout The timeout.
* @param timeUnit The time unit.
*/
public TransportMonitor(final TransportManager manager, final TimeProvider timeProvider, final long timeout, final TimeUnit timeUnit) {
if (manager == null) {
throw new IllegalArgumentException("Manager must not be null");
}
if (timeProvider == null) {
throw new IllegalArgumentException("Time provider must not be null");
}
if (timeout <= 0) {
throw new IllegalArgumentException("Timeout must be greater than 0");
}
if (timeUnit == null) {
throw new IllegalArgumentException("Time unit must not be null");
}
_manager = manager;
_timeProvider = timeProvider;
_lostTimeout = timeUnit.toMillis(timeout);
_slowTimeout = (_lostTimeout * 2) / 3;
final long currentTime = _timeProvider.currentTimeMillis();
_lastHeartbeatTime = new AtomicLong(currentTime);
_status = Status.VITAL;
}
/**
* Returns the transport status.
*
* @return The transport status.
*/
private Status getStatus() {
final long lastHeartbeatTime = _lastHeartbeatTime.get();
final long currentTime = _timeProvider.currentTimeMillis();
final long elapsedTime = currentTime - lastHeartbeatTime;
if (elapsedTime >= _lostTimeout) {
return Status.LOST;
}
if (elapsedTime >= _slowTimeout) {
return Status.SLOW;
}
return Status.VITAL;
}
/**
* Returns the monitor period.
*
* @return The monitor period.
*/
public long getPeriod() {
return _lostTimeout - _slowTimeout;
}
/**
* Updates the heartbeat time.
*/
private void updateHeartbeatTime() {
logger.info("Received transport heartbeat");
final long currentTime = _timeProvider.currentTimeMillis();
_lastHeartbeatTime.set(currentTime);
}
@Override
public void onChannelOpened() {
updateHeartbeatTime();
}
@Override
public void onChannelClosed() {
}
@Override
public void onConnectionSlow() {
}
@Override
public void onConnectionLost() {
}
@Override
public void onError(final Throwable cause) {
}
@Override
public void onSending(final String message) {
}
@Override
public void onReceived(final String message) {
updateHeartbeatTime();
}
@Override
public void onScheduled() {
_manager.addListener(this);
}
@Override
public void onCancelled() {
_manager.removeListener(this);
}
@Override
public void run() {
final Status status = getStatus();
if (status == Status.VITAL) {
logger.info("Heartbeat is recent, connection seems to be vital");
}
if (status == _status) {
return;
}
if (status == Status.LOST) {
logger.error("Heartbeat timed out, connection has been lost");
_manager.handleConnectionLost();
} else if (status == Status.SLOW) {
logger.warn("Heartbeat has been missed, connection may be dead/slow");
_manager.handleConnectionSlow();
}
_status = status;
}
/**
* Defines all transport statuses.
*/
private static enum Status {
/**
* Transport is vital.
*/
VITAL,
/**
* Transport may be dead/slow.
*/
SLOW,
/**
* Transport has been lost.
*/
LOST
}
}
|
package org.jenkinsci.plugins.workflow.graph;
import com.google.common.collect.ImmutableList;
import hudson.model.Action;
import hudson.model.Actionable;
import hudson.model.BallColor;
import hudson.search.SearchItem;
import java.io.IOError;
import java.io.IOException;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import static java.util.logging.Level.*;
import java.util.logging.Logger;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import org.jenkinsci.plugins.workflow.actions.ErrorAction;
import org.jenkinsci.plugins.workflow.actions.LabelAction;
import org.jenkinsci.plugins.workflow.flow.FlowExecution;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.DoNotUse;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
/**
* One node in a flow graph.
*/
@ExportedBean
public abstract class FlowNode extends Actionable {
private final List<FlowNode> parents;
private final String id;
private transient CopyOnWriteArrayList<Action> actions;
private transient final FlowExecution exec;
protected FlowNode(FlowExecution exec, String id, List<FlowNode> parents) {
this.id = id;
this.exec = exec;
this.parents = ImmutableList.copyOf(parents);
}
protected FlowNode(FlowExecution exec, String id, FlowNode... parents) {
this.id = id;
this.exec = exec;
this.parents = ImmutableList.copyOf(parents);
}
/**
* Transient flag that indicates if this node is currently actively executing something.
* <p>It will be false for a node which still has active children, like a step with a running body.
* It will also be false for something that has finished but is pending child node creation,
* such as a completed fork branch which is waiting for the join node to be created.
* <p>This can only go from true to false and is a shortcut for {@link FlowExecution#isCurrentHead}.
*/
@Exported
public final boolean isRunning() {
return getExecution().isCurrentHead(this);
}
/**
* If this node has terminated with an error, return an object that indicates that.
* This is just a convenience method.
*/
public final @CheckForNull ErrorAction getError() {
return getAction(ErrorAction.class);
}
public @Nonnull FlowExecution getExecution() {
return exec;
}
/**
* Returns a read-only view of parents.
*/
public List<FlowNode> getParents() {
return parents;
}
@Restricted(DoNotUse.class)
@Exported(name="parents")
public List<String> getParentIds() {
List<String> ids = new ArrayList<String>(2);
for (FlowNode parent : getParents()) {
ids.add(parent.getId());
}
return ids;
}
/**
* Has to be unique within a {@link FlowExecution}.
*
* Needs to remain stable across serialization and JVM restarts.
*
* @see FlowExecution#getNode(String)
*/
@Exported
public String getId() {
return id;
}
/**
* Reference from the parent {@link SearchItem} is through {@link FlowExecution#getNode(String)}
*/
public final String getSearchUrl() {
return getId();
}
@Exported
public String getDisplayName() {
LabelAction a = getAction(LabelAction.class);
if (a!=null) return a.getDisplayName();
else return getTypeDisplayName();
}
@Exported
public BallColor getIconColor() {
BallColor c = getError()!=null ? BallColor.RED : BallColor.BLUE;
// TODO this should probably also be _anime in case this is a step node with a body and the body is still running (try FlowGraphTable for example)
if (isRunning()) c = c.anime();
return c;
}
/**
* Gets a human readable name for this type of the node.
*
* This is used to implement {@link #getDisplayName()} as a fallback in case {@link LabelAction} doesnt exist.
*/
protected abstract String getTypeDisplayName();
/**
* Returns the URL of this {@link FlowNode}, relative to the context root of Jenkins.
*
* @return
* String like "job/foo/32/execution/node/abcde/" with no leading slash but trailing slash.
*/
@Exported
public String getUrl() throws IOException {
return getExecution().getUrl()+"node/"+getId()+'/';
}
/**
* SPI for subtypes to directly manipulate the actions field.
*
* When a brand new {@link FlowNode} is created, or when {@link FlowNode} and actions are
* stored in close proximity, it is convenient to be able to set the {@link #actions}
* so as to eliminate the separate call to {@link FlowActionStorage#loadActions(FlowNode)}.
*
* This method provides such an opportunity for subtypes.
*/
protected void setActions(List<Action> actions) {
this.actions = new CopyOnWriteArrayList<Action>(actions);
}
/*
We can't use Actionable#actions to store actions because they aren't transient,
and we need to store actions elsewhere because this is the only mutable pat of FlowNode.
So we create a separate transient field and store List of them there, and intercept every mutation.
*/
@Exported
@Override
public synchronized List<Action> getActions() {
if (actions==null) {
try {
actions = new CopyOnWriteArrayList<Action>(exec.loadActions(this));
} catch (IOException e) {
LOGGER.log(WARNING, "Failed to load actions for FlowNode id=" + id, e);
actions = new CopyOnWriteArrayList<Action>();
}
}
return new AbstractList<Action>() {
@Override
public Action get(int index) {
return actions.get(index);
}
@Override
public void add(int index, Action element) {
actions.add(index, element);
persist();
}
@Override
public Action remove(int index) {
Action old = actions.remove(index);
persist();
return old;
}
@Override
public Action set(int index, Action element) {
Action old = actions.set(index, element);
persist();
return old;
}
@Override
public int size() {
return actions.size();
}
private void persist() {
try {
exec.saveActions(FlowNode.this, actions);
} catch (IOException e) {
throw new IOError(e);
}
}
};
}
@Override
public boolean equals(Object obj) {
if (obj instanceof FlowNode) {
FlowNode that = (FlowNode) obj;
return this.id.equals(that.id);
}
return false;
}
@Override
public int hashCode() {
return this.id.hashCode();
}
@Override
public String toString() {
return getClass().getName() + "[id=" + id + "]";
}
private static final Logger LOGGER = Logger.getLogger(FlowNode.class.getName());
}
|
package edu.columbia.gemma.loader.mage;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.biomage.Array.ArrayManufacture;
import org.biomage.ArrayDesign.ArrayDesign;
import org.biomage.ArrayDesign.CompositeGroup;
import org.biomage.ArrayDesign.FeatureGroup;
import org.biomage.ArrayDesign.PhysicalArrayDesign;
import org.biomage.ArrayDesign.ReporterGroup;
import org.biomage.BQS.BibliographicReference;
import org.biomage.BioAssay.BioAssay;
import org.biomage.BioAssay.BioAssayCreation;
import org.biomage.BioAssay.Channel;
import org.biomage.BioAssay.DerivedBioAssay;
import org.biomage.BioAssay.MeasuredBioAssay;
import org.biomage.BioAssay.PhysicalBioAssay;
import org.biomage.BioMaterial.BioSample;
import org.biomage.BioMaterial.BioSource;
import org.biomage.BioMaterial.LabeledExtract;
import org.biomage.Common.Describable;
import org.biomage.Common.Extendable;
import org.biomage.Common.Identifiable;
import org.biomage.Description.Database;
import org.biomage.Description.Description;
import org.biomage.Description.OntologyEntry;
import org.biomage.DesignElement.FeatureInformation;
import org.biomage.DesignElement.FeatureReporterMap;
import org.biomage.DesignElement.ReporterCompositeMap;
import org.biomage.DesignElement.ReporterPosition;
import org.biomage.Experiment.Experiment;
import org.biomage.Experiment.ExperimentDesign;
import org.biomage.Protocol.Hardware;
import org.biomage.Protocol.Protocol;
import org.biomage.QuantitationType.DerivedSignal;
import org.biomage.QuantitationType.MeasuredSignal;
import org.biomage.QuantitationType.PValue;
import org.biomage.QuantitationType.PresentAbsent;
import org.biomage.QuantitationType.QuantitationType;
import org.biomage.QuantitationType.Ratio;
import org.biomage.QuantitationType.SpecializedQuantitationType;
import edu.columbia.gemma.common.Identifscribable;
import edu.columbia.gemma.common.description.DatabaseEntry;
import edu.columbia.gemma.common.description.ExternalDatabase;
import edu.columbia.gemma.common.protocol.Software;
import edu.columbia.gemma.common.quantitationtype.PrimitiveType;
import edu.columbia.gemma.common.quantitationtype.ScaleType;
import edu.columbia.gemma.expression.biomaterial.BioMaterial;
import edu.columbia.gemma.expression.designElement.CompositeSequence;
import edu.columbia.gemma.expression.designElement.Reporter;
import edu.columbia.gemma.expression.experiment.ExperimentalDesign;
import edu.columbia.gemma.expression.experiment.ExperimentalFactor;
import edu.columbia.gemma.expression.experiment.ExpressionExperiment;
import edu.columbia.gemma.expression.experiment.FactorValue;
import edu.columbia.gemma.sequence.biosequence.PolymerType;
import edu.columbia.gemma.sequence.biosequence.SequenceType;
import edu.columbia.gemma.sequence.gene.Taxon;
import edu.columbia.gemma.util.ReflectionUtil;
public class MageMLConverter {
// convertPerson
// convertOrganization
// convertContact
/**
* Used to indicate that a MAGE list should be converted to a Gemma list (or collection)
*/
public static final boolean CONVERT_ALL = false;
/**
* Used to indicate that when a MAGE list is encountered, we should only process the first element of the list.
*/
public static final boolean CONVERT_FIRST_ONLY = true;
public static final Log log = LogFactory.getLog( MageMLConverter.class );
public static final String START_AUDIT_NOTE = "Imported from MAGE";
/**
* Used to hold references to Identifiables, so we don't convert them over and over again.
*/
public Map identifiableCache;
public MageMLConverter() {
identifiableCache = new HashMap();
}
/**
* A generic converter that figures out which specific conversion method to call based on the class of the object.
*
* @param mageObj
* @return
*/
public Object convert( Object mageObj ) {
Object result = findAndInvokeConverter( mageObj );
convertAssociations( mageObj, result );
return result;
}
/**
* TODO this can't clobber an existing array design, and there are a LOT of associations to figure out. TODO - array
* deisgn has subclass physical array design, which we actually use.
*
* @param mageObj
* @return
*/
public edu.columbia.gemma.expression.arrayDesign.ArrayDesign convertArrayDesign( ArrayDesign mageObj ) {
if ( mageObj == null ) return null;
log.debug( "(Incomplete) Converting Array design: " + mageObj.getName() );
edu.columbia.gemma.expression.arrayDesign.ArrayDesign result = edu.columbia.gemma.expression.arrayDesign.ArrayDesign.Factory
.newInstance();
result.setNumberOfFeatures( mageObj.getNumberOfFeatures().intValue() );
// FIXME number of composite features?
if ( !convertIdentifiable( mageObj, result ) ) convertAssociations( mageObj, result );
return result;
}
/**
* @param mageObj
* @param gemmaObj
* @param getter
*/
public void convertArrayDesignAssociations( ArrayDesign mageObj,
edu.columbia.gemma.expression.arrayDesign.ArrayDesign gemmaObj, Method getter ) {
Object associatedObject = intializeConversion( mageObj, gemmaObj, getter );
String associationName = getterToPropertyName( getter );
if ( associatedObject == null ) return;
if ( associationName.equals( "CompositeGroups" ) ) {
assert associatedObject instanceof List;
specialConvertCompositeGroups( ( List ) associatedObject, gemmaObj );
} else if ( associationName.equals( "DesignProviders" ) ) {
assert associatedObject instanceof List;
} else if ( associationName.equals( "FeatureGroups" ) ) {
assert associatedObject instanceof List;
specialConvertFeatureGroups( ( List ) associatedObject, gemmaObj );
} else if ( associationName.equals( "ProtocolApplications" ) ) {
assert associatedObject instanceof List;
} else if ( associationName.equals( "ReporterGroups" ) ) {
assert associatedObject instanceof List;
specialConvertReporterGroups( ( List ) associatedObject, gemmaObj );
} else {
log.debug( "Unsupported or unknown association, or it belongs to the subclass: " + associationName );
}
}
/**
* A no-op, as we don't keep track of this.
*
* @param mageObj
* @return
*/
public Object convertArrayManufacture( ArrayManufacture mageObj ) {
return null; // no-op.
}
/**
* @param actualGemmaAssociationName
* @param gemmaAssociatedObj
* @return
*/
public String convertAssociationName( String actualGemmaAssociationName, Object gemmaAssociatedObj ) {
String inferredGemmaAssociationName;
if ( actualGemmaAssociationName != null ) {
inferredGemmaAssociationName = actualGemmaAssociationName;
} else {
inferredGemmaAssociationName = ReflectionUtil.classToTypeName( ReflectionUtil
.getBaseForImpl( gemmaAssociatedObj ) );
}
return inferredGemmaAssociationName;
}
/**
* Generic method to find the associations a Mage object has and call the appropriate converter method. The
* converters are named after the MAGE class, not the Gemma class.
*
* @param mageObj
* @param gemmaObj
*/
public void convertAssociations( Object mageObj, Object gemmaObj ) {
if ( mageObj == null || gemmaObj == null ) return;
Class classToSeek = ReflectionUtil.getBaseForImpl( gemmaObj );
String gemmaObjName = ReflectionUtil.classToTypeName( classToSeek );
try {
Class[] interfaces = mageObj.getClass().getInterfaces();
for ( int i = 0; i < interfaces.length; i++ ) {
Class infc = interfaces[i];
String infcName = ReflectionUtil.classToTypeName( infc );
if ( !infcName.startsWith( "Has" ) ) continue;
String propertyName = infcName.substring( 3 );
Method getter = mageObj.getClass().getMethod( "get" + propertyName, new Class[] {} );
if ( getter != null ) {
try {
Method converter = this.getClass().getMethod(
"convert" + ReflectionUtil.objectToTypeName( mageObj ) + "Associations",
new Class[] { mageObj.getClass(), classToSeek, getter.getClass() } );
if ( converter == null ) throw new NoSuchMethodException();
converter.invoke( this, new Object[] { mageObj, gemmaObj, getter } );
} catch ( NoSuchMethodException e ) {
log.warn( "Converstion of associations -- Operation not yet supported: " + "convert"
+ ReflectionUtil.objectToTypeName( mageObj ) + "Associations("
+ mageObj.getClass().getName() + ", " + gemmaObjName + ", "
+ getter.getClass().getName() + ")" );
}
}
}
} catch ( NoSuchMethodException e ) {
log.error( e, e );
} catch ( IllegalArgumentException e ) {
log.error( e, e );
} catch ( IllegalAccessException e ) {
log.error( e, e );
} catch ( InvocationTargetException e ) {
log.error( "InvocationTargetException For: " + gemmaObjName, e );
}
}
/**
* @param mageObj
* @return
*/
public edu.columbia.gemma.common.description.BibliographicReference convertBibliographicReference(
BibliographicReference mageObj ) {
if ( mageObj == null ) return null;
log.debug( "Converting BibliographicReference " + mageObj.getTitle() );
edu.columbia.gemma.common.description.BibliographicReference result = edu.columbia.gemma.common.description.BibliographicReference.Factory
.newInstance();
convertDescribable( mageObj, result );
result.setEditor( mageObj.getEditor() );
result.setAuthorList( mageObj.getAuthors() );
result.setIssue( mageObj.getIssue() );
result.setPages( mageObj.getPages() );
result.setPublication( mageObj.getPublication() );
result.setPublisher( mageObj.getPublisher() );
result.setTitle( mageObj.getTitle() );
result.setVolume( mageObj.getVolume() );
result.setYear( mageObj.getYear() );
result.setFullTextURI( mageObj.getURI() ); // FIXME URI is probably not right.
convertAssociations( mageObj, result );
return result;
}
/**
* @param mageObj
* @param gemmaObj
* @param getter
*/
public void convertBibliographicReferenceAssociations( BibliographicReference mageObj,
edu.columbia.gemma.common.description.BibliographicReference gemmaObj, Method getter ) {
Object associatedObject = intializeConversion( mageObj, gemmaObj, getter );
String associationName = getterToPropertyName( getter );
if ( associatedObject == null ) return;
if ( associationName.equals( "Accessions" ) ) {
simpleFillIn( ( List ) associatedObject, gemmaObj, getter, CONVERT_FIRST_ONLY, "PubAccession" );
} else if ( associationName.equals( "Parameters" ) ) {
// no-op, we don't support.
} else {
log.debug( "Unsupported or unknown association: " + associationName );
}
}
/**
* @param mageObj
* @return
*/
public edu.columbia.gemma.expression.bioAssay.BioAssay convertBioAssay( BioAssay mageObj ) {
if ( mageObj == null ) return null;
log.debug( "Converting BioAssay " + mageObj.getIdentifier() );
edu.columbia.gemma.expression.bioAssay.BioAssay result = edu.columbia.gemma.expression.bioAssay.BioAssay.Factory
.newInstance();
// FIXME - we need the array designs to get filled in.
if ( !convertIdentifiable( mageObj, result ) ) {
convertAssociations( mageObj, result );
}
return result;
}
/**
* @param mageObj
* @param gemmaObj
* @param getter
*/
public void convertBioAssayAssociations( BioAssay mageObj,
edu.columbia.gemma.expression.bioAssay.BioAssay gemmaObj, Method getter ) {
log.warn( "convertBioAssayAssociations not fully supported!" );
Object associatedObject = intializeConversion( mageObj, gemmaObj, getter );
String associationName = getterToPropertyName( getter );
if ( associatedObject == null ) return;
if ( associationName.equals( "BioAssayFactorValues" ) ) {
simpleFillIn( ( List ) associatedObject, gemmaObj, getter, CONVERT_ALL, "BioAssayFactorValues" );
} else if ( associationName.equals( "Channels" ) ) {
; // we don't support this.
} else {
log.debug( "Unsupported or unknown association: " + associationName );
}
}
/**
* @param mageObj
* @return
*/
public edu.columbia.gemma.expression.biomaterial.BioMaterial convertBioMaterial(
org.biomage.BioMaterial.BioMaterial mageObj ) {
if ( mageObj == null ) return null;
edu.columbia.gemma.expression.biomaterial.BioMaterial result = edu.columbia.gemma.expression.biomaterial.BioMaterial.Factory
.newInstance();
if ( !convertIdentifiable( mageObj, result ) ) convertAssociations( mageObj, result );
return result;
}
/**
* @param mageObj
* @param gemmaObj
* @param getter
*/
public void convertBioMaterialAssociations( org.biomage.BioMaterial.BioMaterial mageObj, BioMaterial gemmaObj,
Method getter ) {
Object associatedObject = intializeConversion( mageObj, gemmaObj, getter );
String associationName = getterToPropertyName( getter );
if ( associatedObject == null ) return;
if ( associationName.equals( "Characteristics" ) ) {
assert associatedObject instanceof List;
simpleFillIn( ( List ) associatedObject, gemmaObj, getter, CONVERT_ALL, "Characteristics" );
} else if ( associationName.equals( "MaterialType" ) ) {
simpleFillIn( associatedObject, gemmaObj, getter );
} else if ( associationName.equals( "QualityControlStatistics" ) ) {
assert associatedObject instanceof List;
// we don't support : TODO check
} else if ( associationName.equals( "Treatments" ) ) {
assert associatedObject instanceof List;
simpleFillIn( ( List ) associatedObject, gemmaObj, getter, CONVERT_ALL, "Treatments" );
} else {
log.debug( "Unsupported or unknown association, or from subclass: " + associationName );
}
}
/**
* @param mageObj
* @return
*/
public BioMaterial convertBioSample( BioSample mageObj ) {
log.debug( "Converting BioSample: " + mageObj.getIdentifier() );
if ( mageObj == null ) return null;
BioMaterial result = BioMaterial.Factory.newInstance();
if ( !convertIdentifiable( mageObj, result ) ) convertAssociations( mageObj, result );
return result;
}
/**
* TODO - call superclass converter.
*
* @param mageObj
* @param gemmaObj
* @param getter
*/
public void convertBioSampleAssociations( BioSample mageObj, BioMaterial gemmaObj, Method getter ) {
log.debug( "convertBioMaterialAssociations (biosample) Not fully supported yet" );
if ( mageObj == null ) return;
convertBioMaterialAssociations( mageObj, gemmaObj, getter );
Object associatedObject = intializeConversion( mageObj, gemmaObj, getter );
if ( associatedObject == null ) return;
String associationName = getterToPropertyName( getter );
if ( associationName.equals( "Type" ) ) {
// we don't support.
} else {
log.debug( "Unknown or unsupported type, or is for superclass " + associationName );
}
}
/**
* @param mageObj
* @return edu.columbia.gemma.sequence.biosequence.BioSequence
*/
public edu.columbia.gemma.sequence.biosequence.BioSequence convertBioSequence(
org.biomage.BioSequence.BioSequence mageObj ) {
log.debug( "Converting BioSequence " + mageObj.getIdentifier() );
if ( mageObj == null ) return null;
edu.columbia.gemma.sequence.biosequence.BioSequence result = edu.columbia.gemma.sequence.biosequence.BioSequence.Factory
.newInstance();
result.setSequence( mageObj.getSequence() );
if ( mageObj.getLength() != null ) result.setLength( mageObj.getLength().intValue() );
if ( mageObj.getIsApproximateLength() != null )
result.setIsApproximateLength( mageObj.getIsApproximateLength().booleanValue() );
if ( mageObj.getIsCircular() != null ) result.setIsCircular( mageObj.getIsCircular().booleanValue() );
if ( !convertIdentifiable( mageObj, result ) ) convertAssociations( mageObj, result );
return result;
}
/**
* Implementation note: This is passed a 'get' method for an association to one or more MAGE domain objects. In some
* cases, the subsequent call can be computed using reflection; but in other cases it will have to be done by hand,
* as when there is not a direct mapping of Gemma objects to MAGE objects and vice versa.
*
* @param mageObj
* @param gemmaObj
* @param getter
*/
public void convertBioSequenceAssociations( org.biomage.BioSequence.BioSequence mageObj,
edu.columbia.gemma.sequence.biosequence.BioSequence gemmaObj, Method getter ) {
Object associatedObject = intializeConversion( mageObj, gemmaObj, getter );
if ( associatedObject == null ) return;
String associationName = getterToPropertyName( getter );
if ( associationName.equals( "PolymerType" ) ) { // Ontology Entry - enumerated type.
simpleFillIn( associatedObject, gemmaObj, getter );
} else if ( associationName.equals( "SequenceDatabases" ) ) { // list of DatabaseEntries, we use one
List seqdbs = ( List ) associatedObject;
simpleFillIn( seqdbs, gemmaObj, getter, true, "SequenceDatabaseEntry" );
} else if ( associationName.equals( "Type" ) ) { // ontology entry, we map to a enumerated type.
simpleFillIn( associatedObject, gemmaObj, getter, "Type" ); // yes, we do.
} else if ( associationName.equals( "Species" ) ) { // ontology entry, we map to a enumerated type.
simpleFillIn( associatedObject, gemmaObj, getter );
} else if ( associationName.equals( "SeqFeatures" ) ) {
; // list of Sequence features, we ignore
} else if ( associationName.equals( "OntologyEntries" ) ) {
; // list of generic ontology entries, we ignore.
} else {
log.debug( "Unknown or unsupported type " + associationName );
}
}
/**
* @param mageObj
* @return
*/
public edu.columbia.gemma.expression.biomaterial.BioMaterial convertBioSource( BioSource mageObj ) {
if ( mageObj == null ) return null;
edu.columbia.gemma.expression.biomaterial.BioMaterial result = convertBioMaterial( mageObj );
// FIXME: sourceContact. - we don't have this.
return result;
}
/**
* FIXME - need to push anything useful up to a single biomaterial.
*
* @param mageObj
* @param gemmaObj
* @param getter
*/
public void convertBioSourceAssociations( BioSource mageObj, BioMaterial gemmaObj, Method getter ) {
convertBioMaterialAssociations( mageObj, gemmaObj, getter );
Object associatedObject = intializeConversion( mageObj, gemmaObj, getter );
String associationName = getterToPropertyName( getter );
if ( associatedObject == null ) return;
if ( associationName.equals( "SourceContacts" ) ) {
// no-op, we don't support this.
} else {
log.debug( "Unsupported or unknown association: " + associationName );
}
}
/**
* @param mageObj
* @return
*/
public edu.columbia.gemma.common.description.OntologyEntry convertCategory( OntologyEntry mageObj ) {
return convertOntologyEntry( mageObj );
}
/**
* A no-op, since we don't explicitly support channels at the moment.
*
* @param mageObj
* @return
*/
public Object convertChannel( Channel mageObj ) {
return null; // No-op
}
/**
* NO-op, we deal with it elsewhere specially.
*
* @param mageObj
* @return
*/
public Object convertCompositeGroup( CompositeGroup mageObj ) {
if ( mageObj == null ) return null;
return null;
}
/**
* @param mageObj
* @return
*/
public edu.columbia.gemma.expression.designElement.CompositeSequence convertCompositeSequence(
org.biomage.DesignElement.CompositeSequence mageObj ) {
if ( mageObj == null ) return null;
CompositeSequence result = CompositeSequence.Factory.newInstance();
if ( !convertIdentifiable( mageObj, result ) ) convertAssociations( mageObj, result );
return result;
}
/**
* @param mageObj
* @param gemmaObj
* @param getter
*/
public void convertCompositeSequenceAssociations( org.biomage.DesignElement.CompositeSequence mageObj,
edu.columbia.gemma.expression.designElement.CompositeSequence gemmaObj, Method getter ) {
Object associatedObject = intializeConversion( mageObj, gemmaObj, getter );
String associationName = getterToPropertyName( getter );
if ( associatedObject == null ) return;
if ( associationName.equals( "BiologicalCharacteristics" ) ) {
if ( ( ( List ) associatedObject ).size() > 1 )
log.warn( "*** Moroe than one BiologicalCharacteristic for a MAGE CompositeSequence!" );
simpleFillIn( ( List ) associatedObject, gemmaObj, getter, CONVERT_FIRST_ONLY, "BiologicalCharacteristic" );
} else if ( associationName.equals( "CompositeCompositeMaps" ) ) {
; // we don't support.
} else if ( associationName.equals( "ReporterCompositeMaps" ) ) {
// special case. This is complicated, because the mage model has compositeSequence ->
// reportercompositemap(s) -> reporterposition(s) -> reporter(1)
gemmaObj.setReporters( specialConvertReporterCompositeMaps( ( List ) associatedObject ) );
} else {
log.debug( "Unsupported or unknown association: " + associationName );
}
}
/**
* FIXME - what do we do with this? Used for Label of LabeledExtract, and details of treatments and biomaterial
* measurements. - no-op for now.
*
* @param mageObj
* @return
*/
public Object convertCompound( org.biomage.BioMaterial.Compound mageObj ) {
if ( mageObj == null ) return null;
return null;
}
/**
* Todo: this should be set up so we don't get duplicate databases persisted.
*
* @param mageObj
* @return
*/
public ExternalDatabase convertDatabase( Database mageObj ) {
if ( mageObj == null ) return null;
log.debug( "Converting Database " + mageObj.getIdentifier() );
ExternalDatabase result = ExternalDatabase.Factory.newInstance();
result.setWebURI( mageObj.getURI() );
// we don't use version.
if ( !convertIdentifiable( mageObj, result ) ) convertAssociations( mageObj, result );
return result;
}
/**
* @param mageObj
* @param gemmaObj
* @param getter
*/
public void convertDatabaseAssociations( Database mageObj,
edu.columbia.gemma.common.description.ExternalDatabase gemmaObj, Method getter ) {
Object associatedObject = intializeConversion( mageObj, gemmaObj, getter );
String associationName = getterToPropertyName( getter );
if ( associatedObject == null ) return;
if ( associationName.equals( "Contacts" ) )
simpleFillIn( ( List ) associatedObject, gemmaObj, getter, CONVERT_FIRST_ONLY, "Contact" );
else
log.debug( "Unsupported or unknown association: " + associationName );
}
/**
* @param mageObj
* @return
*/
public DatabaseEntry convertDatabaseEntry( org.biomage.Description.DatabaseEntry mageObj ) {
if ( mageObj == null ) return null;
log.debug( "Converting DatabaseEntry " + mageObj.getAccession() );
DatabaseEntry result = DatabaseEntry.Factory.newInstance();
result.setAccession( mageObj.getAccession() );
result.setAccessionVersion( mageObj.getAccessionVersion() );
result.setURI( mageObj.getURI() );
convertAssociations( mageObj, result );
return result;
}
/**
* @param mageObj
* @param gemmaObj
* @param getter
*/
public void convertDatabaseEntryAssociations( org.biomage.Description.DatabaseEntry mageObj,
DatabaseEntry gemmaObj, Method getter ) {
Object associatedObject = intializeConversion( mageObj, gemmaObj, getter );
String associationName = getterToPropertyName( getter );
if ( associatedObject == null ) return;
if ( associationName.equals( "Database" ) )
simpleFillIn( associatedObject, gemmaObj, getter );
else if ( associationName.equals( "Type" ) )
; // we ain't got that.
else
log.debug( "Unsupported or unknown association: " + associationName );
}
/**
* @param mageObj
* @return
*/
public PrimitiveType convertDataType( OntologyEntry mageObj ) {
if ( mageObj == null ) return null;
String val = mageObj.getValue();
if ( val.equals( "boolean" ) ) {
return PrimitiveType.BOOLEAN;
} else if ( val.equalsIgnoreCase( "char" ) ) {
return PrimitiveType.CHAR;
} else if ( val.equalsIgnoreCase( "double" ) ) {
return PrimitiveType.DOUBLE;
} else if ( val.equalsIgnoreCase( "float" ) ) {
return PrimitiveType.FLOAT;
} else if ( val.equalsIgnoreCase( "int" ) ) {
return PrimitiveType.INT;
} else if ( val.equalsIgnoreCase( "long" ) ) {
return PrimitiveType.LONG;
} else if ( val.equalsIgnoreCase( "string" ) ) {
return PrimitiveType.STRING;
} else {
log.error( "Unrecognized DataType " + val );
}
return null;
}
/**
* @param mageObj
* @return
*/
public edu.columbia.gemma.expression.bioAssay.BioAssay convertDerivedBioAssay( DerivedBioAssay mageObj ) {
if ( mageObj == null ) return null;
log.debug( "Converting DerivedBioAssay " + mageObj.getIdentifier() );
edu.columbia.gemma.expression.bioAssay.BioAssay result = convertBioAssay( mageObj );
convertAssociations( mageObj, result ); // FIXME this has to only do the subclass part.
return result;
}
/**
* @param mageObj
* @param gemmaObj
* @param getter
*/
public void convertDerivedBioAssayAssociations( DerivedBioAssay mageObj,
edu.columbia.gemma.expression.bioAssay.BioAssay gemmaObj, Method getter ) {
Object associatedObject = intializeConversion( mageObj, gemmaObj, getter );
String associationName = getterToPropertyName( getter );
if ( associatedObject == null ) return;
if ( associationName.equals( "DerivedBioAssayMap" ) ) {
if ( ( ( List ) associatedObject ).size() > 0 ) log.warn( "Missing out on DerivedBioAssayMap" );
} else if ( associationName.equals( "DerivedBioAssayData" ) ) {
if ( ( ( List ) associatedObject ).size() > 0 ) log.warn( "Missing out on DerivedBioAssayData" );
; // FIXME this may be what we actually use.
;
} else if ( associationName.equals( "Type" ) ) {
// simpleFillIn( associatedObject, gemmaObj, getter, "Type" );
} else {
log.warn( "Unsupported or unknown association, or belongs to superclass: " + associationName );
}
}
/**
* @param mageObj
* @return
*/
public edu.columbia.gemma.common.quantitationtype.QuantitationType convertDerivedSignal( DerivedSignal mageObj ) {
return convertQuantitationType( mageObj );
}
/**
* Convert a MAGE Describable to a Gemma domain object. We only allow a single description, so we take the first
* one. The association to Security and Audit are not filled in here - TODO something about that.
*
* @param mageObj
* @param gemmaObj
*/
public void convertDescribable( Describable mageObj, Identifscribable gemmaObj ) {
if ( mageObj == null ) return;
if ( gemmaObj == null ) throw new IllegalArgumentException( "Must pass in a valid object" );
if ( mageObj.getDescriptions().size() > 0 ) {
gemmaObj.setDescription( convertDescription( ( Description ) mageObj.getDescriptions().get( 0 ) ) );
}
if ( mageObj.getDescriptions().size() > 1 )
log.warn( "***** There were multiple descriptions from a MAGE.Describable! ***** " );
convertExtendable( mageObj, gemmaObj );
}
/**
* todo: mage Description isa Describable.
*
* @param mageObj
* @return edu.columbia.gemma.common.description.Description
*/
public edu.columbia.gemma.common.description.Description convertDescription(
org.biomage.Description.Description mageObj ) {
if ( mageObj == null ) return null;
log.debug( "Converting Description: " + mageObj.getText() );
edu.columbia.gemma.common.description.Description result = edu.columbia.gemma.common.description.Description.Factory
.newInstance();
result.setText( mageObj.getText() );
result.setURI( mageObj.getURI() );
convertAssociations( mageObj, result );
return result;
}
/**
* @param mageObj
* @param gemmaObj
* @param getter
*/
public void convertDescriptionAssociations( Description mageObj,
edu.columbia.gemma.common.description.Description gemmaObj, Method getter ) {
Object associatedObject = intializeConversion( mageObj, gemmaObj, getter );
String associationName = getterToPropertyName( getter );
if ( associatedObject == null ) return;
if ( associationName.equals( "BibliographicReferences" ) ) {
simpleFillIn( ( List ) associatedObject, gemmaObj, getter, CONVERT_FIRST_ONLY, "BibliographicReference" );
} else if ( associationName.equals( "DatabaseReferences" ) ) {
simpleFillIn( ( List ) associatedObject, gemmaObj, getter, CONVERT_ALL, "DatabaseEntries" );
} else if ( associationName.equals( "Annotations" ) ) {
simpleFillIn( ( List ) associatedObject, gemmaObj, getter, CONVERT_ALL, "Annotations" );
} else {
log.debug( "Unsupported or unknown association: " + associationName );
}
}
/**
* @param mageObj
* @return
*/
public edu.columbia.gemma.common.quantitationtype.QuantitationType convertError(
org.biomage.QuantitationType.Error mageObj ) {
return convertQuantitationType( mageObj );
}
/**
* TODO Incomplete
*
* @param mageObj
* @return
*/
public ExpressionExperiment convertExperiment( Experiment mageObj ) {
if ( mageObj == null ) return null;
log.debug( "Incomplete: Converting Experiment: " + mageObj.getName() );
ExpressionExperiment result = ExpressionExperiment.Factory.newInstance();
result.setSource( "Imported from MAGE-ML" );
if ( !convertIdentifiable( mageObj, result ) ) convertAssociations( mageObj, result );
return result;
}
/**
* @param mageObj
* @return
*/
public ExperimentalFactor convertExperimentalFactor( org.biomage.Experiment.ExperimentalFactor mageObj ) {
if ( mageObj == null ) return null;
log.debug( "Converting ExperimentalFactor: " + mageObj.getIdentifier() );
ExperimentalFactor result = ExperimentalFactor.Factory.newInstance();
if ( !convertIdentifiable( mageObj, result ) ) convertAssociations( mageObj, result );
return result;
}
/**
* @param mageObj
* @param gemmaObj
* @param getter
*/
public void convertExperimentalFactorAssociations( org.biomage.Experiment.ExperimentalFactor mageObj,
ExperimentalFactor gemmaObj, Method getter ) {
Object associatedObject = intializeConversion( mageObj, gemmaObj, getter );
String associationName = getterToPropertyName( getter );
if ( associatedObject == null ) return;
if ( associationName.equals( "Category" ) )
simpleFillIn( associatedObject, gemmaObj, getter, "Category" );
else if ( associationName.equals( "Annotations" ) )
simpleFillIn( ( List ) associatedObject, gemmaObj, getter, CONVERT_ALL, "Annotations" );
else if ( associationName.equals( "FactorValues" ) )
simpleFillIn( ( List ) associatedObject, gemmaObj, getter, CONVERT_ALL, "FactorValues" );
else
log.warn( "Unsupported or unknown association: " + associationName );
}
/**
* @param mageObj
* @param gemmaObj
* @param getter
*/
public void convertExperimentAssociations( Experiment mageObj, ExpressionExperiment gemmaObj, Method getter ) {
Object associatedObject = intializeConversion( mageObj, gemmaObj, getter );
String associationName = getterToPropertyName( getter );
if ( associatedObject == null ) return;
if ( associationName.equals( "AnalysisResults" ) ) {
assert associatedObject instanceof List;
simpleFillIn( ( List ) associatedObject, gemmaObj, getter, CONVERT_ALL, null );
} else if ( associationName.equals( "BioAssays" ) ) {
assert associatedObject instanceof List;
simpleFillIn( ( List ) associatedObject, gemmaObj, getter, CONVERT_ALL, "BioAssays" );
} else if ( associationName.equals( "Providers" ) ) {
assert associatedObject instanceof List;
simpleFillIn( ( List ) associatedObject, gemmaObj, getter, CONVERT_FIRST_ONLY, "Provider" );
} else if ( associationName.equals( "BioAssayData" ) ) {
assert associatedObject instanceof List;
// simpleFillIn( ( List ) associatedObject, gemmaObj, getter, CONVERT_ALL, "BioAssayData" );
// FIXME this is a potential problem, need to deal with specially.
log.debug( "Haven't dealt with this yet." );
} else if ( associationName.equals( "ExperimentDesigns" ) ) {
assert associatedObject instanceof List;
simpleFillIn( ( List ) associatedObject, gemmaObj, getter, CONVERT_ALL, "ExperimentalDesigns" );
} else {
log.debug( "Unsupported or unknown association: " + associationName );
}
}
/**
* @param mageObj
* @return
*/
public ExperimentalDesign convertExperimentDesign( ExperimentDesign mageObj ) {
if ( mageObj == null ) return null;
log.debug( "Converting ExperimentDesign" );
ExperimentalDesign result = ExperimentalDesign.Factory.newInstance();
convertDescribable( mageObj, result );
convertAssociations( mageObj, result );
return result;
}
/**
* @param mageObj
* @param gemmaObj
*/
public void convertExperimentDesignAssociations( ExperimentDesign mageObj, ExperimentalDesign gemmaObj,
Method getter ) {
Object associatedObject = intializeConversion( mageObj, gemmaObj, getter );
String associationName = getterToPropertyName( getter );
if ( associatedObject == null ) return;
if ( associationName.equals( "ExperimentalFactors" ) ) {
assert associatedObject instanceof List;
simpleFillIn( ( List ) associatedObject, gemmaObj, getter, CONVERT_ALL, "ExperimentalFactors" );
} else if ( associationName.equals( "NormalizationDescription" ) ) {
simpleFillIn( associatedObject, gemmaObj, getter );
} else if ( associationName.equals( "QualityControlDescription" ) ) {
simpleFillIn( associatedObject, gemmaObj, getter );
} else if ( associationName.equals( "ReplicateDescription" ) ) {
simpleFillIn( associatedObject, gemmaObj, getter );
} else if ( associationName.equals( "TopLevelBioAssays" ) ) {
assert associatedObject instanceof List;
// we don't have this in our model TODO: check
} else if ( associationName.equals( "Types" ) ) {
assert associatedObject instanceof List;
// simpleFillIn( ( List ) associatedObject, gemmaObj, getter, CONVERT_ALL, "Types" ); // TODO quantifier is wrong
} else {
log.warn( "Unsupported or unknown association: " + associationName );
}
}
/**
* This is a no-op.
*
* @param mageObj
* @param gemmaObj
*/
public void convertExtendable( Extendable mageObj, Identifscribable gemmaObj ) {
; // nothing to do, we aren't using this.
}
/**
* @param mageObj
* @param gemmaObj
* @param getter
*/
public void convertExternalDatabaseAssociations( Database mageObj, ExternalDatabase gemmaObj, Method getter ) {
Object associatedObject = intializeConversion( mageObj, gemmaObj, getter );
String associationName = getterToPropertyName( getter );
if ( associatedObject == null ) return;
if ( associationName.equals( "Contacts" ) )
simpleFillIn( ( List ) associatedObject, gemmaObj, getter, CONVERT_FIRST_ONLY, "Contact" );
else
log.debug( "Unsupported or unknown association: " + associationName );
}
/**
* @param mageObj
* @return
*/
public FactorValue convertFactorValue( org.biomage.Experiment.FactorValue mageObj ) {
if ( mageObj == null ) return null;
FactorValue result = FactorValue.Factory.newInstance();
if ( !convertIdentifiable( mageObj, result ) ) convertAssociations( mageObj, result );
return result;
}
/**
* @param mageObj
* @param gemmaObj
* @param getter
*/
public void convertFactorValueAssociations( org.biomage.Experiment.FactorValue mageObj, FactorValue gemmaObj,
Method getter ) {
Object associatedObject = intializeConversion( mageObj, gemmaObj, getter );
String associationName = getterToPropertyName( getter );
if ( associationName.equals( "ExperimentalFactor" ) ) {
simpleFillIn( associatedObject, gemmaObj, getter );
} else if ( associationName.equals( "Measurement" ) ) {
simpleFillIn( associatedObject, gemmaObj, getter, "Measurement" );
} else if ( associationName.equals( "Value" ) ) {
simpleFillIn( associatedObject, gemmaObj, getter, "Value" );
} else {
log.warn( "Unsupported or unknown association: " + associationName );
}
}
/**
* FIXME Unlike in MAGE, feature-reporter map is not an entity. (The mage name is also confusing: it is an
* assocation between a reporter and the features that make it up). Therefore, this is a no-op.
*
* @param mageObj
* @return
*/
public Object convertFeatureReporterMap( FeatureReporterMap mageObj ) {
// NO-OP
return null;
}
/**
* Not supported, a no-op.
*
* @param mageObj
* @return
*/
public Object convertHardware( Hardware mageObj ) {
// no-op
return null;
}
/**
* Copy attributes from a MAGE identifiable to a Gemma identifiscribable.
*
* @param mageObj
* @return boolean True if the object is alreay in the cache and needs no further processing.
*/
public boolean convertIdentifiable( Identifiable mageObj, Identifscribable gemmaObj ) {
if ( mageObj == null ) return false;
if ( gemmaObj == null ) throw new IllegalArgumentException( "Must pass in a valid object" );
if ( isInCache( mageObj ) ) {
log.debug( "Object exists in cache: " + mageObj.getIdentifier() );
gemmaObj = ( Identifscribable ) identifiableCache.get( mageObj.getIdentifier() );
return true;
}
identifiableCache.put( mageObj.getIdentifier(), gemmaObj );
gemmaObj.setIdentifier( mageObj.getIdentifier() );
gemmaObj.setName( mageObj.getName() );
convertDescribable( mageObj, gemmaObj );
return false;
}
/**
* FIXME this is a problem because we don't want separate labeledextract and biomaterial objects.
*
* @param mageObj
* @return
*/
public Object convertLabeledExtract( org.biomage.BioMaterial.LabeledExtract mageObj ) {
if ( mageObj == null ) return null;
log.debug( "Converting LabeledExtract " + mageObj.getIdentifier() );
// log.warn( "Conversion operation not yet fully implemented: convertLabeledExtract" );
BioMaterial result = convertBioMaterial( mageObj );
// TODO labels?
return result;
}
/**
* @param mageObj
* @param gemmaObj
* @param getter
*/
public void convertLabeledExtractAssociations( LabeledExtract mageObj, BioMaterial gemmaObj, Method getter ) {
convertBioMaterialAssociations( mageObj, gemmaObj, getter );
Object associatedObject = intializeConversion( mageObj, gemmaObj, getter );
String associationName = getterToPropertyName( getter );
if ( associatedObject == null ) return;
if ( associationName.equals( "Labels" ) ) {
// we don't use this?
} else {
log.debug( "Unsupported or unknown association, or belongs to superclass: " + associationName );
}
}
/**
* @param mageObj
* @return
*/
public edu.columbia.gemma.expression.bioAssay.BioAssay convertMeasuredBioAssay( MeasuredBioAssay mageObj ) {
if ( mageObj == null ) return null;
log.debug( "Converting MeasuredBioAssay " + mageObj.getIdentifier() );
edu.columbia.gemma.expression.bioAssay.BioAssay result = convertBioAssay( mageObj );
// FIXME this will result in conversion twice because it is identifiable.
convertAssociations( mageObj, result );
return result;
}
/**
* @param mageObj
* @param gemmaObj
* @param getter
*/
public void convertMeasuredBioAssayAssociations( MeasuredBioAssay mageObj,
edu.columbia.gemma.expression.bioAssay.BioAssay gemmaObj, Method getter ) {
Object associatedObject = intializeConversion( mageObj, gemmaObj, getter );
String associationName = getterToPropertyName( getter );
log.debug( "Not supported fully yet" );
if ( associatedObject == null ) return;
if ( associationName.equals( "FeatureExtraction" ) ) {
; // FIXME we may not use this.
;
} else if ( associationName.equals( "MeasuredBioAssayData" ) ) {
; // FIXME we may not use this.
;
} else {
log.debug( "Unsupported or unknown association, or belongs to superclass: " + associationName );
}
}
/**
* @param mageObj
* @return
*/
public edu.columbia.gemma.common.quantitationtype.QuantitationType convertMeasuredSignal( MeasuredSignal mageObj ) {
return convertQuantitationType( mageObj );
}
/**
* @param mageObj
* @return
*/
public edu.columbia.gemma.common.description.Description convertNormalizationDescription( Description mageObj ) {
return convertDescription( mageObj );
}
/**
* @param mageObj
* @return
*/
public edu.columbia.gemma.common.description.OntologyEntry convertOntologyEntry( OntologyEntry mageObj ) {
if ( mageObj == null ) return null;
log.debug( "Converting ontologyEntry" );
edu.columbia.gemma.common.description.OntologyEntry result = edu.columbia.gemma.common.description.OntologyEntry.Factory
.newInstance();
result.setCategory( mageObj.getCategory() );
result.setDescription( mageObj.getDescription() );
result.setValue( mageObj.getValue() );
convertAssociations( mageObj, result );
return result;
}
/**
* @param mageObj
* @param gemmaObj
* @param getter
*/
public void convertOntologyEntryAssociations( OntologyEntry mageObj,
edu.columbia.gemma.common.description.OntologyEntry gemmaObj, Method getter ) {
Object associatedObject = intializeConversion( mageObj, gemmaObj, getter );
String associationName = getterToPropertyName( getter );
if ( associatedObject == null ) return;
if ( associationName.equals( "Associations" ) ) {
simpleFillIn( ( List ) associatedObject, gemmaObj, getter, CONVERT_ALL, "Associations" );
} else if ( associationName.equals( "OntologyReference" ) ) {
simpleFillIn( associatedObject, gemmaObj, getter, "ExternalOntologyReference" );
} else {
log.warn( "Unsupported or unknown association: " + associationName );
}
}
/**
* @param mageObj
* @return
*/
public Object convertPhysicalArrayDesign( org.biomage.ArrayDesign.PhysicalArrayDesign mageObj ) {
if ( mageObj == null ) return null;
log.debug( "Converting PhysicalArrayDesign " + mageObj.getIdentifier() );
edu.columbia.gemma.expression.arrayDesign.ArrayDesign result = convertArrayDesign( mageObj );
// todo: convert the surfaceType and zoneGroups. We don't support these, though we could
convertAssociations( mageObj, result );
return result;
}
/**
* @param mageObj
* @param gemmaObj
* @param getter
*/
public void convertPhysicalArrayDesignAssociations( PhysicalArrayDesign mageObj,
edu.columbia.gemma.expression.arrayDesign.ArrayDesign gemmaObj, Method getter ) {
convertArrayDesignAssociations( mageObj, gemmaObj, getter );
Object associatedObject = intializeConversion( mageObj, gemmaObj, getter );
String associationName = getterToPropertyName( getter );
if ( associatedObject == null ) return;
if ( associationName.equals( "SurfaceType" ) ) {
; // simpleFillIn(associatedObject, gemmaObj, getter); // we don't support this, do we?
} else if ( associationName.equals( "ZoneGroups" ) ) {
assert associatedObject instanceof List;
// we don't support this.
} else {
log.warn( "Unsupported or unknown association, or it belongs to a subclass: " + associationName );
}
}
/**
* @param mageObj
* @return
*/
public edu.columbia.gemma.expression.bioAssay.BioAssay convertPhysicalBioAssay( PhysicalBioAssay mageObj ) {
if ( mageObj == null ) return null;
log.debug( "Converting PhysicalBioAssay " + mageObj.getIdentifier() );
edu.columbia.gemma.expression.bioAssay.BioAssay result = convertBioAssay( mageObj );
convertAssociations( mageObj, result );
return result;
}
/**
* @param mageObj
* @param gemmaObj
* @param getter
*/
public void convertPhysicalBioAssayAssociations( PhysicalBioAssay mageObj,
edu.columbia.gemma.expression.bioAssay.BioAssay gemmaObj, Method getter ) {
Object associatedObject = intializeConversion( mageObj, gemmaObj, getter );
String associationName = getterToPropertyName( getter );
if ( associatedObject == null ) return;
if ( associationName.equals( "BioAssayCreation" ) ) { // we only use this to get the array designs.
specialGetArrayDesignForPhysicalBioAssay( mageObj, gemmaObj );
} else if ( associationName.equals( "BioAssayTreatments" ) ) {
assert associatedObject instanceof List;
// if ( ( ( List ) associatedObject ).size() > 0 ) log.warn( "BioAssayTreatments is being missed" );
// this is not supported in our data model currently.
} else if ( associationName.equals( "PhysicalBioAssayData" ) ) {
assert associatedObject instanceof List;
if ( ( ( List ) associatedObject ).size() > 0 ) log.warn( "PhysicalBioAssayData is being missed" );
} else {
log.debug( "Unsupported or unknown association, or belongs to superclass: " + associationName );
}
}
/**
* @param associatedObject
* @return
*/
public PolymerType convertPolymerType( OntologyEntry mageObj ) {
log.debug( "Converting PolymerType " + mageObj.getValue() );
if ( mageObj.getValue().equalsIgnoreCase( "DNA" ) ) {
return PolymerType.DNA;
} else if ( mageObj.getValue().equalsIgnoreCase( "protein" ) ) {
return PolymerType.PROTEIN;
} else if ( mageObj.getValue().equalsIgnoreCase( "RNA" ) ) {
return PolymerType.RNA;
} else {
log.error( "Unsupported polymer type:" + mageObj.getValue() );
}
return null;
}
/**
* @param mageObj
* @return
*/
public edu.columbia.gemma.common.quantitationtype.QuantitationType convertPresentAbsent( PresentAbsent mageObj ) {
return convertQuantitationType( mageObj );
}
/**
* @param mageObj
* @return
*/
public edu.columbia.gemma.common.protocol.Protocol convertProtocol( Protocol mageObj ) {
if ( mageObj == null ) return null;
// log.warn( "Not fully supported: Protocol" );
edu.columbia.gemma.common.protocol.Protocol result = edu.columbia.gemma.common.protocol.Protocol.Factory
.newInstance();
if ( !convertIdentifiable( mageObj, result ) ) {
result.setText( mageObj.getText() );
result.setTitle( mageObj.getTitle() );
// result.setURI(mageObj.getURI()); // FIXME we should support
convertAssociations( mageObj, result );
}
return result;
}
/**
* @param mageObj
* @param gemmaObj
* @param getter
*/
public void convertProtocolAssociations( Protocol mageObj, edu.columbia.gemma.common.protocol.Protocol gemmaObj,
Method getter ) {
Object associatedObject = intializeConversion( mageObj, gemmaObj, getter );
String associationName = getterToPropertyName( getter );
if ( associatedObject == null ) return;
if ( associationName.equals( "Hardwares" ) ) {
; // not supported
} else if ( associationName.equals( "Softwares" ) ) {
simpleFillIn( ( List ) associatedObject, gemmaObj, getter, CONVERT_ALL, "Softwares" );
} else if ( associationName.equals( "Type" ) ) {
simpleFillIn( associatedObject, gemmaObj, getter );
} else if ( associationName.equals( "ParameterTypes" ) ) {
// FIXME broken.
} else {
log.debug( "Unsupported or unknown association: " + associationName );
}
}
/**
* @param mageObj
* @return
*/
public edu.columbia.gemma.common.quantitationtype.QuantitationType convertPValue( PValue mageObj ) {
return convertQuantitationType( mageObj );
}
/**
* @param mageObj
* @return
*/
public edu.columbia.gemma.common.description.Description convertQualityControlDescription( Description mageObj ) {
return convertDescription( mageObj );
}
/**
* @param mageObj
* @return
*/
public edu.columbia.gemma.common.quantitationtype.QuantitationType convertQuantitationType( QuantitationType mageObj ) {
edu.columbia.gemma.common.quantitationtype.QuantitationType result = edu.columbia.gemma.common.quantitationtype.QuantitationType.Factory
.newInstance();
if ( !convertIdentifiable( mageObj, result ) ) {
result.setIsBackground( mageObj.getIsBackground().booleanValue() );
convertAssociations( mageObj, result );
}
return result;
}
/**
* @param mageObj
* @param gemmaObj
* @param getter
*/
public void convertQuantitationTypeAssociations( QuantitationType mageObj,
edu.columbia.gemma.common.quantitationtype.QuantitationType gemmaObj, Method getter ) {
log.warn( "Not fully implemented" );
Object associatedObject = intializeConversion( mageObj, gemmaObj, getter );
String associationName = getterToPropertyName( getter );
if ( associatedObject == null ) return;
if ( associationName.equals( "Channel" ) ) { // we aren't support this?
; // simpleFillIn( ( List ) associatedObject, gemmaObj, getter, CONVERT_ALL, "Associations" ); // we don't
// support
} else if ( associationName.equals( "ConfidenceIndicators" ) ) { // just another quantitation type.
; // simpleFillIn( associatedObject, gemmaObj, getter, "ExternalOntologyReference" ); // we don't support
} else if ( associationName.equals( "DataType" ) ) {
gemmaObj.setRepresentation( convertDataType( mageObj.getDataType() ) );
} else if ( associationName.equals( "Scale" ) ) {
gemmaObj.setScale( convertScale( mageObj.getScale() ) );
} else if ( associationName.equals( "QuantitationTypeMaps" ) ) {
; // special case - transformations.
} else {
log.debug( "Unsupported or unknown association: " + associationName );
}
}
/**
* @param mageObj
* @return
*/
public edu.columbia.gemma.common.quantitationtype.QuantitationType convertRatio( Ratio mageObj ) {
return convertQuantitationType( mageObj );
}
/**
* @param mageObj
* @return
*/
public edu.columbia.gemma.common.description.Description convertReplicateDescription( Description mageObj ) {
return convertDescription( mageObj );
}
/**
* TODO a reporter has a feature, which has the location information we need for the Gemma reporter.
*
* @param mageObj
* @return edu.columbia.gemma.expression.designElement.Reporter
*/
public edu.columbia.gemma.expression.designElement.Reporter convertReporter(
org.biomage.DesignElement.Reporter mageObj ) {
if ( mageObj == null ) return null;
Reporter result = Reporter.Factory.newInstance();
if ( !convertIdentifiable( mageObj, result ) ) convertAssociations( mageObj, result );
return result;
}
/**
* @param mageObj
* @param gemmaObj
* @param getter
*/
public void convertReporterAssociations( org.biomage.DesignElement.Reporter mageObj, Reporter gemmaObj,
Method getter ) {
Object associatedObject = intializeConversion( mageObj, gemmaObj, getter );
String associationName = getterToPropertyName( getter );
if ( associatedObject == null ) return;
if ( associationName.equals( "FailTypes" ) ) {
// simpleFillIn( ( List ) associatedObject, gemmaObj, getter, CONVERT_ALL, "Associations" ); // we don't
// support
} else if ( associationName.equals( "FeatureReporterMaps" ) ) {
// simpleFillIn( associatedObject, gemmaObj, getter, "ExternalOntologyReference" ); // we don't support
} else if ( associationName.equals( "ImmobilizedCharacteristics" ) ) {
simpleFillIn( ( List ) associatedObject, gemmaObj, getter, CONVERT_FIRST_ONLY, "ImmobilizedCharacteristic" );
} else if ( associationName.equals( "WarningType" ) ) {
specialConvertFeatureReporterMaps( ( List ) associatedObject, gemmaObj );
} else {
log.debug( "Unsupported or unknown association: " + associationName );
}
}
/**
* Unlike in MAGE, reporter-composite map is not an entity. (The mage name is also confusing: it is an assocation
* betwee a composite sequence and the reporters that make it up). Therefore, this is a no-op, we deal with it
* specially.
*
* @param mageObj
* @return
*/
public Object convertReporterCompositeMap( ReporterCompositeMap mageObj ) {
// NO-OP
return null;
}
/**
* No-op, we deal with specially.
*
* @param mageObj
* @return
*/
public Object convertReporterGroup( ReporterGroup mageObj ) {
if ( mageObj == null ) return null;
return null;
}
/**
* @param mageObj
* @return
*/
public ScaleType convertScale( OntologyEntry mageObj ) {
if ( mageObj == null ) return null;
String val = mageObj.getValue();
if ( val.equalsIgnoreCase( "" ) ) {
return ScaleType.FOLDCHANGE;
} else if ( val.equalsIgnoreCase( "foldchange" ) ) {
return ScaleType.LINEAR;
} else if ( val.equalsIgnoreCase( "ln" ) ) {
return ScaleType.LN;
} else if ( val.equalsIgnoreCase( "log10" ) ) {
return ScaleType.LOG10;
} else if ( val.equalsIgnoreCase( "log2" ) ) {
return ScaleType.LOG2;
} else if ( val.equalsIgnoreCase( "other" ) ) {
return ScaleType.OTHER;
} else {
log.error( "Unrecognized Scale " + val );
}
return null;
}
/**
* @param mageObj
* @return
*/
public Software convertSoftware( org.biomage.Protocol.Software mageObj ) {
if ( mageObj == null ) return null;
Software result = Software.Factory.newInstance();
if ( !convertIdentifiable( mageObj, result ) ) {
convertAssociations( mageObj, result );
}
return result;
}
/**
* @param mageObj
* @param gemmaObj
* @param getter
*/
public void convertSoftwareAssociations( org.biomage.Protocol.Software mageObj, Software gemmaObj, Method getter ) {
Object associatedObject = intializeConversion( mageObj, gemmaObj, getter );
String associationName = getterToPropertyName( getter );
if ( associatedObject == null ) return;
if ( associationName.equals( "Hardware" ) ) {
// no-op
} else if ( associationName.equals( "SoftwareManufacturers" ) ) {
simpleFillIn( ( List ) associatedObject, gemmaObj, getter, CONVERT_ALL, "SoftwareManufacturers" );
} else if ( associationName.equals( "Softwares" ) ) {
simpleFillIn( ( List ) associatedObject, gemmaObj, getter, CONVERT_ALL, "SoftwareComponents" );
} else if ( associationName.equals( "Type" ) ) {
simpleFillIn( associatedObject, gemmaObj, getter );
} else {
log.debug( "Unsupported or unknown association: " + associationName );
}
}
/**
* @param mageObj
* @return
*/
public edu.columbia.gemma.common.quantitationtype.QuantitationType convertSpecializedQuantitationType(
SpecializedQuantitationType mageObj ) {
return convertQuantitationType( mageObj );
}
/**
* This is a special case for an OntologyEntry that doesn't map to one in Gemma.
*
* @param species
* @return
*/
public Taxon convertSpecies( OntologyEntry species ) {
Taxon result = Taxon.Factory.newInstance();
log.debug( "Converting Species from " + species.getValue() );
result.setCommonName( species.getValue() );
// FIXME - this should be written to ensure that the result agrees with what is already in the database.
return result;
}
/**
* Special case, OntologyEntry maps to an Enum.
*
* @param mageObj
* @return SequenceType
*/
public SequenceType convertType( OntologyEntry mageObj ) {
if ( mageObj == null ) return null;
log.debug( "Converting sequence type of \"" + mageObj.getValue() + "\"" );
String value = mageObj.getValue();
if ( value.equalsIgnoreCase( "bc" ) ) {
return SequenceType.BAC;
} else if ( value.equalsIgnoreCase( "est" ) ) {
return SequenceType.EST;
} else if ( value.equalsIgnoreCase( "affyprobe" ) ) {
return SequenceType.AFFY_PROBE;
} else if ( value.equalsIgnoreCase( "affytarget" ) ) {
return SequenceType.AFFY_TARGET;
} else if ( value.equalsIgnoreCase( "mrna" ) ) {
return SequenceType.mRNA;
} else if ( value.equalsIgnoreCase( "refseq" ) ) {
return SequenceType.REFSEQ;
} else if ( value.equalsIgnoreCase( "chromosome" ) ) {
return SequenceType.WHOLE_CHROMOSOME;
} else if ( value.equalsIgnoreCase( "genome" ) ) {
return SequenceType.WHOLE_GENOME;
} else if ( value.equalsIgnoreCase( "orf" ) ) {
return SequenceType.ORF;
} else if ( value.equalsIgnoreCase( "dna" ) ) {
return SequenceType.DNA;
} else {
return SequenceType.OTHER;
}
}
/**
* @param mageObj
* @return
*/
public edu.columbia.gemma.common.description.OntologyEntry convertValue( OntologyEntry mageObj ) {
return convertOntologyEntry( mageObj );
}
/**
* Special case: Convert a ReporterCompositeMaps (list) to a Collection of Reporters.
*
* @param reporterCompositeMaps
* @return Collection of Gemma Reporters.
*/
public void specialConvertFeatureReporterMaps( List featureReporterMaps, Reporter rep ) {
if ( featureReporterMaps.size() > 1 ) log.warn( "**** More than one FeatureReporterMap for a Reporter!" );
for ( Iterator iter = featureReporterMaps.iterator(); iter.hasNext(); ) {
FeatureReporterMap rcp = ( FeatureReporterMap ) iter.next();
List rcpps = rcp.getFeatureInformationSources();
for ( Iterator iterator = rcpps.iterator(); iterator.hasNext(); ) {
log.debug( "Found feature information for reporter: " + rep.getIdentifier() );
FeatureInformation rps = ( FeatureInformation ) iterator.next();
org.biomage.DesignElement.Feature repr = rps.getFeature();
rep.setCol( repr.getPosition().getX().intValue() );
rep.setRow( repr.getPosition().getY().intValue() );
// todo: strand...
}
break; // only take the first one
}
}
/**
* Special case: Convert a ReporterCompositeMaps (list) to a Collection of Reporters.
*
* @param reporterCompositeMaps
* @return Collection of Gemma Reporters.
*/
public Collection specialConvertReporterCompositeMaps( List reporterCompositeMaps ) {
if ( reporterCompositeMaps.size() > 1 ) log.warn( "**** More than one ReporterCompositeMaps for a Reporter!" );
Collection result = new ArrayList();
for ( Iterator iter = reporterCompositeMaps.iterator(); iter.hasNext(); ) {
ReporterCompositeMap rcp = ( ReporterCompositeMap ) iter.next();
List rcpps = rcp.getReporterPositionSources();
log.debug( "Found reporters for composite sequence" );
for ( Iterator iterator = rcpps.iterator(); iterator.hasNext(); ) {
ReporterPosition rps = ( ReporterPosition ) iterator.next();
if ( rps == null ) continue;
org.biomage.DesignElement.Reporter repr = rps.getReporter();
if ( repr == null ) continue;
// FIXME: this reporter already exists in memory, probably.
Reporter conv = convertReporter( repr );
if ( conv == null ) {
log.error( "Null converted reporter!" );
continue;
}
result.add( conv );
Integer m = rps.getStart();
if ( m == null ) {
// log.error( "Null start for reporter " + repr.getIdentifier() );
continue;
}
conv.setStartInBioChar( m.intValue() );
}
break; // only take the first one;
}
return result;
}
/**
* @param mageObj
* @return Converted object. If the source object is null, the return value is null.
*/
private Object findAndInvokeConverter( Object mageObj ) {
if ( mageObj == null ) return null;
Object convertedGemmaObj = null;
try {
Method converter = findConverter( mageObj );
if ( converter == null ) return null;
convertedGemmaObj = converter.invoke( this, new Object[] { mageObj } );
} catch ( IllegalArgumentException e ) {
log.error( e );
} catch ( IllegalAccessException e ) {
log.error( e );
} catch ( InvocationTargetException e ) {
log.error( e );
}
return convertedGemmaObj;
}
/**
* @param objectToConvert
* @param converterBaseName
* @param mageTypeToConvert
* @return Converted object. If the input mageObj is null, the return value is null.
*/
private Object findAndInvokeConverter( Object mageObj, String converterBaseName, Class mageTypeToConvert ) {
if ( mageObj == null ) return null;
Method gemmaConverter = findConverter( converterBaseName, mageTypeToConvert );
if ( gemmaConverter == null ) return null;
Object convertedGemmaObj = null;
try {
convertedGemmaObj = gemmaConverter.invoke( this, new Object[] { mageObj } );
} catch ( IllegalArgumentException e ) {
log.error( e );
} catch ( IllegalAccessException e ) {
log.error( e );
} catch ( InvocationTargetException e ) {
log.error( "InvocationTargetException for " + mageObj.getClass().getName() + e );
}
return convertedGemmaObj;
}
/**
* @param setterObj - The object on which we will call the setter
* @param settee - The object we want to set
* @param setteeClass - The class accepted by the setter - not necessarily the class of the setterObj (example:
* DatabaseEntry vs. DatabaseEntryImpl)
* @param propertyName - The property name corresponding to the setteeClass
*/
private void findAndInvokeSetter( Object setterObj, Object settee, Class setteeClass, String propertyName ) {
Method gemmaSetter = findSetter( setterObj, propertyName, setteeClass );
if ( gemmaSetter == null ) {
return;
}
try {
gemmaSetter.invoke( setterObj, new Object[] { settee } );
} catch ( IllegalArgumentException e ) {
log.error( e );
} catch ( IllegalAccessException e ) {
log.error( e );
} catch ( InvocationTargetException e ) {
log.error( e );
}
}
/**
* @param mageObj
* @return
*/
private Method findConverter( Object mageObj ) {
String mageTypeName = ReflectionUtil.objectToTypeName( mageObj );
Method converter = null;
try {
converter = this.getClass().getMethod( "convert" + mageTypeName, new Class[] { mageObj.getClass() } );
} catch ( NoSuchMethodException e ) {
log.warn( "Conversion operation not yet supported: " + "convert" + mageTypeName + "("
+ mageObj.getClass().getName() + ")" );
}
return converter;
}
/**
* @param associationName
* @param mageAssociatedType
* @return
*/
private Method findConverter( String associationName, Class mageAssociatedType ) {
Method gemmaConverter = null;
try {
gemmaConverter = this.getClass()
.getMethod( "convert" + associationName, new Class[] { mageAssociatedType } );
} catch ( NoSuchMethodException e ) {
log.warn( "Conversion operation not yet supported: " + "convert" + associationName );
}
return gemmaConverter;
}
/**
* @param setter - The object on which we want to call the setter
* @param propertyName - The name of the property we want to set
* @param setee - The object which we want to enter as an argument to the setter.
* @return
*/
private Method findSetter( Object setter, String propertyName, Class setee ) {
Method gemmaSetter = null;
try {
gemmaSetter = ReflectionUtil.getBaseForImpl( setter ).getMethod( "set" + propertyName,
new Class[] { setee } );
} catch ( SecurityException e ) {
log.error( e );
} catch ( NoSuchMethodException e ) {
log.error( "No such setter: " + "set" + propertyName + "(" + setee.getName() + ")", e );
}
return gemmaSetter;
}
/**
* For a method like "getFoo", returns "Foo".
*
* @param getter
* @return
*/
private String getterToPropertyName( Method getter ) {
if ( !getter.getName().startsWith( "get" ) ) throw new IllegalArgumentException( "Not a getter" );
return getter.getName().substring( 3 );
}
/**
* Initialize the conversion process by calling the getter and getting the association name
*
* @param mageObj
* @param gemmaObj
* @param getter
* @return The name of the association, taken from the getter.
*/
private Object intializeConversion( Object mageObj, Object gemmaObj, Method getter ) {
Object associatedObject = invokeGetter( mageObj, getter );
if ( associatedObject == null ) {
log.debug( "Getter called on " + mageObj.getClass().getName() + " but failed to return a value: "
+ getter.getName() + " (Probably no data)" );
return null;
}
log.debug( mageObj.getClass().getName() + "--->" + getterToPropertyName( getter ) );
return associatedObject;
}
/**
* Call a 'get' method to retrieve an associated MAGE object for conversion.
*
* @param mageObj
* @param getter
* @return A MAGE domain object, or a List of MAGE domain objects. The caller has to figure out which.
*/
private Object invokeGetter( Object mageObj, Method getter ) {
Object associatedObject = null;
if ( getter == null ) throw new IllegalArgumentException( "Null getter passed" );
if ( mageObj == null ) throw new IllegalArgumentException( "Attempt to run get... on null object" );
try {
// log.debug( "Calling " + getter.getName() + " from " + getter.getDeclaringClass().getName() + " on a "
// + mageObj.getClass().getName() );
associatedObject = getter.invoke( mageObj, new Object[] {} );
} catch ( IllegalArgumentException e ) {
log.error( e, e );
} catch ( IllegalAccessException e ) {
log.error( e, e );
} catch ( InvocationTargetException e ) {
log.error( mageObj.getClass().getName() + "." + getter.getName() + " threw an exception: " + e.getCause(),
e );
}
return associatedObject;
}
/**
* @param mageObj - Identifiable
* @return boolean True if the object is alreay in the cache and needs no further processing.
*/
private boolean isInCache( Identifiable mageObj ) {
return identifiableCache.get( mageObj.getIdentifier() ) != null;
}
/**
* Generic method to fill in a Gemma object where the association in Mage has cardinality of >1.
*
* @param associatedList - The result of the Getter call.
* @param gemmObj - The Gemma object in which to place the converted Mage object(s).
* @param onlyTakeOne - This indicates that the cardinality in the Gemma object is at most 1. Therefore we pare down
* the Mage object list to take just the first one.
* @param actualGemmaAssociationName - for example, a BioSequence hasa "SequenceDatabaseEntry", not a
* "DatabaseEntry". If null, the name is inferred.
*/
private void simpleFillIn( List associatedList, Object gemmaObj, Method getter, boolean onlyTakeOne,
String actualGemmaAssociationName ) {
if ( associatedList == null || gemmaObj == null || getter == null )
throw new IllegalArgumentException( "Null objects" );
if ( associatedList.size() == 0 ) {
log.debug( "List was not null, but empty" );
return;
}
String associationName = actualGemmaAssociationName; // todo, refactor so we use convertAssociationName
if ( associationName == null )
associationName = ReflectionUtil.classToTypeName( associatedList.get( 0 ).getClass() );
try {
if ( onlyTakeOne ) {
log.debug( "Converting a MAGE list to a single instance" );
Object mageObj = associatedList.get( 0 );
Object convertedGemmaObj = findAndInvokeConverter( mageObj );
if ( convertedGemmaObj == null ) return; // not supported.
Class convertedGemmaClass = ReflectionUtil.getBaseForImpl( convertedGemmaObj );
findAndInvokeSetter( gemmaObj, convertedGemmaObj, convertedGemmaClass, associationName );
} else {
log.debug( "Converting a MAGE list to a Gemma list" );
Collection gemmaObjList = new ArrayList();
for ( Iterator iter = associatedList.iterator(); iter.hasNext(); ) {
Object mageObj = iter.next();
Object convertedGemmaObj = findAndInvokeConverter( mageObj );
if ( convertedGemmaObj == null ) continue; // not supported.
gemmaObjList.add( convertedGemmaObj );
}
findAndInvokeSetter( gemmaObj, gemmaObjList, Collection.class, associationName );
}
} catch ( SecurityException e ) {
log.error( e );
} catch ( IllegalArgumentException e ) {
log.error( e );
}
}
/**
* Generic method to fill in a Gemma object's association with a Mage object where the name can be predicted from
* the associated object type. E.g., the Gemma object with an association to "BioSequence" has a "bioSequence"
* property; sometimes instead we have things like ImmobilizedCharacteristic.
*
* @param associatedMageObject The associated object we need to find a place for.
* @param gemmaObj The Gemma object in which to place the converted Mage object.
* @param getter The getter for the Mage object
*/
private void simpleFillIn( Object associatedMageObject, Object gemmaObj, Method getter ) {
this.simpleFillIn( associatedMageObject, gemmaObj, getter, null );
}
/**
* Generic method to fill in a Gemma object's association with a Mage object where the name might be predicted from
* the associated object type. E.g., the Gemma object with an association to "BioSequence" has a "bioSequence"
* property; sometimes instead we have things like ImmobilizedCharacteristic.
*
* @param associatedMageObject The associated object we need to find a place for.
* @param gemmaObj The Gemma object in which to place the converted Mage object.
* @param getter The getter for the Mage object
* @param actualGemmaAssociationName - Replacement name for the Gemma association. This is to handle situations
* where the getter does not have a name that can be figured out. If null, the name is figured out from the
* getter.
*/
private void simpleFillIn( Object associatedMageObject, Object gemmaObj, Method getter,
String actualGemmaAssociationName ) {
if ( associatedMageObject == null ) return;
String associationName = getterToPropertyName( getter );
try {
Class mageAssociatedType = associatedMageObject.getClass();
Object gemmaAssociatedObj = findAndInvokeConverter( associatedMageObject, associationName,
mageAssociatedType );
if ( gemmaAssociatedObj == null ) return;
Class gemmaClass = ReflectionUtil.getImplForBase( gemmaAssociatedObj.getClass() );
String inferredGemmaAssociationName = convertAssociationName( actualGemmaAssociationName,
gemmaAssociatedObj );
findAndInvokeSetter( gemmaObj, gemmaAssociatedObj, gemmaClass, inferredGemmaAssociationName );
} catch ( SecurityException e ) {
log.error( e );
} catch ( IllegalArgumentException e ) {
log.error( e );
}
}
/**
* Extract compositeSequence information from the ArrayDesign package. The ArrayDesign package doesn't have any
* information about the compositeSequences, other than the fact that they belong to this arrayDesign.
*
* @param compositeGroups
* @param gemmaObj
*/
private void specialConvertCompositeGroups( List compositeGroups,
edu.columbia.gemma.expression.arrayDesign.ArrayDesign gemmaObj ) {
if ( compositeGroups.size() > 1 ) log.warn( "*** More than one compositeGroup in an array design!!!" );
log.warn( "Converting compositeGroups" );
Collection designObjs;
if ( gemmaObj.getDesignElements() == null ) {
designObjs = new HashSet();
gemmaObj.setDesignElements( designObjs );
} else {
designObjs = gemmaObj.getDesignElements();
}
for ( Iterator iter = compositeGroups.iterator(); iter.hasNext(); ) {
CompositeGroup rg = ( CompositeGroup ) iter.next();
List reps = rg.getCompositeSequences();
for ( Iterator iterator = reps.iterator(); iterator.hasNext(); ) {
org.biomage.DesignElement.CompositeSequence compseq = ( org.biomage.DesignElement.CompositeSequence ) iterator
.next();
CompositeSequence csconv = convertCompositeSequence( compseq );
if ( !designObjs.contains( csconv ) ) {
log.warn( "Adding new compositeSequence to the ArrayDesign" );
designObjs.add( csconv );
} else {
log.warn( "We already have this compositesequence " + csconv.getIdentifier() );
}
}
}
}
/**
* We don't have features, just reporter, so FIXME
*
* @param featureGroups
* @param gemmaObj
*/
private void specialConvertFeatureGroups( List featureGroups,
edu.columbia.gemma.expression.arrayDesign.ArrayDesign gemmaObj ) {
if ( featureGroups.size() > 1 ) log.warn( "*** More than one featureGroup in an array design!!!" );
log.warn( "Converting featureGroups" );
Collection designObjs;
if ( gemmaObj.getDesignElements() == null ) {
designObjs = new HashSet();
gemmaObj.setDesignElements( designObjs );
} else {
designObjs = gemmaObj.getDesignElements();
}
for ( Iterator iter = featureGroups.iterator(); iter.hasNext(); ) {
FeatureGroup rg = ( FeatureGroup ) iter.next();
List reps = rg.getFeatures();
for ( Iterator iterator = reps.iterator(); iterator.hasNext(); ) {
// org.biomage.DesignElement.Feature feature = ( org.biomage.DesignElement.Feature ) iterator.next();
// edu.columbia.gemma.expression.designElement.Feature csconv = convertFeature( feature );
// if ( !designObjs.contains( csconv ) ) {
// log.warn( "Adding new feature to the ArrayDesign" );
// designObjs.add( csconv );
// } else {
// log.warn( "We already have this feature " + csconv.getIdentifier() );
}
}
}
/**
* Convert all the reporters via the reporter groups.
*
* @param reporterGroups
* @param gemmaObj
*/
private void specialConvertReporterGroups( List reporterGroups,
edu.columbia.gemma.expression.arrayDesign.ArrayDesign gemmaObj ) {
if ( reporterGroups.size() > 1 ) log.warn( "*** More than one reporter group in an array design!!!" );
log.warn( "Converting reporterGroups" );
Collection designObjs;
if ( gemmaObj.getDesignElements() == null ) {
designObjs = new HashSet();
gemmaObj.setDesignElements( designObjs );
} else {
designObjs = gemmaObj.getDesignElements();
}
for ( Iterator iter = reporterGroups.iterator(); iter.hasNext(); ) {
ReporterGroup rg = ( ReporterGroup ) iter.next();
List reps = rg.getReporters();
for ( Iterator iterator = reps.iterator(); iterator.hasNext(); ) {
org.biomage.DesignElement.Reporter reporter = ( org.biomage.DesignElement.Reporter ) iterator.next();
Reporter csconv = convertReporter( reporter );
if ( !designObjs.contains( csconv ) ) {
log.warn( "Adding new reporter to the ArrayDesign" );
designObjs.add( csconv );
} else {
log.warn( "We already have this reporter " + csconv.getIdentifier() );
}
}
}
// gemmaObj.setNumberOfFeatures( designObjs() );
}
/**
* From a PhysicalBioAssay, find the associated ArrayDesign.
*
* @param mageObj
* @param result
*/
private void specialGetArrayDesignForPhysicalBioAssay( PhysicalBioAssay mageObj,
edu.columbia.gemma.expression.bioAssay.BioAssay result ) {
BioAssayCreation bac = mageObj.getBioAssayCreation();
if ( bac == null ) return;
ArrayDesign ad = bac.getArray().getArrayDesign();
if ( ad == null ) return;
log.warn( "Looked in " + mageObj.getIdentifier() + " for ArrayDesign " + ad.getIdentifier() );
edu.columbia.gemma.expression.arrayDesign.ArrayDesign conv = convertArrayDesign( ad );
if ( result.getArrayDesignUsed() == null ) result.setArrayDesignUsed( new ArrayList() );
result.getArrayDesignUsed().add( conv );
}
}
|
package au.gov.dva.sopapi.sopsupport;
import au.gov.dva.sopapi.DateTimeUtils;
import au.gov.dva.sopapi.dtos.sopsupport.components.ConditionDto;
import au.gov.dva.sopapi.exceptions.ProcessingRuleRuntimeException;
import au.gov.dva.sopapi.interfaces.ConditionConfiguration;
import au.gov.dva.sopapi.interfaces.ProcessingRule;
import au.gov.dva.sopapi.interfaces.RuleConfigurationRepository;
import au.gov.dva.sopapi.interfaces.model.Condition;
import au.gov.dva.sopapi.interfaces.model.Deployment;
import au.gov.dva.sopapi.interfaces.model.SoPPair;
import au.gov.dva.sopapi.sopsupport.processingrules.Interval;
import au.gov.dva.sopapi.sopsupport.processingrules.intervalSelectors.AllDaysOfServiceSelector;
import au.gov.dva.sopapi.sopsupport.processingrules.intervalSelectors.FixedDaysPeriodSelector;
import au.gov.dva.sopapi.sopsupport.processingrules.intervalSelectors.FixedYearsPeriodSelector;
import au.gov.dva.sopapi.sopsupport.processingrules.rules.*;
import com.google.common.collect.ImmutableSet;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
public class ConditionFactory {
public static Optional<Condition> create(SoPPair soPPair, ConditionDto conditionDto, RuleConfigurationRepository ruleConfigurationRepository) {
Function<String, Optional<ProcessingRule>> createRule = c -> {
Optional<ConditionConfiguration> conditionConfiguration = ruleConfigurationRepository.getConditionConfigurationFor(c);
Optional<ProcessingRule> processingRuleOptional =
!conditionConfiguration.isPresent() ?
BuildRuleFromCode(c) :
Optional.ofNullable(BuildRuleFromConfig(conditionConfiguration.get()));
return processingRuleOptional;
};
Optional<ProcessingRule> processingRuleOptional = createRule.apply(conditionDto.get_conditionName());
if (!processingRuleOptional.isPresent()) {
return Optional.empty();
}
return Optional.of(new OnsetCondition(
soPPair,
conditionDto.get_incidentDateRangeDto().get_startDate(),
conditionDto.get_incidentDateRangeDto().get_endDate(),
processingRuleOptional.get())
);
}
private static Optional<ProcessingRule> BuildRuleFromCode(String conditionName) {
switch (conditionName) {
case "sprain and strain":
return Optional.of(new AcuteConditionRule(
"F2011L01726", ImmutableSet.of("6(a)", "6(c)"),
"F2011L01727", ImmutableSet.of("6(a)", "6(c)"),
condition -> new Interval(condition.getStartDate().minusDays(7), condition.getStartDate())));
default:
return Optional.empty();
}
}
private static ProcessingRule BuildRuleFromConfig(ConditionConfiguration conditionConfiguration) {
switch (conditionConfiguration.getConditionName()) {
case "lumbar spondylosis":
return new LumbarSpondylosisRule(conditionConfiguration);
case "osteoarthritis":
return new OsteoarthritisRule(conditionConfiguration);
case "intervertebral disc prolapse":
return new InvertebralDiscProlapseRule(conditionConfiguration);
case "thoracic spondylosis":
return new ThoracicSpondylosisRule(conditionConfiguration);
case "rotator cuff syndrome":
return new RotatorCuffSyndromeRule(conditionConfiguration);
case "acquired cataract":
return new GenericProcessingRule(conditionConfiguration, new AllDaysOfServiceSelector());
case "achilles tendinopathy and bursitis":
return new GenericProcessingRule(conditionConfiguration, new FixedDaysPeriodSelector(28));
case "chondromalacia patella":
return new GenericProcessingRule(conditionConfiguration, new FixedDaysPeriodSelector(28));
case "iliotibial band syndrome":
return new GenericProcessingRule(conditionConfiguration, new FixedDaysPeriodSelector(28));
case "malignant melanoma of the skin":
return new GenericProcessingRule(conditionConfiguration, new AllDaysOfServiceSelector());
case "non-melanotic malignant neoplasm of the skin":
return new GenericProcessingRule(conditionConfiguration, new AllDaysOfServiceSelector());
case "patellar tendinopathy":
return new GenericProcessingRule(conditionConfiguration, new FixedDaysPeriodSelector(28));
case "plantar fasciitis":
return new GenericProcessingRuleWithUniqueTestPeriodsForRHandBoP(conditionConfiguration,
new FixedDaysPeriodSelector(84), // test period for standard of proof
new FixedDaysPeriodSelector(84),
new FixedDaysPeriodSelector(168)); // BoP
case "pterygium":
return new GenericProcessingRule(conditionConfiguration, new AllDaysOfServiceSelector());
case "sensorineural hearing loss":
return new GenericProcessingRule(conditionConfiguration, new AllDaysOfServiceSelector());
case "shin splints":
return new GenericProcessingRule(conditionConfiguration, new FixedDaysPeriodSelector(28));
case "solar keratosis":
return new GenericProcessingRule(conditionConfiguration, new AllDaysOfServiceSelector());
case "tinea":
return new GenericProcessingRule(conditionConfiguration, new FixedDaysPeriodSelector(28));
case "tinnitus":
return new GenericProcessingRule(conditionConfiguration, new AllDaysOfServiceSelector());
case "trochanteric bursitis and gluteal tendinopathy":
return new GenericProcessingRule(conditionConfiguration, new FixedDaysPeriodSelector(28));
case "femoroacetabular impingement syndrome":
return new GenericProcessingRule(conditionConfiguration, new FixedDaysPeriodSelector(28));
case "posttraumatic stress disorder":
return new MentalHealthProcessingRule(conditionConfiguration,new AllDaysOfServiceSelector());
case "anxiety disorder":
return new MentalHealthProcessingRule(conditionConfiguration,new FixedYearsPeriodSelector(5));
case "adjustment disorder":
return new MentalHealthProcessingRule(conditionConfiguration,new FixedDaysPeriodSelector(84));
}
return null;
}
public static Optional<SoPPair> getSopPairForConditionName(ImmutableSet<SoPPair> sopPairs, String conditionName) {
Optional<SoPPair> soPPair = sopPairs.stream().filter(s -> s.getConditionName().equalsIgnoreCase(conditionName.trim()))
.findFirst();
return soPPair;
}
}
|
package com.github.podd.utils;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.openrdf.OpenRDFException;
import org.openrdf.model.Model;
import org.openrdf.model.Resource;
import org.openrdf.model.Statement;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.model.ValueFactory;
import org.openrdf.model.impl.LinkedHashModel;
import org.openrdf.model.impl.ValueFactoryImpl;
import org.openrdf.model.util.ModelException;
import org.openrdf.model.vocabulary.OWL;
import org.openrdf.model.vocabulary.RDF;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.RDFHandler;
import org.openrdf.rio.RDFHandlerException;
import org.openrdf.rio.RDFParseException;
import org.openrdf.rio.Rio;
import org.openrdf.rio.UnsupportedRDFormatException;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLOntologyID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.podd.exception.SchemaManifestException;
import com.github.podd.exception.UnmanagedArtifactIRIException;
import com.github.podd.exception.UnmanagedArtifactVersionException;
/**
* Utilities for working with {@link InferredOWLOntologyID}
*
* @author Peter Ansell p_ansell@yahoo.com
*/
public class OntologyUtils
{
private static final Logger log = LoggerFactory.getLogger(OntologyUtils.class);
/**
* Finds the schema imports for the given artifact.
*
* Must not throw an {@link UnmanagedArtifactIRIException} or
* {@link UnmanagedArtifactVersionException} if the artifact does not exist globally, as long as
* it is managed correctly in the given model.
*
* @param artifactID
* @param results
* @param model
* @throws OpenRDFException
* @throws SchemaManifestException
* @throws IOException
* @throws RDFParseException
* @throws UnsupportedRDFormatException
*/
public static List<OWLOntologyID> artifactImports(final InferredOWLOntologyID artifactID, final Model model)
throws OpenRDFException, SchemaManifestException, IOException, RDFParseException, UnsupportedRDFormatException
{
Objects.requireNonNull(artifactID);
Objects.requireNonNull(model);
final Set<OWLOntologyID> results = new LinkedHashSet<OWLOntologyID>();
final Set<URI> schemaOntologyUris = new LinkedHashSet<>();
final Set<URI> schemaVersionUris = new LinkedHashSet<>();
final ConcurrentMap<URI, Set<URI>> importsMap = new ConcurrentHashMap<>(schemaOntologyUris.size());
OntologyUtils.extractOntologyAndVersions(model, schemaOntologyUris, schemaVersionUris);
if(!schemaOntologyUris.contains(artifactID.getOntologyIRI().toOpenRDFURI()))
{
throw new SchemaManifestException(artifactID.getOntologyIRI(),
"Did not find the given ontology IRI in the model: " + artifactID.getOntologyIRI());
}
final List<URI> orderImports =
OntologyUtils.orderImports(model, schemaOntologyUris, schemaVersionUris, importsMap, true);
final Set<URI> artifactImports = new LinkedHashSet<>();
// Be tolerant for artifacts and add imports for both the ontology and the version
OntologyUtils.recursiveFollowImports(artifactImports, importsMap, artifactID.getOntologyIRI().toOpenRDFURI());
if(artifactID.getVersionIRI() != null)
{
OntologyUtils
.recursiveFollowImports(artifactImports, importsMap, artifactID.getVersionIRI().toOpenRDFURI());
}
final List<InferredOWLOntologyID> ontologyIDs = OntologyUtils.modelToOntologyIDs(model, true, false);
final Set<OWLOntologyID> finalOrderImports =
OntologyUtils.finalOrderImports(results, ontologyIDs, orderImports, artifactImports, importsMap);
return new ArrayList<>(finalOrderImports);
}
/**
* Extracts ontology and version IRIs to separate sets, which are both given as parameters.
*
* Only recognises ontology IRIs which have an "ontologyIRI, rdf:type, owl:Ontology" triple.
*
* Only recognises version IRIs which have both "versionIRI, rdf:type, owl:Ontology" and
* "ontologyIRI, owl:versionIRI, versionIRI"
*
* @param model
* The input statements.
* @param schemaOntologyUris
* An output container for all of the ontology IRIs which are not also version IRIs.
* @param schemaVersionUris
* An output container for all of the ontology IRIs which are also versionIRIs.
*/
public static void extractOntologyAndVersions(final Model model, final Set<URI> schemaOntologyUris,
final Set<URI> schemaVersionUris)
{
for(final Statement nextImport : model.filter(null, OWL.VERSIONIRI, null))
{
if(nextImport.getObject() instanceof URI)
{
if(!model.contains((URI)nextImport.getObject(), RDF.TYPE, OWL.ONTOLOGY))
{
model.add((URI)nextImport.getObject(), RDF.TYPE, OWL.ONTOLOGY);
}
}
}
for(final Resource nextOntology : model.filter(null, RDF.TYPE, OWL.ONTOLOGY).subjects())
{
if(nextOntology instanceof URI)
{
if(model.contains(null, OWL.VERSIONIRI, nextOntology))
{
schemaVersionUris.add((URI)nextOntology);
}
else
{
schemaOntologyUris.add((URI)nextOntology);
}
}
}
}
/**
* Call this to reorder the results set according to the order specified in orderImports.
*
* @param results
* @param ontologyIDs
* @param orderImports
* @param artifactImports
* @param importsMap
*/
public static Set<OWLOntologyID> finalOrderImports(final Set<OWLOntologyID> results,
final List<? extends OWLOntologyID> ontologyIDs, final List<URI> orderImports,
final Set<URI> artifactImports, final ConcurrentMap<URI, Set<URI>> importsMap)
{
final Set<OWLOntologyID> finalResults = new LinkedHashSet<OWLOntologyID>();
for(final URI nextImport : orderImports)
{
// Iterate through all of the imports and select those which were actually found
if(artifactImports.contains(nextImport))
{
boolean found = false;
for(final OWLOntologyID nextOntologyID : ontologyIDs)
{
if(nextOntologyID.getOntologyIRI().toOpenRDFURI().equals(nextImport))
{
finalResults.add(nextOntologyID);
found = true;
break;
}
else if(nextOntologyID.getVersionIRI() != null
&& nextOntologyID.getVersionIRI().toOpenRDFURI().equals(nextImport))
{
finalResults.add(nextOntologyID);
found = true;
break;
}
}
if(!found)
{
OntologyUtils.log.error("Could not map import to an ontology ID: ", nextImport);
}
}
}
return finalResults;
}
/**
* @param managementConnection
* @param schemaManagementGraph
* @param model
* @return
* @throws RepositoryException
* @throws ModelException
* @throws IOException
* @throws RDFParseException
* @throws SchemaManifestException
*/
public static List<InferredOWLOntologyID> loadSchemasFromManifest(final RepositoryConnection managementConnection,
final URI schemaManagementGraph, final Model model) throws RepositoryException, ModelException,
IOException, RDFParseException, SchemaManifestException
{
managementConnection.add(model, schemaManagementGraph);
final List<InferredOWLOntologyID> ontologyIDs = OntologyUtils.modelToOntologyIDs(model, false, false);
for(final InferredOWLOntologyID nextOntology : ontologyIDs)
{
final String classpath =
model.filter(nextOntology.getVersionIRI().toOpenRDFURI(), PODD.PODD_SCHEMA_CLASSPATH, null)
.objectString();
if(classpath == null)
{
throw new SchemaManifestException(nextOntology.getVersionIRI(),
"Ontology was not mapped to a classpath: " + nextOntology.toString());
}
final InputStream nextStream = OntologyUtils.class.getResourceAsStream(classpath);
if(nextStream == null)
{
throw new SchemaManifestException(nextOntology.getVersionIRI(),
"Ontology was not found on the classpath: " + classpath);
}
managementConnection.add(nextStream, "", Rio.getParserFormatForFileName(classpath, RDFFormat.RDFXML),
nextOntology.getVersionIRI().toOpenRDFURI());
}
final Model currentVersions = model.filter(null, PODD.OMV_CURRENT_VERSION, null);
for(final Resource nextOntology : currentVersions.subjects())
{
// Ensure that there is only one current version
final URI nextCurrentVersion = model.filter(nextOntology, PODD.OMV_CURRENT_VERSION, null).objectURI();
managementConnection.remove(nextOntology, PODD.OMV_CURRENT_VERSION, null, schemaManagementGraph);
managementConnection.add(nextOntology, PODD.OMV_CURRENT_VERSION, nextCurrentVersion, schemaManagementGraph);
}
return ontologyIDs;
}
/**
* @param model
* @param currentVersionsMap
* @param allVersionsMap
* @param nextSchemaOntologyUri
*/
public static void mapAllVersions(final Model model, final ConcurrentMap<URI, URI> currentVersionsMap,
final ConcurrentMap<URI, Set<URI>> allVersionsMap, final URI nextSchemaOntologyUri)
{
final Set<Value> allVersions = model.filter(nextSchemaOntologyUri, OWL.VERSIONIRI, null).objects();
Set<URI> nextAllVersions = new LinkedHashSet<>();
final Set<URI> putIfAbsent = allVersionsMap.putIfAbsent(nextSchemaOntologyUri, nextAllVersions);
if(putIfAbsent != null)
{
nextAllVersions = putIfAbsent;
}
// If they specified a current version add it to the set
if(currentVersionsMap.containsKey(nextSchemaOntologyUri))
{
nextAllVersions.add(currentVersionsMap.get(nextSchemaOntologyUri));
}
for(final Value nextVersionURI : allVersions)
{
if(nextVersionURI instanceof URI)
{
nextAllVersions.add((URI)nextVersionURI);
}
else
{
OntologyUtils.log.error("Version was not a URI: {} {}", nextSchemaOntologyUri, nextVersionURI);
}
}
if(nextAllVersions.isEmpty())
{
OntologyUtils.log.debug("Could not find any version information for schema ontology: {}",
nextSchemaOntologyUri);
}
}
/**
* @param model
* @param currentVersionsMap
* @param allVersionsMap
* @param importsMap
* @param importOrder
* @param nextOntologyUri
*/
private static void mapAndSortImports(final Model model, final ConcurrentMap<URI, URI> currentVersionsMap,
final ConcurrentMap<URI, Set<URI>> allVersionsMap, final ConcurrentMap<URI, Set<URI>> importsMap,
final List<URI> importOrder, final URI nextOntologyUri)
{
final Set<Value> imports = model.filter(nextOntologyUri, OWL.IMPORTS, null).objects();
Set<URI> nextImportsSet = new LinkedHashSet<>();
final Set<URI> putIfAbsent = importsMap.putIfAbsent(nextOntologyUri, nextImportsSet);
if(putIfAbsent != null)
{
nextImportsSet = putIfAbsent;
}
int maxIndex = 0;
if(imports.isEmpty())
{
if(!nextImportsSet.isEmpty())
{
OntologyUtils.log.error("Found inconsistent imports set: {} {}", nextOntologyUri, nextImportsSet);
}
}
else
{
for(Value nextImport : imports)
{
if(nextImport instanceof URI)
{
if(nextImportsSet.contains(nextImport))
{
// avoid duplicates
continue;
}
if(currentVersionsMap.containsKey(nextImport))
{
// Replace next import with the version
nextImport = currentVersionsMap.get(nextImport);
// Map down to the current version to ensure that we can load multiple
// versions simultaneously (if possible with the rest of the system)
nextImportsSet.add((URI)nextImport);
}
else if(currentVersionsMap.containsValue(nextImport))
{
nextImportsSet.add((URI)nextImport);
}
else
{
boolean foundAllVersion = false;
// Attempt to verify if the version exists
for(final Entry<URI, Set<URI>> nextEntry : allVersionsMap.entrySet())
{
final URI nextAllVersions = nextEntry.getKey();
if(nextAllVersions.equals(nextImport))
{
if(nextEntry.getValue().isEmpty())
{
nextImportsSet.add((URI)nextImport);
}
else
{
// Randomly choose one, as the ontology does not have a current
// version, but it does have some version information
nextImport = nextEntry.getValue().iterator().next();
nextImportsSet.add((URI)nextImport);
}
foundAllVersion = true;
break;
}
else if(nextEntry.getValue().contains(nextImport))
{
nextImportsSet.add((URI)nextImport);
foundAllVersion = true;
break;
}
}
if(!foundAllVersion)
{
OntologyUtils.log.warn("Could not find import: {} imports {}", nextOntologyUri, nextImport);
}
else
{
// This should not be necessary given the sequence of calls above
// nextImportsSet.add((URI)nextImport);
}
}
final int nextIndex = importOrder.indexOf(nextImport);
if(nextIndex >= maxIndex)
{
maxIndex = nextIndex + 1;
}
}
}
}
OntologyUtils.log.debug("adding import for {} at {}", nextOntologyUri, maxIndex);
// TODO: FIXME: This will not allow for multiple versions of a single schema ontology at the
// same time if they have any shared import versions
importOrder.add(maxIndex, nextOntologyUri);
}
/**
* @param model
* @param currentVersionsMap
* @param nextSchemaOntologyUri
* @throws SchemaManifestException
*/
public static URI mapCurrentVersion(final Model model, final ConcurrentMap<URI, URI> currentVersionsMap,
final URI nextSchemaOntologyUri) throws SchemaManifestException
{
try
{
final URI nextCurrentVersionURI =
model.filter(nextSchemaOntologyUri, PODD.OMV_CURRENT_VERSION, null).objectURI();
if(nextCurrentVersionURI == null)
{
// OntologyUtils.log
// .error("Did not find a current version for schema ontology: {}",
// nextSchemaOntologyUri);
// throw new SchemaManifestException(IRI.create(nextSchemaOntologyUri),
// "Did not find a current version for schema ontology: " +
// nextSchemaOntologyUri.stringValue());
}
else
{
final URI putIfAbsent = currentVersionsMap.putIfAbsent(nextSchemaOntologyUri, nextCurrentVersionURI);
if(putIfAbsent != null)
{
OntologyUtils.log.error("Found multiple version URIs for ontology: {} old={} new={}",
nextSchemaOntologyUri, putIfAbsent, nextCurrentVersionURI);
throw new SchemaManifestException(IRI.create(nextSchemaOntologyUri),
"Found multiple version IRIs for ontology");
}
}
return nextCurrentVersionURI;
}
catch(final ModelException e)
{
OntologyUtils.log.error("Could not find a single unique current version for schema ontology: {}",
nextSchemaOntologyUri);
throw new SchemaManifestException(IRI.create(nextSchemaOntologyUri),
"Could not find a single unique current version IRI for schema ontology", e);
}
}
/**
* Extracts the {@link InferredOWLOntologyID} instances that are represented as RDF
* {@link Statement}s in the given {@link Model}.
*
* @param input
* The input model containing RDF statements.
* @return A Collection of {@link InferredOWLOntologyID} instances derived from the statements
* in the model.
*/
public static List<InferredOWLOntologyID> modelToOntologyIDs(final Model input)
{
return OntologyUtils.modelToOntologyIDs(input, false, true);
}
/**
* Extracts the {@link InferredOWLOntologyID} instances that are represented as RDF
* {@link Statement}s in the given {@link Model}.
*
* @param input
* The input model containing RDF statements.
* @param allowVersionless
* True if the algorithm should recognise versionless ontologies, and false to ignore
* them.
* @return A Collection of {@link InferredOWLOntologyID} instances derived from the statements
* in the model.
*/
public static List<InferredOWLOntologyID> modelToOntologyIDs(final Model input, final boolean allowVersionless,
final boolean includeInferred)
{
final List<InferredOWLOntologyID> results = new ArrayList<InferredOWLOntologyID>();
final Model typedOntologies = input.filter(null, RDF.TYPE, OWL.ONTOLOGY);
for(final Statement nextTypeStatement : typedOntologies)
{
if(nextTypeStatement.getSubject() instanceof URI)
{
final Model versions = input.filter(nextTypeStatement.getSubject(), OWL.VERSIONIRI, null);
if(versions.isEmpty())
{
if(allowVersionless)
{
results.add(new InferredOWLOntologyID(IRI.create((URI)nextTypeStatement.getSubject()), null,
null));
}
}
else
{
for(final Statement nextVersion : versions)
{
if(nextVersion.getObject() instanceof URI)
{
final Model inferredOntologies =
input.filter((URI)nextVersion.getObject(), PODD.PODD_BASE_INFERRED_VERSION, null);
if(!includeInferred)
{
results.add(new InferredOWLOntologyID((URI)nextTypeStatement.getSubject(),
(URI)nextVersion.getObject(), null));
}
else
{
if(inferredOntologies.isEmpty())
{
// If there were no poddBase#inferredVersion statements, backup
// trying to infer the versions using owl:imports
final Model importsOntologies =
input.filter(null, OWL.IMPORTS, nextVersion.getObject());
if(importsOntologies.isEmpty())
{
results.add(new InferredOWLOntologyID((URI)nextTypeStatement.getSubject(),
(URI)nextVersion.getObject(), null));
}
else
{
for(final Statement nextImportOntology : importsOntologies)
{
if(nextImportOntology.getSubject() instanceof URI)
{
results.add(new InferredOWLOntologyID((URI)nextTypeStatement
.getSubject(), (URI)nextVersion.getObject(),
(URI)nextImportOntology.getSubject()));
}
else
{
OntologyUtils.log.error("Found a non-URI import statement: {}",
nextImportOntology);
}
}
}
}
else
{
for(final Statement nextInferredOntology : inferredOntologies)
{
if(nextInferredOntology.getObject() instanceof URI)
{
results.add(new InferredOWLOntologyID((URI)nextTypeStatement.getSubject(),
(URI)nextVersion.getObject(), (URI)nextInferredOntology.getObject()));
}
}
}
}
}
}
}
}
}
return results;
}
/**
* Serialises the given collection of {@link InferredOWLOntologyID} objects to RDF, adding the
* {@link Statement}s to the given {@link RDFHandler}.
* <p>
* This method wraps the serialisation from {@link InferredOWLOntologyID#toRDF()}.
*
* @param input
* The collection of {@link InferredOWLOntologyID} objects to render to RDF.
* @param handler
* The handler for handling the RDF statements.
* @throws RDFHandlerException
* If there is an error while handling the statements.
*/
public static void ontologyIDsToHandler(final Collection<InferredOWLOntologyID> input, final RDFHandler handler)
throws RDFHandlerException
{
for(final InferredOWLOntologyID nextOntology : input)
{
for(final Statement nextStatement : nextOntology.toRDF())
{
handler.handleStatement(nextStatement);
}
}
}
public static Model ontologyIDsToModel(final Collection<InferredOWLOntologyID> input, final Model result)
{
return OntologyUtils.ontologyIDsToModel(input, result, true);
}
/**
* Serialises the given collection of {@link InferredOWLOntologyID} objects to RDF, adding the
* {@link Statement}s to the given {@link Model}, or creating a new Model if the given model is
* null.
* <p>
* This method wraps the serialisation from {@link InferredOWLOntologyID#toRDF()}.
*
* @param input
* The collection of {@link InferredOWLOntologyID} objects to render to RDF.
* @param result
* The Model to contain the resulting statements, or null to have one created
* internally
* @param includeInferredOntologyStatements
* @return A model containing the RDF statements about the given ontologies.
* @throws RDFHandlerException
* If there is an error while handling the statements.
*/
public static Model ontologyIDsToModel(final Collection<InferredOWLOntologyID> input, final Model result,
final boolean includeInferredOntologyStatements)
{
Model results = result;
if(results == null)
{
results = new LinkedHashModel();
}
for(final InferredOWLOntologyID nextOntology : input)
{
OntologyUtils.ontologyIDToRDF(nextOntology, results, includeInferredOntologyStatements);
}
return results;
}
public static Model ontologyIDToRDF(final OWLOntologyID ontology, final Model result,
final boolean includeInferredOntologyStatements)
{
final ValueFactory vf = ValueFactoryImpl.getInstance();
if(ontology.getOntologyIRI() != null)
{
result.add(vf.createStatement(ontology.getOntologyIRI().toOpenRDFURI(), RDF.TYPE, OWL.ONTOLOGY));
if(ontology.getVersionIRI() != null)
{
result.add(vf.createStatement(ontology.getVersionIRI().toOpenRDFURI(), RDF.TYPE, OWL.ONTOLOGY));
result.add(vf.createStatement(ontology.getOntologyIRI().toOpenRDFURI(), OWL.VERSIONIRI, ontology
.getVersionIRI().toOpenRDFURI()));
if(includeInferredOntologyStatements && ontology instanceof InferredOWLOntologyID)
{
final InferredOWLOntologyID inferredOntology = (InferredOWLOntologyID)ontology;
if(inferredOntology.getInferredOntologyIRI() != null)
{
result.add(vf.createStatement(inferredOntology.getInferredOntologyIRI().toOpenRDFURI(),
RDF.TYPE, OWL.ONTOLOGY));
result.add(vf.createStatement(inferredOntology.getVersionIRI().toOpenRDFURI(),
PODD.PODD_BASE_INFERRED_VERSION, inferredOntology.getInferredOntologyIRI()
.toOpenRDFURI()));
}
}
}
}
return result;
}
/**
* Orders the schema ontology imports into list that can be uploaded in order to give a good
* chance that dependencies will be uploaded first.
*
* @param model
* @param schemaOntologyUris
* @param schemaVersionUris
* @return An ordered list of {@link URI}s that determine a useful order for uploading schema
* ontologies to ensure that dependencies are available internally when needed.
* @throws SchemaManifestException
*/
public static List<URI> orderImports(final Model model, final Set<URI> schemaOntologyUris,
final Set<URI> schemaVersionUris, final ConcurrentMap<URI, Set<URI>> importsMap,
final boolean allowOntologyUriImports) throws SchemaManifestException
{
final List<URI> importOrder = new ArrayList<>(schemaOntologyUris.size());
final ConcurrentMap<URI, URI> currentVersionsMap = new ConcurrentHashMap<>(schemaOntologyUris.size());
final ConcurrentMap<URI, Set<URI>> allVersionsMap = new ConcurrentHashMap<>(schemaOntologyUris.size());
// Find current version for each schema ontology
for(final URI nextSchemaOntologyUri : schemaOntologyUris)
{
OntologyUtils.mapCurrentVersion(model, currentVersionsMap, nextSchemaOntologyUri);
}
// Find all versions for each schema ontology
for(final URI nextSchemaOntologyUri : schemaOntologyUris)
{
OntologyUtils.mapAllVersions(model, currentVersionsMap, allVersionsMap, nextSchemaOntologyUri);
}
// Map the actual schema ontologies to the correct order, based on
// current versions and all versions with the imports taken into account
for(final URI nextVersionUri : schemaVersionUris)
{
OntologyUtils.mapAndSortImports(model, currentVersionsMap, allVersionsMap, importsMap, importOrder,
nextVersionUri);
}
if(allowOntologyUriImports)
{
for(final URI nextOntologyUri : schemaOntologyUris)
{
OntologyUtils.mapAndSortImports(model, currentVersionsMap, allVersionsMap, importsMap, importOrder,
nextOntologyUri);
}
}
OntologyUtils.postSort(importOrder, importsMap);
OntologyUtils.log.debug("importOrder: {}", importOrder);
return importOrder;
}
private static void postSort(final List<URI> importOrder, final ConcurrentMap<URI, Set<URI>> importsMap)
{
Collections.sort(importOrder, new Comparator<URI>()
{
@Override
public int compare(final URI o1, final URI o2)
{
if(o1.equals(o2))
{
return 0;
}
if(importsMap.containsKey(o1))
{
final Set<URI> set = importsMap.get(o1);
if(set.contains(o2))
{
return 1;
}
else
{
final Set<URI> otherSet = importsMap.get(o2);
if(otherSet.contains(o1))
{
return -1;
}
else
{
return 1;
}
}
}
else if(importsMap.containsKey(o2))
{
final Set<URI> set = importsMap.get(o2);
if(set.contains(o1))
{
return -1;
}
else
{
return 1;
}
}
else
{
// Default to lexical mapping, as there is no direct semantic link between them
// at this point
// FIXME: This should not be part of the comparison as the imports map should always contain one of the URIs
return o1.stringValue().compareTo(o2.stringValue());
}
}
});
}
/**
* Recursively follow the imports for the given URI, based on those identified in the
* importsMap.
*
* @param ontologyImports
* @param importsMap
* @param nextURI
*/
public static void recursiveFollowImports(final Set<URI> ontologyImports,
final ConcurrentMap<URI, Set<URI>> importsMap, final URI nextURI)
{
if(importsMap.containsKey(nextURI))
{
final Set<URI> nextSet = importsMap.get(nextURI);
for(final URI nextSetUri : nextSet)
{
if(!ontologyImports.contains(nextSetUri))
{
ontologyImports.add(nextSetUri);
OntologyUtils.recursiveFollowImports(ontologyImports, importsMap, nextSetUri);
}
}
}
}
/**
* Retrieves imports specified using {@link OWL#IMPORTS}, based on the given version IRIs. Also
* checks to verify that there is an {@link OWL#VERSIONIRI} statement for each of the version
* IRIs. <br>
* This works with the format used by both the schema manifests and the schema management graph.
*
* @param model
* @param schemaVersionUris
* @return
* @throws SchemaManifestException
*/
public static List<OWLOntologyID> schemaManifestImports(final Model model,
final Set<? extends OWLOntologyID> dependentSchemaOntologies) throws SchemaManifestException
{
Objects.requireNonNull(dependentSchemaOntologies);
Objects.requireNonNull(model);
final Set<OWLOntologyID> results = new LinkedHashSet<OWLOntologyID>();
final Set<URI> schemaOntologyUris = new LinkedHashSet<>();
final Set<URI> schemaVersionUris = new LinkedHashSet<>();
final ConcurrentMap<URI, Set<URI>> importsMap = new ConcurrentHashMap<>(schemaOntologyUris.size());
OntologyUtils.extractOntologyAndVersions(model, schemaOntologyUris, schemaVersionUris);
final List<URI> orderImports =
OntologyUtils.orderImports(model, schemaOntologyUris, schemaVersionUris, importsMap, false);
final Set<URI> artifactImports = new LinkedHashSet<>();
for(URI nextOrderedImport : orderImports)
{
for(final OWLOntologyID nextDependentSchemaOntology : dependentSchemaOntologies)
{
if(nextDependentSchemaOntology.getOntologyIRI().toOpenRDFURI().equals(nextOrderedImport)
|| (nextDependentSchemaOntology.getVersionIRI() != null && nextDependentSchemaOntology
.getVersionIRI().toOpenRDFURI().equals(nextOrderedImport)))
{
artifactImports.add(nextDependentSchemaOntology.getVersionIRI().toOpenRDFURI());
// Not tolerant for artifacts... Imports must be directed to version IRIs
// recursiveFollowImports(artifactImports, importsMap,
// artifactID.getOntologyIRI().toOpenRDFURI());
OntologyUtils.recursiveFollowImports(artifactImports, importsMap, nextDependentSchemaOntology
.getVersionIRI().toOpenRDFURI());
}
}
}
OntologyUtils.postSort(orderImports, importsMap);
final List<InferredOWLOntologyID> ontologyIDs = OntologyUtils.modelToOntologyIDs(model, true, false);
final Set<OWLOntologyID> finalOrderImports =
OntologyUtils.finalOrderImports(results, ontologyIDs, orderImports, artifactImports, importsMap);
return new ArrayList<>(finalOrderImports);
}
/**
* Extracts the {@link InferredOWLOntologyID} instances that are represented as RDF
* {@link Statement}s in the given {@link String}.
*
* @param string
* The input string containing RDF statements.
* @param format
* The format of RDF statements in the string
* @return A Collection of {@link InferredOWLOntologyID} instances derived from the statements
* in the string.
* @throws OpenRDFException
* @throws IOException
*/
public static Collection<InferredOWLOntologyID> stringToOntologyID(final String string, final RDFFormat format)
throws OpenRDFException, IOException
{
final Model model = Rio.parse(new StringReader(string), "", format);
return OntologyUtils.modelToOntologyIDs(model);
}
/**
* This method performs a consistency check between the ontology imports specified in the
* schema-manifest with the actual imports specified within the ontology.
*
* If the two sets of imports are not equal, a {@link SchemaManifestException} is thrown.
*
* @param manifestModel
* Contents of the schema-manifest
* @param schemaVersionUris
* Ontology Version IRIs to be loaded
* @throws IOException
* @throws RDFParseException
* @throws UnsupportedRDFormatException
* @throws SchemaManifestException
* If the imports from the two locations are not consistent
*/
public static void validateSchemaManifestImports(final Model manifestModel, final Set<URI> schemaOntologyUris,
final Set<URI> schemaVersionUris) throws IOException, RDFParseException, UnsupportedRDFormatException,
SchemaManifestException
{
for(final URI nextOntologyUri : schemaOntologyUris)
{
if(manifestModel.contains(nextOntologyUri, OWL.IMPORTS, null))
{
OntologyUtils.log.error("Schema ontology in manifest has owl:imports coming directly from it: {}",
nextOntologyUri);
throw new SchemaManifestException(IRI.create(nextOntologyUri),
"Schema ontology in manifest has owl:imports coming directly from it");
}
final Model currentVersion = manifestModel.filter(nextOntologyUri, PODD.OMV_CURRENT_VERSION, null);
if(currentVersion.isEmpty())
{
OntologyUtils.log.error("Missing OMV current version for schema ontology: {}", nextOntologyUri);
throw new SchemaManifestException(IRI.create(nextOntologyUri),
"Missing OMV current version for schema ontology");
}
if(currentVersion.size() > 1)
{
OntologyUtils.log.error("Multiple OMV current versions for schema ontology: {}", nextOntologyUri);
throw new SchemaManifestException(IRI.create(nextOntologyUri),
"Multiple OMV current versions for schema ontology");
}
}
for(final URI nextVersionUri : schemaVersionUris)
{
final Set<Value> importsInManifest = manifestModel.filter(nextVersionUri, OWL.IMPORTS, null).objects();
final String classpathLocation =
manifestModel.filter(nextVersionUri, PODD.PODD_SCHEMA_CLASSPATH, null).objectLiteral()
.stringValue();
final RDFFormat format = Rio.getParserFormatForFileName(classpathLocation, RDFFormat.RDFXML);
try (final InputStream input = OntologyUtils.class.getResourceAsStream(classpathLocation);)
{
if(input == null)
{
throw new SchemaManifestException(IRI.create(nextVersionUri),
"Could not find schema at designated classpath location: " + nextVersionUri.stringValue());
}
final Model model = Rio.parse(input, "", format);
final Set<Value> importsInOwlFile = model.filter(null, OWL.IMPORTS, null).objects();
OntologyUtils.log.debug("Comparing: \n Manifest: {} \n Owl: {}", importsInManifest,
importsInOwlFile);
if(!importsInManifest.equals(importsInOwlFile))
{
throw new SchemaManifestException(IRI.create(nextVersionUri),
"Schema manifest imports not consistent with actual imports");
}
}
}
}
private OntologyUtils()
{
}
}
|
package com.atum.tunetube.youtube;
import org.json.JSONArray;
import org.json.JSONException;
import java.util.LinkedList;
import java.util.List;
public class YoutubeAutocomplete {
/**
* The purpose of this code is to return a List of strings representing the suggested autocomplete options for the query specified.
* @param query
* @param javascript
* @return
*/
public static List<String> extractSuggestions(String query, String javascript){
String json = extractJson(query,javascript);
List<String> output = new LinkedList<>();
if(json == null)
return output;
try {
JSONArray array = new JSONArray(json);
for(int i = 0; i < array.length(); i++){
String term = getSearchTerm(array.getJSONArray(i));
//System.out.println("suggestion: "+term);
if(term != null && !term.isEmpty())
output.add(term);
}
} catch (JSONException e) {
e.printStackTrace();
}
return output;
}
/**
* The purpose of this function is to extract the json object from the javascript output of the youtube autocomplete API.
* @param query
* @param javascript
* @return
*/
private static String extractJson(String query, String javascript) {
int index = javascript.indexOf(query)+query.length()+2;
//index returned -1
if(index == 1+query.length())
return null;
String json = javascript.substring(index);
int endIdx = json.lastIndexOf("]],")+2;
//index returned -1
if(endIdx == 1)
return null;
json = json.substring(0,endIdx);
return json;
}
private static String getSearchTerm(JSONArray jsonArray) throws JSONException {
return jsonArray.getString(0);
}
}
|
package com.bkromhout.minerva.adapters;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Build;
import android.support.annotation.ColorInt;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageButton;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.bkromhout.minerva.R;
import com.bkromhout.minerva.TaggingActivity;
import com.bkromhout.minerva.events.TagCardClickEvent;
import com.bkromhout.minerva.realm.RTag;
import com.bkromhout.minerva.ui.RippleForegroundListener;
import com.bkromhout.minerva.ui.TriStateCheckBox;
import io.realm.RealmBasedRecyclerViewAdapter;
import io.realm.RealmResults;
import org.greenrobot.eventbus.EventBus;
import java.util.List;
/**
* Realm RecyclerView Adapter for tag cards.
*/
public class TagCardAdapter extends RealmBasedRecyclerViewAdapter<RTag, TagCardAdapter.TagCardVH> {
/**
* Help our cards ripple.
*/
private static RippleForegroundListener rippleFgListener = new RippleForegroundListener(R.id.card);
/**
* List of items which are checked. The strings in this list should correspond to names of {@link RTag}s.
*/
private List<String> checkedItems;
/**
* List of items which are partially checked. The strings in this list should correspond to names of {@link RTag}s.
*/
private List<String> partiallyCheckedItems;
/**
* Whether or not we're currently in action mode.
*/
private boolean isInActionMode = false;
/**
* Create a new {@link TagCardAdapter}.
* @param context Context.
* @param realmResults Results of a Realm query to display.
*/
public TagCardAdapter(Context context, RealmResults<RTag> realmResults) {
super(context, realmResults, true, true, null);
this.checkedItems = TaggingActivity.TaggingHelper.get().newCheckedItems;
this.partiallyCheckedItems = TaggingActivity.TaggingHelper.get().newPartiallyCheckedItems;
}
@Override
public TagCardVH onCreateViewHolder(ViewGroup parent, int viewType) {
return new TagCardVH(inflater.inflate(R.layout.tag_card, parent, false));
}
@Override
public void onBindViewHolder(TagCardVH viewHolder, int position) {
RTag tag = realmResults.get(position);
// Set whether or not the color and action buttons are shown.
viewHolder.textColor.setVisibility(isInActionMode ? View.GONE : View.VISIBLE);
viewHolder.bgColor.setVisibility(isInActionMode ? View.GONE : View.VISIBLE);
viewHolder.rename.setVisibility(isInActionMode ? View.VISIBLE : View.GONE);
viewHolder.delete.setVisibility(isInActionMode ? View.VISIBLE : View.GONE);
// Set card click listener.
viewHolder.card.setOnClickListener(v -> {
// Do nothing if in action mode.
if (isInActionMode) return;
CheckBox cbTag = ButterKnife.findById(v, R.id.tag_name);
String tagName = cbTag.getText().toString();
// Try to remove from partially checked items; if that doesn't happen, try to remove from checked items;
// if that also doesn't happen, then add to checked items.
if (!partiallyCheckedItems.remove(tagName) && !checkedItems.remove(tagName)) checkedItems.add(tagName);
// Toggle the check mark state.
cbTag.toggle();
});
// Set name and checked state.
viewHolder.tag.setText(tag.name);
if (partiallyCheckedItems.contains(tag.name)) viewHolder.tag.setPartiallyChecked(true);
else viewHolder.tag.setChecked(checkedItems.contains(tag.name));
// Set the color buttons colors.
setColorButtonColor(viewHolder.textColor, tag.textColor);
setColorButtonColor(viewHolder.bgColor, tag.bgColor);
// Set button click handlers.
viewHolder.rename.setOnClickListener(v -> EventBus.getDefault().post(
new TagCardClickEvent(TagCardClickEvent.Type.RENAME, tag.name)));
viewHolder.delete.setOnClickListener(v -> EventBus.getDefault().post(
new TagCardClickEvent(TagCardClickEvent.Type.DELETE, tag.name)));
viewHolder.textColor.setOnClickListener(v -> EventBus.getDefault().post(
new TagCardClickEvent(TagCardClickEvent.Type.TEXT_COLOR, tag.name)));
viewHolder.bgColor.setOnClickListener(v -> EventBus.getDefault().post(
new TagCardClickEvent(TagCardClickEvent.Type.BG_COLOR, tag.name)));
}
/**
* Take's {@code colorButton}'s layer drawable (which it is assumed it is), finds the {@code circle} layer, and
* tints that drawable the given {@code color}.
* @param colorButton {@code ImageButton} with a {@link LayerDrawable} as its drawable.
* @param color Color to tint the {@code circle} layer of the {@code colorButton}'s {@link LayerDrawable}.
*/
private void setColorButtonColor(ImageButton colorButton, @ColorInt int color) {
LayerDrawable layerDrawable = (LayerDrawable) colorButton.getDrawable();
Drawable colorCircle = layerDrawable.findDrawableByLayerId(R.id.circle);
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) {
// API 21 is really quite stubborn when it comes to colors, annoyingly.
colorCircle = DrawableCompat.wrap(colorCircle);
DrawableCompat.setTint(colorCircle, color);
layerDrawable.setDrawableByLayerId(R.id.circle, colorCircle);
} else DrawableCompat.setTint(colorCircle, color);
}
/**
* Set whether or not we're currently in action mode.
* @param isInActionMode True or false :)
*/
public void setInActionMode(boolean isInActionMode) {
if (this.isInActionMode == isInActionMode) return;
this.isInActionMode = isInActionMode;
notifyDataSetChanged();
}
/**
* TagCardVH class.
*/
public class TagCardVH extends RecyclerView.ViewHolder {
@BindView(R.id.card)
CardView card;
@BindView(R.id.tag_name)
TriStateCheckBox tag;
@BindView(R.id.tag_text_color)
ImageButton textColor;
@BindView(R.id.tag_bg_color)
ImageButton bgColor;
@BindView(R.id.rename_tag)
ImageButton rename;
@BindView(R.id.delete_tag)
ImageButton delete;
public TagCardVH(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
// Make the card ripple when touched.
tag.setOnTouchListener(rippleFgListener);
}
}
}
|
package com.example.android.sunshine.app;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
private final String LOG_TAG = MainActivity.class.getSimpleName();
@Override
protected void onPause() {
Log.v(LOG_TAG, "OnPause");
super.onPause();
// Another activity is taking focus (this activity is about to be "paused").
}
@Override
protected void onStop() {
Log.v(LOG_TAG, "onStop");
super.onStop();
// The activity is no longer visible (it is now "stopped")
}
@Override
protected void onDestroy() {
Log.v(LOG_TAG, "onDestroy");
super.onDestroy();
// The activity is about to be destroyed.
}
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.v(LOG_TAG, "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new ForecastFragment())
.commit();
}
}
@Override
protected void onStart() {
super.onStart();
Log.v(LOG_TAG, "OnStart");
// This activity is about to become visible.
}
@Override
protected void onResume() {
super.onResume();
Log.v(LOG_TAG, "onResume");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@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 == R.id.action_settings) {
startActivity(new Intent(this, SettingsActivity.class));
return true;
}
if (id == R.id.action_map) {
openPreferredLocationInMap();
return true;
}
return super.onOptionsItemSelected(item);
}
private void openPreferredLocationInMap() {
SharedPreferences sharedPrefs =
PreferenceManager.getDefaultSharedPreferences(this);
String location = sharedPrefs.getString(
getString(R.string.pref_location_key),
getString(R.string.pref_location_default));
// Using the URI scheme for showing a location found on a map. This super-handy
// intent can is detailed in the "Common Intents" page of Android developer site:
// http://developer.android.com/guide/components/intent-common.html#Maps
Uri geoLocation = Uri.parse("geo:0,0?").buildUpon()
.appendQueryParameter("q", location)
.build();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(geoLocation);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Log.d(LOG_TAG, "Couldn't call " + location + ", no location found.");
}
}
}
|
package org.xins.server;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.apache.log4j.LogManager;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.helpers.NullEnumeration;
import org.xins.common.MandatoryArgumentChecker;
import org.xins.common.collections.InvalidPropertyValueException;
import org.xins.common.collections.PropertiesPropertyReader;
import org.xins.common.collections.PropertyReader;
import org.xins.common.collections.PropertyReaderConverter;
import org.xins.common.collections.PropertyReaderUtils;
import org.xins.common.io.FileWatcher;
import org.xins.common.text.TextUtils;
import org.xins.logdoc.LogCentral;
import org.xins.logdoc.UnsupportedLocaleException;
/**
* Manager for the runtime configuration file. Owns the watcher for the config
* file and is responsible for triggering actions when the file has actually
* changed.
*
* @version $Revision$ $Date$
* @author Mees Witteman (<a href="mailto:mees.witteman@nl.wanadoo.com">mees.witteman@nl.wanadoo.com</a>)
*/
final class ConfigManager extends Object {
// Class fields
/**
* The object to synchronize on when reading and initializing from the
* runtime configuration file.
*/
static final Object RUNTIME_PROPERTIES_LOCK = new Object();
// Class functions
/**
* Initializes the logging subsystem with fallback default settings.
*/
static void configureLoggerFallback() {
Properties settings = new Properties();
// Send all log messages to the logger named 'console'
settings.setProperty(
"log4j.rootLogger",
"ALL, console");
// Define an appender for the console
settings.setProperty(
"log4j.appender.console",
"org.apache.log4j.ConsoleAppender");
// Use a pattern-layout for the appender
settings.setProperty(
"log4j.appender.console.layout",
"org.apache.log4j.PatternLayout");
// Define the pattern for the appender
settings.setProperty(
"log4j.appender.console.layout.ConversionPattern",
"%16x %6c{1} %-6p %m%n");
// Perform Log4J configuration
PropertyConfigurator.configure(settings);
}
// Constructors
ConfigManager(Engine engine, ServletConfig config)
throws IllegalArgumentException {
// Check preconditions
MandatoryArgumentChecker.check("engine", engine, "config", config);
// Initialize fields
_engine = engine;
_config = config;
_configFileListener = new ConfigurationFileListener();
}
// Fields
/**
* The <code>Engine</code> that owns this <code>ConfigManager</code>. Never
* <code>null</code>.
*/
private final Engine _engine;
/**
* Servlet configuration. Never <code>null</code>.
*/
private final ServletConfig _config;
/**
* The listener that is notified when the configuration file changes. Only
* one instance is created ever.
*/
private final ConfigurationFileListener _configFileListener;
/**
* The name of the runtime configuration file. Initially <code>null</code>.
*/
private String _configFile;
/**
* Watcher for the runtime configuration file. Initially <code>null</code>.
*/
private FileWatcher _configFileWatcher;
// Methods
/**
* Determines the name of the runtime configuration file. The system
* properties will be queried first. If they do not provide it, then the
* servlet initialization properties are tried. Once determined, the name
* will be stored internally.
*/
void determineConfigFile() {
// TODO: Check state
// TODO: What if the name cannot be determined?
final String prop = APIServlet.CONFIG_FILE_SYSTEM_PROPERTY;
String configFile = null;
try {
configFile = System.getProperty(prop);
} catch (SecurityException exception) {
Log.log_3230(exception, prop);
}
// If the name of the configuration file is not set in a system property
// (typically passed on the command-line) try to get it from the servlet
// initialization properties (typically set in a web.xml file)
if (configFile == null || configFile.trim().length() < 1) {
Log.log_3231(prop);
configFile = _config.getInitParameter(prop);
// If it is still not set, then assume null
if (configFile != null && configFile.trim().length() < 1) {
configFile = null;
}
}
_configFile = configFile;
}
/**
* Unifies the file separator character on the _configFile property and then
* reads the runtime properties file, initializes the logging subsystem
* with the read properties and then stores those properties on the engine.
* If the _configFile is empty, then an empty set of properties is set on
* the engine.
*/
void readRuntimeProperties() {
// TODO: Check state
PropertyReader pr;
// If the value is not set only localhost can access the API.
// NOTE: Don't trim the configuration file name, since it may start
// with a space or other whitespace character.
if (_configFile == null || _configFile.length() < 1) {
Log.log_3205(APIServlet.CONFIG_FILE_SYSTEM_PROPERTY);
pr = PropertyReaderUtils.EMPTY_PROPERTY_READER;
} else {
// Unify the file separator character
_configFile = _configFile.replace('/', File.separatorChar);
_configFile = _configFile.replace('\\', File.separatorChar);
// TODO: Allow a slash in the file name?
// Initialize the logging subsystem
Log.log_3300(_configFile);
synchronized (ConfigManager.RUNTIME_PROPERTIES_LOCK) {
Properties properties = new Properties();
try {
// Open file, load properties, close file
FileInputStream in = new FileInputStream(_configFile);
properties.load(in);
in.close();
// No such file
} catch (FileNotFoundException exception) {
Log.log_3301(exception, _configFile);
// Security issue
} catch (SecurityException exception) {
Log.log_3302(exception, _configFile);
// Other I/O error
} catch (IOException exception) {
Log.log_3303(exception, _configFile);
}
// Attempt to configure Log4J
configureLogger(properties);
// Convert to a PropertyReader
pr = new PropertiesPropertyReader(properties);
}
}
// Assign the runtime properties to the Engine
_engine.setRuntimeProperties(pr);
}
/**
* Determines the reload interval for the config file, initializes the API
* if the interval has changed and starts the config file watcher.
*/
void init() {
// TODO: Check the state
// Determine the reload interval
int interval = APIServlet.DEFAULT_CONFIG_RELOAD_INTERVAL;
if (_configFile != null) {
try {
interval = determineConfigReloadInterval();
// If the interval could not be parsed, then use the default
} catch (InvalidPropertyValueException exception) {
// ignore
}
}
// Initialize the API
_engine.initAPI();
// Start the configuration file watch interval, if the location of the
// file is set
if (_configFile != null) {
startConfigFileWatcher(interval);
}
}
void startConfigFileWatcher(int interval)
throws IllegalArgumentException {
// TODO: Describe preconditions
// Check preconditions
if (_configFile == null || _configFile.length() < 1) {
throw new IllegalStateException("Name of runtime configuration file not set.");
} else if (_configFileWatcher != null) {
throw new IllegalStateException("Runtime configuration file watcher exists.");
} else if (interval < 1) {
throw new IllegalArgumentException("interval (" + interval + ") < 1");
}
// Create and start a file watch thread
_configFileWatcher = new FileWatcher(_configFile,
interval,
_configFileListener);
_configFileWatcher.start();
}
/**
* If the config file watcher == <code>null</code>, then the config file
* listener will be re-initialized. If not the file watcher will be
* interrupted.
*/
void reloadPropertiesIfChanged() {
// TODO: Improve method description
if (_configFileWatcher == null) {
_configFileListener.reinit();
} else {
_configFileWatcher.interrupt();
}
}
void configureLogger(Properties properties)
throws IllegalArgumentException {
// Check preconditions
MandatoryArgumentChecker.check("properties", properties);
// Reset Log4J configuration
LogManager.getLoggerRepository().resetConfiguration();
// Reconfigure Log4J
PropertyConfigurator.configure(properties);
// Determine if Log4J is properly initialized
Enumeration appenders =
LogManager.getLoggerRepository().getRootLogger().getAllAppenders();
// If the properties did not include Log4J configuration settings, then
// fallback to default settings
if (appenders instanceof NullEnumeration) {
Log.log_3304(_configFile);
configureLoggerFallback();
// Otherwise log that custom Log4J configuration settings were applied
} else {
Log.log_3305();
}
}
/**
* Determines the interval for checking the runtime properties file for
* modifications.
*
* @return
* the interval to use, always >= 1.
*
* @throws InvalidPropertyValueException
* if the interval cannot be determined because it does not qualify as a
* positive 32-bit unsigned integer number.
*/
int determineConfigReloadInterval()
throws InvalidPropertyValueException {
// Check state
if (_configFile == null || _configFile.length() < 1) {
throw new IllegalStateException("Name of runtime configuration file not set.");
}
_engine.setState(EngineState.DETERMINE_INTERVAL);
// Get the runtime property
final String prop = APIServlet.CONFIG_RELOAD_INTERVAL_PROPERTY;
final String s = _engine.getRuntimeProperties().get(prop);
int interval = -1;
// If the property is set, parse it
if (s != null && s.length() >= 1) {
try {
interval = Integer.parseInt(s);
// Negative value
if (interval < 0) {
Log.log_3409(_configFile, prop, s);
_engine.setState(EngineState.DETERMINE_INTERVAL_FAILED);
throw new InvalidPropertyValueException(
prop, s, "Negative value.");
// Non-negative value
} else {
Log.log_3410(_configFile, prop, s);
}
// Not a valid number string
} catch (NumberFormatException nfe) {
Log.log_3409(_configFile, prop, s);
_engine.setState(EngineState.DETERMINE_INTERVAL_FAILED);
throw new InvalidPropertyValueException(
prop, s, "Not a 32-bit integer number.");
}
// Property not set, use the default
} else {
Log.log_3408(_configFile, prop);
interval = APIServlet.DEFAULT_CONFIG_RELOAD_INTERVAL;
}
return interval;
}
/**
* Determines the log locale.
*/
void determineLogLocale() {
String newLocale = _engine.getRuntimeProperties().get(
LogCentral.LOG_LOCALE_PROPERTY);
if (TextUtils.isEmpty(newLocale)) {
newLocale = _engine.getRuntimeProperties().get(APIServlet.LOG_LOCALE_PROPERTY);
}
// If the log locale is set, apply it
if (newLocale != null) {
String currentLocale = LogCentral.getLocale();
if (!currentLocale.equals(newLocale)) {
Log.log_3306(currentLocale, newLocale);
try {
LogCentral.setLocale(newLocale);
Log.log_3307(currentLocale, newLocale);
} catch (UnsupportedLocaleException exception) {
Log.log_3308(currentLocale, newLocale);
_engine.setState(EngineState.API_INITIALIZATION_FAILED);
return;
}
}
}
}
/**
* Stops the config file watcher thread.
*/
void destroy() {
// TODO: Change state of this object?
// stop the FileWatcher
if (_configFileWatcher != null) {
_configFileWatcher.end();
}
_configFileWatcher = null;
}
// Inner classes
/**
* Listener that reloads the configuration file if it changes.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:ernst.dehaan@nl.wanadoo.com">ernst.dehaan@nl.wanadoo.com</a>)
*
* @since XINS 1.0.0
*/
private final class ConfigurationFileListener
extends Object
implements FileWatcher.Listener {
// Constructors
/**
* Constructs a new <code>ConfigurationFileListener</code> object.
*/
private ConfigurationFileListener() {
// empty
}
// Fields
// Methods
/**
* Re-initializes the framework. The run-time properties are re-read,
* the configuration file reload interval is determined, the API is
* re-initialized and then the new interval is applied to the watch
* thread for the configuration file.
*/
private void reinit() {
Log.log_3407(_configFile);
synchronized (RUNTIME_PROPERTIES_LOCK) {
// Apply the new runtime settings to the logging subsystem
readRuntimeProperties();
// Determine the interval
int newInterval;
try {
newInterval = determineConfigReloadInterval();
} catch (InvalidPropertyValueException exception) {
// Logging is already done in determineConfigReloadInterval()
return;
}
// Re-initialize the API
_engine.initAPI();
updateFileWatcher(newInterval);
}
}
private void updateFileWatcher(int newInterval)
throws IllegalStateException {
// Check state
if (_configFileWatcher == null) {
throw new IllegalStateException("There is no configuration file watcher.");
}
// Update the file watch interval
int oldInterval = _configFileWatcher.getInterval();
if (oldInterval != newInterval) {
if (newInterval == 0 && _configFileWatcher != null) {
_configFileWatcher.end();
_configFileWatcher = null;
} else if (newInterval > 0 && _configFileWatcher == null) {
_configFileWatcher = new FileWatcher(_configFile,
newInterval,
_configFileListener);
_configFileWatcher.start();
} else {
_configFileWatcher.setInterval(newInterval);
Log.log_3403(_configFile, oldInterval, newInterval);
}
}
}
/**
* Callback method called when the configuration file is found while it
* was previously not found.
*
* <p>This will trigger re-initialization.
*/
public void fileFound() {
reinit();
}
/**
* Callback method called when the configuration file is (still) not
* found.
*
* <p>The implementation of this method does not perform any actions.
*/
public void fileNotFound() {
Log.log_3400(_configFile);
}
/**
* Callback method called when the configuration file is (still) not
* modified.
*
* <p>The implementation of this method does not perform any actions.
*/
public void fileNotModified() {
Log.log_3402(_configFile);
}
/**
* Callback method called when the configuration file could not be
* examined due to a <code>SecurityException</code>.
*
* <p>The implementation of this method does not perform any actions.
*
* @param exception
* the caught security exception, should not be <code>null</code>
* (although this is not checked).
*/
public void securityException(SecurityException exception) {
Log.log_3401(exception, _configFile);
}
/**
* Callback method called when the configuration file is modified since
* the last time it was checked.
*
* <p>This will trigger re-initialization.
*/
public void fileModified() {
reinit();
}
}
}
|
// Nenya library - tools for developing networked games
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.media.animation;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import com.threerings.media.AbstractMediaManager;
import com.threerings.media.MediaPanel;
import com.threerings.media.sprite.Sprite;
import com.threerings.media.animation.Animation;
import com.threerings.media.animation.AnimationAdapter;
import com.threerings.media.animation.AnimationObserver;
/**
* A Sprite that wraps an animation so that a sequence of frames can be easily
* moved around the screen. Animations embedded here should not be added
* directly to a media panel as this sprite will manage them. If the enclosed
* animation completes, we remove the sprite from the media panel, since the
* animation would normally do that itself.
*/
public class AnimationSprite extends Sprite
{
public AnimationSprite (Animation anim, MediaPanel owner)
{
super();
_anim = anim;
_owner = owner;
}
public void init ()
{
_anim.init(_mgr);
}
// documentation inherited
public void tick (long tickStamp)
{
super.tick(tickStamp);
_anim.tick(tickStamp);
if (_anim.isFinished()) {
_anim.willFinish(tickStamp);
_owner.removeSprite(AnimationSprite.this);
_anim.didFinish(tickStamp);
} else {
_bounds = (Rectangle)_anim.getBounds().clone();
}
}
// documentation inherited.
public void setLocation (int x, int y)
{
_anim.setLocation(x - _oxoff, y - _oyoff);
super.setLocation(x, y);
}
// documentation inherited
public void willStart (long tickStamp)
{
super.willStart(tickStamp);
_anim.willStart(tickStamp);
}
// documentation inherited
public void paint (Graphics2D gfx) {
// Nothing to paint for ourselves.
_anim.paint(gfx);
}
protected Animation _anim;
protected MediaPanel _owner;
}
|
package com.fonfon.noloss.ui.map;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import com.fonfon.geohash.GeoHash;
import com.fonfon.noloss.R;
import com.fonfon.noloss.lib.BitmapUtils;
import com.fonfon.noloss.BleService;
import com.fonfon.noloss.lib.Device;
import com.fonfon.noloss.lib.LocationChangeService;
import com.fonfon.noloss.ui.BleViewModel;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.ArrayList;
import io.realm.Realm;
import io.realm.RealmResults;
final class MapActivityViewModel extends BleViewModel implements OnMapReadyCallback {
private boolean isFirstLocationChange = false;
private final int markerSize;
private final ArrayList<Marker> markers = new ArrayList<>();
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String address = intent.getStringExtra(BleService.DEVICE_ADDRESS);
Location location = intent.getParcelableExtra(LocationChangeService.LOCATION);
if(action != null && action.equals(LocationChangeService.LOCATION_CHANGED) && address != null && location != null) {
for (Marker marker: markers) {
if(marker.getSnippet().equals(address)) {
marker.setPosition(new LatLng(location.getLatitude(), location.getLongitude()));
marker.setVisible(marker.getPosition().latitude != 0 && marker.getPosition().longitude != 0);
break;
}
}
}
}
};
MapActivityViewModel(AppCompatActivity activity) {
super(activity);
markerSize = activity.getResources().getDimensionPixelSize(R.dimen.marker_size);
}
@Override
public void resume() {
super.resume();
activity.registerReceiver(receiver, new IntentFilter(LocationChangeService.LOCATION_CHANGED));
}
void pause() {
activity.unregisterReceiver(receiver);
}
@Override
public void onMapReady(final GoogleMap googleMap) {
if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return;
}
googleMap.setMyLocationEnabled(true);
googleMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location location) {
if (location != null && !isFirstLocationChange) {
googleMap.animateCamera(
CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(),
location.getLongitude()),
googleMap.getMaxZoomLevel() - 5
)
);
isFirstLocationChange = true;
}
}
});
showMarkers(googleMap);
}
private void showMarkers(final GoogleMap googleMap) {
RealmResults<Device> devices = Realm.getDefaultInstance().where(Device.class).findAll();
for (Device device : devices) {
GeoHash geoHash = GeoHash.fromString(device.getGeoHash());
Location center = geoHash.getCenter();
createMarker(googleMap, new LatLng(center.getLatitude(), center.getLongitude()), device);
}
}
private void createMarker(GoogleMap googleMap, LatLng point, Device device) {
Marker marker = googleMap.addMarker(new MarkerOptions()
.position(point)
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher))
.flat(true)
.title(device.getName())
.visible(!Device.ZERO_GEOHASH.equals(device.getGeoHash()))
.snippet(device.getAddress())
);
markers.add(marker);
Bitmap bitmap = BitmapUtils.stringToBitMap(device.getImage());
if (bitmap != null) {
Bitmap bmp = Bitmap.createScaledBitmap(bitmap, markerSize, markerSize, false);
bitmap.recycle();
marker.setIcon(BitmapDescriptorFactory.fromBitmap(bmp));
}
}
}
|
package com.twitter.mesos.scheduler;
import java.util.concurrent.CountDownLatch;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Supplier;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.google.inject.Inject;
import org.apache.mesos.Protos;
import org.apache.mesos.SchedulerDriver;
import com.twitter.common.application.Lifecycle;
import com.twitter.common.args.Arg;
import com.twitter.common.args.CmdLine;
import com.twitter.common.quantity.Amount;
import com.twitter.common.quantity.Time;
import com.twitter.common.zookeeper.ServerSet;
import com.twitter.common.zookeeper.SingletonService;
import com.twitter.thrift.Status;
/**
* The central driver of the scheduler runtime lifecycle. Handles the transitions from startup and
* initialization through acting as a standby scheduler / log replica and finally to becoming the
* scheduler leader.
*
* <p>TODO(John Sirois): This class contains the old logic of SchedulerMain - now that its extracted
* it should be tested.
*/
class SchedulerLifecycle implements RegisteredListener {
/**
* A {@link SingletonService} scheduler leader candidate that exposes a method for awaiting clean
* shutdown.
*/
interface SchedulerCandidate extends SingletonService.LeadershipListener {
/**
* Waits for this candidate to abdicate or otherwise decide to quit.
*/
void awaitShutdown();
}
@CmdLine(name = "max_registration_delay", help =
"Max allowable delay to allow the driver to register before aborting")
private static final Arg<Amount<Long, Time>> MAX_REGISTRATION_DELAY =
Arg.create(Amount.of(1L, Time.MINUTES));
private static final Logger LOG = Logger.getLogger(SchedulerLifecycle.class.getName());
private final DriverFactory driverFactory;
private final SchedulerCore scheduler;
private final Lifecycle lifecycle;
private final CountDownLatch registeredLatch = new CountDownLatch(1);
private final Driver driver;
private final DriverReference driverRef;
@Inject
SchedulerLifecycle(DriverFactory driverFactory,
SchedulerCore scheduler,
Lifecycle lifecycle,
Driver driver,
DriverReference driverRef) {
this.driverFactory = Preconditions.checkNotNull(driverFactory);
this.scheduler = Preconditions.checkNotNull(scheduler);
this.lifecycle = Preconditions.checkNotNull(lifecycle);
this.driver = Preconditions.checkNotNull(driver);
this.driverRef = Preconditions.checkNotNull(driverRef);
}
/**
* Prepares a scheduler to offer itself as a leader candidate. After this call the scheduler will
* host a live log replica and start syncing data from the leader via the log until it gets called
* upon to lead.
*
* @return A candidate that can be offered for leadership of a distributed election.
*/
public SchedulerCandidate prepare() {
LOG.info("Preparing scheduler candidate");
scheduler.prepare();
return new SchedulerCandidateImpl();
}
@Override
public void registered(String frameworkId) throws RegisterHandlingException {
registeredLatch.countDown();
}
/**
* Maintains a reference to the driver.
*/
static class DriverReference implements Supplier<Optional<SchedulerDriver>> {
private volatile Optional<SchedulerDriver> driver = Optional.absent();
@Override
public Optional<SchedulerDriver> get() {
return driver;
}
private void set(SchedulerDriver ref) {
this.driver = Optional.of(ref);
}
}
/**
* Implementation of the scheduler candidate lifecycle.
*/
private class SchedulerCandidateImpl implements SchedulerCandidate {
@Override public void onLeading(ServerSet.EndpointStatus status) {
LOG.info("Elected as leading scheduler!");
try {
lead();
status.update(Status.ALIVE);
} catch (ServerSet.UpdateException e) {
LOG.log(Level.SEVERE, "Failed to update endpoint status, shutting down.", e);
lifecycle.shutdown();
} catch (RuntimeException e) {
LOG.log(Level.SEVERE, "Unexpected exception attempting to lead, shutting down.", e);
lifecycle.shutdown();
}
}
private void startDaemonThread(String name, Runnable work) {
new ThreadFactoryBuilder()
.setNameFormat(name + "-%d")
.setDaemon(true)
.build()
.newThread(work)
.start();
}
private void lead() {
@Nullable final String frameworkId = scheduler.initialize();
driverRef.set(driverFactory.apply(frameworkId));
scheduler.start();
startDaemonThread("Driver-Runner", new Runnable() {
@Override public void run() {
Protos.Status status = driver.run();
LOG.info("Driver completed with exit code " + status);
lifecycle.shutdown();
}
});
startDaemonThread("Driver-Register-Watchdog", new Runnable() {
@Override public void run() {
LOG.info(String.format("Waiting up to %s for scheduler registration.",
MAX_REGISTRATION_DELAY.get()));
try {
boolean registered = registeredLatch.await(
MAX_REGISTRATION_DELAY.get().getValue(),
MAX_REGISTRATION_DELAY.get().getUnit().getTimeUnit());
if (!registered) {
LOG.severe("Framework has not been registered within the tolerated delay, quitting.");
lifecycle.shutdown();
}
} catch (InterruptedException e) {
LOG.log(Level.WARNING, "Delayed registration check interrupted.", e);
Thread.currentThread().interrupt();
}
}
});
}
@Override
public void onDefeated(@Nullable ServerSet.EndpointStatus status) {
LOG.info("Lost leadership, committing suicide.");
try {
if (status != null) {
status.update(Status.DEAD);
}
driver.stop(); // shut down incoming offers
scheduler.stop(); // shut down offer and slave update processing
} catch (ServerSet.UpdateException e) {
LOG.log(Level.WARNING, "Failed to leave server set.", e);
} finally {
lifecycle.shutdown(); // shut down the server
}
}
@Override
public void awaitShutdown() {
lifecycle.awaitShutdown();
}
}
}
|
package net.sf.jabref.specialfields;
import java.util.ArrayList;
import java.util.List;
import net.sf.jabref.Util;
import net.sf.jabref.BibtexEntry;
import net.sf.jabref.Globals;
import net.sf.jabref.undo.NamedCompound;
public class SpecialFieldsUtils {
public final static String FIELDNAME_PRIORITY = "priority";
public final static String FIELDNAME_RANKING = "ranking";
public final static String FIELDNAME_RELEVANCE = "relevance";
public final static String FIELDNAME_QUALITY = "qualityassured";
public final static String PREF_SPECIALFIELDSENABLED = "specialFieldsEnabled";
public final static Boolean PREF_SPECIALFIELDSENABLED_DEFAULT = Boolean.FALSE;
public final static String PREF_SHOWCOLUMN_RANKING = "showRankingColumn";
public final static Boolean PREF_SHOWCOLUMN_RANKING_DEFAULT = Boolean.TRUE;
public final static String PREF_RANKING_COMPACT = "compactRankingColumn";
public final static Boolean PREF_RANKING_COMPACT_DEFAULT = Boolean.TRUE;
public final static String PREF_SHOWCOLUMN_PRIORITY = "showPriorityColumn";
public final static Boolean PREF_SHOWCOLUMN_PRIORITY_DEFAULT = Boolean.FALSE;
public final static String PREF_SHOWCOLUMN_RELEVANCE = "showRelevanceColumn";
public final static Boolean PREF_SHOWCOLUMN_RELEVANCE_DEFAULT = Boolean.FALSE;
public final static String PREF_SHOWCOLUMN_QUALITY = "showQualityColumn";
public final static Boolean PREF_SHOWCOLUMN_QUALITY_DEFAULT = Boolean.FALSE;
public final static String PREF_AUTOSYNCSPECIALFIELDSTOKEYWORDS = "autoSyncSpecialFieldsToKeywords";
public final static Boolean PREF_AUTOSYNCSPECIALFIELDSTOKEYWORDS_DEFAULT = Boolean.FALSE;
public final static String PREF_SERIALIZESPECIALFIELDS = "serializeSpecialFields";
public final static Boolean PREF_SERIALIZESPECIALFIELDS_DEFAULT = Boolean.TRUE;
/** generic treatment **/
/** no special treatment any more, thanks to enums **/
/**
* @param e - Field to be handled
* @param value - may be null to state that field should be emptied
* @param be - BibTeXEntry to be handled
* @param ce - Filled with undo info (if necessary)
* @param nullFieldIfValueIsTheSame - true: field is nulled if value is the same than the current value in be
*/
public static void updateField(SpecialField e, String value, BibtexEntry be, NamedCompound ce, boolean nullFieldIfValueIsTheSame) {
Util.updateField(be, e.getFieldName(), value, ce, nullFieldIfValueIsTheSame);
// we cannot use "value" here as updateField has side effects: "nullFieldIfValueIsTheSame" nulls the field if value is the same
exportFieldToKeywords(e, be.getField(e.getFieldName()), be, ce);
}
private static void exportFieldToKeywords(SpecialField e, BibtexEntry be, NamedCompound ce) {
exportFieldToKeywords(e, be.getField(e.getFieldName()), be, ce);
}
private static void exportFieldToKeywords(SpecialField e, String newValue, BibtexEntry be, NamedCompound ce) {
if (!SpecialFieldsUtils.keywordSyncEnabled()) return;
ArrayList<String> keywordList = Util.getSeparatedKeywords(be);
List<String> values = e.getKeyWords();
int foundPos = -1;
// cleanup keywords
for (Object value: values) {
int pos = keywordList.indexOf(value);
if (pos >= 0) {
foundPos = pos;
keywordList.remove(pos);
}
}
if (newValue != null) {
if (foundPos == -1) {
keywordList.add(newValue);
} else {
keywordList.add(foundPos, newValue);
}
}
Util.putKeywords(be, keywordList, ce);
}
/**
* Update keywords according to values of special fields
*
* @param nc indicates the undo named compound. May be null
*/
public static void syncKeywordsFromSpecialFields(BibtexEntry be, NamedCompound nc) {
exportFieldToKeywords(Priority.getInstance(), be, nc);
exportFieldToKeywords(Rank.getInstance(), be, nc);
exportFieldToKeywords(Relevance.getInstance(), be, nc);
exportFieldToKeywords(Quality.getInstance(), be, nc);
}
private static void importKeywordsForField(ArrayList<String> keywordList, SpecialField c, BibtexEntry be, NamedCompound nc) {
List<String> values = c.getKeyWords();
String newValue = null;
for (String val: values) {
if (keywordList.contains(val)) {
newValue = val;
break;
}
}
Util.updateField(be, c.getFieldName(), newValue, nc);
}
/**
* updates field values according to keywords
*
* @param nc indicates the undo named compound. May be null
*/
public static void syncSpecialFieldsFromKeywords(BibtexEntry be, NamedCompound ce) {
if (be.getField("keywords") == null)
return;
ArrayList<String> keywordList = Util.getSeparatedKeywords(be.getField("keywords"));
importKeywordsForField(keywordList, Priority.getInstance(), be, ce);
importKeywordsForField(keywordList, Rank.getInstance(), be, ce);
importKeywordsForField(keywordList, Quality.getInstance(), be, ce);
importKeywordsForField(keywordList, Relevance.getInstance(), be, ce);
}
/**
* @param fieldName the fieldName
* @return an instance of that field. The returned object is a singleton. null is returned if fieldName does not indicate a special field
*/
public static SpecialField getSpecialFieldInstanceFromFieldName(String fieldName) {
if (fieldName.equals(FIELDNAME_PRIORITY)) {
return Priority.getInstance();
} else if (fieldName.equals(FIELDNAME_QUALITY)) {
return Quality.getInstance();
} else if (fieldName.equals(FIELDNAME_RANKING)) {
return Rank.getInstance();
} else if (fieldName.equals(FIELDNAME_RELEVANCE)) {
return Relevance.getInstance();
} else {
return null;
}
}
/**
* @param fieldName the name of the field to check
* @return true if given field is a special field, false otherwise
*/
public static boolean isSpecialField(String fieldName) {
return (getSpecialFieldInstanceFromFieldName(fieldName) != null);
}
public static boolean keywordSyncEnabled() {
return Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SPECIALFIELDSENABLED) &&
Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_AUTOSYNCSPECIALFIELDSTOKEYWORDS);
}
}
|
package com.hjwylde.rivers.ui.activities;
import android.Manifest;
import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.MapStyleOptions;
import com.google.android.gms.maps.model.Marker;
import com.google.maps.android.clustering.Cluster;
import com.google.maps.android.clustering.ClusterItem;
import com.google.maps.android.clustering.ClusterManager;
import com.hjwylde.rivers.R;
import com.hjwylde.rivers.models.Section;
import com.hjwylde.rivers.models.SectionMarker;
import com.hjwylde.rivers.ui.contracts.MapsContract;
import com.hjwylde.rivers.ui.util.ClusterRenderer;
import java.util.Collection;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
public final class MapsFragment extends SupportMapFragment implements OnMapReadyCallback, ClusterManager.OnClusterItemClickListener<SectionMarker>, ClusterManager.OnClusterClickListener<SectionMarker> {
private static final int ACCESS_FINE_LOCATION_PERMISSION_REQUEST_CODE = 1;
private GoogleMap mMap;
private UiSettings mUiSettings;
private ClusterManager<SectionMarker> mClusterManager;
private OnMarkerClickListener mOnMarkerClickListener = new OnMarkerClickListener();
private MapsContract.View mView;
public void disableOnMarkerClickListener() {
mOnMarkerClickListener.disable();
}
public void enableOnMarkerClickListener() {
mOnMarkerClickListener.enable();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mView = (MapsContract.View) activity;
}
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(getContext(), R.raw.maps_style));
mUiSettings = mMap.getUiSettings();
mUiSettings.setMapToolbarEnabled(false);
mClusterManager = new ClusterManager<>(getContext(), mMap);
mClusterManager.setRenderer(new ClusterRenderer<>(getContext(), mMap, mClusterManager));
mClusterManager.setOnClusterItemClickListener(this);
mClusterManager.setOnClusterClickListener(this);
mMap.setOnCameraIdleListener(mClusterManager);
mMap.setOnMarkerClickListener(mOnMarkerClickListener);
if (hasAccessFineLocationPermission()) {
enableMyLocation();
} else {
requestAccessFineLocationPermission();
}
mView.refreshMap();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == ACCESS_FINE_LOCATION_PERMISSION_REQUEST_CODE) {
if (grantResults[0] == PERMISSION_GRANTED) {
enableMyLocation();
}
}
}
@Override
public void onResume() {
super.onResume();
if (mMap == null) {
getMapAsync(this);
}
}
public void refreshMap(@NonNull Collection<Section> sections) {
if (mMap == null) {
return;
}
mMap.clear();
mClusterManager.clearItems();
for (Section section : sections) {
mClusterManager.addItem(new SectionMarker(section));
}
mClusterManager.cluster();
}
@Override
public boolean onClusterItemClick(SectionMarker sectionMarker) {
mView.startSectionActivity(sectionMarker.getSection());
return true;
}
@Override
public boolean onClusterClick(Cluster<SectionMarker> cluster) {
LatLngBounds.Builder builder = LatLngBounds.builder();
for (ClusterItem item : cluster.getItems()) {
builder.include(item.getPosition());
}
LatLngBounds bounds = builder.build();
int padding = getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT ? 250 : 100;
mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, padding));
return true;
}
private boolean hasAccessFineLocationPermission() {
return ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PERMISSION_GRANTED;
}
private void requestAccessFineLocationPermission() {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, ACCESS_FINE_LOCATION_PERMISSION_REQUEST_CODE);
}
private void enableMyLocation() {
mMap.setMyLocationEnabled(true);
mUiSettings.setMyLocationButtonEnabled(true);
}
private class OnMarkerClickListener implements GoogleMap.OnMarkerClickListener {
private boolean mEnabled = true;
public void disable() {
mEnabled = false;
}
public void enable() {
mEnabled = true;
}
@Override
public boolean onMarkerClick(Marker marker) {
if (mEnabled && mClusterManager != null) {
return mClusterManager.onMarkerClick(marker);
}
return true;
}
}
}
|
package net.sf.picard.illumina;
import net.sf.picard.util.TabbedTextFileWithHeaderParser;
import net.sf.picard.PicardException;
import net.sf.picard.cmdline.CommandLineProgram;
import net.sf.picard.cmdline.Option;
import net.sf.picard.cmdline.StandardOptionDefinitions;
import net.sf.picard.cmdline.Usage;
import net.sf.picard.io.IoUtil;
import net.sf.picard.metrics.MetricBase;
import net.sf.picard.metrics.MetricsFile;
import net.sf.samtools.util.SequenceUtil;
import net.sf.samtools.util.StringUtil;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.text.NumberFormat;
import net.sf.picard.illumina.parser.IlluminaDataProviderFactory;
import net.sf.picard.illumina.parser.IlluminaDataType;
import net.sf.picard.illumina.parser.AbstractIlluminaDataProvider;
import net.sf.picard.illumina.parser.IlluminaReadData;
/**
* Determine the barcode for each read in an Illumina lane.
* For each tile, a file is written to the basecalls directory of the form s_<lane>_<tile>_barcode.txt.
* An output file contains a line for each read in the tile, aligned with the regular basecall output
* The output file contains the following tab-separated columns:
* - read subsequence at barcode position
* - Y or N indicating if there was a barcode match
* - matched barcode sequence (empty if read did not match one of the barcodes).
*
* @author alecw@broadinstitute.org
*/
public class ExtractIlluminaBarcodes extends CommandLineProgram {
// The following attributes define the command-line arguments
@Usage
public String USAGE =
getStandardUsagePreamble() + "Determine the barcode for each read in an Illumina lane.\n" +
"For each tile, a file is written to the basecalls directory of the form s_<lane>_<tile>_barcode.txt." +
"An output file contains a line for each read in the tile, aligned with the regular basecall output\n" +
"The output file contains the following tab-separated columns: \n" +
" * read subsequence at barcode position\n" +
" * Y or N indicating if there was a barcode match\n" +
" * matched barcode sequence\n" +
"Note that the order of specification of barcodes can cause arbitrary differences in output for poorly matching barcodes.\n\n";
@Option(doc="Deprecated option; use BASECALLS_DIR", mutex = "BASECALLS_DIR")
public File BUSTARD_DIR;
@Option(doc="The Illumina basecalls output directory. ", mutex = "BUSTARD_DIR", shortName="B")
public File BASECALLS_DIR;
@Option(doc="Where to write _barcode.txt files. By default, these are written to BASECALLS_DIR.", optional = true)
public File OUTPUT_DIR;
@Option(doc="Lane number. ", shortName= StandardOptionDefinitions.LANE_SHORT_NAME)
public Integer LANE;
@Option(doc="1-based cycle number of the start of the barcode.", shortName = "BARCODE_POSITION")
public Integer BARCODE_CYCLE;
@Option(doc="Barcode sequence. These must be unique, and all the same length.", mutex = {"BARCODE_FILE"})
public List<String> BARCODE = new ArrayList<String>();
@Option(doc="Tab-delimited file of barcode sequences, and optionally barcode name and library name. " +
"Barcodes must be unique, and all the same length. Column headers must be 'barcode_sequence', " +
"'barcode_name', and 'library_name'.", mutex = {"BARCODE"})
public File BARCODE_FILE;
@Option(doc="Per-barcode and per-lane metrics written to this file.", shortName = StandardOptionDefinitions.METRICS_FILE_SHORT_NAME)
public File METRICS_FILE;
@Option(doc="Maximum mismatches for a barcode to be considered a match.")
public int MAX_MISMATCHES = 1;
@Option(doc="Minimum difference between number of mismatches in the best and second best barcodes for a barcode to be considered a match.")
public int MIN_MISMATCH_DELTA = 1;
@Option(doc="Maximum allowable number of no-calls in a barcode read before it is considered unmatchable.")
public int MAX_NO_CALLS = 2;
private int barcodeLength;
private int tile = 0;
private File barcodeFile = null;
private BufferedWriter writer = null;
private final List<NamedBarcode> namedBarcodes = new ArrayList<NamedBarcode>();
private final List<BarcodeMetric> barcodeMetrics = new ArrayList<BarcodeMetric>();
private BarcodeMetric noMatchBarcodeMetric;
private final NumberFormat tileNumberFormatter = NumberFormat.getNumberInstance();
static class BarcodeMatch {
boolean matched;
String barcode;
int mismatches;
int mismatchesToSecondBest;
}
public ExtractIlluminaBarcodes() {
tileNumberFormatter.setMinimumIntegerDigits(4);
tileNumberFormatter.setGroupingUsed(false);
}
@Override
protected int doWork() {
if(BUSTARD_DIR != null) {
BASECALLS_DIR = BUSTARD_DIR;
}
IoUtil.assertDirectoryIsWritable(BASECALLS_DIR);
IoUtil.assertFileIsWritable(METRICS_FILE);
if (OUTPUT_DIR == null) {
OUTPUT_DIR = BASECALLS_DIR;
}
IoUtil.assertDirectoryIsWritable(OUTPUT_DIR);
for (final NamedBarcode namedBarcode : namedBarcodes) {
barcodeMetrics.add(new BarcodeMetric(namedBarcode));
}
// Create BarcodeMetric for counting reads that don't match any barcode
final StringBuilder noMatchBarcode = new StringBuilder(barcodeLength);
for (int i = 0; i < barcodeLength; ++i) {
noMatchBarcode.append('N');
}
noMatchBarcodeMetric = new BarcodeMetric(new NamedBarcode(noMatchBarcode.toString()));
final IlluminaDataProviderFactory factory = new IlluminaDataProviderFactory(BASECALLS_DIR, LANE,
BARCODE_CYCLE, barcodeLength, IlluminaDataType.BaseCalls, IlluminaDataType.PF);
// This is possible for index-only run.
factory.setAllowZeroLengthFirstEnd(true);
final AbstractIlluminaDataProvider parser = factory.makeDataProvider();
// Process each tile qseq file.
try {
while (parser.hasNext()) {
final IlluminaReadData ird = parser.next();
extractBarcode(ird);
}
if (writer != null) {
writer.close();
writer = null;
}
} catch (IOException e) {
throw new PicardException("IOException writing barcode file " + barcodeFile, e);
}
// Finish metrics tallying.
int totalReads = noMatchBarcodeMetric.READS;
int totalPfReads = noMatchBarcodeMetric.PF_READS;
int totalPfReadsAssigned = 0;
for (final BarcodeMetric barcodeMetric : barcodeMetrics) {
totalReads += barcodeMetric.READS;
totalPfReads += barcodeMetric.PF_READS;
totalPfReadsAssigned += barcodeMetric.PF_READS;
}
if (totalReads > 0) {
noMatchBarcodeMetric.PCT_MATCHES = noMatchBarcodeMetric.READS/(double)totalReads;
double bestPctOfAllBarcodeMatches = 0;
for (final BarcodeMetric barcodeMetric : barcodeMetrics) {
barcodeMetric.PCT_MATCHES = barcodeMetric.READS/(double)totalReads;
if (barcodeMetric.PCT_MATCHES > bestPctOfAllBarcodeMatches) {
bestPctOfAllBarcodeMatches = barcodeMetric.PCT_MATCHES;
}
}
if (bestPctOfAllBarcodeMatches > 0) {
noMatchBarcodeMetric.RATIO_THIS_BARCODE_TO_BEST_BARCODE_PCT =
noMatchBarcodeMetric.PCT_MATCHES/bestPctOfAllBarcodeMatches;
for (final BarcodeMetric barcodeMetric : barcodeMetrics) {
barcodeMetric.RATIO_THIS_BARCODE_TO_BEST_BARCODE_PCT =
barcodeMetric.PCT_MATCHES/bestPctOfAllBarcodeMatches;
}
}
}
if (totalPfReads > 0) {
noMatchBarcodeMetric.PF_PCT_MATCHES = noMatchBarcodeMetric.PF_READS/(double)totalPfReads;
double bestPctOfAllBarcodeMatches = 0;
for (final BarcodeMetric barcodeMetric : barcodeMetrics) {
barcodeMetric.PF_PCT_MATCHES = barcodeMetric.PF_READS/(double)totalPfReads;
if (barcodeMetric.PF_PCT_MATCHES > bestPctOfAllBarcodeMatches) {
bestPctOfAllBarcodeMatches = barcodeMetric.PF_PCT_MATCHES;
}
}
if (bestPctOfAllBarcodeMatches > 0) {
noMatchBarcodeMetric.PF_RATIO_THIS_BARCODE_TO_BEST_BARCODE_PCT =
noMatchBarcodeMetric.PF_PCT_MATCHES/bestPctOfAllBarcodeMatches;
for (final BarcodeMetric barcodeMetric : barcodeMetrics) {
barcodeMetric.PF_RATIO_THIS_BARCODE_TO_BEST_BARCODE_PCT =
barcodeMetric.PF_PCT_MATCHES/bestPctOfAllBarcodeMatches;
}
}
}
// Calculate the normalized matches
if (totalPfReadsAssigned > 0) {
final double mean = (double) totalPfReadsAssigned / (double) barcodeMetrics.size();
for (final BarcodeMetric m : barcodeMetrics) {
m.PF_NORMALIZED_MATCHES = m.PF_READS / mean;
}
}
final MetricsFile<BarcodeMetric, Integer> metrics = getMetricsFile();
for (final BarcodeMetric barcodeMetric : barcodeMetrics) {
metrics.addMetric(barcodeMetric);
}
metrics.addMetric(noMatchBarcodeMetric);
metrics.write(METRICS_FILE);
return 0;
}
/**
* Scan through qseqFile, and create a sibling barcode file with the barcode assignment lined up with the
* tile's qseq file.
*/
private void ensureBarcodeFileOpen(final int tile) {
if (tile == this.tile) {
return;
}
try {
if (writer != null) {
writer.close();
writer = null;
}
this.tile = tile;
barcodeFile = getBarcodeFile(tile);
writer = IoUtil.openFileForBufferedWriting(barcodeFile);
} catch (IOException e) {
throw new PicardException("IOException " + barcodeFile, e);
}
}
/**
* Assign barcodes for a single tile's qseq file
*/
private void extractBarcode(final IlluminaReadData ird) throws IOException {
final String barcodeSubsequence = StringUtil.bytesToString(ird.getBarcodeRead().getBases());
final boolean passingFilter = ird.isPf();
final BarcodeMatch match = findBestBarcode(barcodeSubsequence, passingFilter);
final String yOrN = (match.matched ? "Y" : "N");
ensureBarcodeFileOpen(ird.getTile());
writer.write(StringUtil.join("\t", barcodeSubsequence, yOrN, match.barcode,
String.valueOf(match.mismatches),
String.valueOf(match.mismatchesToSecondBest)));
writer.newLine();
}
/**
* Find the best barcode match for the given read sequence, and accumulate metrics
* @param readSubsequence portion of read containing barcode
* @param passingFilter PF flag for the current read
* @return perfect barcode string, if there was a match within tolerance, or null if not.
*/
private BarcodeMatch findBestBarcode(final String readSubsequence, final boolean passingFilter) {
BarcodeMetric bestBarcodeMetric = null;
int numMismatchesInBestBarcode = readSubsequence.length();
int numMismatchesInSecondBestBarcode = readSubsequence.length();
final byte[] readBytes = net.sf.samtools.util.StringUtil.stringToBytes(readSubsequence);
int numNoCalls = 0;
for (final byte b : readBytes) if (SequenceUtil.isNoCall(b)) ++numNoCalls;
for (final BarcodeMetric barcodeMetric : barcodeMetrics) {
final int numMismatches = countMismatches(barcodeMetric.barcodeBytes, readBytes);
if (numMismatches < numMismatchesInBestBarcode) {
if (bestBarcodeMetric != null) {
numMismatchesInSecondBestBarcode = numMismatchesInBestBarcode;
}
numMismatchesInBestBarcode = numMismatches;
bestBarcodeMetric = barcodeMetric;
} else if (numMismatches < numMismatchesInSecondBestBarcode) {
numMismatchesInSecondBestBarcode = numMismatches;
}
}
final boolean matched = bestBarcodeMetric != null &&
numNoCalls <= MAX_NO_CALLS &&
numMismatchesInBestBarcode <= MAX_MISMATCHES &&
numMismatchesInSecondBestBarcode - numMismatchesInBestBarcode >= MIN_MISMATCH_DELTA;
final BarcodeMatch match = new BarcodeMatch();
if (numNoCalls + numMismatchesInBestBarcode < readSubsequence.length()) {
match.mismatches = numMismatchesInBestBarcode;
match.mismatchesToSecondBest = numMismatchesInSecondBestBarcode;
match.barcode = bestBarcodeMetric.BARCODE.toLowerCase();
}
else {
match.mismatches = readSubsequence.length();
match.mismatches = readSubsequence.length();
match.barcode = "";
}
if (matched) {
++bestBarcodeMetric.READS;
if (passingFilter) {
++bestBarcodeMetric.PF_READS;
}
if (numMismatchesInBestBarcode == 0) {
++bestBarcodeMetric.PERFECT_MATCHES;
if (passingFilter) {
++bestBarcodeMetric.PF_PERFECT_MATCHES;
}
} else if (numMismatchesInBestBarcode == 1) {
++bestBarcodeMetric.ONE_MISMATCH_MATCHES;
if (passingFilter) {
++bestBarcodeMetric.PF_ONE_MISMATCH_MATCHES;
}
}
match.matched = true;
match.barcode = bestBarcodeMetric.BARCODE;
}
else {
++noMatchBarcodeMetric.READS;
if (passingFilter) {
++noMatchBarcodeMetric.PF_READS;
}
}
return match;
}
/**
* Compare barcode sequence to bases from read
* @return how many bases did not match
*/
private int countMismatches(final byte[] barcodeBytes, final byte[] readSubsequence) {
int numMismatches = 0;
for (int i = 0; i < barcodeBytes.length; ++i) {
if (!SequenceUtil.isNoCall(readSubsequence[i]) && !SequenceUtil.basesEqual(barcodeBytes[i], readSubsequence[i])) {
++numMismatches;
}
}
return numMismatches;
}
/**
* Create a barcode filename corresponding to the given tile qseq file.
*/
private File getBarcodeFile(final int tile) {
return new File(OUTPUT_DIR, "s_" + LANE + "_" + tileNumberFormatter.format(tile) + "_barcode.txt");
}
/**
* Validate that POSITION >= 1, and that all BARCODEs are the same length and unique
*
* @return null if command line is valid. If command line is invalid, returns an array of error message
* to be written to the appropriate place.
*/
@Override
protected String[] customCommandLineValidation() {
final ArrayList<String> messages = new ArrayList<String>();
if (BARCODE_CYCLE < 1) {
messages.add("Invalid BARCODE_POSITION=" + BARCODE_CYCLE + ". Value must be positive.");
}
if (BARCODE_FILE != null) {
parseBarcodeFile(messages);
} else {
Set<String> barcodes = new HashSet<String>();
barcodeLength = BARCODE.get(0).length();
for (final String barcode : BARCODE) {
if (barcode.length() != barcodeLength) {
messages.add("Barcode " + barcode + " has different length from first barcode.");
}
if (barcodes.contains(barcode)) {
messages.add("Barcode " + barcode + " specified more than once.");
}
barcodes.add(barcode);
NamedBarcode namedBarcode = new NamedBarcode(barcode);
namedBarcodes.add(namedBarcode);
}
}
if (namedBarcodes.size() == 0) {
messages.add("No barcodes have been specified.");
}
if (messages.size() == 0) {
return null;
}
return messages.toArray(new String[messages.size()]);
}
public static void main(final String[] argv) {
System.exit(new ExtractIlluminaBarcodes().instanceMain(argv));
}
private static final String BARCODE_SEQUENCE_COLUMN = "barcode_sequence";
private static final String BARCODE_NAME_COLUMN = "barcode_name";
private static final String LIBRARY_NAME_COLUMN = "library_name";
private void parseBarcodeFile(ArrayList<String> messages) {
final TabbedTextFileWithHeaderParser barcodesParser = new TabbedTextFileWithHeaderParser(BARCODE_FILE);
if (!barcodesParser.hasColumn(BARCODE_SEQUENCE_COLUMN)) {
messages.add(BARCODE_FILE + " does not have " + BARCODE_SEQUENCE_COLUMN + " column header");
return;
}
boolean hasBarcodeName = barcodesParser.hasColumn(BARCODE_NAME_COLUMN);
boolean hasLibraryName = barcodesParser.hasColumn(LIBRARY_NAME_COLUMN);
barcodeLength = 0;
Set<String> barcodes = new HashSet<String>();
for (final TabbedTextFileWithHeaderParser.Row row : barcodesParser) {
final String barcode = row.getField(BARCODE_SEQUENCE_COLUMN);
if (barcodeLength == 0) barcodeLength = barcode.length();
if (barcode.length() != barcodeLength) {
messages.add("Barcode " + barcode + " has different length from first barcode.");
}
if (barcodes.contains(barcode)) {
messages.add("Barcode " + barcode + " specified more than once in " + BARCODE_FILE);
}
barcodes.add(barcode);
final String barcodeName = (hasBarcodeName? row.getField(BARCODE_NAME_COLUMN): "");
final String libraryName = (hasLibraryName? row.getField(LIBRARY_NAME_COLUMN): "");
NamedBarcode namedBarcode = new NamedBarcode(barcode, barcodeName, libraryName);
namedBarcodes.add(namedBarcode);
}
}
private static class NamedBarcode {
public final String barcode;
public final String barcodeName;
public final String libraryName;
public NamedBarcode(String barcode, String barcodeName, String libraryName) {
this.barcode = barcode;
this.barcodeName = barcodeName;
this.libraryName = libraryName;
}
public NamedBarcode(String barcode) {
this.barcode = barcode;
this.barcodeName = "";
this.libraryName = "";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
NamedBarcode that = (NamedBarcode) o;
if (barcode != null ? !barcode.equals(that.barcode) : that.barcode != null) return false;
return true;
}
@Override
public int hashCode() {
return barcode != null ? barcode.hashCode() : 0;
}
}
/**
* Metrics produced by the ExtractIlluminaBarcodes program that is used to parse data in
* the basecalls directory and determine to which barcode each read should be assigned.
*/
public static class BarcodeMetric extends MetricBase {
/**
* The barcode (from the set of expected barcodes) for which the following metrics apply.
* Note that the "symbolic" barcode of NNNNNN is used to report metrics for all reads that
* do not match a barcode.
*/
public String BARCODE;
public String BARCODE_NAME = "";
public String LIBRARY_NAME = "";
/** The total number of reads matching the barcode. */
public int READS = 0;
/** The number of PF reads matching this barcode (always less than or equal to READS). */
public int PF_READS = 0;
/** The number of all reads matching this barcode that matched with 0 errors or no-calls. */
public int PERFECT_MATCHES = 0;
/** The number of PF reads matching this barcode that matched with 0 errors or no-calls. */
public int PF_PERFECT_MATCHES = 0;
/** The number of all reads matching this barcode that matched with 1 error or no-call. */
public int ONE_MISMATCH_MATCHES = 0;
/** The number of PF reads matching this barcode that matched with 1 error or no-call. */
public int PF_ONE_MISMATCH_MATCHES = 0;
/** The percentage of all reads in the lane that matched to this barcode. */
public double PCT_MATCHES = 0d;
/**
* The rate of all reads matching this barcode to all reads matching the most prevelant barcode. For the
* most prevelant barcode this will be 1, for all others it will be less than 1. One over the lowest
* number in this column gives you the fold-difference in representation between barcodes.
*/
public double RATIO_THIS_BARCODE_TO_BEST_BARCODE_PCT = 0d;
/** The percentage of PF reads in the lane that matched to this barcode. */
public double PF_PCT_MATCHES = 0d;
/**
* The rate of PF reads matching this barcode to PF reads matching the most prevelant barcode. For the
* most prevelant barcode this will be 1, for all others it will be less than 1. One over the lowest
* number in this column gives you the fold-difference in representation of PF reads between barcodes.
*/
public double PF_RATIO_THIS_BARCODE_TO_BEST_BARCODE_PCT = 0d;
/**
* The "normalized" matches to each barcode. This is calculated as the number of pf reads matching
* this barcode over the sum of all pf reads matching any barcode (excluding orphans). If all barcodes
* are represented equally this will be 1.
*/
public double PF_NORMALIZED_MATCHES;
protected final byte[] barcodeBytes;
public BarcodeMetric(final NamedBarcode namedBarcode) {
this.BARCODE = namedBarcode.barcode;
this.BARCODE_NAME = namedBarcode.barcodeName;
this.LIBRARY_NAME = namedBarcode.libraryName;
this.barcodeBytes = net.sf.samtools.util.StringUtil.stringToBytes(this.BARCODE);
}
/**
* This ctor is necessary for when reading metrics from file
*/
public BarcodeMetric() {
barcodeBytes = null;
}
}
}
|
package battlecode.world;
import battlecode.common.GameConstants;
import battlecode.common.MapLocation;
import battlecode.common.RobotType;
import battlecode.common.Team;
import gnu.trove.list.array.TIntArrayList;
import gnu.trove.map.hash.TIntObjectHashMap;
import gnu.trove.procedure.TIntObjectProcedure;
import gnu.trove.procedure.TIntProcedure;
import gnu.trove.procedure.TObjectProcedure;
import net.sf.jsi.SpatialIndex;
import net.sf.jsi.rtree.RTree;
import net.sf.jsi.Rectangle;
import net.sf.jsi.Point;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumMap;
import java.util.Map;
/**
* This class is used to hold information about the robots, trees, and bullets
* in the game world.
*/
public strictfp class ObjectInfo {
private final float mapWidth;
private final float mapHeight;
private final MapLocation mapTopLeft;
private final TIntObjectHashMap<InternalRobot> gameRobotsByID;
private final TIntObjectHashMap<InternalTree> gameTreesByID;
private final TIntObjectHashMap<InternalBullet> gameBulletsByID;
private final SpatialIndex treeIndex;
private final SpatialIndex robotIndex;
private final SpatialIndex bulletIndex;
private final TIntArrayList dynamicBodyExecOrder;
private Map<Team, Map<RobotType, Integer>> robotTypeCount = new EnumMap<>(
Team.class);
private int[] robotCount = new int[3];
private int[] treeCount = new int[3];
public ObjectInfo(LiveMap gm){
this.mapWidth = gm.getWidth();
this.mapHeight = gm.getHeight();
this.mapTopLeft = gm.getOrigin();
this.gameTreesByID = new TIntObjectHashMap<>();
this.gameRobotsByID = new TIntObjectHashMap<>();
this.gameBulletsByID = new TIntObjectHashMap<>();
treeIndex = new RTree();
robotIndex = new RTree();
bulletIndex = new RTree();
dynamicBodyExecOrder = new TIntArrayList();
treeIndex.init(null);
robotIndex.init(null);
bulletIndex.init(null);
robotTypeCount.put(Team.A, new EnumMap<>(
RobotType.class));
robotTypeCount.put(Team.B, new EnumMap<>(
RobotType.class));
}
public int getRobotTypeCount(Team team, RobotType type) {
if (robotTypeCount.get(team).containsKey(type)) {
return robotTypeCount.get(team).get(type);
} else {
return 0;
}
}
/**
* Apply an operation for every bullet.
* Return false to stop iterating.
* If you call destroyBullet() on a bullet that hasn't been seen yet,
* that bullet will be silently skipped.
*
* @param op a lambda (bullet) -> boolean
*/
public void eachBullet(TObjectProcedure<InternalBullet> op) {
// Trove doesn't throw errors when we delete a map entry while iterating
// it just silently skips the entry later...
// which is exactly the behaviour we want.
gameBulletsByID.forEachValue(op);
}
/**
* Apply an operation for every tree.
* Return false to stop iterating.
* If you call destroyTree() on a tree that hasn't been seen yet,
* that tree will be silently skipped.
*
* @param op a lambda (bullet) -> void
*/
public void eachTree(TObjectProcedure<InternalTree> op) {
gameTreesByID.forEachValue(op);
}
/**
* Apply an operation for every robot, ordered based on robot ID hash (effectively random).
* Return false to stop iterating.
* If you call destroyRobot() on a robot that hasn't been seen yet,
* that robot will be silently skipped.
*
* @param op a lambda (bullet) -> void
*/
public void eachRobot(TObjectProcedure<InternalRobot> op) {
gameRobotsByID.forEachValue(op);
//eachRobotBySpawnOrder(op);
}
/**
* Apply an operation for every Bullet and Robot, in the order the
* bodies should be updated. Robots update in spawn order, and
* Bullets update immediately before the robot that fired them.
* Return false to stop iterating.
*
* If a body is removed during iteration, the body is cleanly skipped.
*
* @param op a lambda (body) -> void
*/
public void eachDynamicBodyByExecOrder(TObjectProcedure<InternalBody> op) {
// We can't modify the ArrayList we are looping over
int[] spawnOrderArray = dynamicBodyExecOrder.toArray();
for (int id : spawnOrderArray) {
// Check if body still exists.
// This can produce bugs if a bullet and a robot can have the same ID.
if (existsRobot(id)) {
boolean returnedTrue = op.execute(gameRobotsByID.get(id));
if (!returnedTrue) {
break;
}
} else if (existsBullet(id)) {
boolean returnedTrue = op.execute(gameBulletsByID.get(id));
if (!returnedTrue) {
break;
}
} else {
// The body does not exist, so it was deleted in an earlier
// iteration and should be skipped.
continue;
}
}
}
/**
* This allocates; prefer eachTree()
*/
public Collection<InternalTree> trees() {
return gameTreesByID.valueCollection();
}
/**
* This allocates; prefer eachBullet()
*/
public Collection<InternalBullet> bullets() {
return gameBulletsByID.valueCollection();
}
/**
* This allocates; prefer eachRobot()
*/
public Collection<InternalRobot> robots() {
return gameRobotsByID.valueCollection();
}
/**
* This allocates; prefer eachTree()
*/
public InternalTree[] treesArray() {
return gameTreesByID.values(new InternalTree[gameTreesByID.size()]);
}
/**
* This allocates; prefer eachBullet()
*/
public InternalBullet[] bulletsArray() {
return gameBulletsByID.values(new InternalBullet[gameBulletsByID.size()]);
}
/**
* This allocates; prefer eachRobot()
*/
public InternalRobot[] robotsArray() {
return gameRobotsByID.values(new InternalRobot[gameRobotsByID.size()]);
}
public int getTreeCount(Team team) {
return treeCount[team.ordinal()];
}
public int getRobotCount(Team team) {
return robotCount[team.ordinal()];
}
public InternalTree getTreeByID(int id){
return gameTreesByID.get(id);
}
public InternalRobot getRobotByID(int id){
return gameRobotsByID.get(id);
}
public InternalBullet getBulletByID(int id){
return gameBulletsByID.get(id);
}
public void moveBullet(InternalBullet bullet, MapLocation newLocation) {
MapLocation loc = bullet.getLocation();
bulletIndex.delete(fromPoint(loc),bullet.getID());
bulletIndex.add(fromPoint(newLocation),bullet.getID());
}
public void moveRobot(InternalRobot robot, MapLocation newLocation) {
MapLocation loc = robot.getLocation();
robotIndex.delete(fromPoint(loc),robot.getID());
robotIndex.add(fromPoint(newLocation),robot.getID());
}
public void spawnTree(InternalTree tree){
incrementTreeCount(tree.getTeam());
int id = tree.getID();
gameTreesByID.put(id, tree);
MapLocation loc = tree.getLocation();
treeIndex.add(fromPoint(loc),tree.getID());
}
public void spawnRobot(InternalRobot robot){
incrementRobotCount(robot.getTeam());
incrementRobotTypeCount(robot.getTeam(), robot.getType());
int id = robot.getID();
gameRobotsByID.put(id, robot);
dynamicBodyExecOrder.add(id);
MapLocation loc = robot.getLocation();
robotIndex.add(fromPoint(loc),robot.getID());
}
public void spawnBullet(InternalBullet bullet, InternalRobot parent){
int id = bullet.getID();
gameBulletsByID.put(id, bullet);
// We insert the bullet immediately before its parent (i.e. the robot
// which fired it). This means that the bullet will first update immediately
// before its parent next updates, and after any bullets previously fired
// by this robot have updated again.
int parentIndex = dynamicBodyExecOrder.indexOf(parent.getID());
dynamicBodyExecOrder.insert(parentIndex, id);
MapLocation loc = bullet.getLocation();
bulletIndex.add(fromPoint(loc),bullet.getID());
}
public boolean existsTree(int id){
return gameTreesByID.containsKey(id);
}
public boolean existsRobot(int id){
return gameRobotsByID.containsKey(id);
}
public boolean existsBullet(int id){
return gameBulletsByID.containsKey(id);
}
public void destroyTree(int id){
InternalTree tree = getTreeByID(id);
decrementTreeCount(tree.getTeam());
MapLocation loc = tree.getLocation();
gameTreesByID.remove(id);
treeIndex.delete(fromPoint(loc),id);
}
public void destroyRobot(int id){
InternalRobot robot = getRobotByID(id);
decrementRobotCount(robot.getTeam());
decrementRobotTypeCount(robot.getTeam(), robot.getType());
MapLocation loc = robot.getLocation();
gameRobotsByID.remove(id);
dynamicBodyExecOrder.remove(id);
robotIndex.delete(fromPoint(loc),id);
}
public void destroyBullet(int id){
InternalBullet b = getBulletByID(id);
MapLocation loc = b.getLocation();
gameBulletsByID.remove(id);
dynamicBodyExecOrder.remove(id);
bulletIndex.delete(fromPoint(loc),id);
}
public InternalTree[] getAllTreesWithinRadius(MapLocation center, float radius){
float searchRadius = radius + GameConstants.NEUTRAL_TREE_MAX_RADIUS;
ArrayList<InternalTree> returnTrees = new ArrayList<InternalTree>();
treeIndex.nearestN(
new Point(center.x,center.y), // Search from center
new TIntProcedure() { // Add each to a list
public boolean execute(int i) {
InternalTree potentialTree = getTreeByID(i);
if (potentialTree.getLocation().isWithinDistance(center,potentialTree.getRadius()+radius))
returnTrees.add(potentialTree);
return true; // Keep searching for results
}
},
Integer.MAX_VALUE,
searchRadius
);
return returnTrees.toArray(new InternalTree[returnTrees.size()]);
}
public InternalRobot[] getAllRobotsWithinRadius(MapLocation center, float radius){
float searchRadius = radius + GameConstants.MAX_ROBOT_RADIUS;
ArrayList<InternalRobot> returnRobots = new ArrayList<InternalRobot>();
robotIndex.nearestN(
new Point(center.x,center.y), // Search from center
new TIntProcedure() { // Add each to a list
public boolean execute(int i) {
InternalRobot potentialRobot = getRobotByID(i);
if (potentialRobot.getLocation().isWithinDistance(center,potentialRobot.getType().bodyRadius+radius))
returnRobots.add(potentialRobot);
return true; // Keep searching for results
}
},
Integer.MAX_VALUE,
searchRadius
);
return returnRobots.toArray(new InternalRobot[returnRobots.size()]);
}
public InternalBullet[] getAllBulletsWithinRadius(MapLocation center, float radius){
ArrayList<InternalBullet> returnBullets = new ArrayList<InternalBullet>();
// Add each to a list
bulletIndex.nearestN(
new Point(center.x,center.y), // Search from center
i -> {
returnBullets.add(getBulletByID(i));
return true;
},
Integer.MAX_VALUE,
radius
);
return returnBullets.toArray(new InternalBullet[returnBullets.size()]);
}
public InternalTree getTreeAtLocation(MapLocation loc){
// even though it only contains one element, arraylist is required to be accessed from inside TIntProcedure
ArrayList<InternalTree> returnTrees = new ArrayList<InternalTree>();
treeIndex.nearest(
new Point(loc.x,loc.y),
i -> {
InternalTree potentialTree = getTreeByID(i);
if (potentialTree.getLocation().isWithinDistance(loc,potentialTree.getRadius()))
returnTrees.add(potentialTree);
return false; // Don't need any more results
},
GameConstants.NEUTRAL_TREE_MAX_RADIUS // Furthest distance
);
if(returnTrees.size() > 0)
return returnTrees.get(0);
else
return null;
}
public InternalRobot getRobotAtLocation(MapLocation loc){
// even though it only contains one element, arraylist is required to be accessed from inside TIntProcedure
ArrayList<InternalRobot> returnRobots = new ArrayList<InternalRobot>();
robotIndex.nearest(
new Point(loc.x,loc.y),
new TIntProcedure() {
public boolean execute(int i) {
InternalRobot potentialRobot = getRobotByID(i);
if (potentialRobot.getLocation().isWithinDistance(loc,potentialRobot.getType().bodyRadius))
returnRobots.add(potentialRobot);
return false; // Don't need any more results
}
},
GameConstants.MAX_ROBOT_RADIUS // Furthest distance
);
if(returnRobots.size() > 0)
return returnRobots.get(0);
else
return null;
}
public boolean isEmpty(MapLocation loc, float radius){
return getAllTreesWithinRadius(loc, radius).length == 0 &&
getAllRobotsWithinRadius(loc, radius).length == 0;
}
public boolean isEmptyExceptForRobot(MapLocation loc, float radius, InternalRobot robot){
if (getAllTreesWithinRadius(loc, radius).length != 0)
return false;
InternalRobot[] robots = getAllRobotsWithinRadius(loc, radius);
if (robots.length == 0) {
return true;
} else if (robots.length == 1) {
return robot.equals(robots[0]);
} else {
return false;
}
}
public boolean noRobotsExceptForRobot(MapLocation loc, float radius, InternalRobot robot){
InternalRobot[] robots = getAllRobotsWithinRadius(loc, radius);
if (robots.length == 0) {
return true;
} else if (robots.length == 1) {
return robot.equals(robots[0]);
} else {
return false;
}
}
private Rectangle fromPoint(float x, float y) {
return new Rectangle(x,y,x,y);
}
private Rectangle fromPoint(Point p) {
return new Rectangle(p.x,p.y,p.x,p.y);
}
private Rectangle fromPoint(MapLocation loc) {
return new Rectangle(loc.x,loc.y,loc.x,loc.y);
}
private void incrementRobotCount(Team team) {
robotCount[team.ordinal()]++;
}
private void decrementRobotCount(Team team) {
robotCount[team.ordinal()]
}
private void incrementTreeCount(Team team) {
treeCount[team.ordinal()]++;
}
private void decrementTreeCount(Team team) {
treeCount[team.ordinal()]
}
private void incrementRobotTypeCount(Team team, RobotType type) {
if (robotTypeCount.get(team).containsKey(type)) {
robotTypeCount.get(team).put(type,
robotTypeCount.get(team).get(type) + 1);
} else {
robotTypeCount.get(team).put(type, 1);
}
}
private void decrementRobotTypeCount(Team team, RobotType type) {
Integer currentCount = getRobotTypeCount(team, type);
robotTypeCount.get(team).put(type,currentCount - 1);
}
}
|
package com.wikijourney.wikijourney.views;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.wikijourney.wikijourney.R;
import com.wikijourney.wikijourney.functions.CustomInfoWindow;
import com.wikijourney.wikijourney.functions.Map;
import com.wikijourney.wikijourney.functions.POI;
import com.wikijourney.wikijourney.functions.UI;
import org.json.JSONException;
import org.json.JSONObject;
import org.osmdroid.api.IMapController;
import org.osmdroid.bonuspack.overlays.Marker;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import java.util.ArrayList;
import cz.msebera.android.httpclient.Header;
public class MapFragment extends Fragment {
// Variables for API
private static final String API_URL = "http://wikijourney.eu/api/api.php?";
private String language = "fr";
private double paramRange;
private int paramMaxPoi;
private String paramPlace;
private int paramMethod; //Could be around or place, depends on which button was clicked.
//Now the variables we are going to use for the rest of the program.
private LocationManager locationManager;
private LocationListener locationListener;
private Snackbar locatingSnackbar;
private Snackbar downloadSnackbar;
public MapFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_map, container, false);
// These lines initialize the map settings
final MapView map = (MapView) view.findViewById(R.id.map);
map.setTileSource(TileSourceFactory.MAPNIK);
map.setBuiltInZoomControls(true);
map.setMultiTouchControls(true);
IMapController mapController = map.getController();
mapController.setZoom(16);
// We get the Bundle values
Bundle args = getArguments();
try {
paramMaxPoi = args.getInt(HomeFragment.EXTRA_OPTIONS[0]);
} catch (Exception e) {
paramMaxPoi = getResources().getInteger(R.integer.default_maxPOI);
}
try {
paramRange = args.getDouble(HomeFragment.EXTRA_OPTIONS[1]);
} catch (Exception e) {
paramRange = getResources().getInteger(R.integer.default_range);
}
try {
paramPlace = args.getString(HomeFragment.EXTRA_OPTIONS[2]);
} catch (Exception e) {
paramPlace = "null"; // Place value
}
try {
paramMethod = args.getInt(HomeFragment.EXTRA_OPTIONS[3]);
} catch (Exception e) {
// I totally forgot what this does, maybe so we don't refresh the Map if the user already has geolocated himself...
// Or if the user chose Around Me method or Around A Place method... Oops
int previousFragmentId = getActivity().getFragmentManager().getBackStackEntryCount()-1;
FragmentManager.BackStackEntry backEntry = getActivity().getFragmentManager().getBackStackEntryAt(previousFragmentId);
if (backEntry.getName().equals("MapFragmentFindingPoi")) {
paramMethod = HomeFragment.METHOD_AROUND;
} else {
paramMethod = -1;
}
}
if (paramMethod == HomeFragment.METHOD_AROUND) {
// Display a Snackbar while the phone locates the user, so he doesn't think the app crashed
locatingSnackbar = Snackbar.make(getActivity().findViewById(R.id.fragment_container), R.string.locating_snackbar, Snackbar.LENGTH_INDEFINITE);
locatingSnackbar.show();
// Acquire a reference to the system Location Manager
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
// Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
// Define a listener that responds to location updates
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Once located, download the info from the API and display the map
locatingSnackbar.dismiss();
drawMap(location, map, locationManager, this);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
// Register the listener with the Location Manager to receive location updates
// locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else if(paramMethod == HomeFragment.METHOD_PLACE) {
// TODO
// drawMap(paramPlace, map);
}
return view;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onDetach() {
super.onDetach();
// Stop the Geolocation if the user leaves the MapFragment early
locationManager.removeUpdates(locationListener);
locatingSnackbar.dismiss();
downloadSnackbar.dismiss();
}
private void drawMap(Location location, MapView map, LocationManager locationManager, LocationListener locationListener) {
// TODO Temporary fix
// This stop the location updates, so the map doesn't always refresh
locationManager.removeUpdates(locationListener);
IMapController mapController = map.getController();
// This starts the map at the desired point
final GeoPoint startPoint = new GeoPoint(location.getLatitude(), location.getLongitude());
mapController.setCenter(startPoint);
// Now we add a marker using osmBonusPack
Marker startMarker = new Marker(map);
startMarker.setPosition(startPoint);
startMarker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
map.getOverlays().add(startMarker);
// And we have to use this to refresh the map
map.invalidate();
// We can change some properties of the marker (don't forget to refresh the map !!)
startMarker.setInfoWindow(new CustomInfoWindow(map));
Drawable icon = ContextCompat.getDrawable(getActivity(), R.drawable.ic_place);
startMarker.setIcon(icon);
startMarker.setTitle(getString(R.string.you_are_here));
map.invalidate();
// We get the POI around the user with WikiJourney API
String url;
url = API_URL + "long=" + startPoint.getLongitude() + "&lat=" + startPoint.getLatitude()
+ "&maxPOI=" + paramMaxPoi + "&range=" + paramRange + "&lg=" + language;
// Check if the Internet is up
final ConnectivityManager connMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
// These are needed for the download library and the methods called later
final Context context = this.getActivity();
final MapFragment mapFragment = this;
if (networkInfo != null && networkInfo.isConnected()) {
// Show a Snackbar while we wait for WikiJourney server, so the user doesn't think the app crashed
downloadSnackbar = Snackbar.make(getView(), R.string.snackbar_downloading, Snackbar.LENGTH_INDEFINITE);
downloadSnackbar.show();
// Donwload from the WJ API
AsyncHttpClient client = new AsyncHttpClient();
client.setTimeout(30_000); // Set timeout to 30s, the server may be slow...
client.get(context, url, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
downloadSnackbar.dismiss();
ArrayList<POI> poiArrayList;
String errorOccurred;
String errorMessage = null;
// We check if the download worked
try {
errorOccurred = response.getJSONObject("err_check").getString("value");
if (errorOccurred.equals("true")) {
errorMessage = response.getJSONObject("err_check").getString("err_msg");
}
} catch (JSONException e) {
e.printStackTrace();
}
if (errorMessage != null) {
UI.openPopUp(mapFragment.getActivity(), mapFragment.getResources().getString(R.string.error_download_api_response_title), errorMessage);
} else {
poiArrayList = POI.parseApiJson(response, context);
Map.drawPOI(mapFragment, poiArrayList);
}
}
@Override
public void onProgress(long bytesWritten, long totalSize) {
Log.d("progress", "Downloading " + bytesWritten + " of " + totalSize);
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
try {
Log.e("Error", errorResponse.toString());
} catch (Exception e) {
Log.e("Error", "Error while downloading the API response");
}
finally {
UI.openPopUp(mapFragment.getActivity(), getResources().getString(R.string.error_download_api_response_title), getResources().getString(R.string.error_download_api_response));
}
}
@Override
public void onRetry(int retryNo) {
Log.e("Error", "Retrying for the " + retryNo + " time");
super.onRetry(retryNo);
}
});
} else {
UI.openPopUp(mapFragment.getActivity(), getResources().getString(R.string.error_activate_internet_title), getResources().getString(R.string.error_activate_internet));
}
}
/*public void drawMap(String place, MapView map) {
IMapController mapController = map.getController();
// This starts the map at the desired point
final GeoPoint startPoint = new GeoPoint(location.getLatitude(), location.getLongitude());
mapController.setCenter(startPoint);
// Now we add a marker using osmBonusPack
Marker startMarker = new Marker(map);
startMarker.setPosition(startPoint);
startMarker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
map.getOverlays().add(startMarker);
// And we have to use this to refresh the map
map.invalidate();
// We can change some properties of the marker (don't forget to refresh the map !!)
startMarker.setInfoWindow(new CustomInfoWindow(map));
Drawable icon = ContextCompat.getDrawable(getActivity(), R.drawable.ic_place);
startMarker.setIcon(icon);
startMarker.setTitle(getString(R.string.you_are_here));
map.invalidate();
// We get the POI around the user with WikiJourney API
String url;
url = API_URL + "long=" + startPoint.getLongitude() + "&lat=" + startPoint.getLatitude()
+ "&maxPOI=" + paramMaxPoi + "&lg=" + language;
ConnectivityManager connMgr = (ConnectivityManager)
getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new DownloadApi(this).execute(url, place);
} else {
UI.openPopUp(new HomeFragment(), getResources().getString(R.string.error_activate_internet_title), getResources().getString(R.string.error_activate_internet));
}
}*/
}
|
package com.worldspotlightapp.android.ui;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.maps.android.clustering.Cluster;
import com.google.maps.android.clustering.ClusterManager;
import com.google.maps.android.clustering.view.DefaultClusterRenderer;
import com.viewpagerindicator.UnderlinePageIndicator;
import com.worldspotlightapp.android.R;
import com.worldspotlightapp.android.maincontroller.modules.ParseResponse;
import com.worldspotlightapp.android.maincontroller.modules.videosmodule.VideosModuleObserver;
import com.worldspotlightapp.android.maincontroller.modules.videosmodule.response.VideosModuleVideosListResponse;
import com.worldspotlightapp.android.model.Video;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
public class MainActivity extends AbstractBaseActivityObserver {
private static final String TAG = "MainActivity";
private FragmentManager mFragmentManager;
private ClusterManager<Video> mClusterManager;
private List<Video> mVideosList;
// The last parse response before processed.
// If a parse response has been processed, it will be null
private ParseResponse mParseResponse;
// Views
private GoogleMap mMap;
// ViewPager for preview
private ViewPager mVideosPreviewViewPager;
private UnderlinePageIndicator mVideosPreviewViewPagerIndicator;
private VideosPreviewViewPagerAdapter mVideosPreviewViewPagerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFragmentManager = getSupportFragmentManager();
// Link the views
mVideosPreviewViewPager = (ViewPager) findViewById(R.id.videos_preview_view_pager);
mVideosPreviewViewPagerIndicator = (UnderlinePageIndicator) findViewById(R.id.videos_preview_view_pager_indicator);
setupMapIfNeeded();
}
private void setupMapIfNeeded() {
// If the map was already set, exit
if (mMap != null) {
return;
}
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
mClusterManager = new ClusterManager<Video>(this, mMap);
VideosRenderer videosRenderer = new VideosRenderer(mContext, mMap, mClusterManager);
mClusterManager.setRenderer(videosRenderer);
// mMap.setOnCameraChangeListener(mClusterManager);
mMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition cameraPosition) {
mClusterManager.onCameraChange(cameraPosition);
// Show the viewpager
mVideosPreviewViewPager.setVisibility(View.GONE);
mVideosPreviewViewPagerIndicator.setVisibility(View.GONE);
}
});
mMap.setOnMarkerClickListener(mClusterManager);
mMap.setOnInfoWindowClickListener(mClusterManager);
mClusterManager.setOnClusterItemClickListener(new ClusterManager.OnClusterItemClickListener<Video>() {
@Override
public boolean onClusterItemClick(Video video) {
Intent startVideoDetailsActivityIntent = new Intent(mContext, VideoDetailsActivity.class);
startVideoDetailsActivityIntent.putExtra(Video.INTENT_KEY_OBJECT_ID, video.getObjectId());
startActivity(startVideoDetailsActivityIntent);
return true;
}
});
mClusterManager.setOnClusterClickListener(new ClusterManager.OnClusterClickListener<Video>() {
@Override
public boolean onClusterClick(Cluster<Video> cluster) {
// Show the viewpager
mVideosPreviewViewPager.setVisibility(View.VISIBLE);
mVideosPreviewViewPagerIndicator.setVisibility(View.VISIBLE);
List<Video> videosListToShow = new ArrayList<Video>();
for (Video video: cluster.getItems()) {
videosListToShow.add(video);
}
mVideosPreviewViewPagerAdapter = new VideosPreviewViewPagerAdapter(mFragmentManager, videosListToShow);
mVideosPreviewViewPager.setAdapter(mVideosPreviewViewPagerAdapter);
// Set the view pager in the view pager indicator
mVideosPreviewViewPagerIndicator.setViewPager(mVideosPreviewViewPager);
mVideosPreviewViewPagerIndicator.setFades(false);
return true;
}
});
mVideosModule.requestVideosList(this);
mNotificationModule.showLoadingDialog(mContext);
}
@Override
public void update(Observable observable, Object o) {
Log.v(TAG, "Data received from " + observable);
if (observable instanceof VideosModuleObserver) {
if (o instanceof VideosModuleVideosListResponse) {
VideosModuleVideosListResponse videosModuleVideosListResponse = (VideosModuleVideosListResponse)o;
mParseResponse = videosModuleVideosListResponse.getParseResponse();
mVideosList = videosModuleVideosListResponse.getVideosList();
if (mIsInForeground) {
processDataIfExists();
}
observable.deleteObserver(this);
}
}
}
@Override
protected void processDataIfExists() {
setupMapIfNeeded();
// 1. Check if the data exists
// If there were not data received from backend, then
// Not do anything
if (mParseResponse == null) {
return;
}
// 2. Process the data
if (!mParseResponse.isError()) {
// The sign up was correct. Go to the Main activity
mClusterManager.addItems(mVideosList);
mClusterManager.cluster();
} else {
// Some error happend
mNotificationModule.showToast(mParseResponse.getHumanRedableResponseMessage(mContext), true);
}
mNotificationModule.dismissLoadingDialog();
// 3. Remove the answers
mParseResponse = null;
}
private class VideosRenderer extends DefaultClusterRenderer<Video> {
public VideosRenderer(Context context, GoogleMap map, ClusterManager<Video> clusterManager) {
super(context, map, clusterManager);
}
@Override
protected void onBeforeClusterItemRendered(Video item, MarkerOptions markerOptions) {
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_default_maps_marker));
}
}
}
|
package br.com.http.utils;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
/**
* Represents an IPv4 address and uses 32-bit (four-byte) addresses representation. IPv4 addresses may be written in any
* notation expressing a 32-bit integer value, but for human convenience this class uses the dot-decimal notation, which
* consists of four octets of the address expressed individually in decimal and separated by periods (from 0.0.0.0 to
* 255.255.255.255).
*
* This class also supports the CIDR notation, which is a compact representation of an IP address and its associated
* routing prefix. The notation is constructed from the IP address and the prefix size, the latter being equivalent to
* the number of leading 1 bits in the routing prefix mask. The IP address is expressed according to the standards of
* IPv4. It is followed by a separator character, the slash ('/') character, and the prefix size expressed as a decimal
* number. The address may denote a single, distinct interface address or the beginning address of an entire network.
* The maximum size of the network is given by the number of addresses that are possible with the remaining,
* least-significant bits below the prefix. This is often called the host identifier. For example:
*
* <ul>
* <li>192.168.100.0/24 represents the given IPv4 address and its associated routing prefix 192.168.100.0, or
* equivalently, its subnet mask 255.255.255.0.</li>
* <li>the IPv4 block 192.168.100.0/22 represents the 1,024 IPv4 addresses from 192.168.100.0 to 192.168.103.255.</li>
* </ul>
*
* @author flsusp
*/
public class IPv4 implements IP {
private static final Pattern IPv4_PATTERN = Pattern
.compile("\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}(\\/(3[0-2]|2[0-9]|1[0-9]|[1-9]))?\\z");
private static final Pattern IPv4_CLASS_PATTERN = Pattern.compile("\\/(3[0-2]|2[0-9]|1[0-9]|[1-9])");
private static final Set<IPv4> privateIPAddresses = new HashSet<>();
static {
privateIPAddresses.add(new IPv4("127.0.0.1"));
privateIPAddresses.add(new IPv4("10.0.0.0/8"));
privateIPAddresses.add(new IPv4("172.16.0.0/12"));
privateIPAddresses.add(new IPv4("192.168.0.0/16"));
}
private final String address;
private final long rangeStart;
private final long rangeEnd;
public IPv4(String address) {
super();
if (StringUtils.isEmpty(address)) {
throw new InvalidIPv4Exception(address);
}
if (!IPv4_PATTERN.matcher(address).matches()) {
throw new InvalidIPv4Exception(address);
}
this.address = address;
this.rangeStart = getAddressAsLong(removeIPClass(address));
this.rangeEnd = getAddressAsLong(toString(calculateHigherIPAddressAccordingToClass(toBytes(),
extractIPClass(address))));
}
protected static String toString(byte[] bytes) {
int i = 4;
String ipAddress = "";
for (byte raw : bytes) {
ipAddress += (raw & 0xFF);
if (--i > 0) {
ipAddress += ".";
}
}
return ipAddress;
}
protected static int extractIPClass(String address) {
Matcher matcher = IPv4_CLASS_PATTERN.matcher(address);
if (matcher.find()) {
return Integer.valueOf(matcher.group().replace("/", ""));
} else {
return 32;
}
}
protected static byte[] calculateHigherIPAddressAccordingToClass(byte[] bytes, int ipClass) {
boolean[] bits = toBits(bytes);
bits = calculateHigherIPAddressAccordingToClass(bits, ipClass);
return toBytes(bits);
}
protected static boolean[] calculateHigherIPAddressAccordingToClass(boolean[] bits, int ipClass) {
for (int i = 0; i < bits.length; i++) {
if (ipClass > 0) {
ipClass
} else {
bits[i] = true;
}
}
return bits;
}
private static byte[] toBytes(boolean[] bits) {
byte[] result = new byte[(bits.length + Byte.SIZE - 1) / Byte.SIZE];
for (int i = 0; i < bits.length; i++) {
if (bits[i])
result[i / Byte.SIZE] = (byte) (result[i / Byte.SIZE] | (0x80 >>> (i % Byte.SIZE)));
}
return result;
}
private static boolean[] toBits(byte[] bytes) {
boolean[] bits = new boolean[bytes.length * Byte.SIZE];
for (int i = 0; i < Byte.SIZE * bytes.length; i++) {
bits[i] = (bytes[i / Byte.SIZE] << i % Byte.SIZE & 0x80) == 0 ? false : true;
}
return bits;
}
protected static String removeIPClass(String address) {
return IPv4_CLASS_PATTERN.matcher(address).replaceFirst("");
}
public static long getAddressAsLong(String address) {
String[] parts = address.split("[.]");
return Long.valueOf(parts[3]) + 256l * Long.valueOf(parts[2]) + 256l * 256l * Long.valueOf(parts[1]) + 256l
* 256l * 256l * Long.valueOf(parts[0]);
}
@Override
public boolean isPrivate() {
for (IPv4 privateIPAddress : privateIPAddresses) {
if (privateIPAddress.matches(this)) {
return true;
}
}
return false;
}
@Override
public boolean isPublic() {
return !isPrivate();
}
@Override
public long toLong() {
return rangeStart;
}
protected static byte[] toBytes(String address) {
String[] parts = address.split("\\.");
byte[] bytes = new byte[4];
for (int i = 0; i < 4; i++) {
int value = Integer.valueOf(parts[i]);
bytes[i] = (byte) value;
}
return bytes;
}
@Override
public byte[] toBytes() {
return toBytes(removeIPClass(address));
}
@Override
public boolean matches(IP ip) {
return ip.toLong() >= rangeStart && ip.toLong() <= rangeEnd;
}
@Override
public boolean isIPv4() {
return true;
}
@Override
public boolean isIPv6() {
return false;
}
@Override
public String toString() {
return address;
}
}
|
package de.danoeh.antennapod.fragment;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import de.danoeh.antennapod.R;
import de.danoeh.antennapod.activity.MainActivity;
import de.danoeh.antennapod.activity.OnlineFeedViewActivity;
import de.danoeh.antennapod.activity.OpmlImportActivity;
import de.danoeh.antennapod.discovery.CombinedSearcher;
import de.danoeh.antennapod.discovery.FyydPodcastSearcher;
import de.danoeh.antennapod.discovery.ItunesPodcastSearcher;
import de.danoeh.antennapod.fragment.gpodnet.GpodnetMainFragment;
/**
* Provides actions for adding new podcast subscriptions.
*/
public class AddFeedFragment extends Fragment {
public static final String TAG = "AddFeedFragment";
private static final int REQUEST_CODE_CHOOSE_OPML_IMPORT_PATH = 1;
private EditText combinedFeedSearchBox;
private MainActivity activity;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View root = inflater.inflate(R.layout.addfeed, container, false);
activity = (MainActivity) getActivity();
((AppCompatActivity) getActivity()).setSupportActionBar(root.findViewById(R.id.toolbar));
root.findViewById(R.id.btn_search_itunes).setOnClickListener(v
-> activity.loadChildFragment(OnlineSearchFragment.newInstance(ItunesPodcastSearcher.class)));
root.findViewById(R.id.btn_search_fyyd).setOnClickListener(v
-> activity.loadChildFragment(OnlineSearchFragment.newInstance(FyydPodcastSearcher.class)));
root.findViewById(R.id.btn_search_gpodder).setOnClickListener(v
-> activity.loadChildFragment(new GpodnetMainFragment()));
combinedFeedSearchBox = root.findViewById(R.id.combinedFeedSearchBox);
combinedFeedSearchBox.setOnEditorActionListener((v, actionId, event) -> {
performSearch();
return true;
});
root.findViewById(R.id.btn_add_via_url).setOnClickListener(v
-> showAddViaUrlDialog());
View butOpmlImport = root.findViewById(R.id.btn_opml_import);
butOpmlImport.setOnClickListener(v -> {
try {
Intent intentGetContentAction = new Intent(Intent.ACTION_GET_CONTENT);
intentGetContentAction.addCategory(Intent.CATEGORY_OPENABLE);
intentGetContentAction.setType("*/*");
startActivityForResult(intentGetContentAction, REQUEST_CODE_CHOOSE_OPML_IMPORT_PATH);
} catch (ActivityNotFoundException e) {
Log.e(TAG, "No activity found. Should never happen...");
}
});
root.findViewById(R.id.search_icon).setOnClickListener(view -> performSearch());
return root;
}
private void showAddViaUrlDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(R.string.add_podcast_by_url);
View content = View.inflate(getContext(), R.layout.edit_text_dialog, null);
EditText editText = content.findViewById(R.id.text);
editText.setHint(R.string.add_podcast_by_url_hint);
ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
String clipboardContent = clipboard.getText() != null ? clipboard.getText().toString() : "";
if (clipboardContent.trim().startsWith("http")) {
editText.setText(clipboardContent.trim());
}
builder.setView(content);
builder.setPositiveButton(R.string.confirm_label, (dialog, which) -> addUrl(editText.getText().toString()));
builder.setNegativeButton(R.string.cancel_label, null);
builder.show();
}
private void addUrl(String url) {
Intent intent = new Intent(getActivity(), OnlineFeedViewActivity.class);
intent.putExtra(OnlineFeedViewActivity.ARG_FEEDURL, url);
startActivity(intent);
}
private void performSearch() {
String query = combinedFeedSearchBox.getText().toString();
if (query.matches("http[s]?:
addUrl(query);
return;
}
activity.loadChildFragment(OnlineSearchFragment.newInstance(CombinedSearcher.class, query));
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
// So, we certainly *don't* have an options menu,
// but unless we say we do, old options menus sometimes
// persist. mfietz thinks this causes the ActionBar to be invalidated
setHasOptionsMenu(true);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK || data == null) {
return;
}
Uri uri = data.getData();
if (requestCode == REQUEST_CODE_CHOOSE_OPML_IMPORT_PATH) {
Intent intent = new Intent(getContext(), OpmlImportActivity.class);
intent.setData(uri);
startActivity(intent);
}
}
}
|
package me.echeung.moemoekyun.service;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v4.app.NotificationCompat;
import android.support.v4.media.app.NotificationCompat.MediaStyle;
import android.support.v7.graphics.Palette;
import me.echeung.listenmoeapi.models.Song;
import me.echeung.moemoekyun.App;
import me.echeung.moemoekyun.R;
import me.echeung.moemoekyun.ui.activities.MainActivity;
import me.echeung.moemoekyun.utils.AlbumArtUtil;
import me.echeung.moemoekyun.utils.ThemeUtil;
public class AppNotification {
public static final String NOTIFICATION_CHANNEL_NAME = "Default";
public static final String NOTIFICATION_CHANNEL_ID = "default";
private static final int NOTIFICATION_ID = 1;
private RadioService service;
private NotificationManager notificationManager;
AppNotification(RadioService service) {
this.service = service;
notificationManager = (NotificationManager) service.getSystemService(Context.NOTIFICATION_SERVICE);
}
void update() {
if (!service.isStreamStarted()) {
return;
}
final Song song = getCurrentSong();
final Bitmap albumArt = AlbumArtUtil.getCurrentAlbumArt();
final boolean isPlaying = service.isPlaying();
// Play/pause action
final NotificationCompat.Action playPauseAction = new NotificationCompat.Action(
isPlaying ? R.drawable.ic_pause_white_24dp : R.drawable.ic_play_arrow_white_24dp,
isPlaying ? service.getString(R.string.action_pause) : service.getString(R.string.action_play),
getPlaybackActionService(RadioService.PLAY_PAUSE));
// Build the notification
final Intent action = new Intent(service, MainActivity.class);
action.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
final PendingIntent clickIntent = PendingIntent.getActivity(service, 0, action, PendingIntent.FLAG_UPDATE_CURRENT);
final PendingIntent deleteIntent = getPlaybackActionService(RadioService.STOP);
int color = ThemeUtil.getAccentColor(service);
if (App.getPreferenceUtil().shouldColorNotification() && albumArt != null && !AlbumArtUtil.isDefaultAlbumArt()) {
color = Palette.from(albumArt).generate().getVibrantColor(color);
}
MediaStyle style = new MediaStyle().setMediaSession(service.getMediaSession().getSessionToken());
final NotificationCompat.Builder builder = new NotificationCompat.Builder(service, NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_icon)
.setLargeIcon(albumArt)
.setContentIntent(clickIntent)
.setDeleteIntent(deleteIntent)
.addAction(playPauseAction)
.setContentTitle(service.getString(R.string.app_name))
.setOngoing(isPlaying)
.setShowWhen(false)
.setStyle(style.setShowActionsInCompactView(0))
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setOnlyAlertOnce(true)
.setColor(color);
if (song != null) {
builder.setContentTitle(song.getTitle());
builder.setContentText(song.getArtistString());
builder.setSubText(song.getAlbumString());
// Add favorite action if logged in
if (App.getAuthUtil().isAuthenticated()) {
builder.addAction(new NotificationCompat.Action(
song.isFavorite() ? R.drawable.ic_star_white_24dp : R.drawable.ic_star_border_white_24dp,
song.isFavorite() ? service.getString(R.string.action_unfavorite) : service.getString(R.string.action_favorite),
getPlaybackActionService(RadioService.TOGGLE_FAVORITE)));
builder.setStyle(style.setShowActionsInCompactView(0, 1));
}
}
final Notification notification = builder.build();
if (isPlaying) {
service.startForeground(NOTIFICATION_ID, notification);
} else {
service.stopForeground(false);
notificationManager.notify(NOTIFICATION_ID, notification);
}
}
private Song getCurrentSong() {
return App.getRadioViewModel().getCurrentSong();
}
private PendingIntent getPlaybackActionService(final String action) {
final Intent intent = new Intent(service, RadioService.class);
intent.setAction(action);
return PendingIntent.getService(service, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
}
|
package org.jivesoftware.openfire.muc.spi;
import org.dom4j.Element;
import org.jivesoftware.openfire.PacketException;
import org.jivesoftware.openfire.PacketRouter;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.jivesoftware.openfire.muc.*;
import org.jivesoftware.openfire.user.UserAlreadyExistsException;
import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.Log;
import org.jivesoftware.util.NotFoundException;
import org.xmpp.packet.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* Representation of users interacting with the chat service. A user
* may join serveral rooms hosted by the chat service. That means that
* we are going to have an instance of this class for the user and several
* MUCRoles for each joined room.<p>
*
* This room occupant is being hosted by this JVM. When the room occupant
* is hosted by another cluster node then an instance of {@link RemoteMUCRole}
* will be used instead.
*
* @author Gaston Dombiak
*/
public class LocalMUCUser implements MUCUser {
/** The chat server this user belongs to. */
private MultiUserChatServer server;
/** Real system XMPPAddress for the user. */
private JID realjid;
/** Table: key roomName.toLowerCase(); value LocalMUCRole. */
private Map<String, LocalMUCRole> roles = new ConcurrentHashMap<String, LocalMUCRole>();
/** Deliver packets to users. */
private PacketRouter router;
/**
* Time of last packet sent.
*/
private long lastPacketTime;
/**
* Create a new chat user.
*
* @param chatserver the server the user belongs to.
* @param packetRouter the router for sending packets from this user.
* @param jid the real address of the user
*/
LocalMUCUser(MultiUserChatServerImpl chatserver, PacketRouter packetRouter, JID jid) {
this.realjid = jid;
this.router = packetRouter;
this.server = chatserver;
}
/**
* Returns true if the user is currently present in one or more rooms.
*
* @return true if the user is currently present in one or more rooms.
*/
public boolean isJoined() {
return !roles.isEmpty();
}
/**
* Get all roles for this user.
*
* @return Iterator over all roles for this user
*/
public Collection<LocalMUCRole> getRoles() {
return Collections.unmodifiableCollection(roles.values());
}
/**
* Adds the role of the user in a particular room.
*
* @param roomName The name of the room.
* @param role The new role of the user.
*/
public void addRole(String roomName, LocalMUCRole role) {
roles.put(roomName, role);
}
/**
* Removes the role of the user in a particular room.<p>
*
* Note: PREREQUISITE: A lock on this object has already been obtained.
*
* @param roomName The name of the room we're being removed
*/
public void removeRole(String roomName) {
roles.remove(roomName);
}
/**
* Get time (in milliseconds from System currentTimeMillis()) since last packet.
*
* @return The time when the last packet was sent from this user
*/
public long getLastPacketTime() {
return lastPacketTime;
}
/**
* Generate a conflict packet to indicate that the nickname being requested/used is already in
* use by another user.
*
* @param packet the packet to be bounced.
* @param error the reason why the operation failed.
*/
private void sendErrorPacket(Packet packet, PacketError.Condition error) {
if (packet instanceof IQ) {
IQ reply = IQ.createResultIQ((IQ) packet);
reply.setChildElement(((IQ) packet).getChildElement().createCopy());
reply.setError(error);
router.route(reply);
}
else {
Packet reply = packet.createCopy();
reply.setError(error);
reply.setFrom(packet.getTo());
reply.setTo(packet.getFrom());
router.route(reply);
}
}
/**
* Obtain the address of the user. The address is used by services like the core
* server packet router to determine if a packet should be sent to the handler.
* Handlers that are working on behalf of the server should use the generic server
* hostname address (e.g. server.com).
*
* @return the address of the packet handler.
*/
public JID getAddress() {
return realjid;
}
public void process(Packet packet) throws UnauthorizedException, PacketException {
if (packet instanceof IQ) {
process((IQ)packet);
}
else if (packet instanceof Message) {
process((Message)packet);
}
else if (packet instanceof Presence) {
process((Presence)packet);
}
}
/**
* This method does all packet routing in the chat server. Packet routing is actually very
* simple:
*
* <ul>
* <li>Discover the room the user is talking to (server packets are dropped)</li>
* <li>If the room is not registered and this is a presence "available" packet, try to join the
* room</li>
* <li>If the room is registered, and presence "unavailable" leave the room</li>
* <li>Otherwise, rewrite the sender address and send to the room.</li>
* </ul>
*
* @param packet The packet to route.
*/
public void process(Message packet) {
// Ignore messages of type ERROR sent to a room
if (Message.Type.error == packet.getType()) {
return;
}
lastPacketTime = System.currentTimeMillis();
JID recipient = packet.getTo();
String group = recipient.getNode();
if (group == null) {
// Ignore packets to the groupchat server
// In the future, we'll need to support TYPE_IQ queries to the server for MUC
Log.info(LocaleUtils.getLocalizedString("muc.error.not-supported") + " "
+ packet.toString());
}
else {
MUCRole role = roles.get(group);
if (role == null) {
if (server.hasChatRoom(group)) {
boolean declinedInvitation = false;
Element userInfo = null;
if (Message.Type.normal == packet.getType()) {
// An user that is not an occupant could be declining an invitation
userInfo = packet.getChildElement(
"x", "http://jabber.org/protocol/muc#user");
if (userInfo != null
&& userInfo.element("decline") != null) {
// A user has declined an invitation to a room
// WARNING: Potential fraud if someone fakes the "from" of the
// message with the JID of a member and sends a "decline"
declinedInvitation = true;
}
}
if (declinedInvitation) {
Element info = userInfo.element("decline");
server.getChatRoom(group).sendInvitationRejection(
new JID(info.attributeValue("to")),
info.elementTextTrim("reason"),
packet.getFrom());
}
else {
// The sender is not an occupant of the room
sendErrorPacket(packet, PacketError.Condition.not_acceptable);
}
}
else {
// The sender is not an occupant of a NON-EXISTENT room!!!
sendErrorPacket(packet, PacketError.Condition.recipient_unavailable);
}
}
else {
// Check and reject conflicting packets with conflicting roles
// In other words, another user already has this nickname
if (!role.getUserAddress().equals(packet.getFrom())) {
sendErrorPacket(packet, PacketError.Condition.conflict);
}
else {
try {
if (packet.getSubject() != null && packet.getSubject().trim().length() > 0 &&
Message.Type.groupchat == packet.getType() &&
(packet.getBody() == null || packet.getBody().trim().length() == 0)) {
// An occupant is trying to change the room's subject
role.getChatRoom().changeSubject(packet, role);
}
else {
// An occupant is trying to send a private, send public message,
// invite someone to the room or reject an invitation
Message.Type type = packet.getType();
String resource = packet.getTo().getResource();
if (resource == null || resource.trim().length() == 0) {
resource = null;
}
if (resource == null && Message.Type.groupchat == type) {
// An occupant is trying to send a public message
role.getChatRoom().sendPublicMessage(packet, role);
}
else if (resource != null
&& (Message.Type.chat == type || Message.Type.normal == type)) {
// An occupant is trying to send a private message
role.getChatRoom().sendPrivatePacket(packet, role);
}
else if (resource == null && Message.Type.normal == type) {
// An occupant could be sending an invitation or declining an
// invitation
Element userInfo = packet.getChildElement(
"x",
"http://jabber.org/protocol/muc#user");
// Real real real UGLY TRICK!!! Will and MUST be solved when
// persistence will be added. Replace locking with transactions!
LocalMUCRoom room = (LocalMUCRoom) role.getChatRoom();
if (userInfo != null && userInfo.element("invite") != null) {
// An occupant is sending invitations
// Try to keep the list of extensions sent together with the
// message invitation. These extensions will be sent to the
// invitees.
List<Element> extensions = new ArrayList<Element>(packet
.getElement().elements());
extensions.remove(userInfo);
// Send invitations to invitees
for (Iterator it=userInfo.elementIterator("invite");it.hasNext();) {
Element info = (Element) it.next();
// Add the user as a member of the room if the room is
// members only
if (room.isMembersOnly()) {
room.lock.writeLock().lock();
try {
room.addMember(info.attributeValue("to"), null, role);
}
finally {
room.lock.writeLock().unlock();
}
}
// Send the invitation to the invitee
room.sendInvitation(new JID(info.attributeValue("to")),
info.elementTextTrim("reason"), role, extensions);
}
}
else if (userInfo != null
&& userInfo.element("decline") != null) {
// An occupant has declined an invitation
Element info = userInfo.element("decline");
room.sendInvitationRejection(new JID(info.attributeValue("to")),
info.elementTextTrim("reason"), packet.getFrom());
}
else {
sendErrorPacket(packet, PacketError.Condition.bad_request);
}
}
else {
sendErrorPacket(packet, PacketError.Condition.bad_request);
}
}
}
catch (ForbiddenException e) {
sendErrorPacket(packet, PacketError.Condition.forbidden);
}
catch (NotFoundException e) {
sendErrorPacket(packet, PacketError.Condition.recipient_unavailable);
}
catch (ConflictException e) {
sendErrorPacket(packet, PacketError.Condition.conflict);
}
}
}
}
}
public void process(IQ packet) {
// Ignore IQs of type ERROR or RESULT sent to a room
if (IQ.Type.error == packet.getType()) {
return;
}
lastPacketTime = System.currentTimeMillis();
JID recipient = packet.getTo();
String group = recipient.getNode();
if (group == null) {
// Ignore packets to the groupchat server
// In the future, we'll need to support TYPE_IQ queries to the server for MUC
Log.info(LocaleUtils.getLocalizedString("muc.error.not-supported") + " "
+ packet.toString());
}
else {
MUCRole role = roles.get(group);
if (role == null) {
// TODO: send error message to user (can't send packets to group you haven't
// joined)
}
else if (IQ.Type.result == packet.getType()) {
// Only process IQ result packet if it's a private packet sent to another
// room occupant
if (packet.getTo().getResource() != null) {
try {
// User is sending an IQ result packet to another room occupant
role.getChatRoom().sendPrivatePacket(packet, role);
}
catch (NotFoundException e) {
// Do nothing. No error will be sent to the sender of the IQ result packet
}
}
}
else {
// Check and reject conflicting packets with conflicting roles
// In other words, another user already has this nickname
if (!role.getUserAddress().equals(packet.getFrom())) {
sendErrorPacket(packet, PacketError.Condition.conflict);
}
else {
try {
Element query = packet.getElement().element("query");
if (query != null &&
"http://jabber.org/protocol/muc#owner".equals(query.getNamespaceURI())) {
role.getChatRoom().getIQOwnerHandler().handleIQ(packet, role);
}
else if (query != null &&
"http://jabber.org/protocol/muc#admin".equals(query.getNamespaceURI())) {
role.getChatRoom().getIQAdminHandler().handleIQ(packet, role);
}
else {
if (packet.getTo().getResource() != null) {
// User is sending an IQ packet to another room occupant
role.getChatRoom().sendPrivatePacket(packet, role);
}
else {
sendErrorPacket(packet, PacketError.Condition.bad_request);
}
}
}
catch (ForbiddenException e) {
sendErrorPacket(packet, PacketError.Condition.forbidden);
}
catch (NotFoundException e) {
sendErrorPacket(packet, PacketError.Condition.recipient_unavailable);
}
catch (ConflictException e) {
sendErrorPacket(packet, PacketError.Condition.conflict);
}
catch (NotAllowedException e) {
sendErrorPacket(packet, PacketError.Condition.not_allowed);
}
catch (Exception e) {
sendErrorPacket(packet, PacketError.Condition.internal_server_error);
Log.error(e);
}
}
}
}
}
public void process(Presence packet) {
// Ignore presences of type ERROR sent to a room
if (Presence.Type.error == packet.getType()) {
return;
}
lastPacketTime = System.currentTimeMillis();
JID recipient = packet.getTo();
String group = recipient.getNode();
if (group != null) {
MUCRole role = roles.get(group);
if (role == null) {
// If we're not already in a room, we either are joining it or it's not
// properly addressed and we drop it silently
if (recipient.getResource() != null
&& recipient.getResource().trim().length() > 0) {
if (packet.isAvailable()) {
try {
// Get or create the room
MUCRoom room = server.getChatRoom(group, packet.getFrom());
// User must support MUC in order to create a room
Element mucInfo = packet.getChildElement("x",
"http://jabber.org/protocol/muc");
HistoryRequest historyRequest = null;
String password = null;
// Check for password & requested history if client supports MUC
if (mucInfo != null) {
password = mucInfo.elementTextTrim("password");
if (mucInfo.element("history") != null) {
historyRequest = new HistoryRequest(mucInfo);
}
}
// The user joins the room
role = room.joinRoom(recipient.getResource().trim(),
password,
historyRequest,
this,
packet.createCopy());
// If the client that created the room is non-MUC compliant then
// unlock the room thus creating an "instant" room
if (mucInfo == null && room.isLocked() && !room.isManuallyLocked()) {
room.unlock(role);
}
}
catch (UnauthorizedException e) {
sendErrorPacket(packet, PacketError.Condition.not_authorized);
}
catch (ServiceUnavailableException e) {
sendErrorPacket(packet, PacketError.Condition.service_unavailable);
}
catch (UserAlreadyExistsException e) {
sendErrorPacket(packet, PacketError.Condition.conflict);
}
catch (RoomLockedException e) {
sendErrorPacket(packet, PacketError.Condition.recipient_unavailable);
}
catch (ForbiddenException e) {
sendErrorPacket(packet, PacketError.Condition.forbidden);
}
catch (RegistrationRequiredException e) {
sendErrorPacket(packet, PacketError.Condition.registration_required);
}
catch (ConflictException e) {
sendErrorPacket(packet, PacketError.Condition.conflict);
}
catch (NotAcceptableException e) {
sendErrorPacket(packet, PacketError.Condition.not_acceptable);
}
catch (NotAllowedException e) {
sendErrorPacket(packet, PacketError.Condition.not_allowed);
}
}
else {
// TODO: send error message to user (can't send presence to group you
// haven't joined)
}
}
else {
if (packet.isAvailable()) {
// A resource is required in order to join a room
sendErrorPacket(packet, PacketError.Condition.bad_request);
}
// TODO: send error message to user (can't send packets to group you haven't
// joined)
}
}
else {
// Check and reject conflicting packets with conflicting roles
// In other words, another user already has this nickname
if (!role.getUserAddress().equals(packet.getFrom())) {
sendErrorPacket(packet, PacketError.Condition.conflict);
}
else {
if (Presence.Type.unavailable == packet.getType()) {
try {
// TODO Consider that different nodes can be creating and processing this presence at the same time (when remote node went down)
removeRole(group);
role.getChatRoom().leaveRoom(role);
}
catch (Exception e) {
Log.error(e);
}
}
else {
try {
String resource = (recipient.getResource() == null
|| recipient.getResource().trim().length() == 0 ? null
: recipient.getResource().trim());
if (resource == null
|| role.getNickname().equalsIgnoreCase(resource)) {
// Occupant has changed his availability status
role.getChatRoom().presenceUpdated(role, packet);
}
else {
// Occupant has changed his nickname. Send two presences
// to each room occupant
// Check if occupants are allowed to change their nicknames
if (!role.getChatRoom().canChangeNickname()) {
sendErrorPacket(packet, PacketError.Condition.not_acceptable);
}
// Answer a conflic error if the new nickname is taken
else if (role.getChatRoom().hasOccupant(resource)) {
sendErrorPacket(packet, PacketError.Condition.conflict);
}
else {
// Send "unavailable" presence for the old nickname
Presence presence = role.getPresence().createCopy();
// Switch the presence to OFFLINE
presence.setType(Presence.Type.unavailable);
presence.setStatus(null);
// Add the new nickname and status 303 as properties
Element frag = presence.getChildElement("x",
"http://jabber.org/protocol/muc#user");
frag.element("item").addAttribute("nick", resource);
frag.addElement("status").addAttribute("code", "303");
role.getChatRoom().send(presence);
// Send availability presence for the new nickname
String oldNick = role.getNickname();
role.getChatRoom().nicknameChanged(role, packet, oldNick, resource);
}
}
}
catch (Exception e) {
Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
}
}
}
}
}
}
}
|
package com.github.finder;
public class Main{
public Main(String[] arguments){
}
public static void main(String[] args){
new Main(args);
}
private Args parseArguments(String[] arguments){
Args args = new Args();
try {
CmdLineParser parser = new CmdLineParser(args);
parser.parseArgument(arguments);
} catch (CmdLineException e) {
}
return args;
}
}
|
package nu.yona.app.ui.frinends;
import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersAdapter;
import java.util.List;
import nu.yona.app.R;
import nu.yona.app.api.model.DayActivity;
import nu.yona.app.enums.ChartTypeEnum;
import nu.yona.app.ui.StickyHeaderHolder;
import nu.yona.app.ui.YonaActivity;
public class TimelineStickyAdapter extends RecyclerView.Adapter<TimelineHolder> implements StickyRecyclerHeadersAdapter<StickyHeaderHolder>
{
private List<DayActivity> dayActivityList;
private final View.OnClickListener listener;
private Context mContext;
/**
* Instantiates a new Per day sticky adapter.
*
* @param chartItem the chart item
* @param listener the listener
*/
public TimelineStickyAdapter(List<DayActivity> chartItem, View.OnClickListener listener)
{
this.dayActivityList = chartItem;
this.listener = listener;
}
@Override
public TimelineHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
mContext = parent.getContext();
View childView = null;
switch (ChartTypeEnum.getChartTypeEnum(viewType))
{
case NOGO_CONTROL:
childView = LayoutInflater.from(parent.getContext()).inflate(R.layout.timeline_nogo_layout, parent, false);
break;
case TIME_BUCKET_CONTROL:
childView = LayoutInflater.from(parent.getContext()).inflate(R.layout.timeline_timebucket_layout, parent, false);
break;
case TIME_FRAME_CONTROL:
childView = LayoutInflater.from(parent.getContext()).inflate(R.layout.timeline_timeframe_layout, parent, false);
break;
case TITLE:
childView = LayoutInflater.from(parent.getContext()).inflate(R.layout.header_timeline, parent, false);
break;
case LINE:
childView = LayoutInflater.from(parent.getContext()).inflate(R.layout.horizontal_line_view, parent, false);
break;
default:
break;
}
return new TimelineHolder(childView, listener, ChartTypeEnum.getChartTypeEnum(viewType));
}
@Override
public void onBindViewHolder(final TimelineHolder holder, int position)
{
DayActivity dayActivity = (DayActivity) getItem(position);
holder.getView().setTag(dayActivity);
setUpTimeLineViewHolderWithDayActivity(holder, dayActivity);
}
private void setUpTimeLineViewHolderWithDayActivity(TimelineHolder holder, DayActivity dayActivity)
{
switch (dayActivity.getChartTypeEnum())
{
case TIME_FRAME_CONTROL:
setUpTimeFrameControlHolderView(dayActivity, holder);
break;
case TIME_BUCKET_CONTROL:
setUpTimeBucketControlHolderView(dayActivity, holder);
break;
case SPREAD_CONTROL:
break;
case NOGO_CONTROL:
setUpNoGoHolderView(dayActivity, holder);
break;
case TITLE:
holder.getmHeaderCategoryTypeGoal().setText(dayActivity.getYonaGoal().getActivityCategoryName());
default:
break;
}
}
private void setUpTimeFrameControlHolderView(DayActivity dayActivity, TimelineHolder holder)
{
holder.getmTimeFrameGraph().chartValuePre(dayActivity.getTimeZoneSpread());
updateProfileImage(holder, dayActivity);
}
private void setUpTimeBucketControlHolderView(DayActivity dayActivity, TimelineHolder holder)
{
holder.getmTimebucketGraph().graphArguments(dayActivity.getTotalMinutesBeyondGoal(),
(int) dayActivity.getYonaGoal().getMaxDurationMinutes(), dayActivity.getTotalActivityDurationMinutes());
updateProfileImage(holder, dayActivity);
}
private void setUpNoGoHolderView(DayActivity dayActivity, TimelineHolder holder)
{
if (dayActivity.getGoalAccomplished())
{
holder.getmNogoImage().setImageResource(R.drawable.adult_happy);
}
else
{
holder.getmNogoImage().setImageResource(R.drawable.adult_sad);
}
holder.getmTxtNogo().setText(dayActivity.getYonaGoal().getNickName());
holder.getmTxtNogoTime().setText(mContext.getString(R.string.nogogoalbeyond, String.valueOf(dayActivity.getTotalMinutesBeyondGoal())));
}
private void updateProfileImage(TimelineHolder holder, DayActivity dayActivity)
{
holder.getProfileImageTxt().setVisibility(View.VISIBLE);
holder.getProfileImageTxt().setText(dayActivity.getYonaGoal().getNickName().substring(0, 1).toUpperCase());
if (dayActivity.getLinks().getYonaUser() != null)
{
holder.getProfileImageTxt().setBackground(ContextCompat.getDrawable(YonaActivity.getActivity(), R.drawable.bg_small_friend_round));
}
else
{
holder.getProfileImageTxt().setBackground(ContextCompat.getDrawable(YonaActivity.getActivity(), R.drawable.bg_small_self_round));
}
}
@Override
public int getItemViewType(int position)
{
return dayActivityList.get(position).getChartTypeEnum().getId();
}
/**
* Gets item.
*
* @param position the position
* @return the item
*/
public Object getItem(int position)
{
return dayActivityList.get(position);
}
@Override
public StickyHeaderHolder onCreateHeaderViewHolder(ViewGroup parent)
{
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.message_header_layout, parent, false);
return new StickyHeaderHolder(view)
{
};
}
@Override
public long getHeaderId(int position)
{
return dayActivityList.get(position).getStickyHeaderId();
}
@Override
public void onBindHeaderViewHolder(StickyHeaderHolder holder, int position)
{
Object yonaObject = getItem(position);
if (yonaObject != null)
{
holder.getHeaderText().setText(((DayActivity) yonaObject).getStickyTitle());
}
}
@Override
public int getItemCount()
{
return dayActivityList.size();
}
/**
* Notify data set change.
*
* @param dayActivities the yona messages
*/
public void notifyDataSetChange(final List<DayActivity> dayActivities)
{
this.dayActivityList = dayActivities;
notifyDataSetChanged();
}
/**
* Clear.
*/
public void clear()
{
while (getItemCount() > 0)
{
remove((DayActivity) getItem(0));
}
}
/**
* Remove.
*
* @param item the item
*/
public void remove(DayActivity item)
{
int position = dayActivityList.indexOf(item);
if (position > -1)
{
dayActivityList.remove(position);
notifyItemRemoved(position);
}
}
}
|
package org.helioviewer.gl3d.view;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import javax.media.opengl.GL;
import org.helioviewer.base.logging.Log;
import org.helioviewer.gl3d.GL3DKeyController;
import org.helioviewer.gl3d.GL3DKeyController.GL3DKeyListener;
import org.helioviewer.gl3d.camera.GL3DCamera;
import org.helioviewer.gl3d.camera.GL3DCameraListener;
import org.helioviewer.gl3d.changeevent.CameraChangeChangedReason;
import org.helioviewer.gl3d.scenegraph.GL3DState;
import org.helioviewer.viewmodel.changeevent.ChangeEvent;
import org.helioviewer.viewmodel.view.RegionView;
import org.helioviewer.viewmodel.view.SubimageDataView;
import org.helioviewer.viewmodel.view.View;
import org.helioviewer.viewmodel.view.jp2view.JHVJPXView;
import org.helioviewer.viewmodel.view.opengl.GLView;
/**
* The {@link GL3DCameraView} is responsible for applying the currently active
* {@link GL3DCamera}. Since applying the view space transformation is the first
* transformation to be applied in a scene, this view must be executed before
* the {@link GL3DSceneGraphView}.
*
* @author Simon Spoerri (simon.spoerri@fhnw.ch)
*
*/
public class GL3DCameraView extends AbstractGL3DView implements GL3DView, GL3DCameraListener {
private GL3DCamera camera;
private List<GL3DCameraListener> listeners = new ArrayList<GL3DCameraListener>();
public GL3DCameraView() {
// Register short keys for changing the interaction
GL3DKeyController.getInstance().addListener(new GL3DKeyListener() {
public void keyHit(KeyEvent e) {
camera.setCurrentInteraction(camera.getPanInteraction());
}
}, KeyEvent.VK_P);
GL3DKeyController.getInstance().addListener(new GL3DKeyListener() {
public void keyHit(KeyEvent e) {
camera.setCurrentInteraction(camera.getRotateInteraction());
}
}, KeyEvent.VK_R);
GL3DKeyController.getInstance().addListener(new GL3DKeyListener() {
public void keyHit(KeyEvent e) {
camera.setCurrentInteraction(camera.getZoomInteraction());
}
}, KeyEvent.VK_Z);
// Center Image when pressing alt+c
GL3DKeyController.getInstance().addListener(new GL3DKeyListener() {
public void keyHit(KeyEvent e) {
if (e.isAltDown()) {
camera.setPanning(0, 0);
camera.updateCameraTransformation();
}
}
}, KeyEvent.VK_C);
}
public void render3D(GL3DState state) {
GL gl = state.gl;
if (this.camera != null) {
state.setActiveChamera(this.camera);
if (this.getView() != null) {
this.renderChild(gl);
}
}
}
protected void setViewSpecificImplementation(View newView, ChangeEvent changeEvent) {
}
public GL3DCamera getCurrentCamera() {
return this.camera;
}
public void setCurrentCamera(GL3DCamera cam) {
if (this.camera != null) {
this.camera.removeCameraListener(this);
this.camera.deactivate();
}
cam.activate(this.camera);
this.camera = cam;
this.camera.addCameraListener(this);
Log.debug("GL3DCameraView: Set Current Camera to " + this.camera);
notifyViewListeners(new ChangeEvent(new CameraChangeChangedReason(this, this.camera)));
}
public void cameraMoved(GL3DCamera camera) {
for (GL3DCameraListener l : this.listeners) {
l.cameraMoved(camera);
}
}
public void cameraMoving(GL3DCamera camera) {
for (GL3DCameraListener l : this.listeners) {
l.cameraMoving(camera);
}
}
public void addCameraListener(GL3DCameraListener listener) {
this.listeners.add(listener);
}
public void removeCameraListener(GL3DCameraListener listener) {
this.listeners.remove(listener);
}
protected void renderChild(GL gl) {
if (view instanceof GLView) {
((GLView) view).renderGL(gl, false);
} else {
textureHelper.renderImageDataToScreen(gl, view.getAdapter(RegionView.class).getRegion(), view.getAdapter(SubimageDataView.class).getSubimageData(), view.getAdapter(JHVJPXView.class));
}
}
}
|
package edu.berkeley.bid;
import java.io.*;
import java.util.zip.*;
public final class UTILS {
private UTILS() {}
static {
System.loadLibrary("bidmatmkl");
}
public static native int getnumthreads( );
public static native void setnumthreads( int n );
public static native void memcpybi( int n, byte [] a, long startA, int [] b, long startB );
public static native void memcpybf( int n, byte [] a, long startA, float [] b, long startB );
public static native void memcpybd( int n, byte [] a, long startA, double [] b, long startB );
public static native void memcpyib( int n, int [] a, long startA, byte [] b, long startB );
public static native void memcpyfb( int n, float [] a, long startA, byte [] b, long startB );
public static native void memcpydb( int n, double [] a, long startA, byte [] b, long startB );
public static OutputStream _getOutputStream(String fname, int compressionLevel) throws IOException {
FileOutputStream fout = new FileOutputStream(fname);
switch (compressionLevel) {
case 0: return new GZIPOutputStream(fout, 1024*1024){{def.setLevel(0);}};
case 1: return new GZIPOutputStream(fout, 1024*1024){{def.setLevel(1);}};
case 2: return new GZIPOutputStream(fout, 1024*1024){{def.setLevel(2);}};
case 3: return new GZIPOutputStream(fout, 1024*1024){{def.setLevel(3);}};
case 4: return new GZIPOutputStream(fout, 1024*1024){{def.setLevel(4);}};
case 5: return new GZIPOutputStream(fout, 1024*1024){{def.setLevel(5);}};
case 6: return new GZIPOutputStream(fout, 1024*1024){{def.setLevel(6);}};
case 7: return new GZIPOutputStream(fout, 1024*1024){{def.setLevel(7);}};
case 8: return new GZIPOutputStream(fout, 1024*1024){{def.setLevel(8);}};
case 9: return new GZIPOutputStream(fout, 1024*1024){{def.setLevel(9);}};
default: throw new RuntimeException("Unsupported compression level "+compressionLevel);
}
}
}
|
package org.estgroup.phphub.ui.view;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.kennyc.view.MultiStateView;
import org.estgroup.phphub.R;
import org.estgroup.phphub.common.Constant;
import org.estgroup.phphub.common.base.BaseActivity;
import butterknife.Bind;
public class ReplyListActivity extends BaseActivity {
private static final String TOPIC_ID = "topic_id";
private static final String TOPIC_REPLY_URL = "reply_url";
@Bind(R.id.multiStateView)
MultiStateView multiStateView;
@Bind(R.id.wv_content)
WebView contentView;
int topicId;
String replyUrl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.replyUrl = getIntent().getStringExtra(TOPIC_REPLY_URL);
this.topicId = getIntent().getIntExtra(TOPIC_ID, 0);
contentView.loadUrl(replyUrl, getHttpHeaderAuth());
contentView.getSettings().setJavaScriptEnabled(true);
contentView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains(Constant.DEEP_LINK_PREFIX)) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
startActivity(Intent.createChooser(intent, ""));
}
} else {
navigator.navigateToWebView(ReplyListActivity.this, url);
}
return true;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
multiStateView.setViewState(MultiStateView.VIEW_STATE_LOADING);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
multiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu_publish, menu);
if (getIntent().getIntExtra(TOPIC_ID, 0) == 0) {
menu.findItem(R.id.action_publish).setVisible(false);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_publish:
navigator.navigateToReplyTopic(this, topicId, replyUrl);
break;
}
return super.onOptionsItemSelected(item);
}
public static Intent getCallingIntent(Context context, String replyUrl) {
Intent callingIntent = new Intent(context, ReplyListActivity.class);
callingIntent.putExtra(TOPIC_ID, 0);
callingIntent.putExtra(TOPIC_REPLY_URL, replyUrl);
return callingIntent;
}
public static Intent getCallingIntent(Context context, int topicId, String replyUrl) {
Intent callingIntent = new Intent(context, ReplyListActivity.class);
callingIntent.putExtra(TOPIC_ID, topicId);
callingIntent.putExtra(TOPIC_REPLY_URL, replyUrl);
return callingIntent;
}
@Override
protected int getLayoutResId() {
return R.layout.reply_list;
}
@Override
protected CharSequence getTitleName() {
return getString(R.string.reply_list);
}
}
|
package laas.openrobots.ontology.connectors;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import laas.openrobots.ontology.exceptions.OntologyConnectorException;
import laas.openrobots.ontology.helpers.Helpers;
import laas.openrobots.ontology.helpers.Logger;
import laas.openrobots.ontology.helpers.Pair;
import laas.openrobots.ontology.helpers.VerboseLevel;
import laas.openrobots.ontology.modules.events.EventModule;
import laas.openrobots.ontology.modules.events.IEventConsumer;
import laas.openrobots.ontology.modules.events.IWatcher;
import laas.openrobots.ontology.modules.events.OroEvent;
import laas.openrobots.ontology.modules.events.IWatcher.EventType;
import laas.openrobots.ontology.service.IService;
/** Implements a socket interface to {@code oro-server} RPC methods.<br/>
* <br/>
* The protocol is ASCII-based (ie, you can connect to the server with <em>telnet</em> to test everything).<br/>
* <br/>
*
* <h2>Requests</h2>
* The general structure of a request to the server is:
* <pre>
* method_name
* [parameter1]
* [parameter2]
* [...]
* #end#
* </pre>
*
* <em>parameters</em> can be either:
* <ul>
* <li>strings (quotes are not necessary, and are removed if present),</li>
* <li>integers (strings made only of numbers),</li>
* <li>floats (strings made of numbers with a dot somewhere),</li>
* <li>booleans (strings equal to <em>true</em> or <em>false</em>, case insensitive),</li>
* <li>(ordered) lists or (unordered) sets of strings, with this structure: <em>[val1, val2, ..., valn]</em>. If strings contain commas, they must be (single or doubled) quoted.</li>
* <li>map of (key, value) pairs of strings, with this structure: <em>{key1:val1, key2:val2, ...}</em>. If strings (be keys or values) contain commas, they must be (single or doubled) quoted.</li>
* </ul>
* Please note that collections of collections are not supported.<br/>
*
* <br/>
*
* <h2>Responses</h2>
* The server response has this structure if the request succeeded:
* <pre>
* ok
* [return_value]
* #end#
* </pre>
* <br/>
* And this structure in case of failure:
* <pre>
* error
* [name of the exception, if available]
* [human-readable error message - that *may* spend over several lines]
* #end#
* </pre>
*
* <h2>Events</h2>
* If an event has been registered (cf {@link EventModule#registerEvent(String, String, Set, IEventConsumer)}),
* the server may send the following type of message when the event it triggered.
* <pre>
* event
* [event_id]
* [event_return_value]
* #end#
* </pre>
* The {@code event_id} will match the id returned at event registration. The
* return values depend on the type of event. Details are provided on the {@link EventType}
* page.
*
* <h2>Some examples</h2>
* You can test this example by directly connecting to the server with a tool like <em>telnet</em>.<br/>
* <br/>
*
* <h3>Retrieving a human-friendly list of available methods on the server</h3>
* <pre>
* > help
* </pre>
*
* <h3>Retrieving a machine-friendly list of available methods on the server</h3>
* <pre>
* > listMethods
* > #end#
* </pre>
*
* <h3>Adding facts to the knowledge base</h3>
* <pre>
* > add
* > [human rdf:type Human, human rdfs:label "Ramses", myself sees Ramses]
* > #end#
* </pre>
*
* <h3>Retrieving facts</h3>
* This command should return the list of humans the robot currently sees.
* <pre>
* > find
* > [?humans rdf:type Human, myself sees ?humans]
* > #end#
* </pre>
*
* <h3>Registering an event</h3>
* The example below registers an trigger upon new instances of humans.
* <pre>
* > registerEvent
* > new_instance //event type
* > on_true //triggering type
* > [Human]
* > #end#
* </pre>
*
* The server answer ok, with a unique ID bound to this so-called "event watcher"
* <pre>
* > ok
* > 4565-4587995-112355-21446
* > #end#
* </pre>
*
* If a new human appears in the ontology, the server send this kind of notification
* <pre>
* > event
* > 4565-4587995-112355-21446
* > [ramses]
* > #end#
* </pre>
*
* Please refer to {@link IWatcher.EventType} page for the list of event types and
* {@link IWatcher.TriggeringType} for the list of ways the trigger an
* event.
*
* @since 0.6.0
* @author slemaign
*
*/
public class SocketConnector implements IConnector, Runnable {
/** Maximum time (in seconds) the server should keep alive a socket when inactive.
*
* This value may be configured by the option keep_alive_socket_duration in the server configuration file.
*/
int KEEP_ALIVE_SOCKET_DURATION;
public static final String DEFAULT_PORT = "6969";
public static final String MESSAGE_TERMINATOR = "#end#";
private Charset charset = Charset.forName("UTF-8");
int port;
ServerSocketChannel server = null;
HashMap<String, IService> registredServices;
private volatile boolean keepOn = true;
/**
* Inner class that is forked at incoming connections.
* @author slemaign
*
*/
public class ClientWorker implements Runnable, IEventConsumer {
private SocketChannel client;
private ByteBuffer buffer = ByteBuffer.allocate(4096);
private String remainsOfMyBuffer = "";
private Selector selector;
private SelectionKey key;
private String name;
private boolean keepOnThisWorker = true;
volatile private boolean incomingEvent = false;
private List<Pair<UUID, OroEvent>> eventsQueue;
ClientWorker(SocketChannel client) {
try {
selector = Selector.open();
} catch (IOException e1) {
Logger.log("SocketConnector error: impossible to get a selector" +
"for a socket! Better to quit now :-/\n", VerboseLevel.FATAL_ERROR);
Logger.log("Exception: " + e1.getLocalizedMessage() + "\n", VerboseLevel.DEBUG);
System.exit(1);
}
this.client = client;
//Set the socket in non-blocking mode
try {
client.configureBlocking(false);
} catch (IOException e) {
Logger.log("SocketConnector error: impossible to set the socket " +
"in non-blocking mode! I kill it now.\n", VerboseLevel.SERIOUS_ERROR);
Logger.log("Exception: " + e.getLocalizedMessage() + "\n", VerboseLevel.DEBUG);
return;
}
try {
key = client.register(selector, SelectionKey.OP_WRITE | SelectionKey.OP_READ);
} catch (ClosedChannelException e) {
Logger.log("SocketConnector error: the socket has been closed" +
"before any operation! I kill it now.\n", VerboseLevel.SERIOUS_ERROR);
Logger.log("Exception: " + e.getLocalizedMessage() + "\n", VerboseLevel.DEBUG);
return;
}
this.name = "ClientWorker " + client.toString();
eventsQueue = new ArrayList<Pair<UUID, OroEvent>>();
}
public String getName(){
return name;
}
public void consumeEvent(UUID watcherId, OroEvent e) {
incomingEvent = true;
synchronized (this) {
eventsQueue.add(new Pair<UUID, OroEvent>(watcherId, e));
}
}
public void run() {
List<String> req = null;
long timeLastActivity = System.currentTimeMillis();
while(keepOn && keepOnThisWorker){
try {
Thread.sleep(20);
} catch (InterruptedException e) {}
if (System.currentTimeMillis() - timeLastActivity > (KEEP_ALIVE_SOCKET_DURATION * 1000)) {
Logger.log("Connection " + getName() + " has been closed because it was inactive since " + KEEP_ALIVE_SOCKET_DURATION + " sec. Please use the \"close\" method in your clients to close properly the socket.\n", VerboseLevel.WARNING);
keepOnThisWorker = false;
break;
}
try{
req = null;
buffer.clear();
int count = client.read( buffer );
if (count > 0) {
buffer.flip();
req = parseBuffer(buffer);
}
} catch (IOException e) {
Logger.log("Read failed on one of the opened socket (" + getName() + "). Killing it.\n", VerboseLevel.SERIOUS_ERROR);
keepOnThisWorker = false;
break;
}
if (req != null)
{
timeLastActivity = System.currentTimeMillis();
//Execute the request
String res = handleRequest(req);
Logger.log("<< Send response: " + res + "\n", VerboseLevel.DEBUG);
//Send data back to client
try {
client.write(charset.encode(res + "\n"));
} catch (IOException e) {
Logger.log("SocketConnector error: impossible to" +
"write to a socket! I kill it now.\n", VerboseLevel.SERIOUS_ERROR);
Logger.log("Exception: " + e.getLocalizedMessage() + "\n", VerboseLevel.DEBUG);
return;
}
}
if (incomingEvent) {
incomingEvent = false;
List<Pair<UUID, OroEvent>> tmpEvtsQueue = new ArrayList<Pair<UUID,OroEvent>>(eventsQueue);
Iterator<Pair<UUID, OroEvent>> it = tmpEvtsQueue.iterator();
while(it.hasNext()) {
Pair<UUID, OroEvent> evt = it.next();
OroEvent e = evt.getRight();
try {
String evtMsg = "event\n" +
evt.getLeft() + "\n" +
(e.getEventContext() != "" ?
e.getEventContext() + "\n":
"") +
MESSAGE_TERMINATOR + "\n";
client.write(charset.encode(evtMsg));
} catch (IOException e1) {
Logger.log("SocketConnector error: impossible to" +
"write to a socket! I kill it now.\n", VerboseLevel.SERIOUS_ERROR);
Logger.log("Exception: " + e1.getLocalizedMessage() + "\n", VerboseLevel.DEBUG);
return;
}
eventsQueue.remove(evt);
Logger.log("Event " + evt.getLeft() + " notified.\n", VerboseLevel.VERBOSE);
}
}
}
}
private List<String> parseBuffer(ByteBuffer buffer) {
String req = remainsOfMyBuffer + charset.decode(buffer).toString();
req = req.replaceAll("\r\n|\r", "\n");
List<String> res = new ArrayList<String>();
//Special case for the command "help": we don't require to enter
//the message terminaison string.
if (req.startsWith("help")) {
res.add("help");
remainsOfMyBuffer = req.substring(5); //len("help\n") = 5
return res;
}
int i = req.indexOf(MESSAGE_TERMINATOR);
if (i >= 0) {
String rawReq = req.substring(0, i);
res = Arrays.asList(rawReq.split("\n"));
remainsOfMyBuffer = req.substring(i + MESSAGE_TERMINATOR.length() + 1);
return res;
}
remainsOfMyBuffer = req;
return null;
}
public String handleRequest(List<String> list) {
boolean methodFound = false;
String result = "error\n\n";
String queryName = list.get(0);
Logger.log(">> Got incoming request: " + queryName + " with " + (list.size() - 1) + " parameters\n", VerboseLevel.DEBUG);
if (queryName.equalsIgnoreCase("close")){
Logger.log("Closing communication with client " + getName() + ".\n");
keepOnThisWorker = false;
return "Closing now!";
}
else
{
for (String key : registredServices.keySet()){
Method m = registredServices.get(key).getMethod();
if (registredServices.get(key).getName().equalsIgnoreCase(queryName) && m.getParameterTypes().length == list.size() - 1)
{
methodFound = true;
boolean invokationDone = false;
try {
Object o = registredServices.get(key).getObj();
result = "ok\n";
Object[] args = new Object[m.getParameterTypes().length];
if ( list.size() != 1 &&
m.getParameterTypes().length == 0)
{
Logger.log("Error while executing the request: method \""+ queryName + "\" expects no parameters.\n", VerboseLevel.ERROR);
result = "error\n" +
"NotImplementedException\n" +
"Method " + queryName + " expects no parameters.";
return result + "\n" + MESSAGE_TERMINATOR;
}
int i = 0;
int shiftSpecialCases = 0;
if (list.size() > 1) {
for (Class<?> param : m.getParameterTypes()) {
try {
//TODO: This is hackish.
if (param.equals(IEventConsumer.class)) {
args[i] = this;
shiftSpecialCases ++;
}
else {
Object ob = Helpers.deserialize(list.get(i + 1), param);
Logger.log("Parameter: " + ob.toString() + "\n", VerboseLevel.DEBUG);
args[i + shiftSpecialCases] = ob;
i++;
}
} catch (IndexOutOfBoundsException e)
{
Logger.log("Error while executing the request: missing parameters for method \""+ queryName + "\".\n", VerboseLevel.ERROR);
result = "error\n" +
"NotImplementedException\n" +
"missing parameters for method " + queryName + ".";
return result + "\n" + MESSAGE_TERMINATOR;
}
}
if (i != list.size() - 1) {
Logger.log("Error while executing the request: too many parameters provided for " +
"method \""+ queryName + "\" (" + i + " were expected).\n", VerboseLevel.ERROR);
result = "error\n" +
"NotImplementedException\n" +
"Too many parameters provided for " +
"method \""+ queryName + "\" (" + i + " were expected).";
return result + "\n" + MESSAGE_TERMINATOR;
}
}
if (m.getReturnType() == void.class)
{
if (m.getParameterTypes().length == 0) m.invoke(o); else m.invoke(o, args);
invokationDone = true;
}
if ( m.getReturnType() == String.class ||
m.getReturnType() == Double.class ||
m.getReturnType() == double.class ||
m.getReturnType() == Integer.class ||
m.getReturnType() == int.class ||
m.getReturnType() == Boolean.class ||
m.getReturnType() == boolean.class ||
m.getReturnType() == Float.class ||
m.getReturnType() == float.class)
{
result += (m.getParameterTypes().length == 0) ? m.invoke(o).toString() : m.invoke(o, args).toString();
invokationDone = true;
} else {
List<Class<?>> rTypes = new ArrayList<Class<?>>();
rTypes.add(m.getReturnType());
rTypes.addAll(Arrays.asList(m.getReturnType().getInterfaces()));
for (Class<?> rType : rTypes ) {
if (rType == Serializable.class) {
result += (m.getParameterTypes().length == 0) ? m.invoke(o).toString() : m.invoke(o, args).toString();
invokationDone = true;
break;
}
//TODO : Lot of cleaning to do here
if (rType == Map.class) {
result += Helpers.stringify(((Map<?, ?>)(((m.getParameterTypes().length == 0) ? m.invoke(o) : m.invoke(o, args)))));
invokationDone = true;
break;
}
if (rType == Set.class) {
result += Helpers.stringify(((Set<?>)(((m.getParameterTypes().length == 0) ? m.invoke(o) : m.invoke(o, args)))));
invokationDone = true;
break;
}
if (rType == List.class) {
result += Helpers.stringify(((List<?>)(((m.getParameterTypes().length == 0) ? m.invoke(o) : m.invoke(o, args)))));
invokationDone = true;
break;
}
}
}
if (!invokationDone) {
Logger.log("Error while executing the request: no way to serialize the return value of method '"+ queryName + "' (return type is " + m.getReturnType().getName() + ").\nPlease contact the maintainer :-)\n", VerboseLevel.SERIOUS_ERROR);
result ="error\n" +
"\n" +
"No way to serialize return value of method '" + queryName + "' (return type is " + m.getReturnType().getName() + ").";
}
} catch (IllegalArgumentException e) {
Logger.log("Error while executing the request '" + queryName + "': " + e.getClass().getName() + " -> " + e.getLocalizedMessage() + "\n", VerboseLevel.ERROR);
result = "error\n" +
e.getClass().getName() + "\n" +
e.getLocalizedMessage().replace("\"", "'");
} catch (ClassCastException e) {
Logger.log("Error while executing the request '" + queryName + "': " + e.getClass().getName() + " -> " + e.getLocalizedMessage() + "\n", VerboseLevel.ERROR);
result = "error\n" +
e.getClass().getName() + "\n" +
e.getLocalizedMessage().replace("\"", "'");
} catch (IllegalAccessException e) {
Logger.log("Error while executing the request '" + queryName + "': " + e.getClass().getName() + " -> " + e.getLocalizedMessage() + "\n", VerboseLevel.ERROR);
result = "error\n" +
e.getClass().getName() + "\n" +
e.getLocalizedMessage().replace("\"", "'");
} catch (InvocationTargetException e) {
Logger.log("Error while executing the request '" + queryName + "': " + e.getCause().getClass().getName() + " -> " + e.getCause().getLocalizedMessage() + "\n", VerboseLevel.ERROR);
result = "error\n" +
e.getCause().getClass().getName() + "\n" +
e.getCause().getLocalizedMessage().replace("\"", "'");
}
break;
}
}
if (!methodFound){
Logger.log("Error while executing the request: method \""+ queryName + "\" not implemented by the ontology server.\n", VerboseLevel.ERROR);
result = "error\n" +
"NotImplementedException\n" +
"Method " + queryName + " not implemented by the ontology server.";
}
return result + "\n" + MESSAGE_TERMINATOR;
}
}
}
public SocketConnector(
Properties params,
HashMap<String, IService> registredServices) {
port = Integer.parseInt(params.getProperty("port", DEFAULT_PORT)); //defaulted to port DEFAULT_PORT if no port provided in the configuration file.
KEEP_ALIVE_SOCKET_DURATION = Integer.parseInt(params.getProperty("keep_alive_socket_duration", "60")); //defaulted to 1 min if no duration is provided in the configuration file.
this.registredServices = registredServices;
}
@Override
public void finalizeConnector() throws OntologyConnectorException {
//Objects created in run method are finalized when
//program terminates and thread exits
if (server != null) {
try{
server.close();
} catch (IOException e) {
throw new OntologyConnectorException("Could not close the socket server!");
}
}
keepOn = false;
}
@Override
public void initializeConnector() throws OntologyConnectorException {
Thread t = new Thread(this, "Socket connector");
t.start();
}
@Override
public void run() {
try{
server = ServerSocketChannel.open();
server.socket().bind(new InetSocketAddress(port));
} catch (IOException e) {
Logger.log("Error while creating the server: could not listen on port " + port + ". Port busy?\n", VerboseLevel.FATAL_ERROR);
System.exit(-1);
}
Logger.log("Server started on port " + port + "\n", VerboseLevel.IMPORTANT);
while(keepOn){
ClientWorker w;
try{
w = new ClientWorker(server.accept());
Thread t = new Thread(w, w.getName());
t.start();
} catch (IOException e) {
if (!server.socket().isClosed()) {
Logger.log("Accept failed on port " + port + "\n", VerboseLevel.FATAL_ERROR);
System.exit(1);
}
}
}
}
@Override
public void refreshServiceList(
Map<String, IService> registredServices) {
// TODO Auto-generated method stub
}
}
|
package com.kuxhausen.huemore;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.DialogFragment;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import com.kuxhausen.huemore.network.GetBulbList;
import com.kuxhausen.huemore.persistence.DatabaseDefinitions;
import com.kuxhausen.huemore.persistence.DatabaseDefinitions.GroupColumns;
import com.kuxhausen.huemore.persistence.DatabaseDefinitions.InternalArguments;
import com.kuxhausen.huemore.persistence.DatabaseDefinitions.PreferencesKeys;
import com.kuxhausen.huemore.state.api.Bulb;
public class EditGroupDialogFragment extends DialogFragment implements
GetBulbList.OnBulbListReturnedListener {
ArrayList<String> bulbNameList;
ListView bulbsListView;
ArrayAdapter<String> rayAdapter;
EditText nameEditText;
Bulb[] bulbArray;
HashMap<String, Integer> nameToBulb;
Boolean[] preChecked;
String initialName;
private GodObject parrentActivity;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception.
try {
parrentActivity = (GodObject) activity;
} catch (ClassCastException e) {
}
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
bulbNameList = new ArrayList<String>();
nameToBulb = new HashMap<String, Integer>();
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View groupDialogView = inflater.inflate(R.layout.edit_group_dialog,
null);
bulbsListView = ((ListView) groupDialogView
.findViewById(R.id.listView1));
bulbsListView.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
rayAdapter = new ArrayAdapter<String>(this.getActivity(),
android.R.layout.simple_list_item_multiple_choice, bulbNameList);
bulbsListView.setAdapter(rayAdapter);
builder.setView(groupDialogView);
nameEditText = (EditText) groupDialogView.findViewById(R.id.editText1);
GetBulbList pushGroupMood = new GetBulbList(getActivity(), this,
parrentActivity);
pushGroupMood.execute();
Bundle args = this.getArguments();
if (args != null && args.containsKey(InternalArguments.GROUP_NAME)) {
String groupName = args.getString(InternalArguments.GROUP_NAME);
// Look up bulbs for that mood from database
String[] groupColumns = { GroupColumns.BULB };
String[] gWhereClause = { groupName };
Cursor groupCursor = this.getActivity().getContentResolver()
.query(DatabaseDefinitions.GroupColumns.GROUPBULBS_URI, // Use
// the
// default
// content
// URI
// for
// the
// provider.
groupColumns, // Return the note ID and title for
// each note.
GroupColumns.GROUP + "=?", // selection clause
gWhereClause, // selection clause args
null // Use the default sort order.
);
ArrayList<Integer> groupStates = new ArrayList<Integer>();
while (groupCursor.moveToNext()) {
groupStates.add(groupCursor.getInt(0));
}
Integer[] bulbS = groupStates.toArray(new Integer[groupStates
.size()]);
preChecked = new Boolean[50];
for (int checkedSpot : bulbS) {
preChecked[checkedSpot - 1] = true;// have to account by the off
// by one in bulb Numbers
}
nameEditText.setText(groupName);
initialName = groupName;
}
builder.setPositiveButton(R.string.accept,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
// if there was a previous mood we're editing, remove it
if (initialName != null) {
String groupSelect = GroupColumns.GROUP + "=?";
String[] groupArg = { initialName };
getActivity()
.getContentResolver()
.delete(DatabaseDefinitions.GroupColumns.GROUPBULBS_URI,
groupSelect, groupArg);
}
ArrayList<Integer> checkedBulbs = new ArrayList<Integer>();
SparseBooleanArray set = bulbsListView
.getCheckedItemPositions();
for (int i = 0; i < rayAdapter.getCount(); i++) {
if (set.get(i)) {
checkedBulbs.add(nameToBulb.get((rayAdapter
.getItem(i))));
}
}
String groupname = nameEditText.getText().toString();
for (int i = 0; i < checkedBulbs.size(); i++) {
// Defines an object to contain the new values to
// insert
ContentValues mNewValues = new ContentValues();
/*
* Sets the values of each column and inserts the
* word. The arguments to the "put" method are
* "column name" and "value"
*/
mNewValues.put(
DatabaseDefinitions.GroupColumns.GROUP,
groupname);
mNewValues.put(
DatabaseDefinitions.GroupColumns.BULB,
checkedBulbs.get(i));
mNewValues
.put(DatabaseDefinitions.GroupColumns.PRECEDENCE,
i);
getActivity().getContentResolver()
.insert(DatabaseDefinitions.GroupColumns.GROUPS_URI,
mNewValues // the values to insert
);
}
}
}).setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
@Override
public void onListReturned(Bulb[] result) {
if (result == null)
return;
bulbArray = result;
for (int i = 0; i < bulbArray.length; i++) {
// bulbNameList.add(bulb.name);
Bulb bulb = bulbArray[i];
bulb.number = i + 1;
nameToBulb.put(bulb.name, bulb.number);
rayAdapter.add(bulb.name);
if (preChecked != null && preChecked[i] != null
&& preChecked[i] == true)
bulbsListView.setItemChecked(i, true);
}
}
}
|
package laas.openrobots.ontology.connectors;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Map.Entry;
import laas.openrobots.ontology.Pair;
import laas.openrobots.ontology.exceptions.OntologyConnectorException;
public class SocketConnector implements IConnector, Runnable {
int port = 4444;
ServerSocket server = null;
HashMap<Pair<String, String>, Pair<Method, Object>> registredServices;
private volatile boolean keepOn = true;
/**
* Inner class that is forked at incoming connections.
* @author slemaign
*
*/
class ClientWorker implements Runnable {
private Socket client;
private String name;
private Boolean keepOnThisWorker = true;
ClientWorker(Socket client) {
this.client = client;
this.name = "ClientWorker " + client.toString();
}
public String getName(){
return name;
}
public void run(){
BufferedReader in = null;
PrintWriter out = null;
try{
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
} catch (IOException e) {
System.err.println("in or out failed");
System.exit(-1);
}
while(keepOn && keepOnThisWorker){
try{
ArrayList<String> request = new ArrayList<String>();
String line;
while (true) {
line = in.readLine().trim();
if (line.equalsIgnoreCase("#end#"))
break;
else request.add(line);
}
//Send data back to client
String res = handleRequest(request);
out.println(res);
} catch (IOException e) {
System.out.println("Read failed");
System.exit(-1);
}
}
}
public String handleRequest(ArrayList<String> request) {
boolean methodFound = false;
String result = "error\n\n";
String queryName = request.get(0);
System.out.println(" * Got a request: ");
for (String s : request)
System.out.println(s);
if (queryName.equalsIgnoreCase("close")){
System.out.println(" * Closing a communication with a client");
keepOnThisWorker = false;
return "Closing now!";
}
else
{
for (Pair<String,String> name : registredServices.keySet()){
Method m = registredServices.get(name).getLeft();
Object o = registredServices.get(name).getRight();
if (name.getLeft().equalsIgnoreCase(queryName) &&
(
(request.size() == 1) ?
m.getParameterTypes().length == 0 :
(m.getParameterTypes().length == request.size() - 1)
)
)
{
methodFound = true;
boolean invokationDone = false;
try {
result = "ok\n";
Object[] args = new Object[m.getParameterTypes().length];
int i = 0;
if (request.size() > 1) {
for (Class<?> param : m.getParameterTypes()) {
args[i] = deserialize(request.get(i + 1), param);
i++;
}
}
if (m.getReturnType() == void.class)
{
if (m.getParameterTypes().length == 0) m.invoke(o); else m.invoke(o, args);
invokationDone = true;
}
if (m.getReturnType() == String.class || m.getReturnType() == Double.class || m.getReturnType() == Integer.class || m.getReturnType() == Boolean.class || m.getReturnType() == Float.class) {
result += (m.getParameterTypes().length == 0) ? m.invoke(o).toString() : m.invoke(o, args).toString();
invokationDone = true;
} else {
List<Class<?>> rTypes = new ArrayList<Class<?>>();
rTypes.add(m.getReturnType());
rTypes.addAll(Arrays.asList(m.getReturnType().getInterfaces()));
for (Class<?> rType : rTypes ) {
if (rType == Serializable.class) {
result += (m.getParameterTypes().length == 0) ? m.invoke(o).toString() : m.invoke(o, args).toString();
invokationDone = true;
break;
}
if (rType == Map.class) {
result += mapToString(((Map<?, ?>)(((m.getParameterTypes().length == 0) ? m.invoke(o) : m.invoke(o, args)))));
invokationDone = true;
break;
}
if (rType == Set.class) {
result += setToString(((Set<?>)(((m.getParameterTypes().length == 0) ? m.invoke(o) : m.invoke(o, args)))));
invokationDone = true;
break;
}
if (rType == List.class) {
result += listToString(((List<?>)(((m.getParameterTypes().length == 0) ? m.invoke(o) : m.invoke(o, args)))));
invokationDone = true;
break;
}
}
}
if (!invokationDone) {
System.err.println("ERROR while executing the request: no way to serialize the return value of method '"+ queryName + "' (return type is " + m.getReturnType().getName() + ").");
result ="error\n" +
"\n" +
"No way to serialize return value of method '" + queryName + "' (return type is " + m.getReturnType().getName() + ").";
}
} catch (IllegalArgumentException e) {
System.err.println("ERROR while executing the request '" + queryName + "': " + e.getClass().getName() + " -> " + e.getLocalizedMessage());
result = "error\n" +
e.getClass().getName() + "\n" +
e.getLocalizedMessage().replace("\"", "'");
} catch (ClassCastException e) {
System.err.println("ERROR while executing the request '" + queryName + "': " + e.getClass().getName() + " -> " + e.getLocalizedMessage());
result = "error\n" +
e.getClass().getName() + "\n" +
e.getLocalizedMessage().replace("\"", "'");
} catch (IllegalAccessException e) {
System.err.println("ERROR while executing the request '" + queryName + "': " + e.getClass().getName() + " -> " + e.getLocalizedMessage());
result = "error\n" +
e.getClass().getName() + "\n" +
e.getLocalizedMessage().replace("\"", "'");
} catch (InvocationTargetException e) {
System.err.println("ERROR while executing the request '" + queryName + "': " + e.getCause().getClass().getName() + " -> " + e.getCause().getLocalizedMessage());
result = "error\n" +
e.getCause().getClass().getName() + "\n" +
e.getCause().getLocalizedMessage().replace("\"", "'");
}
break;
}
}
if (!methodFound){
System.err.println("ERROR while executing the request: method \""+ queryName + "\" (with " + (request.size() - 1) + " parameters) not implemented by the ontology server.");
result = "error\n" +
"NotImplementedException\n" +
"Method " + queryName + " (with " + (request.size() - 1) + " parameters) not implemented by the ontology server.";
}
return result + "\n#end#";
}
}
private <V> String listToString(List<V> list) {
String str = "[";
for (V v : list) {
str += v.toString() + ",";
}
str = str.substring(0, str.length() - 1) + "]";
return str;
}
private <V> String setToString(Set<V> list) {
String str = "[";
for (V v : list) {
str += v.toString() + ",";
}
str = str.substring(0, str.length() - 1) + "]";
return str;
}
private <K, V> String mapToString(Map<K, V> map) {
String str = "{";
for (Entry<K, V> es : map.entrySet()) {
str += es.getKey().toString() + ":" + es.getValue().toString() + ",";
}
str = str.substring(0, str.length() - 1) + "}";
return str;
}
private Object deserialize(String val, Class<?> type) {
//not typed because of Method::invoke requirements <- that's what I call a bad excuse
if (type == String.class)
return val;
if (type == Integer.class)
return Integer.parseInt(val);
if (type == Double.class)
return Double.parseDouble(val);
if (type == Boolean.class)
return Boolean.parseBoolean(val);
//assumes it's a list or map
boolean isValidMap = true;
boolean isValidSet = true;
//First, inspect the string to determine the type.
//If it starts and ends with {}, it's a map
//If it starts and ends with [], it's a set
if ( !val.substring(0, 1).equals("{") || !val.substring(val.length() - 1, val.length()).equals("}"))
isValidMap = false;
if ( !val.substring(0, 1).equals("[") || !val.substring(val.length() - 1, val.length()).equals("]"))
isValidSet = false;
val = val.substring(1, val.length() - 1); //remove the [] or {}
//checks that every elements of the map is made of tokens separated by :
for (String s : val.split(","))
if (!isValidMap || !s.contains(":"))
isValidMap = false;
assert(!(isValidMap && isValidSet));
//if the string looks like a map and a map is indeed expected...
if (isValidMap && Map.class.isAssignableFrom(type)){
Map<String, String> result = new HashMap<String, String>();
for (String s : val.split(","))
result.put(s.trim().split(":")[0], s.trim().split(":")[1]);
return result;
}
//if the string looks like a set and a set of a list is indeed expected...
else if (isValidSet && Set.class.isAssignableFrom(type)){
Set<String> result = new HashSet<String>();
for (String s : val.split(","))
result.add(s.trim());
return result;
}
//if the string looks like a set and a list of a list is indeed expected...
else if (isValidSet && List.class.isAssignableFrom(type)){
List<String> result = new ArrayList<String>();
for (String s : val.split(","))
result.add(s.trim());
return result;
}
else throw new IllegalArgumentException("Unable to deserialize the parameter of the query! (a " + type.getName() + " was expected, received \"" + val + "\")");
}
}
public SocketConnector(
Properties params,
HashMap<Pair<String, String>, Pair<Method, Object>> registredServices) {
port = Integer.parseInt(params.getProperty("port", "6969")); //defaulted to port 6969 if no port provided in the configuration file.
this.registredServices = registredServices;
}
@Override
public void finalizeConnector() throws OntologyConnectorException {
//Objects created in run method are finalized when
//program terminates and thread exits
keepOn = false;
if (server != null) {
try{
server.close();
} catch (IOException e) {
throw new OntologyConnectorException("[ERROR] Could not close the socket server!");
}
}
}
@Override
public void initializeConnector() throws OntologyConnectorException {
Thread t = new Thread(this, "Socket connector");
t.start();
}
@Override
public void refreshServiceList(
Map<Pair<String, String>, Pair<Method, Object>> registredServices) {
// TODO Auto-generated method stub
}
@Override
public void run() {
try{
server = new ServerSocket(port);
} catch (IOException e) {
System.err.println("[ERROR] Error while creating the server: could not listen on port " + port + ". Port busy?");
System.exit(-1);
}
System.out.println(" * Server started on port " + port);
while(keepOn){
ClientWorker w;
try{
w = new ClientWorker(server.accept());
Thread t = new Thread(w, w.getName());
t.start();
} catch (IOException e) {
System.err.println("Accept failed on port " + port);
System.exit(-1);
}
}
}
}
|
package fxlauncher;
import javax.xml.bind.annotation.XmlAttribute;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.Adler32;
public class LibraryFile {
@XmlAttribute
String file;
@XmlAttribute
Long checksum;
@XmlAttribute
Long size;
@XmlAttribute
OS os;
public boolean needsUpdate(Path cacheDir) {
Path path = cacheDir.resolve(file);
try {
return !Files.exists(path) || Files.size(path) != size || checksum(path) != checksum;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public LibraryFile() {
}
public LibraryFile(Path basepath, Path file) throws IOException {
this.file = basepath.relativize(file).toString().replace("\\", "/");
this.size = Files.size(file);
this.checksum = checksum(file);
String filename = file.getFileName().toString().toLowerCase();
Pattern osPattern = Pattern.compile(".+-(linux|win|mac)\\.[^.]+$");
Matcher osMatcher = osPattern.matcher(filename);
if (osMatcher.matches()) {
this.os = OS.valueOf(osMatcher.group(1));
} else {
if (filename.endsWith(".dll")) {
this.os = OS.win;
} else if (filename.endsWith(".dylib")) {
this.os = OS.mac;
} else if (filename.endsWith(".so")) {
this.os = OS.linux;
}
}
}
public boolean loadForCurrentPlatform() {
return os == null || os == OS.current;
}
public URL toURL(Path cacheDir) {
try {
return cacheDir.resolve(file).toFile().toURI().toURL();
} catch (MalformedURLException whaat) {
throw new RuntimeException(whaat);
}
}
private static long checksum(Path path) throws IOException {
try (InputStream input = Files.newInputStream(path)) {
Adler32 checksum = new Adler32();
byte[] buf = new byte[16384];
int read;
while ((read = input.read(buf)) > -1)
checksum.update(buf, 0, read);
return checksum.getValue();
}
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
LibraryFile that = (LibraryFile) o;
if (!file.equals(that.file)) return false;
if (!checksum.equals(that.checksum)) return false;
return size.equals(that.size);
}
public int hashCode() {
int result = file.hashCode();
result = 31 * result + checksum.hashCode();
result = 31 * result + size.hashCode();
return result;
}
}
|
package org.stepic.droid.ui.activities;
import android.content.Intent;
import android.content.pm.ShortcutInfo;
import android.content.pm.ShortcutManager;
import android.graphics.drawable.Icon;
import android.os.Bundle;
import android.support.annotation.NonNull;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import org.stepic.droid.R;
import org.stepic.droid.analytic.Analytic;
import org.stepic.droid.model.Profile;
import org.stepic.droid.notifications.StepicInstanceIdService;
import org.stepic.droid.util.AppConstants;
import org.stepic.droid.web.StepicProfileResponse;
import java.util.Arrays;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;
public class SplashActivity extends BackToExitActivityBase {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//This stops from opening again from the Splash screen when minimized
if (!isTaskRoot()) {
finish();
return;
}
threadPoolExecutor.execute(
new Runnable() {
@Override
public void run() {
try {
// make this "ping" request for updating refresh tokens and log out user, if it is revoked.
// also it should update the profile
StepicProfileResponse response = api.getUserProfile().execute().body();
if (response == null) {
return;
}
Profile profile = response.getProfile();
if (profile != null) {
sharedPreferenceHelper.storeProfile(profile);
}
} catch (Exception e) {
//ignore
//offline or access is revoked
}
}
}
);
defineShortcuts();
if (checkPlayServices() && !sharedPreferenceHelper.isGcmTokenOk()) {
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
StepicInstanceIdService.Companion.updateAnywhere(api, sharedPreferenceHelper, analytic); //FCM!
}
});
}
if (savedInstanceState == null) {
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
int numberOfLaunches = sharedPreferenceHelper.incrementNumberOfLaunches();
//after first increment it is 0, because of default value is -1.
if (numberOfLaunches <= 0) {
analytic.reportEvent(Analytic.System.FIRST_LAUNCH_AFTER_INSTALL);
}
if (numberOfLaunches < AppConstants.LAUNCHES_FOR_EXPERT_USER) {
analytic.reportEvent(Analytic.Interaction.START_SPLASH, numberOfLaunches + "");
} else {
analytic.reportEvent(Analytic.Interaction.START_SPLASH_EXPERT, numberOfLaunches + "");
}
}
});
}
if (sharedPreferenceHelper.isFirstTime() || !sharedPreferenceHelper.isScheduleAdded() || sharedPreferenceHelper.isNeedDropCoursesIn114()) {
//fix v11 bug:
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
if (sharedPreferenceHelper.isFirstTime()) {
databaseFacade.dropOnlyCourseTable(); //v11 bug, when slug was not cached. We can remove it, when all users will have v1.11 or above. (flavour problem)
sharedPreferenceHelper.afterFirstTime();
sharedPreferenceHelper.afterScheduleAdded();
sharedPreferenceHelper.afterNeedDropCoursesIn114();
defaultFilter.setNeedResolveLanguage(); //if user 1st time and v1.16 or more --> resolve language
} else if (!sharedPreferenceHelper.isScheduleAdded()) {
databaseFacade.dropOnlyCourseTable();
sharedPreferenceHelper.afterScheduleAdded();
sharedPreferenceHelper.afterNeedDropCoursesIn114();
} else if (sharedPreferenceHelper.isNeedDropCoursesIn114()) {
databaseFacade.dropOnlyCourseTable();
sharedPreferenceHelper.afterNeedDropCoursesIn114();
}
mainHandler.post(new Function0<Unit>() {
@Override
public Unit invoke() {
checkRemoteConfigs();
return Unit.INSTANCE;
}
});
}
});
} else {
checkRemoteConfigs();
}
}
private void defineShortcuts() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N_MR1) {
ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);
String findCoursesLabel = getString(R.string.find_courses_title);
Intent findCoursesIntent = screenManager.getShowFindCoursesIntent(getApplicationContext());
findCoursesIntent.setAction(AppConstants.OPEN_SHORTCUT_FIND_COURSES);
ShortcutInfo findCoursesShortcut = new ShortcutInfo.Builder(this, AppConstants.FIND_COURSES_SHORTCUT_ID)
.setShortLabel(findCoursesLabel)
.setLongLabel(findCoursesLabel)
.setIcon(Icon.createWithResource(this, R.mipmap.ic_search_icon_shortcut))
.setIntent(findCoursesIntent)
.build();
String profileLabel = getString(R.string.profile_title);
Intent mainFeedActivityIntent = screenManager.getMyCoursesIntent(getApplicationContext());
mainFeedActivityIntent.setAction(AppConstants.OPEN_SHORTCUT_PROFILE);
Intent profileIntent = screenManager.getProfileIntent(getApplicationContext());
profileIntent.setAction(AppConstants.OPEN_SHORTCUT_PROFILE);
ShortcutInfo profileShortcut = new ShortcutInfo.Builder(this, AppConstants.PROFILE_SHORTCUT_ID)
.setShortLabel(profileLabel)
.setLongLabel(profileLabel)
.setIcon(Icon.createWithResource(this, R.mipmap.ic_profile_shortcut))
.setIntents(new Intent[]{mainFeedActivityIntent, profileIntent})
.build();
shortcutManager.setDynamicShortcuts(Arrays.asList(findCoursesShortcut, profileShortcut));
}
}
private void checkRemoteConfigs() {
if (!isFinishing()) {
if (checkPlayServices()) {
firebaseRemoteConfig.fetch().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
analytic.reportEvent(Analytic.RemoteConfig.FETCHED_SUCCESSFUL);
firebaseRemoteConfig.activateFetched();
} else {
analytic.reportEvent(Analytic.RemoteConfig.FETCHED_UNSUCCESSFUL);
}
}
});
//do not wait fetch, because fail of it may be about 3 mins. User can't wait for it!
showNextScreen();
} else {
showNextScreen();
}
}
}
private void showNextScreen() {
if (!isFinishing()) {
if (sharedPreferenceHelper.getAuthResponseFromStore() != null) {
screenManager.showMainFeedFromSplash(SplashActivity.this);
} else {
screenManager.showLaunchFromSplash(this);
}
}
}
}
|
package ixa.kaflib;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.io.File;
import java.io.Reader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.io.IOException;
import org.jdom2.JDOMException;
import org.jdom2.Element;
public class KAFDocument {
public enum Layer {
text, terms, deps, chunks, entities, properties, categories, coreferences, opinions, relations, srl, constituency;
}
public class FileDesc {
public String author;
public String title;
public String filename;
public String filetype;
public Integer pages;
public String creationtime;
private FileDesc() {}
}
public class Public {
public String publicId;
public String uri;
private Public() {
}
}
public class LinguisticProcessor {
String name;
String timestamp;
String beginTimestamp;
String endTimestamp;
String version;
private LinguisticProcessor(String name) {
this.name = name;
}
/* Deprecated */
private LinguisticProcessor(String name, String timestamp, String version) {
this.name = name;
this.timestamp = timestamp;
this.version = version;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public boolean hasTimestamp() {
return this.timestamp != null;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public void setTimestamp() {
String timestamp = createTimestamp();
this.timestamp = timestamp;
}
public String getTimestamp() {
return this.timestamp;
}
public boolean hasBeginTimestamp() {
return beginTimestamp != null;
}
public void setBeginTimestamp(String timestamp) {
this.beginTimestamp = timestamp;
}
public void setBeginTimestamp() {
String timestamp = createTimestamp();
this.beginTimestamp = timestamp;
}
public String getBeginTimestamp() {
return beginTimestamp;
}
public boolean hasEndTimestamp() {
return endTimestamp != null;
}
public void setEndTimestamp(String timestamp) {
this.endTimestamp = timestamp;
}
public void setEndTimestamp() {
String timestamp = createTimestamp();
this.endTimestamp = timestamp;
}
public String getEndTimestamp() {
return endTimestamp;
}
public boolean hasVersion() {
return version != null;
}
public void setVersion(String version) {
this.version = version;
}
public String getVersion() {
return version;
}
}
/** Language identifier */
private String lang;
/** KAF version */
private String version;
/** Linguistic processors */
private Map<String, List<LinguisticProcessor>> lps;
private FileDesc fileDesc;
private Public _public;
/** Identifier manager */
private IdManager idManager;
/** Keeps all the annotations of the document */
private AnnotationContainer annotationContainer;
/** Creates an empty KAFDocument element */
public KAFDocument(String lang, String version) {
this.lang = lang;
this.version = version;
lps = new LinkedHashMap<String, List<LinguisticProcessor>>();
idManager = new IdManager();
annotationContainer = new AnnotationContainer();
}
/** Creates a new KAFDocument and loads the contents of the file passed as argument
* @param file an existing KAF file to be loaded into the library.
*/
public static KAFDocument createFromFile(File file) throws IOException {
KAFDocument kaf = null;
try {
kaf = ReadWriteManager.load(file);
} catch(JDOMException e) {
e.printStackTrace();
}
return kaf;
}
/** Creates a new KAFDocument loading the content read from the reader given on argument.
* @param stream Reader to read KAF content.
*/
public static KAFDocument createFromStream(Reader stream) throws IOException {
KAFDocument kaf = null;
try {
kaf = ReadWriteManager.load(stream);
} catch(JDOMException e) {
e.printStackTrace();
}
return kaf;
}
/** Sets the language of the processed document */
public void setLang(String lang) {
this.lang = lang;
}
/** Returns the language of the processed document */
public String getLang() {
return lang;
}
/** Sets the KAF version */
public void setVersion(String version) {
this.version = version;
}
/** Returns the KAF version */
public String getVersion() {
return version;
}
/** Adds a linguistic processor to the document header. The timestamp is added implicitly. */
public LinguisticProcessor addLinguisticProcessor(String layer, String name) {
String timestamp = createTimestamp();
LinguisticProcessor lp = new LinguisticProcessor(name);
//lp.setBeginTimestamp(timestamp); // no default timestamp
List<LinguisticProcessor> layerLps = lps.get(layer);
if (layerLps == null) {
layerLps = new ArrayList<LinguisticProcessor>();
lps.put(layer, layerLps);
}
layerLps.add(lp);
return lp;
}
public void addLinguisticProcessors(Map<String, List<LinguisticProcessor>> lps) {
for (Map.Entry<String, List<LinguisticProcessor>> entry : lps.entrySet()) {
List<LinguisticProcessor> layerLps = entry.getValue();
for (LinguisticProcessor lp : layerLps) {
LinguisticProcessor newLp = this.addLinguisticProcessor(entry.getKey(), lp.name);
if (lp.hasTimestamp()) newLp.setTimestamp(lp.getTimestamp());
if (lp.hasBeginTimestamp()) newLp.setBeginTimestamp(lp.getBeginTimestamp());
if (lp.hasEndTimestamp()) newLp.setEndTimestamp(lp.getEndTimestamp());
if (lp.hasVersion()) newLp.setVersion(lp.getVersion());
}
}
}
/** Returns a hash of linguistic processors from the document.
* Hash: layer => LP
*/
public Map<String, List<LinguisticProcessor>> getLinguisticProcessors() {
return lps;
}
/** Returns wether the given linguistic processor is already defined or not. Both name and version must be exactly the same. */
public boolean linguisticProcessorExists(String layer, String name, String version) {
List<LinguisticProcessor> layerLPs = lps.get(layer);
if (layerLPs == null) {
return false;
}
for (LinguisticProcessor lp : layerLPs) {
if (lp.version == null) {
return false;
}
else if (lp.name.equals(name) && lp.version.equals(version)) {
return true;
}
}
return false;
}
/** Returns wether the given linguistic processor is already defined or not. Both name and version must be exactly the same. */
public boolean linguisticProcessorExists(String layer, String name) {
List<LinguisticProcessor> layerLPs = lps.get(layer);
if (layerLPs == null) {
return false;
}
for (LinguisticProcessor lp : layerLPs) {
if (lp.version != null) {
return false;
}
else if (lp.name.equals(name)) {
return true;
}
}
return false;
}
public FileDesc createFileDesc() {
this.fileDesc = new FileDesc();
return this.fileDesc;
}
public FileDesc getFileDesc() {
return this.fileDesc;
}
public Public createPublic() {
this._public = new Public();
return this._public;
}
public Public getPublic() {
return this._public;
}
/** Returns the annotation container used by this object */
AnnotationContainer getAnnotationContainer() {
return annotationContainer;
}
/** Set raw text **/
public void setRawText(String rawText) {
annotationContainer.setRawText(rawText);
}
/** Creates a WF object to load an existing word form. It receives the ID as an argument. The WF is added to the document object.
* @param id word form's ID.
* @param form text of the word form itself.
* @return a new word form.
*/
public WF newWF(String id, String form, int sent) {
idManager.updateWFCounter(id);
WF newWF = new WF(this.annotationContainer, id, form, sent);
annotationContainer.add(newWF);
return newWF;
}
/** Creates a new WF object. It assigns an appropriate ID to it and it also assigns offset and length
* attributes. The WF is added to the document object.
* @param form text of the word form itself.
* @return a new word form.
*/
public WF newWF(String form, int offset) {
String newId = idManager.getNextWFId();
int offsetVal = offset;
WF newWF = new WF(this.annotationContainer, newId, form, 0);
newWF.setOffset(offsetVal);
newWF.setLength(form.length());
annotationContainer.add(newWF);
return newWF;
}
/** Creates a new WF object. It assigns an appropriate ID to it. The WF is added to the document object.
* @param form text of the word form itself.
* @return a new word form.
*/
public WF newWF(String form, int offset, int sent) {
String newId = idManager.getNextWFId();
WF newWF = new WF(this.annotationContainer, newId, form, sent);
newWF.setOffset(offset);
newWF.setLength(form.length());
annotationContainer.add(newWF);
return newWF;
}
/** Creates a Term object to load an existing term. It receives the ID as an argument. The Term is added to the document object.
* @param id term's ID.
* @param type type of term. There are two types of term: open and close.
* @param lemma the lemma of the term.
* @param pos part of speech of the term.
* @param wfs the list of word forms this term is formed by.
* @return a new term.
*/
public Term newTerm(String id, Span<WF> span) {
idManager.updateTermCounter(id);
Term newTerm = new Term(id, span, false);
annotationContainer.add(newTerm);
return newTerm;
}
public Term newTerm(String id, Span<WF> span, boolean isComponent) {
idManager.updateTermCounter(id);
Term newTerm = new Term(id, span, isComponent);
if (!isComponent) {
annotationContainer.add(newTerm);
}
return newTerm;
}
public Term newTerm(String id, Span<WF> span, Integer position) {
idManager.updateTermCounter(id);
Term newTerm = new Term(id, span, false);
annotationContainer.add(newTerm, position);
return newTerm;
}
/** Creates a new Term. It assigns an appropriate ID to it. The Term is added to the document object.
* @param type the type of the term. There are two types of term: open and close.
* @param lemma the lemma of the term.
* @param pos part of speech of the term.
* @param wfs the list of word forms this term is formed by.
* @return a new term.
*/
public Term newTerm(Span<WF> span) {
String newId = idManager.getNextTermId();
Term newTerm = new Term(newId, span, false);
annotationContainer.add(newTerm);
return newTerm;
}
/** Creates a new Term. It assigns an appropriate ID to it. The Term is added to the document object.
* @param type the type of the term. There are two types of term: open and close.
* @param lemma the lemma of the term.
* @param pos part of speech of the term.
* @param wfs the list of word forms this term is formed by.
* @return a new term.
*/
public Term newTermOptions(String morphofeat, Span<WF> span) {
String newId = idManager.getNextTermId();
Term newTerm = new Term(newId, span, false);
newTerm.setMorphofeat(morphofeat);
annotationContainer.add(newTerm);
return newTerm;
}
public Term newCompound(List<Term> terms, String lemma) {
Span<WF> span = new Span<WF>();
for (Term term : terms) {
span.addTargets(term.getSpan().getTargets());
}
String newId = idManager.getNextMwId();
Term compound = newTerm(newId, span, annotationContainer.termPosition(terms.get(0)));
compound.setLemma(lemma);
for (Term term : terms) {
compound.addComponent(term);
term.setCompound(compound);
this.annotationContainer.remove(term);
}
return compound;
}
/** Creates a Sentiment object.
* @return a new sentiment.
*/
public Term.Sentiment newSentiment() {
Term.Sentiment newSentiment = new Term.Sentiment();
return newSentiment;
}
/** Creates a new dependency. The Dep is added to the document object.
* @param from the origin term of the dependency.
* @param to the target term of the dependency.
* @param rfunc relational function of the dependency.
* @return a new dependency.
*/
public Dep newDep(Term from, Term to, String rfunc) {
Dep newDep = new Dep(from, to, rfunc);
annotationContainer.add(newDep);
return newDep;
}
/** Creates a chunk object to load an existing chunk. It receives it's ID as an argument. The Chunk is added to the document object.
* @param id chunk's ID.
* @param head the chunk head.
* @param phrase type of the phrase.
* @param terms the list of the terms in the chunk.
* @return a new chunk.
*/
public Chunk newChunk(String id, String phrase, Span<Term> span) {
idManager.updateChunkCounter(id);
Chunk newChunk = new Chunk(id, span);
newChunk.setPhrase(phrase);
annotationContainer.add(newChunk);
return newChunk;
}
/** Creates a new chunk. It assigns an appropriate ID to it. The Chunk is added to the document object.
* @param head the chunk head.
* @param phrase type of the phrase.
* @param terms the list of the terms in the chunk.
* @return a new chunk.
*/
public Chunk newChunk(String phrase, Span<Term> span) {
String newId = idManager.getNextChunkId();
Chunk newChunk = new Chunk(newId, span);
newChunk.setPhrase(phrase);
annotationContainer.add(newChunk);
return newChunk;
}
/** Creates an Entity object to load an existing entity. It receives the ID as an argument. The entity is added to the document object.
* @param id the ID of the named entity.
* @param type entity type. 8 values are posible: Person, Organization, Location, Date, Time, Money, Percent, Misc.
* @param references it contains one or more span elements. A span can be used to reference the different occurrences of the same named entity in the document. If the entity is composed by multiple words, multiple target elements are used.
* @return a new named entity.
*/
public Entity newEntity(String id, List<Span<Term>> references) {
idManager.updateEntityCounter(id);
Entity newEntity = new Entity(id, references);
annotationContainer.add(newEntity);
return newEntity;
}
/** Creates a new Entity. It assigns an appropriate ID to it. The entity is added to the document object.
* @param type entity type. 8 values are posible: Person, Organization, Location, Date, Time, Money, Percent, Misc.
* @param references it contains one or more span elements. A span can be used to reference the different occurrences of the same named entity in the document. If the entity is composed by multiple words, multiple target elements are used.
* @return a new named entity.
*/
public Entity newEntity(List<Span<Term>> references) {
String newId = idManager.getNextEntityId();
Entity newEntity = new Entity(newId, references);
annotationContainer.add(newEntity);
return newEntity;
}
/** Creates a coreference object to load an existing Coref. It receives it's ID as an argument. The Coref is added to the document.
* @param id the ID of the coreference.
* @param references different mentions (list of targets) to the same entity.
* @return a new coreference.
*/
public Coref newCoref(String id, List<Span<Term>> mentions) {
idManager.updateCorefCounter(id);
Coref newCoref = new Coref(id, mentions);
annotationContainer.add(newCoref);
return newCoref;
}
/** Creates a new coreference. It assigns an appropriate ID to it. The Coref is added to the document.
* @param references different mentions (list of targets) to the same entity.
* @return a new coreference.
*/
public Coref newCoref(List<Span<Term>> mentions) {
String newId = idManager.getNextCorefId();
Coref newCoref = new Coref(newId, mentions);
annotationContainer.add(newCoref);
return newCoref;
}
/** Creates a new property. It receives it's ID as an argument. The property is added to the document.
* @param id the ID of the property.
* @param lemma the lemma of the property.
* @param references different mentions (list of targets) to the same property.
* @return a new coreference.
*/
public Feature newProperty(String id, String lemma, List<Span<Term>> references) {
idManager.updatePropertyCounter(id);
Feature newProperty = new Feature(id, lemma, references);
annotationContainer.add(newProperty);
return newProperty;
}
/** Creates a new property. It assigns an appropriate ID to it. The property is added to the document.
* @param lemma the lemma of the property.
* @param references different mentions (list of targets) to the same property.
* @return a new coreference.
*/
public Feature newProperty(String lemma, List<Span<Term>> references) {
String newId = idManager.getNextPropertyId();
Feature newProperty = new Feature(newId, lemma, references);
annotationContainer.add(newProperty);
return newProperty;
}
/** Creates a new category. It receives it's ID as an argument. The category is added to the document.
* @param id the ID of the category.
* @param lemma the lemma of the category.
* @param references different mentions (list of targets) to the same category.
* @return a new coreference.
*/
public Feature newCategory(String id, String lemma, List<Span<Term>> references) {
idManager.updateCategoryCounter(id);
Feature newCategory = new Feature(id, lemma, references);
annotationContainer.add(newCategory);
return newCategory;
}
/** Creates a new category. It assigns an appropriate ID to it. The category is added to the document.
* @param lemma the lemma of the category.
* @param references different mentions (list of targets) to the same category.
* @return a new coreference.
*/
public Feature newCategory(String lemma, List<Span<Term>> references) {
String newId = idManager.getNextCategoryId();
Feature newCategory = new Feature(newId, lemma, references);
annotationContainer.add(newCategory);
return newCategory;
}
/** Creates a new opinion object. It assigns an appropriate ID to it. The opinion is added to the document.
* @return a new opinion.
*/
public Opinion newOpinion() {
String newId = idManager.getNextOpinionId();
Opinion newOpinion = new Opinion(newId);
annotationContainer.add(newOpinion);
return newOpinion;
}
/** Creates a new opinion object. It receives its ID as an argument. The opinion is added to the document.
* @return a new opinion.
*/
public Opinion newOpinion(String id) {
idManager.updateOpinionCounter(id);
Opinion newOpinion = new Opinion(id);
annotationContainer.add(newOpinion);
return newOpinion;
}
/** Creates a new relation between entities and/or sentiment features. It assigns an appropriate ID to it. The relation is added to the document.
* @param from source of the relation
* @param to target of the relation
* @return a new relation
*/
public Relation newRelation(Relational from, Relational to) {
String newId = idManager.getNextRelationId();
Relation newRelation = new Relation(newId, from, to);
annotationContainer.add(newRelation);
return newRelation;
}
/** Creates a new relation between entities and/or sentiment features. It receives its ID as an argument. The relation is added to the document.
* @param id the ID of the relation
* @param from source of the relation
* @param to target of the relation
* @return a new relation
*/
public Relation newRelation(String id, Relational from, Relational to) {
idManager.updateRelationCounter(id);
Relation newRelation = new Relation(id, from, to);
annotationContainer.add(newRelation);
return newRelation;
}
/** Creates a new srl predicate. It receives its ID as an argument. The predicate is added to the document.
* @param id the ID of the predicate
* @param span span containing the targets of the predicate
* @return a new predicate
*/
public Predicate newPredicate(String id, Span<Term> span) {
idManager.updatePredicateCounter(id);
Predicate newPredicate = new Predicate(id, span);
annotationContainer.add(newPredicate);
return newPredicate;
}
/** Creates a new srl predicate. It assigns an appropriate ID to it. The predicate is added to the document.
* @param span span containing all the targets of the predicate
* @return a new predicate
*/
public Predicate newPredicate(Span<Term> span) {
String newId = idManager.getNextPredicateId();
Predicate newPredicate = new Predicate(newId, span);
annotationContainer.add(newPredicate);
return newPredicate;
}
/** Creates a Role object to load an existing role. It receives the ID as an argument. It doesn't add the role to the predicate.
* @param id role's ID.
* @param predicate the predicate which this role is part of
* @param semRole semantic role
* @param span span containing all the targets of the role
* @return a new role.
*/
public Predicate.Role newRole(String id, Predicate predicate, String semRole, Span<Term> span) {
idManager.updateRoleCounter(id);
Predicate.Role newRole = new Predicate.Role(id, semRole, span);
return newRole;
}
/** Creates a new Role object. It assigns an appropriate ID to it. It uses the ID of the predicate to create a new ID for the role. It doesn't add the role to the predicate.
* @param predicate the predicate which this role is part of
* @param semRole semantic role
* @param span span containing all the targets of the role
* @return a new role.
*/
public Predicate.Role newRole(Predicate predicate, String semRole, Span<Term> span) {
String newId = idManager.getNextRoleId();
Predicate.Role newRole = new Predicate.Role(newId, semRole, span);
return newRole;
}
/** Creates a new external reference.
* @param resource indicates the identifier of the resource referred to.
* @param reference code of the referred element.
* @return a new external reference object.
*/
public ExternalRef newExternalRef(String resource, String reference) {
return new ExternalRef(resource, reference);
}
public Tree newConstituent(TreeNode root) {
Tree tree = new Tree(root);
annotationContainer.add(tree);
return tree;
}
public void addConstituencyFromParentheses(String parseOut) throws Exception {
Tree.parenthesesToKaf(parseOut, this);
}
public NonTerminal newNonTerminal(String id, String label) {
NonTerminal tn = new NonTerminal(id, label);
String newEdgeId = idManager.getNextEdgeId();
tn.setEdgeId(newEdgeId);
return tn;
}
public NonTerminal newNonTerminal(String label) {
String newId = idManager.getNextNonterminalId();
String newEdgeId = idManager.getNextEdgeId();
NonTerminal newNonterminal = new NonTerminal(newId, label);
newNonterminal.setEdgeId(newEdgeId);
return newNonterminal;
}
public Terminal newTerminal(String id, Span<Term> span) {
Terminal tn = new Terminal(id, span);
String newEdgeId = idManager.getNextEdgeId();
tn.setEdgeId(newEdgeId);
return tn;
}
public Terminal newTerminal(Span<Term> span) {
String newId = idManager.getNextTerminalId();
String newEdgeId = idManager.getNextEdgeId();
Terminal tn = new Terminal(newId, span);
tn.setEdgeId(newEdgeId);
return tn;
}
public static Span<WF> newWFSpan() {
return new Span<WF>();
}
public static Span<WF> newWFSpan(List<WF> targets) {
return new Span<WF>(targets);
}
public static Span<WF> newWFSpan(List<WF> targets, WF head) {
return new Span<WF>(targets, head);
}
public static Span<Term> newTermSpan() {
return new Span<Term>();
}
public static Span<Term> newTermSpan(List<Term> targets) {
return new Span<Term>(targets);
}
public static Span<Term> newTermSpan(List<Term> targets, Term head) {
return new Span<Term>(targets, head);
}
void addUnknownLayer(Element layer) {
annotationContainer.add(layer);
}
/** Returns the raw text **/
public String getRawText() {
return annotationContainer.getRawText();
}
/** Returns a list containing all WFs in the document */
public List<WF> getWFs() {
return annotationContainer.getText();
}
/** Returns a list with all sentences. Each sentence is a list of WFs. */
public List<List<WF>> getSentences() {
return annotationContainer.getSentences();
}
public Integer getFirstSentence() {
return annotationContainer.getText().get(0).getSent();
}
public Integer getNumSentences() {
List<WF> wfs = annotationContainer.getText();
Integer firstSentence = wfs.get(0).getSent();
Integer lastSentence = wfs.get(wfs.size()-1).getSent();
return lastSentence - firstSentence + 1;
}
public List<Integer> getSentsByParagraph(Integer para) {
if (this.annotationContainer.sentsIndexedByParagraphs.get(para) == null) System.out.println(para+": 0");
return new ArrayList<Integer>(this.annotationContainer.sentsIndexedByParagraphs.get(para));
}
public Integer getNumParagraphs() {
return this.annotationContainer.sentsIndexedByParagraphs.keySet().size();
}
/** Returns a list with all terms in the document. */
public List<Term> getTerms() {
return annotationContainer.getTerms();
}
/** Returns a list of terms containing the word forms given on argument.
* @param wfs a list of word forms whose terms will be found.
* @return a list of terms containing the given word forms.
*/
public List<Term> getTermsByWFs(List<WF> wfs) {
return annotationContainer.getTermsByWFs(wfs);
}
public List<Term> getSentenceTerms(int sent) {
return annotationContainer.getSentenceTerms(sent);
}
public List<Dep> getDeps() {
return annotationContainer.getDeps();
}
public List<Chunk> getChunks() {
return annotationContainer.getChunks();
}
/** Returns a list with all entities in the document */
public List<Entity> getEntities() {
return annotationContainer.getEntities();
}
public List<Coref> getCorefs() {
return annotationContainer.getCorefs();
}
/** Returns a list with all relations in the document */
public List<Feature> getProperties() {
return annotationContainer.getProperties();
}
/** Returns a list with all relations in the document */
public List<Feature> getCategories() {
return annotationContainer.getCategories();
}
public List<Opinion> getOpinions() {
return annotationContainer.getOpinions();
}
/** Returns a list with all relations in the document */
public List<Relation> getRelations() {
return annotationContainer.getRelations();
}
public List<Tree> getConstituents() {
return annotationContainer.getConstituents();
}
public List<Element> getUnknownLayers() {
return annotationContainer.getUnknownLayers();
}
public List<WF> getWFsBySent(Integer sent) {
return this.annotationContainer.textIndexedBySent.get(sent);
}
public List<WF> getWFsByPara(Integer para) {
return this.annotationContainer.getLayerByPara(para, this.annotationContainer.textIndexedBySent);
}
public List<Term> getTermsBySent(Integer sent) {
return this.annotationContainer.termsIndexedBySent.get(sent);
}
public List<Term> getTermsByPara(Integer para) {
return this.annotationContainer.getLayerByPara(para, this.annotationContainer.termsIndexedBySent);
}
public List<Entity> getEntitiesBySent(Integer sent) {
return this.annotationContainer.entitiesIndexedBySent.get(sent);
}
public List<Entity> getEntitiesByPara(Integer para) {
return this.annotationContainer.getLayerByPara(para, this.annotationContainer.entitiesIndexedBySent);
}
public List<Dep> getDepsBySent(Integer sent) {
return this.annotationContainer.depsIndexedBySent.get(sent);
}
public List<Dep> getDepsByPara(Integer para) {
return this.annotationContainer.getLayerByPara(para, this.annotationContainer.depsIndexedBySent);
}
public List<Chunk> getChunksBySent(Integer sent) {
return this.annotationContainer.chunksIndexedBySent.get(sent);
}
public List<Chunk> getChunksByPara(Integer para) {
return this.annotationContainer.getLayerByPara(para, this.annotationContainer.chunksIndexedBySent);
}
public List<Predicate> getPredicatesBySent(Integer sent) {
return this.annotationContainer.predicatesIndexedBySent.get(sent);
}
public List<Predicate> getPredicatesByPara(Integer para) {
return this.annotationContainer.getLayerByPara(para, this.annotationContainer.predicatesIndexedBySent);
}
/** Returns current timestamp. */
public String createTimestamp() {
Date date = new Date();
//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd H:mm:ss");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String formattedDate = sdf.format(date);
return formattedDate;
}
/** Copies the annotations to another KAF document */
private void copyAnnotationsToKAF(KAFDocument kaf,
List<WF> wfs,
List<Term> terms,
List<Dep> deps,
List<Chunk> chunks,
List<Entity> entities,
List<Coref> corefs,
List<Feature> properties,
List<Feature> categories,
List<Opinion> opinions,
List<Relation> relations,
List<Predicate> predicates
) {
HashMap<String, WF> copiedWFs = new HashMap<String, WF>();
HashMap<String, Term> copiedTerms = new HashMap<String, Term>();
HashMap<String, Relational> copiedRelationals = new HashMap<String, Relational>();
// WFs
for (WF wf : wfs) {
WF wfCopy = new WF(wf, kaf.getAnnotationContainer());
kaf.insertWF(wfCopy);
copiedWFs.put(wf.getId(), wfCopy);
}
// Terms
for (Term term : terms) {
Term termCopy = new Term(term, copiedWFs);
kaf.insertTerm(termCopy);
copiedTerms.put(term.getId(), termCopy);
}
// Deps
for (Dep dep : deps) {
Dep depCopy = new Dep(dep, copiedTerms);
kaf.insertDep(depCopy);
}
// Chunks
for (Chunk chunk : chunks) {
Chunk chunkCopy = new Chunk(chunk, copiedTerms);
kaf.insertChunk(chunkCopy);
}
// Entities
for (Entity entity : entities) {
Entity entityCopy = new Entity(entity, copiedTerms);
kaf.insertEntity(entityCopy);
copiedRelationals.put(entity.getId(), entityCopy);
}
// Coreferences
for (Coref coref : corefs) {
Coref corefCopy = new Coref(coref, copiedTerms);
kaf.insertCoref(corefCopy);
}
// Properties
for (Feature property : properties) {
Feature propertyCopy = new Feature(property, copiedTerms);
kaf.insertProperty(propertyCopy);
copiedRelationals.put(property.getId(), propertyCopy);
}
// Categories
for (Feature category : categories) {
Feature categoryCopy = new Feature(category, copiedTerms);
kaf.insertCategory(categoryCopy);
copiedRelationals.put(category.getId(), categoryCopy);
}
// Opinions
for (Opinion opinion : opinions) {
Opinion opinionCopy = new Opinion(opinion, copiedTerms);
kaf.insertOpinion(opinionCopy);
}
// Relations
for (Relation relation : relations) {
Relation relationCopy = new Relation(relation, copiedRelationals);
kaf.insertRelation(relationCopy);
}
// Predicates
/*
for (Predicate predicate : predicates) {
Predicate predicateCopy = new Predicate(predicate, copiedTerms);
kaf.insertPredicate(predicateCopy);
}
*/
}
/** Returns a new document containing all annotations related to the given WFs */
/* Couldn't index opinion by terms. Terms are added after the Opinion object is created, and there's no way to access the annotationContainer from the Opinion.*/
public KAFDocument split(List<WF> wfs) {
List<Term> terms = this.annotationContainer.getTermsByWFs(wfs);
List<Dep> deps = this.annotationContainer.getDepsByTerms(terms);
List<Chunk> chunks = this.annotationContainer.getChunksByTerms(terms);
List<Entity> entities = this.annotationContainer.getEntitiesByTerms(terms);
List<Coref> corefs = this.annotationContainer.getCorefsByTerms(terms);
List<Feature> properties = this.annotationContainer.getPropertiesByTerms(terms);
List<Feature> categories = this.annotationContainer.getCategoriesByTerms(terms);
// List<Opinion> opinions = this.annotationContainer.getOpinionsByTerms(terms);
List<Predicate> predicates = this.annotationContainer.getPredicatesByTerms(terms);
List<Relational> relationals = new ArrayList<Relational>();
relationals.addAll(properties);
relationals.addAll(categories);
relationals.addAll(entities);
List<Relation> relations = this.annotationContainer.getRelationsByRelationals(relationals);
KAFDocument newKaf = new KAFDocument(this.getLang(), this.getVersion());
newKaf.addLinguisticProcessors(this.getLinguisticProcessors());
this.copyAnnotationsToKAF(newKaf, wfs, terms, deps, chunks, entities, corefs, properties, categories, new ArrayList<Opinion>(), relations, predicates);
return newKaf;
}
/** Joins the document with another one. **/
public void join(KAFDocument doc) {
HashMap<String, WF> copiedWFs = new HashMap<String, WF>(); // hash[old_id => new_WF_obj]
HashMap<String, Term> copiedTerms = new HashMap<String, Term>(); // hash[old_id => new_Term_obj]
HashMap<String, Relational> copiedRelationals = new HashMap<String, Relational>();
// Linguistic processors
Map<String, List<LinguisticProcessor>> lps = doc.getLinguisticProcessors();
for (Map.Entry<String, List<LinguisticProcessor>> entry : lps.entrySet()) {
String layer = entry.getKey();
List<LinguisticProcessor> lpList = entry.getValue();
for (LinguisticProcessor lp : lpList) {
if (!this.linguisticProcessorExists(layer, lp.name, lp.version)) {
// Here it uses a deprecated method
this.addLinguisticProcessor(layer, lp.name, lp.timestamp, lp.version);
}
}
}
// WFs
for (WF wf : doc.getWFs()) {
WF wfCopy = new WF(wf, this.annotationContainer);
this.insertWF(wfCopy);
copiedWFs.put(wf.getId(), wfCopy);
}
// Terms
for (Term term : doc.getTerms()) {
Term termCopy = new Term(term, copiedWFs);
this.insertTerm(termCopy);
copiedTerms.put(term.getId(), termCopy);
}
// Deps
for (Dep dep : doc.getDeps()) {
Dep depCopy = new Dep(dep, copiedTerms);
this.insertDep(depCopy);
}
// Chunks
for (Chunk chunk : doc.getChunks()) {
Chunk chunkCopy = new Chunk(chunk, copiedTerms);
this.insertChunk(chunkCopy);
}
// Entities
for (Entity entity : doc.getEntities()) {
Entity entityCopy = new Entity(entity, copiedTerms);
this.insertEntity(entityCopy);
copiedRelationals.put(entity.getId(), entityCopy);
}
// Coreferences
for (Coref coref : doc.getCorefs()) {
Coref corefCopy = new Coref(coref, copiedTerms);
this.insertCoref(corefCopy);
}
// Properties
for (Feature property : doc.getProperties()) {
Feature propertyCopy = new Feature(property, copiedTerms);
this.insertProperty(propertyCopy);
copiedRelationals.put(property.getId(), propertyCopy);
}
// Categories
for (Feature category : doc.getCategories()) {
Feature categoryCopy = new Feature(category, copiedTerms);
this.insertCategory(categoryCopy);
copiedRelationals.put(category.getId(), categoryCopy);
}
// Opinions
for (Opinion opinion : doc.getOpinions()) {
Opinion opinionCopy = new Opinion(opinion, copiedTerms);
this.insertOpinion(opinionCopy);
}
// Relations
for (Relation relation : doc.getRelations()) {
Relation relationCopy = new Relation(relation, copiedRelationals);
this.insertRelation(relationCopy);
}
}
public String insertWF(WF wf) {
String newId = idManager.getNextWFId();
wf.setId(newId);
annotationContainer.add(wf);
return newId;
}
public String insertTerm(Term term) {
String newId = idManager.getNextTermId();
term.setId(newId);
annotationContainer.add(term);
return newId;
}
public void insertDep(Dep dep) {
annotationContainer.add(dep);
}
public String insertChunk(Chunk chunk) {
String newId = idManager.getNextChunkId();
chunk.setId(newId);
annotationContainer.add(chunk);
return newId;
}
public String insertEntity(Entity entity) {
String newId = idManager.getNextEntityId();
entity.setId(newId);
annotationContainer.add(entity);
return newId;
}
public String insertCoref(Coref coref) {
String newId = idManager.getNextCorefId();
coref.setId(newId);
annotationContainer.add(coref);
return newId;
}
public String insertProperty(Feature property) {
String newId = idManager.getNextPropertyId();
property.setId(newId);
annotationContainer.add(property);
return newId;
}
public String insertCategory(Feature category) {
String newId = idManager.getNextCategoryId();
category.setId(newId);
annotationContainer.add(category);
return newId;
}
public String insertOpinion(Opinion opinion) {
String newId = idManager.getNextOpinionId();
opinion.setId(newId);
annotationContainer.add(opinion);
return newId;
}
public String insertRelation(Relation relation) {
String newId = idManager.getNextRelationId();
relation.setId(newId);
annotationContainer.add(relation);
return newId;
}
/** Saves the KAF document to an XML file.
* @param filename name of the file in which the document will be saved.
*/
public void save(String filename) {
ReadWriteManager.save(this, filename);
}
public String toString() {
return ReadWriteManager.kafToStr(this);
}
/** Prints the document on standard output. */
public void print() {
ReadWriteManager.print(this);
}
/*** DEPRECATED METHODS ***/
/** Deprecated */
public LinguisticProcessor addLinguisticProcessor(String layer, String name, String version) {
LinguisticProcessor lp = this.addLinguisticProcessor(layer, name);
lp.setVersion(version);
return lp;
}
/** Deprecated */
public LinguisticProcessor addLinguisticProcessor(String layer, String name, String timestamp, String version) {
LinguisticProcessor lp = this.addLinguisticProcessor(layer, name);
lp.setTimestamp(timestamp);
lp.setVersion(version);
return lp;
}
/** Deprecated */
public WF newWF(String id, String form) {
return this.newWF(id, form, 0);
}
/** Deprecated */
public WF newWF(String form) {
return this.newWF(form, 0);
}
/** Deprecated */
public WF createWF(String id, String form) {
return this.newWF(id, form, 0);
}
/** Deprecated */
public WF createWF(String form) {
return this.newWF(form, 0);
}
/** Deprecated */
public WF createWF(String form, int offset) {
return this.newWF(form, offset);
}
/** Deprecated */
public Term newTerm(String id, String type, String lemma, String pos, Span<WF> span) {
Term term = newTerm(id, span);
term.setType(type);
term.setLemma(lemma);
term.setPos(pos);
return term;
}
/** Deprecated */
public Term newTerm(String type, String lemma, String pos, Span<WF> span) {
Term term = newTerm(span);
term.setType(type);
term.setLemma(lemma);
term.setPos(pos);
return term;
}
/** Deprecated */
public Term newTermOptions(String type, String lemma, String pos, String morphofeat, Span<WF> span) {
Term newTerm = newTermOptions(morphofeat, span);
newTerm.setType(type);
newTerm.setLemma(lemma);
newTerm.setPos(pos);
return newTerm;
}
/** Deprecated */
public Term createTerm(String id, String type, String lemma, String pos, List<WF> wfs) {
return this.newTerm(id, type, lemma, pos, this.<WF>list2Span(wfs));
}
/** Deprecated */
public Term createTerm(String type, String lemma, String pos, List<WF> wfs) {
return this.newTerm(type, lemma, pos, this.<WF>list2Span(wfs));
}
/** Deprecated */
public Term createTermOptions(String type, String lemma, String pos, String morphofeat, List<WF> wfs) {
return this.newTermOptions(type, lemma, pos, morphofeat, this.<WF>list2Span(wfs));
}
/** Deprecated */
public Term.Sentiment createSentiment() {
return this.newSentiment();
}
/** Deprecated */
/*
public Component newComponent(String id, Term term, String lemma, String pos) {
Component newComponent = this.newComponent(id, term);
newComponent.setLemma(lemma);
newComponent.setPos(pos);
return newComponent;
}
*/
/** Deprecated */
/*public Component newComponent(Term term, String lemma, String pos) {
Term.Component newComponent = this.newComponent(term);
newComponent.setLemma(lemma);
newComponent.setPos(pos);
return newComponent;
}
*/
/** Deprecated */
/*
public Component createComponent(String id, Term term, String lemma, String pos) {
return this.newComponent(id, term, lemma, pos);
}
*/
/** Deprecated */
/*
public Component createComponent(Term term, String lemma, String pos) {
return this.newComponent(term, lemma, pos);
}
*/
/** Deprecated */
public Dep createDep(Term from, Term to, String rfunc) {
return this.createDep(from, to, rfunc);
}
/** Deprecated */
public Chunk createChunk(String id, Term head, String phrase, List<Term> terms) {
return this.newChunk(id, phrase, this.<Term>list2Span(terms, head));
}
/** Deprecated */
public Chunk createChunk(Term head, String phrase, List<Term> terms) {
return this.newChunk(phrase, this.<Term>list2Span(terms, head));
}
/** Deprecated */
public Entity createEntity(String id, String type, List<List<Term>> references) {
List<Span<Term>> spanReferences = new ArrayList<Span<Term>>();
for (List<Term> list : references) {
spanReferences.add(this.list2Span(list));
}
Entity entity = this.newEntity(id, spanReferences);
entity.setType(type);
return entity;
}
/** Deprecated */
public Entity createEntity(String type, List<List<Term>> references) {
List<Span<Term>> spanReferences = new ArrayList<Span<Term>>();
for (List<Term> list : references) {
spanReferences.add(this.list2Span(list));
}
Entity entity = this.newEntity(spanReferences);
entity.setType(type);
return entity;
}
/** Deprecated */
public Coref createCoref(String id, List<List<Target>> references) {
List<Span<Term>> spanReferences = new ArrayList<Span<Term>>();
for (List<Target> list : references) {
spanReferences.add(this.targetList2Span(list));
}
return this.newCoref(id, spanReferences);
}
/** Deprecated */
public Coref createCoref(List<List<Target>> references) {
List<Span<Term>> spanReferences = new ArrayList<Span<Term>>();
for (List<Target> list : references) {
spanReferences.add(this.targetList2Span(list));
}
return this.newCoref(spanReferences);
}
/** Deprecated */
public Feature createProperty(String id, String lemma, List<List<Term>> references) {
List<Span<Term>> spanReferences = new ArrayList<Span<Term>>();
for (List<Term> list : references) {
spanReferences.add(this.list2Span(list));
}
return this.newProperty(id, lemma, spanReferences);
}
/** Deprecated */
public Feature createProperty(String lemma, List<List<Term>> references) {
List<Span<Term>> spanReferences = new ArrayList<Span<Term>>();
for (List<Term> list : references) {
spanReferences.add(this.list2Span(list));
}
return this.newProperty(lemma, spanReferences);
}
/** Deprecated */
public Feature createCategory(String id, String lemma, List<List<Term>> references) {
List<Span<Term>> spanReferences = new ArrayList<Span<Term>>();
for (List<Term> list : references) {
spanReferences.add(this.list2Span(list));
}
return this.newCategory(id, lemma, spanReferences);
}
/** Deprecated */
public Feature createCategory(String lemma, List<List<Term>> references) {
List<Span<Term>> spanReferences = new ArrayList<Span<Term>>();
for (List<Term> list : references) {
spanReferences.add(this.list2Span(list));
}
return this.newCategory(lemma, spanReferences);
}
/** Deprecated */
public Opinion createOpinion() {
return this.newOpinion();
}
/** Deprecated */
public Opinion createOpinion(String id) {
return this.newOpinion(id);
}
/** Deprecated */
public Relation createRelation(Relational from, Relational to) {
return this.newRelation(from, to);
}
/** Deprecated */
public Relation createRelation(String id, Relational from, Relational to) {
return this.newRelation(id, from, to);
}
/** Deprecated */
public ExternalRef createExternalRef(String resource, String reference) {
return this.newExternalRef(resource, reference);
}
public static Target createTarget(Term term) {
return new Target(term, false);
}
/** Deprecated. Creates a new target. This method is overloaded. In this case, it receives a boolean argument which defines whether the target term is the head or not.
* @param term target term.
* @param isHead a boolean argument which defines whether the target term is the head or not.
* @return a new target.
*/
public static Target createTarget(Term term, boolean isHead) {
return new Target(term, isHead);
}
public void removeLayer(Layer layer) {
this.annotationContainer.removeLayer(layer);
}
/** Converts a List into a Span */
static <T> Span<T> list2Span(List<T> list) {
Span<T> span = new Span<T>();
for (T elem : list) {
span.addTarget(elem);
}
return span;
}
/** Converts a List into a Span */
static <T> Span<T> list2Span(List<T> list, T head) {
Span<T> span = new Span<T>();
for (T elem : list) {
if (head == elem) {
span.addTarget(elem, true);
} else {
span.addTarget(elem);
}
}
return span;
}
/** Converts a Target list into a Span of terms */
static Span<Term> targetList2Span(List<Target> list) {
Span<Term> span = new Span<Term>();
for (Target target : list) {
if (target.isHead()) {
span.addTarget(target.getTerm(), true);
} else {
span.addTarget(target.getTerm());
}
}
return span;
}
/** Converts a Span into a Target list */
static List<Target> span2TargetList(Span<Term> span) {
List<Target> list = new ArrayList<Target>();
for (Term t : span.getTargets()) {
list.add(KAFDocument.createTarget(t, (t==span.getHead())));
}
return list;
}
/** Deprecated. Returns a list of terms containing the word forms given on argument.
* @param wfIds a list of word form IDs whose terms will be found.
* @return a list of terms containing the given word forms.
*/
public List<Term> getTermsFromWFs(List<String> wfIds) {
return annotationContainer.getTermsByWFIds(wfIds);
}
}
|
package jkanvas.util;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Path2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RectangularShape;
import java.awt.geom.RoundRectangle2D;
import jkanvas.KanvasContext;
/**
* Utility methods for painting.
*
* @author Joschi <josua.krause@gmail.com>
*/
public final class PaintUtil {
/** Hidden default constructor. */
private PaintUtil() {
throw new AssertionError();
}
/**
* Creates a rectangle to draw a point.
*
* @param pos The point.
* @param size The size of the point.
* @return The rectangle.
*/
public static Rectangle2D pixel(final Point2D pos, final double size) {
final double s2 = size * 0.5;
return new Rectangle2D.Double(pos.getX() - s2, pos.getY() - s2, size, size);
}
/**
* Creates a rectangle to draw a point.
*
* @param pos The point.
* @return The rectangle.
*/
public static Rectangle2D pixel(final Point2D pos) {
return pixel(pos, 1);
}
/**
* Creates a circle to draw a point.
*
* @param pos The point.
* @param size The size of the point.
* @return The circle.
*/
public static Ellipse2D pixelRound(final Point2D pos, final double size) {
return createCircle(pos.getX(), pos.getY(), size * 0.5);
}
/**
* Adds padding to a rectangle.
*
* @param rect The rectangle.
* @param padding The padding.
* @return The rectangle with the padding.
*/
public static Rectangle2D addPadding(final RectangularShape rect, final double padding) {
final double p2 = padding * 2;
return new Rectangle2D.Double(rect.getX() - padding, rect.getY() - padding,
rect.getWidth() + p2, rect.getHeight() + p2);
}
/**
* Adds padding to a rectangle.
*
* @param rect The rectangle. The result will also be stored in the rectangle.
* @param padding The padding.
*/
public static void addPaddingInplace(final RectangularShape rect, final double padding) {
final double p2 = padding * 2;
rect.setFrame(rect.getX() - padding, rect.getY() - padding,
rect.getWidth() + p2, rect.getHeight() + p2);
}
/**
* Converts a rectangle to a round rectangle.
*
* @param rect The rectangle.
* @param radius The radius of the round rectangle.
* @return The round rectangle.
*/
public static RoundRectangle2D toRoundRectangle(
final RectangularShape rect, final double radius) {
final double r2 = radius * 2;
return new RoundRectangle2D.Double(rect.getX() - radius, rect.getY() - radius,
rect.getWidth() + r2, rect.getHeight() + r2, radius, radius);
}
/**
* Scales a rectangle so that the center point stays the same.
*
* @param rect The rectangle to scale.
* @param scale The scaling factor.
* @return The scaled rectangle.
*/
public static Rectangle2D scaleCenter(final RectangularShape rect, final double scale) {
final double w = rect.getWidth() * scale;
final double h = rect.getHeight() * scale;
return new Rectangle2D.Double(rect.getCenterX() - w * 0.5,
rect.getCenterY() - h * 0.5, w, h);
}
/**
* Fits a rectangle into the given rectangle. The aspect ratio of the
* resulting rectangle is given by <code>w</code> and <code>h</code>.
*
* @param rect The rectangle.
* @param w The width for defining the aspect ratio.
* @param h The height for defining the aspect ratio.
* @return A rectangle with the given aspect ratio that fits into the given
* rectangle.
*/
public static Rectangle2D fitInto(final RectangularShape rect,
final double w, final double h) {
final double s = fitIntoScale(rect, w, h);
final double nw = w * s;
final double nh = h * s;
final double px = (rect.getWidth() - nw) * 0.5;
final double py = (rect.getHeight() - nh) * 0.5;
return new Rectangle2D.Double(rect.getX() + px, rect.getY() + py, nw, nh);
}
/**
* Scales the given width and height so that they are maximally not larger
* than the size of the given rectangle.
*
* @param rect The rectangle.
* @param w The width.
* @param h The height.
* @return The scale for the width and height.
*/
public static double fitIntoScale(final RectangularShape rect,
final double w, final double h) {
final double rw = rect.getWidth();
final double rh = rect.getHeight();
final double hRatio = rh / h;
final double verWidth = w * hRatio;
return verWidth <= rw ? hRatio : rw / w;
}
/**
* Scales a rectangle such that the rectangle fits into a pixel rectangle.
*
* @param pixWidth The pixel rectangle width.
* @param pixHeight The pixel rectangle height.
* @param w The rectangle width.
* @param h The rectangle height.
* @param fit If set to <code>true</code> the rectangle will be completely
* visible. When set to <code>false</code> as much as possible from
* the rectangle will be visible without showing anything else.
* @return The scaling to apply.
*/
public static double fitIntoPixelScale(final int pixWidth, final int pixHeight,
final double w, final double h, final boolean fit) {
final double rw = pixWidth / w;
final double rh = pixHeight / h;
return fit ? Math.min(rw, rh) : Math.max(rw, rh);
}
/**
* Creates a circle with the given radius.
*
* @param x The x position.
* @param y The y position.
* @param r The radius.
* @return The circle.
*/
public static Ellipse2D createCircle(final double x, final double y, final double r) {
final double r2 = r * 2;
return new Ellipse2D.Double(x - r, y - r, r2, r2);
}
/**
* Creates a line with a given width without using a stroke.
*
* @param x1 The first x coordinate.
* @param y1 The first y coordinate.
* @param x2 The second x coordinate.
* @param y2 The second y coordinate.
* @param width The width of the line.
* @return The shape of the line.
*/
public static Shape createLine(final double x1, final double y1,
final double x2, final double y2, final double width) {
final Point2D ortho = VecUtil.setLength(
new Point2D.Double(y1 - y2, x2 - x1), width * 0.5);
final Path2D gp = new Path2D.Double();
gp.moveTo(x1 + ortho.getX(), y1 + ortho.getY());
gp.lineTo(x2 + ortho.getX(), y2 + ortho.getY());
gp.lineTo(x2 - ortho.getX(), y2 - ortho.getY());
gp.lineTo(x1 - ortho.getX(), y1 - ortho.getY());
gp.closePath();
return gp;
}
/**
* Interpolates between two colors.
*
* @param from The color to interpolate from.
* @param to The color to interpolate to.
* @param t The interpolation value from <code>0</code> to <code>1</code>.
* @return The interpolated color.
*/
public static Color interpolate(final Color from, final Color to, final double t) {
if(Double.isNaN(t)) throw new IllegalArgumentException("NaN");
if(t > 1 || t < 0) throw new IllegalArgumentException("" + t);
final float[] fromRGBA = new float[4];
final float[] toRGBA = new float[4];
from.getRGBComponents(fromRGBA);
to.getRGBComponents(toRGBA);
final double r = fromRGBA[0] * (1 - t) + toRGBA[0] * t;
final double g = fromRGBA[1] * (1 - t) + toRGBA[1] * t;
final double b = fromRGBA[2] * (1 - t) + toRGBA[2] * t;
final double a = fromRGBA[3] * (1 - t) + toRGBA[3] * t;
return new Color((float) r, (float) g, (float) b, (float) a);
}
/**
* Sets the alpha value of a color. Hint: Consider using
* {@link #setAlpha(Graphics2D, double)}.
*
* @param col The color.
* @param alpha The new alpha value.
* @return The color with transparency.
*/
public static Color setAlpha(final Color col, final double alpha) {
final float[] comp = col.getRGBComponents(null);
return new Color(comp[0], comp[1], comp[2], (float) alpha);
}
/**
* Multiplies the alpha value of a color. Hint: Consider using
* {@link #setAlpha(Graphics2D, double)}.
*
* @param col The color.
* @param alpha The alpha value to multiply to the previous value.
* @return The color with new transparency.
*/
public static Color mulAlpha(final Color col, final double alpha) {
final float[] comp = col.getRGBComponents(null);
return new Color(comp[0], comp[1], comp[2], (float) (alpha * comp[3]));
}
/**
* Creates a color with transparency. Hint: Consider using
* {@link #setAlpha(Graphics2D, double)}.
*
* @param h The hue value. <code>1</code> represents <code>360</code> degrees.
* @param s The saturation value.
* @param b The brightness value.
* @param alpha The alpha value.
* @return The color.
*/
public static Color hsbaColor(
final double h, final double s, final double b, final double alpha) {
return setAlpha(Color.getHSBColor((float) h, (float) s, (float) b), alpha);
}
/**
* Removes the transparency of the given color.
*
* @param col The color.
* @return The same color without transparency.
*/
public static Color noAlpha(final Color col) {
return noAlpha(col, null);
}
/**
* Removes the transparency of the given color.
*
* @param col The color.
* @param alpha An optional array with a length of at least one that is used
* to store the previous alpha value of the color in slot 0.
* @return The same color without transparency.
*/
public static Color noAlpha(final Color col, final float[] alpha) {
final float[] comp = col.getRGBComponents(null);
if(alpha != null) {
alpha[0] = comp[3];
}
if(comp[3] == 1) return col;
return new Color(comp[0], comp[1], comp[2]);
}
/**
* Sets the alpha value of the given graphics context via composite.
*
* @param g The graphics context.
* @param alpha The alpha value.
*/
public static void setAlpha(final Graphics2D g, final double alpha) {
if(alpha >= 1) return;
final Composite comp = g.getComposite();
if(comp instanceof AlphaComposite) {
final AlphaComposite ac = (AlphaComposite) comp;
if(ac.getRule() == AlphaComposite.SRC_OVER) {
g.setComposite(ac.derive((float) (ac.getAlpha() * alpha)));
return;
}
}
System.err.println("Warning: cannot derive composite: " + comp);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, (float) alpha));
}
public static void drawShape(final Graphics2D g, final Rectangle2D rect,
final KanvasContext ctx, final Color other) {
g.setColor(other);
g.fill(rect);
final double t = Math.min(1 / ctx.toComponentLength(1), 1);
g.setColor(PaintUtil.interpolate(Color.BLACK, other, t));
g.draw(rect);
}
}
|
package au.com.southsky.jfreesane;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import au.com.southsky.jfreesane.SaneOption.OptionUnits;
import au.com.southsky.jfreesane.SaneSession.SaneParameters;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
/**
* Wraps an {@link InputStream} to provide some methods for deserializing SANE-related types.
*
* @author James Ring (sjr@jdns.org)
*/
public class SaneInputStream extends InputStream {
private static final Logger logger = Logger.getLogger(SaneInputStream.class.getName());
private final SaneSession saneSession;
private InputStream wrappedStream;
private OptionGroup currentGroup;
public SaneInputStream(SaneSession saneSession, InputStream wrappedStream) {
this.saneSession = saneSession;
this.wrappedStream = wrappedStream;
}
@Override
public int read() throws IOException {
return wrappedStream.read();
}
public List<SaneDevice> readDeviceList() throws IOException, SaneException {
// Status first
SaneStatus status = readStatus();
if (!SaneStatus.STATUS_GOOD.equals(status)) {
throw new SaneException(status);
}
// now we're reading an array, decode the length of the array (which
// includes the null if the array is non-empty)
int length = readWord().integerValue() - 1;
if (length <= 0) {
return ImmutableList.of();
}
ImmutableList.Builder<SaneDevice> result = ImmutableList.builder();
for (int i = 0; i < length; i++) {
SaneDevice device = readSaneDevicePointer();
if (device == null) {
throw new IllegalStateException("null pointer encountered when not expected");
}
result.add(device);
}
// read past a trailing byte in the response that I haven't figured
// out yet...
readWord();
return result.build();
}
/**
* Reads a single {@link SaneDevice} definition pointed to by the pointer at the current location
* in the stream. Returns {@code null} if the pointer is a null pointer.
*/
private SaneDevice readSaneDevicePointer() throws IOException {
if (!readPointer()) {
// TODO(sjr): why is there always a null pointer here?
// return null;
}
// now we assume that there's a sane device ready to parse
return readSaneDevice();
}
/**
* Reads a single pointer and returns {@code true} if it was non-null.
*/
private boolean readPointer() throws IOException {
return readWord().integerValue() != 0;
}
private SaneDevice readSaneDevice() throws IOException {
String deviceName = readString();
String deviceVendor = readString();
String deviceModel = readString();
String deviceType = readString();
return new SaneDevice(this.saneSession, deviceName, deviceVendor, deviceModel, deviceType);
}
public String readString() throws IOException {
// read the length
int length = readWord().integerValue();
if (length == 0) {
return "";
}
// now read all the bytes
byte[] input = new byte[length];
if (read(input) != input.length) {
throw new IllegalStateException("truncated input while reading string");
}
// skip the null terminator
return new String(input, 0, input.length - 1, Charsets.ISO_8859_1);
}
public SaneParameters readSaneParameters() throws IOException {
int frame = readWord().integerValue();
boolean lastFrame = readWord().integerValue() == 1;
int bytesPerLine = readWord().integerValue();
int pixelsPerLine = readWord().integerValue();
int lines = readWord().integerValue();
int depth = readWord().integerValue();
return new SaneSession.SaneParameters(frame, lastFrame, bytesPerLine, pixelsPerLine, lines,
depth);
}
public SaneStatus readStatus() throws IOException {
return SaneStatus.fromWireValue(readWord().integerValue());
}
public SaneWord readWord() throws IOException {
return SaneWord.fromStream(this);
}
public SaneOptionDescriptor readOptionDescriptor() throws IOException {
// discard pointer
readWord();
String optionName = readString();
String optionTitle = readString();
String optionDescription = readString();
int typeInt = readWord().integerValue();
// TODO: range check here
OptionValueType valueType = SaneEnums.valueOf(OptionValueType.class, typeInt);
if (valueType == OptionValueType.GROUP) {
// a new group applies!
currentGroup = new OptionGroup(optionTitle);
}
int unitsInt = readWord().integerValue();
// TODO: range check here
OptionUnits units = SaneEnums.valueOf(OptionUnits.class, unitsInt);
int size = readWord().integerValue();
// constraint type
int capabilityWord = readWord().integerValue();
int constraintTypeInt = readWord().integerValue();
// TODO: range check here
OptionValueConstraintType constraintType = SaneEnums.valueOf(
OptionValueConstraintType.class, constraintTypeInt);
// decode the constraint
List<String> stringConstraints = null;
List<SaneWord> valueConstraints = null;
RangeConstraint rangeConstraint = null;
switch (constraintType) {
case NO_CONSTRAINT:
// inputStream.readWord(); // discard empty list
break;
case STRING_LIST_CONSTRAINT:
stringConstraints = Lists.newArrayList();
int n = readWord().integerValue();
for (int i = 0; i < n; i++) {
String stringConstraint = readString();
// the last element is a null terminator, don't add that
if (i < n - 1) {
stringConstraints.add(stringConstraint);
}
}
break;
case VALUE_LIST_CONSTRAINT:
valueConstraints = Lists.newArrayList();
n = readWord().integerValue();
for (int i = 0; i < n; i++) {
// first element is list length, don't add that
SaneWord value = readWord();
if (i != 0) {
valueConstraints.add(value);
}
}
break;
case RANGE_CONSTRAINT:
// TODO: still don't understand the 6 values
SaneWord w0 = readWord();
SaneWord w1 = readWord();
SaneWord w2 = readWord();
SaneWord w3 = readWord();
// int w4 = inputStream.readWord().integerValue();
switch (valueType) {
case INT:
case FIXED:
rangeConstraint = new RangeConstraint(w1, w2, w3);
break;
default:
logger.log(Level.WARNING, "Ignoring invalid option type/constraint combination: "
+ "value_type=%s,constraint_type=%s for option %s. "
+ "Option will be treated by jfreesane as unconstrained", new Object[] { valueType,
constraintType, optionName });
}
break;
default:
throw new IllegalStateException("Unknown constraint type");
}
return new SaneOptionDescriptor(optionName, optionTitle, optionDescription, currentGroup,
valueType, units, size, SaneEnums.enumSet(OptionCapability.class, capabilityWord),
constraintType, rangeConstraint, stringConstraints, valueConstraints);
}
}
|
package me.mneri.csv;
import me.mneri.csv.exception.CsvConversionException;
import me.mneri.csv.exception.CsvException;
import me.mneri.csv.exception.UncheckedCsvException;
import me.mneri.csv.exception.UnexpectedCharacterException;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
* Read csv streams and automatically transform lines into Java objects.
*
* @param <T> The type of the Java objects to read.
* @author Massimo Neri <<a href="mailto:hello@mneri.me">hello@mneri.me</a>>
*/
public final class CsvReader<T> implements Closeable {
// States
private static final byte ERROR = -1;
private static final byte START = 0;
private static final byte QUOTE = 1;
private static final byte ESCAP = 2;
private static final byte STRNG = 3;
private static final byte CARRG = 4;
private static final byte FINSH = 5;
// Actions
private static final byte NO_OP = 0;
private static final byte ACCUM = 1;
private static final byte FIELD = 2;
private static final byte NLINE = 4;
//@formatter:off
private static final byte[][] ACTIONS = {
// * " , \r \n eof
{ ACCUM , NO_OP , FIELD , NO_OP , FIELD | NLINE, NO_OP }, // START
{ ACCUM , NO_OP , ACCUM , ACCUM , ACCUM , NO_OP }, // QUOTE
{ NO_OP , ACCUM , FIELD , NO_OP , FIELD | NLINE, FIELD | NLINE }, // ESCAP
{ ACCUM , ACCUM , FIELD , NO_OP , FIELD | NLINE, FIELD | NLINE }, // STRNG
{ NO_OP , NO_OP , NO_OP , NO_OP , FIELD | NLINE, NO_OP }, // CARRG
{ NO_OP , NO_OP , NO_OP , NO_OP , NO_OP , NO_OP }}; // FINSH
//@formatter:on
//@formatter:off
private static final byte[][] TRANSITIONS = {
// * " , \r \n eof
{ STRNG , QUOTE , START , CARRG , FINSH , FINSH }, // START
{ QUOTE , ESCAP , QUOTE , QUOTE , QUOTE , ERROR }, // QUOTE
{ ERROR , QUOTE , START , CARRG , FINSH , FINSH }, // ESCAP
{ STRNG , STRNG , START , CARRG , FINSH , FINSH }, // STRNG
{ ERROR , ERROR , ERROR , ERROR , FINSH , ERROR }, // CARRG
{ ERROR , ERROR , ERROR , ERROR , ERROR , ERROR }}; // FINSH
//@formatter:on
//@formatter:off
private static final int ELEMENT_NOT_READ = 0;
private static final int ELEMENT_READ = 1;
private static final int NO_SUCH_ELEMENT = 2;
private static final int CLOSED = 3;
//@formatter:on
private static final int DEFAULT_BUFFER_SIZE = 8192;
private char[] buffer;
private CsvDeserializer<T> deserializer;
private T element;
private RecyclableCsvLine line = new RecyclableCsvLine();
private int lines;
private int next;
private Reader reader;
private int size;
private int state = ELEMENT_NOT_READ;
private CsvReader(Reader reader, CsvDeserializer<T> deserializer) {
this.reader = reader;
this.deserializer = deserializer;
buffer = new char[DEFAULT_BUFFER_SIZE];
}
private void checkClosedState() {
if (state == CLOSED) {
throw new IllegalStateException("The reader is closed.");
}
}
/**
* Closes the stream and releases any system resources associated with it. Once the stream has been closed, further
* {@link CsvReader#hasNext()}, {@link CsvReader#next()} and {@link CsvReader#skip(int)} invocations will throw an
* {@link IOException}. Closing a previously closed stream has no effect.
*
* @throws IOException if an I/O error occurs.
*/
@Override
public void close() throws IOException {
if (state == CLOSED) {
return;
}
state = CLOSED;
buffer = null;
deserializer = null;
element = null;
line = null;
reader.close();
reader = null;
}
private int columnOf(int charCode) {
switch (charCode) {
//@formatter:off
case '"' : return 1;
case ',' : return 2;
case '\r': return 3;
case '\n': return 4;
case -1 : return 5; // EOF
default : return 0;
//@formatter:on
}
}
/**
* Returns {@code true} if the reader has more elements. (In other words, returns {@code true} if
* {@link CsvReader#next()} would return an element rather than throwing an exception).
*
* @return {@code true} if the reader has more elements.
* @throws CsvException if the csv is not properly formatted.
* @throws IOException if an I/O error occurs.
*/
public boolean hasNext() throws CsvException, IOException {
//@formatter:off
if (state == ELEMENT_READ) { return true; }
else if (state == NO_SUCH_ELEMENT) { return false; }
//@formatter:on
checkClosedState();
byte row = START;
while (true) {
int nextChar = read();
int column = columnOf(nextChar);
int action = ACTIONS[row][column];
if ((action & ACCUM) != 0) {
line.put((char) nextChar);
} else if ((action & FIELD) != 0) {
line.markField();
if ((action & NLINE) != 0) {
lines++;
try {
T object = deserializer.deserialize(line);
line.clear();
element = object;
state = ELEMENT_READ;
return true;
} catch (Exception e) {
throw new CsvConversionException(line, e);
}
}
}
row = TRANSITIONS[row][column];
if (row == FINSH) {
state = NO_SUCH_ELEMENT;
return false;
} else if (row == ERROR) {
throw new UnexpectedCharacterException(lines, nextChar);
}
}
}
private Iterator<T> iterator() {
return new Iterator<T>() {
@Override
public boolean hasNext() {
//@formatter:off
try { return CsvReader.this.hasNext(); }
catch (CsvException e) { throw new UncheckedCsvException(e); }
catch (IOException e) { throw new UncheckedIOException(e); }
//@formatter:on
}
@Override
public T next() {
//@formatter:off
try { return CsvReader.this.next(); }
catch (CsvException e) { throw new UncheckedCsvException(e); }
catch (IOException e) { throw new UncheckedIOException(e); }
//@formatter:on
}
};
}
/**
* Return the next element in the reader.
*
* @return The next element.
* @throws CsvException if the csv is not properly formatted.
* @throws IOException if an I/O error occurs.
*/
public T next() throws CsvException, IOException {
if (!hasNext()) {
throw new NoSuchElementException();
}
T result = element;
element = null;
state = ELEMENT_NOT_READ;
return result;
}
/**
* Opens a file for reading, returning a {@code CsvReader}. Bytes from the file are decoded into characters using
* the default JVM charset. Reading commences at the beginning of the file.
*
* @param file the file to open.
* @param deserializer the deserializer used to convert csv lines into objects.
* @param <T> the type of the objects to read.
* @return A new {@code CsvReader} to read the specified file.
* @throws IOException if an I/O error occurs.
*/
public static <T> CsvReader<T> open(File file, CsvDeserializer<T> deserializer) throws IOException {
return open(file, Charset.defaultCharset(), deserializer);
}
/**
* Opens a file for reading, returning a {@code CsvReader}. Bytes from the file are decoded into characters using
* the specified charset. Reading commences at the beginning of the file.
*
* @param file the file to open.
* @param charset the charset of the file.
* @param deserializer the deserializer used to convert csv lines into objects.
* @param <T> the type of the objects to read.
* @return A new {@code CsvReader} to read the specified file.
* @throws IOException if an I/O error occurs.
*/
public static <T> CsvReader<T> open(File file, Charset charset, CsvDeserializer<T> deserializer) throws IOException {
return open(Files.newBufferedReader(file.toPath(), charset), deserializer);
}
/**
* Return a new {@code CsvReader} using the specified {@link Reader} for reading. Bytes from the file are decoded
* into characters using the reader's charset. Reading commences at the point specified by the reader.
*
* @param reader the {@link Reader} to read from.
* @param deserializer the deserializer used to convert csv lines into objects.
* @param <T> the type of the objects to read.
* @return A new {@code CsvReader} to read the specified file.
*/
public static <T> CsvReader<T> open(Reader reader, CsvDeserializer<T> deserializer) {
return new CsvReader<>(reader, deserializer);
}
private int read() throws IOException {
if (next >= size) {
if ((size = reader.read(buffer, 0, buffer.length)) < 0) {
return -1;
}
next = 0;
}
return buffer[next++];
}
/**
* Skip the next elements of the reader.
*
* @param n The number of elements to skip.
* @throws CsvException if the csv is not properly formatted.
* @throws IOException if an I/O error occurs.
*/
public void skip(int n) throws CsvException, IOException {
checkClosedState();
if (state == NO_SUCH_ELEMENT) {
return;
}
int toSkip = n;
if (state == ELEMENT_READ) {
element = null;
state = ELEMENT_NOT_READ;
if (--toSkip == 0) {
return;
}
}
byte row = START;
while (true) {
int nextChar = read();
int column = columnOf(nextChar);
int action = ACTIONS[row][column];
if ((action & NLINE) != 0) {
lines++;
if (--toSkip == 0) {
return;
}
row = START;
} else {
row = TRANSITIONS[row][column];
if (row == FINSH) {
state = NO_SUCH_ELEMENT;
return;
} else if (row == ERROR) {
throw new UnexpectedCharacterException(lines, nextChar);
}
}
}
}
private Spliterator<T> spliterator() {
int characteristics = Spliterator.IMMUTABLE | Spliterator.ORDERED;
return Spliterators.spliteratorUnknownSize(iterator(), characteristics);
}
/**
* Opens a file for reading, returning a {@link Stream}. Bytes from the file are decoded into characters using
* the default JVM charset. Reading commences at the beginning of the file.
*
* @param file the file to open.
* @param deserializer the deserializer used to convert csv lines into objects.
* @param <T> the type of the objects to read.
* @return A new {@link Stream} of objects read from the specified file.
* @throws IOException if an I/O error occurs.
*/
public static <T> Stream<T> stream(File file, CsvDeserializer<T> deserializer) throws IOException {
return stream(file, Charset.defaultCharset(), deserializer);
}
/**
* Opens a file for reading, returning a {@link Stream}. Bytes from the file are decoded into characters using
* the specified charset. Reading commences at the beginning of the file.
*
* @param file the file to open.
* @param charset the charset of the file.
* @param deserializer the deserializer used to convert csv lines into objects.
* @param <T> the type of the objects to read.
* @return A new {@link Stream} of objects read from the specified file.
* @throws IOException if an I/O error occurs.
*/
public static <T> Stream<T> stream(File file, Charset charset, CsvDeserializer<T> deserializer) throws IOException {
return stream(Files.newBufferedReader(file.toPath(), charset), deserializer);
}
/**
* Return a new {@link Stream} of objects using the specified {@link Reader} for reading. Bytes from the file are
* decoded into characters using the reader's charset. Reading commences at the point specified by the reader.
*
* @param reader the {@link Reader} to read from.
* @param deserializer the deserializer used to convert csv lines into objects.
* @param <T> the type of the objects to read.
* @return A new {@code CsvReader} to read the specified file.
*/
public static <T> Stream<T> stream(Reader reader, CsvDeserializer<T> deserializer) {
//@formatter:off
CsvReader<T> csvReader = CsvReader.open(reader, deserializer);
return StreamSupport.stream(csvReader.spliterator(), false)
.onClose(() -> { try { csvReader.close(); } catch (Exception ignored) { } });
//@formatter:on
}
}
|
package ch.bind.philib.net.examples;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.Random;
import ch.bind.philib.lang.ThreadUtil;
import ch.bind.philib.net.SocketAddresses;
import ch.bind.philib.net.tcp.TcpConnection;
//TODO: reply data validation
//TODO: speed measurements
//TODO: many threads
public class TcpEchoClient {
private TcpConnection connection;
public static void main(String[] args) throws Exception {
new TcpEchoClient().run();
}
private void run() throws IOException, InterruptedException {
// InetSocketAddress endpoint = SocketAddresses.fromIp("10.0.0.66",
// 1234);
// InetSocketAddress endpoint = SocketAddresses.fromIp("10.95.162.221",
// 1234);
byte[] buf = new byte[8 * 1024];
new Random().nextBytes(buf);
ByteBuffer seedBuffer = ByteBuffer.wrap(buf);
InetSocketAddress endpoint = SocketAddresses.fromIp("127.0.0.1", 1234);
EchoSession session = new EchoSession();
connection = TcpConnection.open(endpoint, session);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
connection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
long lastT = System.currentTimeMillis();
connection.sendBlocking(seedBuffer);
long seeded = seedBuffer.capacity();
int loop = 1;
long lastRx = 0, lastTx = 0;
final long start = System.currentTimeMillis();
while (connection.isConnected()) {
long sleepUntil = start + (loop * 30000L);
ThreadUtil.sleepUntilMs(sleepUntil);
long rx = session.getRx();
long tx = session.getTx();
long rxDiff = rx - lastRx;
long txDiff = tx - lastTx;
long now = System.currentTimeMillis();
long tDiff = now - lastT;
double rxMbPerSec = (rxDiff / (1024f * 1024f)) / (tDiff / 1000f);
double txMbPerSec = (txDiff / (1024f * 1024f)) / (tDiff / 1000f);
System.out.printf("seeded=%d total=%d in %d ms; last 5sec rx=%d, tx=%d bytes => %.3f %.3f mb/sec%n",
seeded, (rx + tx), (now - start), rxDiff, txDiff, rxMbPerSec, txMbPerSec);
if (seeded < 128 * 1024) {
System.out.println("seeding an additional " + seedBuffer.capacity() + " bytes into the echo chain");
seedBuffer.rewind();
connection.sendBlocking(seedBuffer);
seeded += seedBuffer.capacity();
}
// if (rxDiff == 0 || txDiff == 0) {
// session.forceWrite();
loop++;
lastRx = rx;
lastTx = tx;
lastT = now;
}
}
}
|
package io.github.aritzhack.aritzh.bds;
import com.google.common.base.Strings;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import io.github.aritzhack.aritzh.logging.OSLogger;
import io.github.aritzhack.aritzh.logging.core.ILogger;
import io.github.aritzhack.aritzh.logging.core.LogLevel;
import io.github.aritzhack.aritzh.util.API;
import io.github.aritzhack.aritzh.util.ReflectionUtil;
import java.io.File;
import java.io.PrintStream;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* @author aritzh
*/
public class BDSUtil {
private static final String CLASS_NAME_TAG = "0__className";
private static final String ARRAY_TYPE_TAG = "0__arrayType";
private static final String ARRAY_LENGTH_TAG = "0__arrayLength";
private static final String PRIMITIVE_VALUE_TAG = "0__value";
private static final String ROOT_OBJ_TAG = "0__root";
private static final String BACKREF_PREFIX = "0__back_";
private static final String IDX_TAG = "0__ID";
private static final String NULL_TAG = "0__null__";
public static final BDS NULL_BDS = BDS.createEmpty(NULL_TAG);
private static ILogger LOG = new OSLogger.Builder(System.out, "SAWS-Serialization").setLevel(LogLevel.INFO).build();
@API
public static BDS serialize(Object instance) throws SerializationException {
return instance == null ? NULL_BDS : serializeInternal2(ROOT_OBJ_TAG, instance, HashMultimap.<Map.Entry<String, Integer>, Map.Entry<Integer, Object>>create(), new IntRef(-1));
}
@API
public static <T> T deserialize(BDS data) throws SerializationException {
return deserializeInternal(data, Maps.<Integer, Object>newHashMap(), Sets.<UnresolvedReference>newHashSet());
}
public static boolean isNull(BDS bds) {
return bds == null || NULL_TAG.equals(bds.getName());
}
private static BDS serializeInternal2(String name, Object instance, Multimap<Map.Entry<String, Integer>, Map.Entry<Integer, Object>> alreadyWritten, IntRef biggest) throws SerializationException {
if (instance == null) return NULL_BDS;
Class<?> type = instance.getClass();
BDS bds = BDS.createEmpty(name);
bds.addInt(IDX_TAG, ++biggest.value);
if (Byte.class.equals(type) || byte.class.equals(type)) {
bds.addString(CLASS_NAME_TAG, "Byte");
bds.addByte(PRIMITIVE_VALUE_TAG, (Byte) instance);
} else if (Character.class.equals(type) || byte.class.equals(type)) {
bds.addString(CLASS_NAME_TAG, "Char");
bds.addChar(PRIMITIVE_VALUE_TAG, (Character) instance);
} else if (Short.class.equals(type) || short.class.equals(type)) {
bds.addString(CLASS_NAME_TAG, "Short");
bds.addShort(PRIMITIVE_VALUE_TAG, (Short) instance);
} else if (Integer.class.equals(type) || int.class.equals(type)) {
bds.addString(CLASS_NAME_TAG, "Int");
bds.addInt(PRIMITIVE_VALUE_TAG, (Integer) instance);
} else if (Long.class.equals(type) || long.class.equals(type)) {
bds.addString(CLASS_NAME_TAG, "Long");
bds.addLong(PRIMITIVE_VALUE_TAG, (Long) instance);
} else if (Float.class.equals(type) || float.class.equals(type)) {
bds.addString(CLASS_NAME_TAG, "Float");
bds.addFloat(PRIMITIVE_VALUE_TAG, (Float) instance);
} else if (Double.class.equals(type) || double.class.equals(type)) {
bds.addString(CLASS_NAME_TAG, "Double");
bds.addDouble(PRIMITIVE_VALUE_TAG, (Double) instance);
} else if (String.class.equals(type)) {
bds.addString(CLASS_NAME_TAG, "String");
bds.addString(PRIMITIVE_VALUE_TAG, (String) instance);
} else if (File.class.equals(type)) {
bds.addString(CLASS_NAME_TAG, "File");
bds.addString(PRIMITIVE_VALUE_TAG, ((File) instance).getAbsolutePath());
} else {
int idx = findCycle(instance, type, alreadyWritten);
if (idx != -1) bds.addInt(BACKREF_PREFIX + type.getName(), idx);
else {
alreadyWritten.put(Maps.immutableEntry(type.getName(), instance.hashCode()), Maps.immutableEntry(biggest.value, instance));
if (type.isArray()) {
bds.addString(CLASS_NAME_TAG, "Array");
bds.addString(ARRAY_TYPE_TAG, type.getComponentType().getName());
int length = Array.getLength(instance);
bds.addInt(ARRAY_LENGTH_TAG, length);
for (int i = 0; i < length; i++) {
Object o = Array.get(instance, i);
BDS element = serializeInternal2("Item" + i, o, alreadyWritten, biggest);
bds.addBDS(element);
}
} else if (Collection.class.isAssignableFrom(type)) {
Collection c = (Collection) instance;
bds.addString(CLASS_NAME_TAG, "Collection");
bds.addString(ARRAY_TYPE_TAG, type.getName());
bds.addInt(ARRAY_LENGTH_TAG, c.size());
Iterator<?> iter = c.iterator();
int i = 0;
while (iter.hasNext()) {
bds.addBDS(serializeInternal2("Item" + i++, iter.next(), alreadyWritten, biggest));
}
} else {
for (Field f : ReflectionUtil.getAllFields(type)) {
if (f.isAnnotationPresent(Transient.class)) break;
if (!f.isAccessible()) {
try {
f.setAccessible(true);
} catch (SecurityException e) {
throw new SerializationException("Error serializing: Cannot access field " + f.getName() + " of class " + type, e);
}
}
try {
try {
bds.addBDS(serializeInternal2(f.getName(), f.get(instance), alreadyWritten, biggest));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} catch (StackOverflowError e) {
throw new SerializationException("Most probably a cycle exists in the object structure, and it could not be fixed. Provide a good hashCode and equals to your classes to fix it", e);
}
}
}
}
}
return bds;
}
private static int findCycle(Object instance, Class<?> type, Multimap<Map.Entry<String, Integer>, Map.Entry<Integer, Object>> alreadyWritten) {
Integer idx = null;
Collection<Map.Entry<Integer, Object>> entries = alreadyWritten.get(Maps.immutableEntry(type.getName(), instance.hashCode()));
for (Map.Entry<Integer, Object> entry : entries) {
if (entry.getValue().equals(instance)) {
idx = entry.getKey();
break;
}
}
if (idx != null) {
LOG.d("A cycle has been detected! Object of class {} has already been serialized!", type.getName());
return idx;
}
return -1;
}
private static <T> T deserializeInternal(BDS bds, Map<Integer, Object> pastInstances, Set<UnresolvedReference> unresolvedReferences) throws SerializationException {
if (isNull(bds)) return null;
String className = bds.getString(CLASS_NAME_TAG);
Class<?> clazz;
try {
clazz = Class.forName(className);
} catch (ClassNotFoundException e) {
throw new SerializationException("Error deserializing: Class " + className + " could not be found", e);
}
T instance;
try {
instance = (T) clazz.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new SerializationException("Error deserializing: Class " + className + " could not be instantiated. Add a public empty constructor", e);
} catch (ClassCastException e) {
throw new SerializationException("Error deserializing: Tried to cast class " + className + ", but failed!", e);
}
for (Field f : ReflectionUtil.getAllFields(instance.getClass())) {
if (f.isAnnotationPresent(Transient.class)) continue;
Class<?> fType = f.getType();
String fName = f.getName();
if (!f.isAccessible()) {
try {
f.setAccessible(true);
} catch (SecurityException e) {
throw new SerializationException("Error deserializing: Cannot access field " + f.getName() + " from class " + className, e);
}
}
Object value;
if (Byte.class.equals(fType) || byte.class.equals(fType)) {
value = bds.getByte(fName);
} else if (Character.class.equals(fType) || byte.class.equals(fType)) {
value = bds.getChar(fName);
} else if (Short.class.equals(fType) || short.class.equals(fType)) {
value = bds.getShort(fName);
} else if (Integer.class.equals(fType) || int.class.equals(fType)) {
value = bds.getInt(fName);
} else if (Long.class.equals(fType) || long.class.equals(fType)) {
value = bds.getLong(fName);
} else if (Float.class.equals(fType) || float.class.equals(fType)) {
value = bds.getFloat(fName);
} else if (Double.class.equals(fType) || double.class.equals(fType)) {
value = bds.getDouble(fName);
} else if (String.class.equals(fType)) {
value = bds.getString(fName);
} else {
BDS child = bds.getBDS(fName);
if (child == null) {
Integer ref = bds.getInt(BACKREF_PREFIX + className + fName);
if (ref == null) {
throw new SerializationException("Error deserializing: Field " + fName + " of class " + className + " cannot be deserialized!");
} else if (pastInstances.containsKey(ref)) {
value = pastInstances.get(ref);
} else {
value = null;
unresolvedReferences.add(new UnresolvedReference(instance, f, ref));
}
} else {
value = deserializeInternal(child, pastInstances, unresolvedReferences);
}
}
try {
f.set(instance, value);
} catch (IllegalAccessException e) {
throw new SerializationException("Error deserializing: Could not set value of the field " + fName + " of the class " + className, e);
}
}
if (ROOT_OBJ_TAG.equals(bds.getName())) {
Set<UnresolvedReference> toReSolve = new HashSet<>(unresolvedReferences);
while (!toReSolve.isEmpty()) {
unresolvedReferences = toReSolve;
toReSolve = Sets.newHashSet();
for (UnresolvedReference ur : unresolvedReferences) {
if (pastInstances.containsKey(ur.idx)) {
try {
ur.f.set(ur.instance, pastInstances.get(ur.idx));
} catch (IllegalAccessException e) {
assert false; // Should never happen, as we have made it accessible before
}
} else if (ur.idx == 0) {
try {
ur.f.set(ur.instance, instance);
} catch (IllegalAccessException e) {
assert false; // Should never happen, as we have made it accessible before
}
} else toReSolve.add(ur);
}
}
}
pastInstances.put(bds.getInt(IDX_TAG), instance);
return instance;
}
public static void debug(BDS bds, PrintStream out) {
debug(bds, out, 0);
}
private static void debug(BDS bds, PrintStream out, int level) {
out.println(Strings.repeat("\t", level) + "BDS: " + bds.getName());
if (bds.getAllBytes().size() != 0) {
out.println(Strings.repeat("\t", level + 1) + "Bytes:");
for (String s : bds.getAllBytes()) {
out.println(Strings.repeat("\t", level + 2) + s + ": " + bds.getByte(s));
}
}
if (bds.getAllChars().size() != 0) {
out.println(Strings.repeat("\t", level + 1) + "Chars:");
for (String s : bds.getAllChars()) {
out.println(Strings.repeat("\t", level + 2) + s + ": " + (int) bds.getChar(s));
}
}
if (bds.getAllShorts().size() != 0) {
out.println(Strings.repeat("\t", level + 1) + "Shorts:");
for (String s : bds.getAllShorts()) {
out.println(Strings.repeat("\t", level + 2) + s + ": " + bds.getShort(s));
}
}
if (bds.getAllInts().size() != 0) {
out.println(Strings.repeat("\t", level + 1) + "Ints:");
for (String s : bds.getAllInts()) {
out.println(Strings.repeat("\t", level + 2) + s + ": " + bds.getInt(s));
}
}
if (bds.getAllLongs().size() != 0) {
out.println(Strings.repeat("\t", level + 1) + "Longs:");
for (String s : bds.getAllLongs()) {
out.println(Strings.repeat("\t", level + 2) + s + ": " + bds.getLong(s));
}
}
if (bds.getAllFloats().size() != 0) {
out.println(Strings.repeat("\t", level + 1) + "Floats:");
for (String s : bds.getAllFloats()) {
out.println(Strings.repeat("\t", level + 2) + s + ": " + bds.getFloat(s));
}
}
if (bds.getAllDoubles().size() != 0) {
out.println(Strings.repeat("\t", level + 1) + "Doubles:");
for (String s : bds.getAllDoubles()) {
out.println(Strings.repeat("\t", level + 2) + s + ": " + bds.getDouble(s));
}
}
if (bds.getAllStrings().size() != 0) {
out.println(Strings.repeat("\t", level + 1) + "Strings:");
for (String s : bds.getAllStrings()) {
out.println(Strings.repeat("\t", level + 2) + s + ": " + bds.getString(s));
}
}
if (bds.getAllByteArrays().size() != 0) {
out.println(Strings.repeat("\t", level + 1) + "Byte Arrays:");
for (String s : bds.getAllByteArrays()) {
out.println(Strings.repeat("\t", level + 2) + s + ": " + Arrays.toString(bds.getByteArray(s)));
}
}
if (bds.getAllCharArrays().size() != 0) {
out.println(Strings.repeat("\t", level + 1) + "Char Arrays:");
for (String s : bds.getAllCharArrays()) {
out.print(Strings.repeat("\t", level + 2) + s + ": [");
char[] charArray = bds.getCharArray(s);
for (int i = 0; i < charArray.length; i++) {
char c = charArray[i];
out.print((int) c);
if (i != charArray.length - 1) out.print(", ");
}
out.println("]");
}
}
if (bds.getAllShortArrays().size() != 0) {
out.println(Strings.repeat("\t", level + 1) + "Short Arrays:");
for (String s : bds.getAllShortArrays()) {
out.println(Strings.repeat("\t", level + 2) + s + ": " + Arrays.toString(bds.getShortArray(s)));
}
}
if (bds.getAllIntArrays().size() != 0) {
out.println(Strings.repeat("\t", level + 1) + "Int Arrays:");
for (String s : bds.getAllIntArrays()) {
out.println(Strings.repeat("\t", level + 2) + s + ": " + Arrays.toString(bds.getIntArray(s)));
}
}
if (bds.getAllLongArrays().size() != 0) {
out.println(Strings.repeat("\t", level + 1) + "Long Arrays:");
for (String s : bds.getAllLongArrays()) {
out.println(Strings.repeat("\t", level + 2) + s + ": " + Arrays.toString(bds.getLongArray(s)));
}
}
if (bds.getAllFloatArrays().size() != 0) {
out.println(Strings.repeat("\t", level + 1) + "Float Arrays:");
for (String s : bds.getAllFloatArrays()) {
out.println(Strings.repeat("\t", level + 2) + s + ": " + Arrays.toString(bds.getFloatArray(s)));
}
}
if (bds.getAllDoubleArrays().size() != 0) {
out.println(Strings.repeat("\t", level + 1) + "Double Arrays:");
for (String s : bds.getAllDoubleArrays()) {
out.println(Strings.repeat("\t", level + 2) + s + ": " + Arrays.toString(bds.getDoubleArray(s)));
}
}
if (bds.getAllStringArrays().size() != 0) {
out.println(Strings.repeat("\t", level + 1) + "String:");
for (String s : bds.getAllStringArrays()) {
out.println(Strings.repeat("\t", level + 2) + s + ": " + Arrays.toString(bds.getStringArray(s)));
}
}
if (bds.getAllBDSs().size() != 0) {
out.println(Strings.repeat("\t", level + 1) + "BDSs:");
for (String s : bds.getAllBDSs()) {
debug(bds.getBDS(s), out, level + 2);
}
}
if (bds.getAllBDSArrays().size() != 0) {
out.println(Strings.repeat("\t", level + 1) + "BDS Arrays:");
for (String s : bds.getAllBDSArrays()) {
out.println(Strings.repeat("\t", level + 2) + s + " = [");
for (BDS nBds : bds.getBDSArray(s)) {
debug(nBds, out, level + 3);
}
out.print(Strings.repeat("\t", level + 1) + "]");
}
}
out.println();
}
private static class IntRef {
int value;
public IntRef(int value) {
this.value = value;
}
}
private static class UnresolvedReference {
final Object instance;
final Field f;
final int idx;
public UnresolvedReference(Object instance, Field f, int idx) {
this.instance = instance;
this.f = f;
this.idx = idx;
}
}
}
|
package ch.rasc.s4ws.grid;
import java.io.IOException;
import java.util.Collection;
import org.springframework.expression.ParseException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Ordering;
public class PropertyOrderingFactory {
private final static ObjectMapper mapper = new ObjectMapper();
private PropertyOrderingFactory() {
// singleton
}
public static <T> Ordering<T> createOrdering(String propertyName) {
try {
Ordering<T> ordering = new PropertyOrdering<>(propertyName);
return ordering;
} catch (ParseException e) {
return null;
}
}
public static <T> Ordering<T> createOrdering(String propertyName, SortDirection sortDirection) {
try {
Ordering<T> ordering = new PropertyOrdering<>(propertyName);
if (sortDirection == SortDirection.DESC) {
ordering = ordering.reverse();
}
return ordering;
} catch (ParseException e) {
return null;
}
}
public static <T> Ordering<T> createOrderingFromSorters(String sortInfo) throws JsonParseException,
JsonMappingException, IOException {
if (sortInfo == null) {
return null;
}
Collection<SortInfo> sortInfos = mapper.readValue(sortInfo, new TypeReference<Collection<SortInfo>>() {
//nothing here
});
Ordering<T> ordering = null;
if (sortInfos != null) {
for (SortInfo sorter : sortInfos) {
Ordering<T> propertyOrdering = createOrdering(sorter.getProperty(), sorter.getDirection());
if (ordering == null) {
ordering = propertyOrdering;
} else {
ordering = ordering.compound(propertyOrdering);
}
}
}
return ordering;
}
}
|
package org.cruk.seq;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.ParseException;
import org.cruk.util.CommandLineUtility;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Serializer;
/**
* Utility for trimming entries in a FASTQ file to a given trimLength.
*
* @author eldrid01
*/
public class TrimFastq extends CommandLineUtility
{
public static int DEFAULT_START = 1;
public static int DEFAULT_LENGTH = 36;
private String fastqFilename;
private String summaryFilename;
private int trimStart;
private int trimLength;
/**
* Runs the TrimFastq utility with the given command-line arguments.
*
* @param args
*/
public static void main(String[] args)
{
TrimFastq trimFastq = new TrimFastq(args);
trimFastq.execute();
}
/**
* Initializes a new TrimFastq utility instance with the given command-line arguments.
*
* @param args
*/
private TrimFastq(String[] args)
{
super("fastq_file", args);
}
/**
* Parse command line arguments.
*
* @param args
*/
protected void parseCommandLineArguments(String[] args)
{
CommandLineParser parser = new DefaultParser();
options.addOption("s", "trim-start", true, "Start position for trimmed sequences (default: " + DEFAULT_START + ")");
options.addOption("l", "trim-length", true, "Length of trimmed sequences (default: " + DEFAULT_LENGTH + ")");
options.addOption("o", "output-file", true, "Output file for trimmed FASTQ sequences (default: stdout)");
options.addOption("x", "summary-file", true, "Output file containing trimming summary statistics");
trimStart = DEFAULT_START;
trimLength = DEFAULT_LENGTH;
try
{
CommandLine commandLine = parser.parse(options, args);
if (commandLine.hasOption("trim-start"))
{
try
{
trimStart = Integer.parseInt(commandLine.getOptionValue("trim-start"));
}
catch (NumberFormatException e)
{
error("Error parsing command line option: trim-start must be an integer number.");
}
}
if (commandLine.hasOption("trim-length"))
{
try
{
trimLength = Integer.parseInt(commandLine.getOptionValue("trim-length"));
}
catch (NumberFormatException e)
{
error("Error parsing command line option: trim length must be an integer number");
}
}
if (commandLine.hasOption("output-file"))
{
outputFilename = commandLine.getOptionValue("output-file");
}
if (commandLine.hasOption("summary-file"))
{
summaryFilename = commandLine.getOptionValue("summary-file");
}
args = commandLine.getArgs();
if (args.length == 0)
{
error("Error parsing command line: missing FASTQ filename", true);
}
if (args.length > 1)
{
error("Error parsing command line: additional arguments and/or unrecognized options");
}
fastqFilename = args[0];
}
catch (ParseException e)
{
error("Error parsing command-line options: " + e.getMessage(), true);
}
}
/**
* Runs the FASTQ trimming utility.
*
* @throws Exception
*/
protected void run() throws Exception
{
trimStart
if (trimStart < 0)
error("Invalid start position for trimming");
if (trimLength < 1)
error("Invalid trim length");
int trimEnd = trimStart + trimLength;
try
{
FastqReader reader = new FastqReader(fastqFilename);
int minLength = 0;
int maxLength = 0;
Fastq fastq;
while ((fastq = reader.readFastq()) != null)
{
int length = fastq.getLength();
if (trimEnd > length)
error("Sequence too short for trimming (" + fastq.getDescription() + ", length " + length + ")");
if (minLength == 0)
{
minLength = length;
}
else
{
minLength = Math.min(minLength, length);
}
maxLength = Math.max(maxLength, length);
fastq = fastq.trim(trimStart, trimLength);
out.print(fastq.toString());
}
reader.close();
writeSummary(trimLength, minLength, maxLength);
}
catch (FastqFormatException e)
{
error(e.getMessage());
}
}
/**
* Writes an XML file containing a summary of the trimming.
*
* @param trimLength the length to which sequences were trimmed.
* @param minLength the smallest sequence length
* @param maxLength the largest sequence length
*/
private void writeSummary(int trimLength, int minLength, int maxLength)
{
if (summaryFilename == null) return;
BufferedOutputStream outputStream = null;
try
{
outputStream = new BufferedOutputStream(new FileOutputStream(summaryFilename));
}
catch (IOException e)
{
error("Error creating file " + summaryFilename);
}
try
{
Element root = new Element("TrimmingSummary");
Element element = new Element("TrimLength");
element.appendChild(Integer.toString(trimLength));
root.appendChild(element);
element = new Element("MinimumSequenceLength");
element.appendChild(Integer.toString(minLength));
root.appendChild(element);
element = new Element("MaximumSequenceLength");
element.appendChild(Integer.toString(maxLength));
root.appendChild(element);
Document document = new Document(root);
Serializer serializer;
serializer = new Serializer(outputStream, "ISO-8859-1");
serializer.setIndent(2);
serializer.setMaxLength(64);
serializer.setLineSeparator("\n");
serializer.write(document);
outputStream.flush();
}
catch (UnsupportedEncodingException e)
{
error(e);
}
catch (IOException e)
{
error("Error writing summary XML file");
}
finally
{
try
{
outputStream.close();
}
catch (IOException e)
{
error("Error closing file " + summaryFilename);
}
}
}
}
|
package cn.momia.mapi.api.v1.teacher;
import cn.momia.api.course.CourseServiceApi;
import cn.momia.api.course.dto.Course;
import cn.momia.api.course.dto.CourseMaterial;
import cn.momia.api.course.dto.CourseSku;
import cn.momia.api.course.dto.TeacherCourse;
import cn.momia.api.teacher.OldTeacherServiceApi;
import cn.momia.api.teacher.dto.Student;
import cn.momia.api.user.ChildServiceApi;
import cn.momia.api.user.TeacherServiceApi;
import cn.momia.api.user.UserServiceApi;
import cn.momia.api.user.dto.Child;
import cn.momia.api.user.dto.ChildComment;
import cn.momia.api.user.dto.ChildRecord;
import cn.momia.api.user.dto.ChildTag;
import cn.momia.api.user.dto.Teacher;
import cn.momia.api.user.dto.TeacherStatus;
import cn.momia.api.user.dto.User;
import cn.momia.common.core.dto.PagedList;
import cn.momia.common.core.http.MomiaHttpResponse;
import cn.momia.common.core.util.TimeUtil;
import cn.momia.common.webapp.config.Configuration;
import cn.momia.mapi.api.AbstractApi;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@RestController
@RequestMapping("/v1/teacher")
public class TeacherV1Api extends AbstractApi {
@Autowired private CourseServiceApi courseServiceApi;
@Autowired private ChildServiceApi childServiceApi;
@Autowired private UserServiceApi userServiceApi;
@Autowired private TeacherServiceApi teacherServiceApi;
@Autowired private OldTeacherServiceApi oldTeacherServiceApi;
@RequestMapping(value = "/status", method = RequestMethod.GET)
public MomiaHttpResponse status(@RequestParam String utoken) {
if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;
TeacherStatus status = teacherServiceApi.status(utoken);
Teacher teacher = completeTeacherImgs(teacherServiceApi.get(utoken));
JSONObject statusJson = (JSONObject) JSON.toJSON(teacher);
statusJson.put("status", status.getStatus());
statusJson.put("msg", status.getMsg());
return MomiaHttpResponse.SUCCESS(statusJson);
}
private Teacher completeTeacherImgs(Teacher teacher) {
teacher.setPic(completeSmallImg(teacher.getPic()));
return teacher;
}
@RequestMapping(value = "/signup", method = RequestMethod.POST)
public MomiaHttpResponse signup(@RequestParam String utoken, @RequestParam String teacher) {
if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;
if (StringUtils.isBlank(teacher)) return MomiaHttpResponse.BAD_REQUEST;
return MomiaHttpResponse.SUCCESS(teacherServiceApi.add(utoken, teacher));
}
@RequestMapping(value = "/experience", method = RequestMethod.POST)
public MomiaHttpResponse addExperience(@RequestParam String utoken, @RequestParam String experience) {
if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;
if (StringUtils.isBlank(experience)) return MomiaHttpResponse.BAD_REQUEST;
return MomiaHttpResponse.SUCCESS(teacherServiceApi.addExperience(utoken, experience));
}
@RequestMapping(value = "/experience", method = RequestMethod.GET)
public MomiaHttpResponse getExperience(@RequestParam String utoken, @RequestParam int id) {
if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;
if (id <= 0) return MomiaHttpResponse.BAD_REQUEST;
return MomiaHttpResponse.SUCCESS(teacherServiceApi.getExperience(utoken, id));
}
@RequestMapping(value = "/experience/delete", method = RequestMethod.POST)
public MomiaHttpResponse addExperience(@RequestParam String utoken, @RequestParam int id) {
if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;
if (id <= 0) return MomiaHttpResponse.BAD_REQUEST;
return MomiaHttpResponse.SUCCESS(teacherServiceApi.deleteExperience(utoken, id));
}
@RequestMapping(value = "/education", method = RequestMethod.POST)
public MomiaHttpResponse addEducation(@RequestParam String utoken, @RequestParam String education) {
if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;
if (StringUtils.isBlank(education)) return MomiaHttpResponse.BAD_REQUEST;
return MomiaHttpResponse.SUCCESS(teacherServiceApi.addEducation(utoken, education));
}
@RequestMapping(value = "/education", method = RequestMethod.GET)
public MomiaHttpResponse getEducation(@RequestParam String utoken, @RequestParam int id) {
if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;
if (id <= 0) return MomiaHttpResponse.BAD_REQUEST;
return MomiaHttpResponse.SUCCESS(teacherServiceApi.getEducation(utoken, id));
}
@RequestMapping(value = "/education/delete", method = RequestMethod.POST)
public MomiaHttpResponse addEducation(@RequestParam String utoken, @RequestParam int id) {
if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;
if (id <= 0) return MomiaHttpResponse.BAD_REQUEST;
return MomiaHttpResponse.SUCCESS(teacherServiceApi.deleteEducation(utoken, id));
}
@RequestMapping(value = "/material", method = RequestMethod.GET)
public MomiaHttpResponse getMaterial(@RequestParam String utoken, @RequestParam(value = "mid") int materialId) {
if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;
if (materialId <= 0) return MomiaHttpResponse.BAD_REQUEST;
return MomiaHttpResponse.SUCCESS(completeMaterialImgs(courseServiceApi.getMaterial(utoken, materialId)));
}
private CourseMaterial completeMaterialImgs(CourseMaterial material) {
material.setCover(completeMiddleImg(material.getCover()));
return material;
}
@RequestMapping(value = "/material/list", method = RequestMethod.GET)
public MomiaHttpResponse listMaterials(@RequestParam String utoken, @RequestParam int start) {
if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;
if (start < 0) return MomiaHttpResponse.BAD_REQUEST;
PagedList<CourseMaterial> pagedMaterials = courseServiceApi.listMaterials(utoken, start, Configuration.getInt("PageSize.Material"));
completeMaterialsImgs(pagedMaterials.getList());
return MomiaHttpResponse.SUCCESS(pagedMaterials);
}
private List<CourseMaterial> completeMaterialsImgs(List<CourseMaterial> materials) {
for (CourseMaterial material : materials) {
completeMaterialImgs(material);
}
return materials;
}
@RequestMapping(value = "/course/ongoing", method = RequestMethod.GET)
public MomiaHttpResponse ongoing(@RequestParam String utoken) {
if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;
JSONObject resultJson = new JSONObject();
User user = userServiceApi.get(utoken);
TeacherCourse teacherCourse = courseServiceApi.getOngoingTeacherCourse(user.getId());
if (teacherCourse.exists()) {
teacherCourse.setCover(completeMiddleImg(teacherCourse.getCover()));
resultJson.put("course", teacherCourse);
resultJson.put("students", completeStudentsImgs(oldTeacherServiceApi.ongoingStudents(utoken, teacherCourse.getCourseId(), teacherCourse.getCourseSkuId())));
}
return MomiaHttpResponse.SUCCESS(resultJson);
}
@RequestMapping(value = "/course/notfinished", method = RequestMethod.GET)
public MomiaHttpResponse notfinished(@RequestParam String utoken, @RequestParam int start) {
if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;
if (start < 0) return MomiaHttpResponse.BAD_REQUEST;
User user = userServiceApi.get(utoken);
PagedList<TeacherCourse> courses = courseServiceApi.queryNotFinishedByTeacher(user.getId(), start, Configuration.getInt("PageSize.Course"));
completeMiddleTeacherCoursesImgs(courses.getList());
return MomiaHttpResponse.SUCCESS(courses);
}
private List<TeacherCourse> completeMiddleTeacherCoursesImgs(List<TeacherCourse> teacherCourses) {
for (TeacherCourse teacherCourse : teacherCourses) {
teacherCourse.setCover(completeMiddleImg(teacherCourse.getCover()));
}
return teacherCourses;
}
@RequestMapping(value = "/course/notfinished/student", method = RequestMethod.GET)
public MomiaHttpResponse notfinishedStudents(@RequestParam String utoken,
@RequestParam(value = "coid") long courseId,
@RequestParam(value = "sid") long courseSkuId) {
if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;
if (courseId <= 0 || courseSkuId <= 0) return MomiaHttpResponse.BAD_REQUEST;
List<Student> students = oldTeacherServiceApi.notfinishedStudents(utoken, courseId, courseSkuId);
completeStudentsImgs(students);
return MomiaHttpResponse.SUCCESS(students);
}
private List<Student> completeStudentsImgs(List<Student> students) {
for (Student student : students) {
completeStudentImgs(student);
}
return students;
}
private Student completeStudentImgs(Student student) {
student.setAvatar(completeSmallImg(student.getAvatar()));
return student;
}
@RequestMapping(value = "/course/finished", method = RequestMethod.GET)
public MomiaHttpResponse finished(@RequestParam String utoken, @RequestParam int start) {
if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;
if (start < 0) return MomiaHttpResponse.BAD_REQUEST;
User user = userServiceApi.get(utoken);
PagedList<TeacherCourse> courses = courseServiceApi.queryFinishedByTeacher(user.getId(), start, Configuration.getInt("PageSize.Course"));
completeMiddleTeacherCoursesImgs(courses.getList());
return MomiaHttpResponse.SUCCESS(courses);
}
@RequestMapping(value = "/course/finished/student", method = RequestMethod.GET)
public MomiaHttpResponse finishedStudents(@RequestParam String utoken,
@RequestParam(value = "coid") long courseId,
@RequestParam(value = "sid") long courseSkuId) {
if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;
if (courseId <= 0 || courseSkuId <= 0) return MomiaHttpResponse.BAD_REQUEST;
List<Student> students = oldTeacherServiceApi.finishedStudents(utoken, courseId, courseSkuId);
completeStudentsImgs(students);
return MomiaHttpResponse.SUCCESS(students);
}
@RequestMapping(value = "/course/checkin", method = RequestMethod.POST)
public MomiaHttpResponse checkin(@RequestParam String utoken,
@RequestParam(value = "uid") long userId,
@RequestParam(value = "pid") long packageId,
@RequestParam(value = "coid") long courseId,
@RequestParam(value = "sid") long courseSkuId) {
if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;
if (userId <= 0 || packageId <= 0 || courseId <= 0 || courseSkuId <= 0) return MomiaHttpResponse.BAD_REQUEST;
return MomiaHttpResponse.SUCCESS(oldTeacherServiceApi.checkin(utoken, userId, packageId, courseId, courseSkuId));
}
@RequestMapping(value = "/student", method = RequestMethod.GET)
public MomiaHttpResponse student(@RequestParam String utoken, @RequestParam(value = "cid") long childId, @RequestParam int start) {
if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;
if (childId <= 0 || start < 0) return MomiaHttpResponse.BAD_REQUEST;
JSONObject studentJson = new JSONObject();
if (start == 0) {
Child child = childServiceApi.get(utoken, childId);
if (!child.exists()) return MomiaHttpResponse.FAILED("");
studentJson.put("child", buildStudent(child));
}
PagedList<ChildComment> pagedComments = childServiceApi.listComments(utoken, childId, start, Configuration.getInt("PageSize.ChildComment"));
studentJson.put("comments", buildStudentComments(pagedComments));
return MomiaHttpResponse.SUCCESS(studentJson);
}
private JSONObject buildStudent(Child child) {
JSONObject student = new JSONObject();
student.put("id", child.getId());
student.put("userId", child.getUserId());
student.put("avatar", completeSmallImg(child.getAvatar()));
student.put("name", child.getName());
student.put("birthday", child.getBirthday());
student.put("sex", child.getSex());
return student;
}
private PagedList<JSONObject> buildStudentComments(PagedList<ChildComment> pagedComments) {
Set<Long> teacherUserIds = new HashSet<Long>();
Set<Long> courseIds = new HashSet<Long>();
Set<Long> courseSkuIds = new HashSet<Long>();
for (ChildComment comment : pagedComments.getList()) {
teacherUserIds.add(comment.getTeacherUserId());
courseIds.add(comment.getCourseId());
courseSkuIds.add(comment.getCourseSkuId());
}
List<User> teacherUsers = userServiceApi.list(teacherUserIds, User.Type.MINI);
Map<Long, User> teacherUsersMap = new HashMap<Long, User>();
for (User user : teacherUsers) {
teacherUsersMap.put(user.getId(), user);
}
List<Course> courses = courseServiceApi.list(courseIds);
Map<Long, Course> coursesMap = new HashMap<Long, Course>();
for (Course course : courses) {
coursesMap.put(course.getId(), course);
}
List<CourseSku> skus = courseServiceApi.listSkus(courseSkuIds);
Map<Long, CourseSku> skusMap = new HashMap<Long, CourseSku>();
for (CourseSku sku : skus) {
skusMap.put(sku.getId(), sku);
}
List<JSONObject> studentComments = new ArrayList<JSONObject>();
for (ChildComment comment : pagedComments.getList()) {
User teacherUser = teacherUsersMap.get(comment.getTeacherUserId());
Course course = coursesMap.get(comment.getCourseId());
CourseSku sku = skusMap.get(comment.getCourseSkuId());
if (teacherUser == null || course == null || sku == null) continue;
JSONObject studentComment = new JSONObject();
studentComment.put("date", TimeUtil.SHORT_DATE_FORMAT.format(sku.getStartTime()));
studentComment.put("title", course.getTitle());
studentComment.put("content", comment.getContent());
studentComment.put("teacher", teacherUser.getNickName());
studentComments.add(studentComment);
}
PagedList<JSONObject> pagedStudentComments = new PagedList<JSONObject>();
pagedStudentComments.setTotalCount(pagedComments.getTotalCount());
pagedStudentComments.setNextIndex(pagedComments.getNextIndex());
pagedStudentComments.setList(studentComments);
return pagedStudentComments;
}
@RequestMapping(value = "/student/record", method = RequestMethod.GET)
public MomiaHttpResponse record(@RequestParam String utoken,
@RequestParam(value = "cid") long childId,
@RequestParam(value = "coid") long courseId,
@RequestParam(value = "sid") long courseSkuId) {
if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;
if (courseId <= 0 || courseSkuId <= 0 || childId <= 0) return MomiaHttpResponse.BAD_REQUEST;
Child child = childServiceApi.get(utoken, childId);
if (!child.exists()) return MomiaHttpResponse.FAILED("");
List<ChildTag> tags = childServiceApi.listAllTags();
ChildRecord record = childServiceApi.getRecord(utoken, childId, courseId, courseSkuId);
JSONObject recordJson = new JSONObject();
recordJson.put("child", buildStudent(child));
recordJson.put("tags", tags);
recordJson.put("record", record);
return MomiaHttpResponse.SUCCESS(recordJson);
}
@RequestMapping(value = "/student/record", method = RequestMethod.POST)
public MomiaHttpResponse record(@RequestParam String utoken,
@RequestParam(value = "cid") long childId,
@RequestParam(value = "coid") long courseId,
@RequestParam(value = "sid") long courseSkuId,
@RequestParam String record) {
if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;
if (courseId <= 0 || courseSkuId <= 0 || childId <= 0 || StringUtils.isBlank(record)) return MomiaHttpResponse.BAD_REQUEST;
return MomiaHttpResponse.SUCCESS(childServiceApi.record(utoken, childId, courseId, courseSkuId, record));
}
@RequestMapping(value = "/student/comment", method = RequestMethod.POST)
public MomiaHttpResponse comment(@RequestParam String utoken,
@RequestParam(value = "cid") long childId,
@RequestParam(value = "coid") long courseId,
@RequestParam(value = "sid") long courseSkuId,
@RequestParam String comment) {
if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;
if (courseId <= 0 || courseSkuId <= 0 || childId <= 0 || StringUtils.isBlank(comment)) return MomiaHttpResponse.BAD_REQUEST;
return MomiaHttpResponse.SUCCESS(childServiceApi.comment(utoken, childId, courseId, courseSkuId, comment));
}
}
|
package com.axelor.tools.i18n;
import com.axelor.common.Inflector;
import com.axelor.common.StringUtils;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import com.google.common.io.CharStreams;
import com.opencsv.CSVParser;
import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class I18nExtractor {
private static Logger log = LoggerFactory.getLogger(I18nExtractor.class);
private static final Pattern PATTERN_XML =
Pattern.compile("\\" + File.separator + "(domains|objects|views)\\" + File.separator);
private static final Pattern PATTERN_I18N =
Pattern.compile("((_t\\s*\\()|(I18n.get\\s*\\()|(T.apply\\s*\\()|(/\\*\\$\\$\\(\\*/))\\s*");
private static final Pattern PATTERN_HTML =
Pattern.compile("((\\{\\{(.*?)\\|\\s*t\\s*\\}\\})|(x-translate.*?\\>(.*?)\\<))");
private static final Pattern PATTERN_EXCLUDE =
Pattern.compile("(\\.min\\.)|(main.webapp.lib)|(js.i18n)");
private static final Set<String> VIEW_TYPES =
Sets.newHashSet(
"form", "grid", "tree", "calendar", "kanban", "cards", "gantt", "chart", "custom");
private static final Set<String> FIELD_NODES =
Sets.newHashSet(
"string",
"boolean",
"integer",
"long",
"decimal",
"date",
"time",
"datetime",
"binary",
"enum",
"one-to-one",
"many-to-one",
"one-to-many",
"many-to-many");
private static final Set<String> TEXT_ATTRS =
Sets.newHashSet("tag", "prompt", "placeholder", "x-true-text", "x-false-text");
private static final Set<String> TEXT_NODES =
Sets.newHashSet("option", "message", "static", "help");
private static final String[] CSV_HEADER = {"key", "message", "comment", "context"};
private static class I18nItem {
private String text;
private Path file;
private int line;
public I18nItem(String text, Path file, int line) {
this.text = text;
this.file = file;
this.line = line;
}
}
private abstract static class I18nTextVisitor extends SimpleFileVisitor<Path> {
private Path base;
private String entityName;
private String viewType;
public I18nTextVisitor(Path base) {
this.base = base;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
String name = file.getFileName().toString();
try {
if (name.endsWith(".xml")) processXml(file);
if (name.endsWith(".html")) processHtml(file);
if (name.endsWith(".jsp")) processHtml(file);
if (name.endsWith(".jsp")) processJava(file);
if (name.endsWith(".java")) processJava(file);
if (name.endsWith(".groovy")) processJava(file);
if (name.endsWith(".js") && !PATTERN_EXCLUDE.matcher(file.toString()).find()) {
processJava(file);
processHtml(file);
}
} catch (Exception e) {
log.error(e.getMessage());
}
return FileVisitResult.CONTINUE;
}
protected abstract void accept(I18nItem item);
private void processXml(final Path file) throws Exception {
boolean isView = file.toString().indexOf("views") > -1;
if (isView) {
processHtml(file);
processJava(file);
}
if (!PATTERN_XML.matcher(file.toString()).find()) {
return;
}
log.debug("processing XML for: {}", base.getParent().relativize(file));
final SAXParserFactory factory = SAXParserFactory.newInstance();
final SAXParser parser = factory.newSAXParser();
final DefaultHandler handler =
new DefaultHandler() {
private Locator locator;
private boolean readText = false;
private StringBuilder readTextLines = new StringBuilder();
@Override
public void setDocumentLocator(Locator locator) {
this.locator = locator;
}
@Override
public void startElement(
String uri, String localName, String qName, Attributes attributes)
throws SAXException {
String name = attributes.getValue("name");
String title = attributes.getValue("title");
String help = attributes.getValue("help");
String message = attributes.getValue("message");
String error = attributes.getValue("error");
if ("entity".equals(qName)) {
entityName = name;
}
if (VIEW_TYPES.contains(qName)) {
viewType = qName;
}
if (name != null
&& StringUtils.isBlank(title)
&& (FIELD_NODES.contains(qName)
|| "item".equals(qName)
|| ("tree".equals(viewType) && "column".equals(qName)))) {
title = Inflector.getInstance().humanize(name);
}
if ("true".equals(help) && entityName != null && name != null) {
help = "help:" + entityName + "." + name;
}
accept(new I18nItem(title, file, locator.getLineNumber()));
accept(new I18nItem(help, file, locator.getLineNumber()));
accept(new I18nItem(message, file, locator.getLineNumber()));
accept(new I18nItem(error, file, locator.getLineNumber()));
for (String attr : TEXT_ATTRS) {
accept(new I18nItem(attributes.getValue(attr), file, locator.getLineNumber()));
}
if (TEXT_NODES.contains(qName)) {
readText = true;
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (TEXT_NODES.contains(qName)) {
String text = StringUtils.stripIndent(readTextLines.toString());
accept(new I18nItem(text, file, locator.getLineNumber()));
readText = false;
readTextLines.setLength(0);
}
if ("entity".equals(qName)) {
entityName = null;
}
if (VIEW_TYPES.contains(qName)) {
viewType = null;
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (readText) {
readTextLines.append(new String(ch, start, length));
}
}
};
parser.parse(file.toFile(), handler);
}
private void processHtml(Path file) throws Exception {
String source = null;
try (Reader reader = new FileReader(file.toFile())) {
source = CharStreams.toString(reader);
} catch (IOException e) {
throw e;
}
log.debug("processing HTML for: {}", base.getParent().relativize(file));
Matcher matcher = PATTERN_HTML.matcher(source);
while (matcher.find()) {
int line = getLine(source, matcher.end());
String text = matcher.group(3);
if (text == null) {
text = matcher.group(5);
}
text = text.trim();
if (text.startsWith("\\'") && text.endsWith("\\'")) {
text = text.substring(2, text.length() - 2);
} else if (text.startsWith("\\\"") && text.endsWith("\\\"")) {
text = text.substring(2, text.length() - 2);
}
consumePlain(text, file, line);
matcher.region(matcher.end(), source.length());
}
}
private int consumePlain(String text, Path file, int line) {
String str = text.trim();
if (str.indexOf('\'') == 0 || str.indexOf('"') == 0) {
str = str.substring(1, str.length() - 1);
}
accept(new I18nItem(str, file, line));
return text.length();
}
private int consume(String source, Path file, int line) {
char first = source.charAt(0);
if (first != '"' && first != '\'') {
return 0;
}
StringBuilder sb = new StringBuilder();
int i = 1;
boolean isString = true;
while (true) {
char next = source.charAt(i++);
if (!isString && next == ')') {
break;
}
if (!isString && next == first) {
isString = true;
continue;
}
if (next == first) {
isString = source.charAt(i - 2) == '\\';
}
if (isString) {
sb.append(next);
} else if (next == ',') { // next argument
accept(new I18nItem(sb.toString(), file, line));
sb = new StringBuilder();
}
}
accept(new I18nItem(sb.toString(), file, line));
return i;
}
private void processJava(Path file) throws Exception {
String source = null;
try (Reader reader = new FileReader(file.toFile())) {
source = CharStreams.toString(reader);
} catch (IOException e) {
throw e;
}
log.debug("processing Java for: {}", base.getParent().relativize(file));
Matcher matcher = PATTERN_I18N.matcher(source);
while (matcher.find()) {
int line = getLine(source, matcher.end());
int end = consume(source.substring(matcher.end()), file, line);
matcher.region(matcher.end() + end, source.length());
}
}
private int getLine(String source, int index) {
String sub = source.substring(0, index);
return Splitter.on('\n').splitToList(sub).size();
}
public void walk() {
try {
Files.walkFileTree(base, this);
} catch (IOException e) {
}
}
}
public void extract(final Path base, boolean update, boolean withContext) {
final Path srcPath = base.resolve("src/main");
if (!Files.exists(srcPath)) {
return;
}
log.info("extracting: {}", "translatable strings...");
final Multimap<String, String> items = HashMultimap.create();
final I18nTextVisitor visitor =
new I18nTextVisitor(srcPath) {
@Override
protected void accept(I18nItem item) {
if (StringUtils.isBlank(item.text)) return;
String location = null;
if (item.file != null) {
location = "" + srcPath.relativize(item.file) + ":" + item.line;
}
if (item.text.length() != item.text.trim().length()) {
log.warn(
"Remove leading/trailing white spaces from '{}', of following text: '{}'",
location,
item.text);
}
items.put(item.text.trim(), location);
}
};
visitor.walk();
// don't generate empty templates
if (items.isEmpty()) {
return;
}
List<String> keys = new ArrayList<>(items.keySet());
List<String[]> values = new ArrayList<>();
Collections.sort(keys);
for (String key : keys) {
String context = "";
if (withContext) {
List<String> locations = new ArrayList<>(items.get(key));
Collections.sort(locations);
context = Joiner.on('\n').join(locations).trim();
}
String[] line = {key, "", "", context};
values.add(line);
}
try {
update(base, values, update);
} catch (IOException e) {
}
}
private void update(final Path base, final List<String[]> lines, boolean all) throws IOException {
// first save the template
Path template = base.resolve("src/main/resources/i18n/messages.csv");
log.info("generating: " + base.relativize(template));
save(template, lines);
if (!all) {
return;
}
// then update all languages
Files.walkFileTree(
template.getParent(),
new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
final String name = file.getFileName().toString();
final Pattern pattern = Pattern.compile("messages_([a-zA-Z_]+)\\.csv");
final Matcher matcher = pattern.matcher(name);
if (matcher.matches()) {
log.info("updating: " + base.relativize(file));
update(file, lines);
}
return FileVisitResult.CONTINUE;
}
});
// generate initial templates for some languages
String[] langs = {"en", "fr"};
for (String lang : langs) {
Path target = template.resolveSibling("messages_" + lang + ".csv");
if (!Files.exists(target)) {
log.info("generating: " + base.relativize(target));
Files.copy(template, target);
}
}
}
private boolean isEmpty(String[] items) {
if (items == null || items.length == 0) return true;
if (items.length == 1 && (items[0] == null || "".equals(items[0].trim()))) return true;
return false;
}
private void update(Path file, List<String[]> lines) throws IOException {
if (!file.toFile().exists()) return;
final Map<String, Map<String, String>> values = new HashMap<>();
try (final CSVReader reader =
new CSVReader(
new InputStreamReader(new FileInputStream(file.toFile()), Charsets.UTF_8),
CSVParser.DEFAULT_SEPARATOR,
CSVParser.DEFAULT_QUOTE_CHARACTER,
'\0')) {
String[] headers = reader.readNext();
if (headers.length < 2) {
throw new IOException("Invalid language file: " + file);
}
String[] items = null;
while ((items = reader.readNext()) != null) {
if (items.length != headers.length || isEmpty(items)) continue;
Map<String, String> value = new HashMap<>();
for (int i = 0; i < headers.length; i++) {
value.put(headers[i], items[i]);
}
values.put(value.get("key"), value);
}
} catch (IOException e) {
throw e;
}
for (String[] line : lines) {
Map<String, String> current = values.get(line[0]);
if (current != null) {
line[1] = current.get("message");
line[2] = current.get("comment");
}
}
save(file, lines);
}
private void save(Path file, List<String[]> values) throws IOException {
Files.createDirectories(file.getParent());
try (CSVWriter csv =
new CSVWriter(
new OutputStreamWriter(new FileOutputStream(file.toFile()), Charsets.UTF_8))) {
csv.writeNext(CSV_HEADER);
for (String[] line : values) {
for (int i = 0; i < line.length; i++) {
if (StringUtils.isBlank(line[i])) {
line[i] = null;
}
}
csv.writeNext(line);
}
} catch (IOException e) {
throw e;
}
}
}
|
package org.folio.cataloging;
import org.folio.cataloging.integration.GlobalStorage;
import org.folio.cataloging.log.Log;
import org.folio.cataloging.log.MessageCatalog;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Booch utility which acts as a central points for collecting static functions.
*
* @author agazzarini
* @author paulm
* @since 1.0
*/
public abstract class F {
private final static Log LOGGER = new Log(F.class);
private final static String [] EMPTY_ARRAY = {};
private final static int [] EMPTY_INT_ARRAY = {};
/**
* Provides a convenient way to deal with null lists, but replacing null inputs with a null-object (an empty list).
*
* @param values the input array.
* @return the same input, if this is not null, otherwise an empty immutable array.
*/
public static <T> List<T> safe(final List<T> values) {
return values != null ? values : Collections.emptyList();
}
/**
* Provides a convenient way to deal with null array, but replacing null inputs with a null-object (an empty array).
*
* @param values the input array.
* @return the same input, if this is not null, otherwise an empty immutable array.
*/
public static String [] safe(final String [] values) {
return values != null ? values : EMPTY_ARRAY;
}
/**
* Provides a convenient way to deal with null array, but replacing null inputs with a null-object (an empty array).
*
* @param values the input array.
* @return the same input, if this is not null, otherwise an empty immutable array.
*/
public static int [] safe(final int [] values) {
return values != null ? values : EMPTY_INT_ARRAY;
}
/**
* Adds blank spaces to the given string until it reaches the given length.
*
* @param toPad the string to pad.
* @param padLength the padding length.
* @return the padded string.
*/
public static String fixedCharPadding(String toPad, int padLength) {
toPad = toPad.trim().replaceFirst("^0+", "");
StringBuilder builder = new StringBuilder(toPad);
for (int index = 0 , howManyTimes = (padLength - toPad.length()); index < howManyTimes; index++) {
builder.append(" ");
}
return builder.toString();
}
/**
* Returns true if the given string is not null or empty.
*
* @param value the input string.
* @return true if the given string is not null or empty.
*/
public static boolean isNotNullOrEmpty(final String value) {
return value != null && value.trim().length() != 0;
}
/**
* Returns the locale associated with the given code.
*
* @param code the locale code.
* @return the locale associated with the given code, Locale#ENGLISH in case the code is empty or null.
*/
public static Locale locale(final String code) {
return isNotNullOrEmpty(code) ? Locale.forLanguageTag(code) : Locale.ENGLISH;
}
/**
* Utility for making deep copies (vs. clone()'s shallow copies) of objects.
* Objects are first serialized and then deserialized. Error
* checking is fairly minimal in this implementation. If an object is
* encountered that cannot be serialized (or that references an object
* that cannot be serialized) an error is printed to System.err and
* null is returned. Depending on your specific application, it might
* make more sense to have copy(...) re-throw the exception.
*
* A later version of this class includes some minor optimizations.
*
* @return a copy of the object, or null if the object cannot be serialized.
*/
public static Object deepCopy(final Object orig) {
try(final ByteArrayOutputStream bos = new ByteArrayOutputStream();
final ObjectOutputStream out = new ObjectOutputStream(bos)) {
out.writeObject(orig);
out.flush();
out.close();
final ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
return in.readObject();
}
catch(final Exception exception) {
LOGGER.error(MessageCatalog._00013_IO_FAILURE, exception);
return null;
}
}
/**
* Returns the string version of the incoming object, or null (if the object is null).
*
* @param obj the input.
* @return the string version of the incoming object, or null.
*/
public static String asNullableString(final Object obj) {
return (obj != null) ? String.valueOf(obj) : null;
}
public static Character characterFromXML(String s) {
if (s.length() == 0) {
return null;
}
else {
return s.charAt(0);
}
}
public static String stringFromXML(String s) {
if (s.length() == 0) {
return null;
}
else {
return s;
}
}
public static String getFormattedDate(final String formatString) {
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(formatString);
return LocalDateTime.now().format(formatter);
}
/**
* Fix empty flag string.
*
* @param flag -- the string flag to fix.
* @return fixed string.
*/
public static String fixEmptyFlag(final String flag){
return GlobalStorage.YES_FLAG.equalsIgnoreCase(flag)? flag.toUpperCase() :GlobalStorage.NO_FLAG;
}
/**
* Split string over multiple lines if exceed of specified number chars.
*
* @param inputString -- the input string to split.
* @param lineSize -- the number of chars used to split string.
* @return list of string.
*/
public static List<String> splitString(final String inputString, final int lineSize) {
List<String> result = new ArrayList<>();
Pattern p = Pattern.compile("\\b.{1," + (lineSize-1) + "}\\b\\W?");
Matcher m = p.matcher(inputString);
while(m.find()) {
result.add(m.group());
}
return result;
}
}
|
package org.hildan.fxlog;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;
import javafx.stage.Stage;
import org.hildan.fxlog.config.Config;
import org.hildan.fxlog.controllers.MainController;
import org.hildan.fxlog.errors.ErrorDialog;
import org.hildan.fxlog.version.VersionChecker;
import org.jetbrains.annotations.NotNull;
public class FXLog extends Application {
public static final String APP_NAME = "FX Log";
public static final String LAST_VERSION_URL = "https://bintray.com/joffrey-bion/applications/fx-log/_latestVersion";
public static final String GITHUB_URL = "https://github.com/joffrey-bion/fx-log";
public static final String BASE_PACKAGE = '/' + FXLog.class.getPackage().getName().replace('.', '/');
private static final String VIEWS_PATH = BASE_PACKAGE + "/view";
@Override
public void start(Stage stage) {
// fail gracefully on any thread with a dialog
Thread.setDefaultUncaughtExceptionHandler((t, e) -> Platform.runLater(() -> ErrorDialog.uncaughtException(e)));
Thread.currentThread().setUncaughtExceptionHandler((t, e) -> ErrorDialog.uncaughtException(e));
try {
URL url = getClass().getResource(BASE_PACKAGE + "/view/main.fxml");
FXMLLoader loader = new FXMLLoader(url);
Parent root = loader.load();
Scene scene = new Scene(root);
Config.getInstance().getCurrentTheme().apply(scene);
stage.setTitle(APP_NAME);
stage.setScene(scene);
stage.setOnCloseRequest(event -> {
Platform.exit();
System.exit(0);
});
stage.show();
VersionChecker.checkForUpdates(false);
MainController controller = loader.getController();
configureDragAndDrop(scene, controller);
autoOpenFile(controller);
} catch (Exception e) {
ErrorDialog.uncaughtException(e);
}
}
/**
* Loads the given view.
*
* @param viewFilename
* the name of the view. It can be a path relative to the views package.
*
* @return the Parent returned by the FXMLLoader
* @throws IOException
* if the resource couldn't be loaded for some reason
*/
public static Parent loadView(@NotNull String viewFilename) throws IOException {
URL url = FXLog.class.getResource(VIEWS_PATH + '/' + viewFilename);
return FXMLLoader.load(url);
}
private void autoOpenFile(@NotNull MainController controller) {
Config config = Config.getInstance();
if (config.getColumnizers().isEmpty()) {
return; // can't parse logs, better not open a file
}
List<String> params = getParameters().getRaw();
if (!params.isEmpty()) {
String filename = params.get(0);
try {
controller.startTailingFile(new File(filename));
} catch (FileNotFoundException e) {
ErrorDialog.fileNotFound(filename);
}
} else if (config.getOpenLastFileAtStartup()) {
List<String> recentFiles = config.getRecentFiles();
if (!recentFiles.isEmpty()) {
controller.openRecentFile(recentFiles.get(0));
}
}
}
private static void configureDragAndDrop(@NotNull Scene scene, @NotNull MainController controller) {
scene.setOnDragOver(event -> {
Dragboard db = event.getDragboard();
if (db.hasFiles()) {
event.acceptTransferModes(TransferMode.ANY);
} else {
event.consume();
}
});
// Dropping over surface
scene.setOnDragDropped(event -> {
Dragboard db = event.getDragboard();
boolean success = false;
if (db.hasFiles()) {
success = true;
for (File file : db.getFiles()) {
try {
controller.startTailingFile(file);
} catch (FileNotFoundException e) {
ErrorDialog.fileNotFound(file.getAbsolutePath());
}
}
}
event.setDropCompleted(success);
event.consume();
});
}
@Override
public void stop() {
try {
Config.getInstance().persist();
} catch (IOException e) {
ErrorDialog.configWriteException(e);
} catch (Exception e) {
ErrorDialog.uncaughtException(e);
}
}
public static void main(String[] args) {
launch(args);
}
}
|
package org.javacs;
import com.google.common.collect.ImmutableList;
import com.sun.source.tree.*;
import com.sun.source.util.JavacTask;
import com.sun.source.util.TreePath;
import com.sun.source.util.Trees;
import com.sun.tools.javac.api.JavacScope;
import com.sun.tools.javac.comp.GetStaticLevel;
import org.eclipse.lsp4j.CompletionItem;
import org.eclipse.lsp4j.CompletionItemKind;
import javax.lang.model.element.*;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Stream;
public class Completions implements Function<TreePath, Stream<CompletionItem>> {
public static Stream<CompletionItem> at(FocusedResult compiled) {
return compiled.cursor
.map(new Completions(compiled.task))
.orElseGet(Stream::empty);
}
private final JavacTask task;
private final Trees trees;
private final Elements elements;
private final Name thisName, superName;
private Completions(JavacTask task) {
this.task = task;
this.trees = Trees.instance(task);
this.elements = task.getElements();
this.thisName = task.getElements().getName("this");
this.superName = task.getElements().getName("super");
}
@Override
public Stream<CompletionItem> apply(TreePath path) {
Tree leaf = path.getLeaf();
Scope scope = trees.getScope(path);
if (leaf instanceof MemberSelectTree) {
MemberSelectTree select = (MemberSelectTree) leaf;
TreePath expressionPath = new TreePath(path.getParentPath(), select.getExpression());
return completeMembers(expressionPath, scope);
}
else if (leaf instanceof MemberReferenceTree) {
MemberReferenceTree select = (MemberReferenceTree) leaf;
TreePath expressionPath = new TreePath(path.getParentPath(), select.getQualifierExpression());
return completeMembers(expressionPath, scope);
}
else if (leaf instanceof NewClassTree) {
return constructors(scope);
}
else if (leaf instanceof IdentifierTree) {
return allSymbols(scope);
}
else return Stream.empty();
}
/**
* Suggest all accessible members of expression
*/
private Stream<CompletionItem> completeMembers(TreePath expression, Scope from) {
Element element = trees.getElement(expression);
TypeMirror type = trees.getTypeMirror(expression);
if (element == null || type == null)
return Stream.empty();
boolean isStatic = isTypeSymbol(element);
List<? extends Element> all = members(type);
Stream<CompletionItem> filter = all.stream()
.filter(e -> isAccessible(e, from))
.filter(e -> e.getModifiers().contains(Modifier.STATIC) == isStatic)
.flatMap(e -> completionItem(e, distance(e, from)));
if (isStatic) {
filter = Stream.concat(
Stream.of(namedProperty("class")),
filter
);
}
List<CompletionItem> parentClassThis = parentClassScope(from, element)
.filter(classScope -> !isStaticScope(classScope, from) && !isStaticMethod(from))
.map(this::thisAndSuper)
.orElseGet(Collections::emptyList);
filter = Stream.concat(parentClassThis.stream(), filter);
return filter;
}
/**
* If element is the TypeElement of a parent class of from, return its scope
*/
private Optional<Scope> parentClassScope(Scope scope, Element element) {
Scope foundClassScope = null;
while (scope != null) {
if (element.equals(scope.getEnclosingClass()))
foundClassScope = scope;
scope = scope.getEnclosingScope();
}
return Optional.ofNullable(foundClassScope);
}
private List<CompletionItem> thisAndSuper(Scope classScope) {
return ImmutableList.of(namedProperty("this"), namedProperty("super"));
}
/**
* All members of element, if it is TypeElement
*/
private List<? extends Element> members(TypeMirror expressionType) {
if (expressionType == null)
return Collections.emptyList();
return typeElement(expressionType)
.map(elements::getAllMembers)
.orElseGet(Collections::emptyList);
}
/**
* Suggest a simple completion 'name'
*/
private static CompletionItem namedProperty(String name) {
CompletionItem item = new CompletionItem();
item.setKind(CompletionItemKind.Property);
item.setLabel(name);
item.setInsertText(name);
item.setSortText("0/" + name);
return item;
}
private boolean isTypeSymbol(Element element) {
if (element == null)
return false;
switch (element.getKind()) {
case CLASS:
case INTERFACE:
case ENUM:
return true;
default:
return false;
}
}
private Optional<TypeElement> typeElement(TypeMirror type) {
if (type instanceof DeclaredType) {
DeclaredType declared = (DeclaredType) type;
Element element = declared.asElement();
if (element instanceof TypeElement)
return Optional.of((TypeElement) element);
}
return Optional.empty();
}
private Stream<CompletionItem> constructors(Scope start) {
// TODO autocomplete classes that are imported *anywhere* on the source path and sort them second
return findAllSymbols(start).stream()
.filter(this::isTypeSymbol)
.filter(e -> isAccessible(e, start))
.flatMap(this::explodeConstructors)
.flatMap(constructor -> completionItem(constructor, 0));
}
private Stream<ExecutableElement> explodeConstructors(Element element) {
List<? extends Element> all = members(element.asType());
return all.stream().flatMap(this::asConstructor);
}
private Stream<ExecutableElement> asConstructor(Element element) {
if (element.getKind() == ElementKind.CONSTRUCTOR)
return Stream.of((ExecutableElement) element);
else
return Stream.empty();
}
/**
* Suggest all completions that are visible from scope
*/
private Stream<CompletionItem> allSymbols(Scope scope) {
Set<Element> all = findAllSymbols(scope);
return all.stream()
.filter(e -> isAccessible(e, scope))
.flatMap(e -> completionItem(e, distance(e, scope)));
}
private Set<Element> findAllSymbols(Scope scope) {
Set<Element> all = doAllSymbols(scope);
// Add all members of this package
packageOf(scope.getEnclosingClass())
.map(PackageElement::getEnclosedElements)
.ifPresent(all::addAll);
return all;
}
private Optional<PackageElement> packageOf(Element enclosing) {
return Optional.ofNullable(elements.getPackageOf(enclosing));
}
/**
* Recursively check each enclosing scope for members that are visible from the starting scope.
*
* Visibility takes into consideration static / virtual, but not accessibility modifiers.
* We'll deal with those later.
*/
private Set<Element> doAllSymbols(final Scope start) {
Set<Element> acc = new LinkedHashSet<>();
Scope scope = start;
while (scope != null) {
for (Element each : scope.getLocalElements()) {
// Don't include 'this' or 'super' except in the closest scope
boolean skipThis = scope != start || isStaticMethod(scope);
if (skipThis && isThisOrSuper(each))
continue;
acc.add(each);
}
// If this is the scope of a class, add all accessible members of the class
if (scope.getEnclosingClass() != null) {
boolean isStatic = isStaticScope(scope, start) || isStaticMethod(scope);
for (Element each : elements.getAllMembers(scope.getEnclosingClass())) {
// If this is a virtual scope, we have access to all members
// If this is a static scope, we only have access to static members
if (!isStatic || each.getModifiers().contains(Modifier.STATIC))
acc.add(each);
}
}
scope = scope.getEnclosingScope();
}
return acc;
}
private boolean isStaticMethod(Scope scope) {
return scope.getEnclosingMethod() != null && scope.getEnclosingMethod().getModifiers().contains(Modifier.STATIC);
}
private Optional<Scope> classScope(TypeElement classElement) {
if (classElement == null)
return Optional.empty();
TreePath classPath = trees.getPath(classElement);
if (classPath == null)
return Optional.empty();
return Optional.ofNullable(trees.getScope(classPath));
}
private boolean isStaticScope(Scope toOuter, Scope fromInner) {
if (!isParentScope(toOuter, fromInner))
return true;
// It sucks that we have to break through the public API but I can't find any other way to get this info
JavacScope inner = (JavacScope) fromInner;
JavacScope outer = (JavacScope) toOuter;
if (outer == null)
return false;
// TODO is countStaticClasses enough?
int outerStaticLevel = GetStaticLevel.getStaticLevel(outer.getEnv().info) + countStatics(outer);
int innerStaticLevel = GetStaticLevel.getStaticLevel(inner.getEnv().info) + countStatics(inner);
return outerStaticLevel < innerStaticLevel;
}
private int countStatics(Scope scope) {
int count = 0;
Element c = scope.getEnclosingMethod() != null ? scope.getEnclosingMethod() : scope.getEnclosingClass();
while (c != null) {
if (c.getModifiers().contains(Modifier.STATIC))
count++;
c = c.getEnclosingElement();
}
return count;
}
private boolean isParentScope(final Scope toOuter, final Scope fromInner) {
Scope next = fromInner;
while (next != null) {
if (next.equals(toOuter))
return true;
else
next = next.getEnclosingScope();
}
return false;
}
private boolean isThisOrSuper(Element each) {
Name name = each.getSimpleName();
return name.equals(thisName) || name.equals(superName);
}
private int distance(Element e, Scope scope) {
// TODO
return 0;
}
private Stream<CompletionItem> completionItem(Element e, int distance) {
String name = e.getKind() == ElementKind.CONSTRUCTOR ? Hovers.constructorName((ExecutableElement) e) : e.getSimpleName().toString();
String sortText = distance + "/" + name;
switch (e.getKind()) {
case PACKAGE:
return Stream.empty();
case ENUM:
case CLASS: {
CompletionItem item = new CompletionItem();
item.setKind(CompletionItemKind.Class);
item.setLabel(name);
item.setInsertText(name);
item.setSortText(sortText);
return Stream.of(item);
}
case ANNOTATION_TYPE:
case INTERFACE:
case TYPE_PARAMETER: {
CompletionItem item = new CompletionItem();
item.setKind(CompletionItemKind.Reference);
item.setLabel(name);
item.setInsertText(name);
item.setSortText(sortText);
return Stream.of(item);
}
case ENUM_CONSTANT: {
CompletionItem item = new CompletionItem();
item.setKind(CompletionItemKind.Enum);
item.setLabel(name);
item.setDetail(e.getEnclosingElement().getSimpleName().toString());
item.setInsertText(name);
item.setSortText(sortText);
return Stream.of(item);
}
case FIELD: {
CompletionItem item = new CompletionItem();
item.setKind(CompletionItemKind.Property);
item.setLabel(name);
item.setDetail(ShortTypePrinter.print(e.asType()));
docstring(e).ifPresent(item::setDocumentation);
item.setInsertText(name);
item.setSortText(sortText);
return Stream.of(item);
}
case PARAMETER:
case LOCAL_VARIABLE:
case EXCEPTION_PARAMETER: {
CompletionItem item = new CompletionItem();
item.setKind(CompletionItemKind.Variable);
item.setLabel(name);
item.setInsertText(name);
item.setSortText(sortText);
return Stream.of(item);
}
case METHOD: {
ExecutableElement method = (ExecutableElement) e;
CompletionItem item = new CompletionItem();
item.setKind(CompletionItemKind.Method);
item.setLabel(Hovers.methodSignature(method));
item.setDetail(ShortTypePrinter.print(method.getReturnType()));
docstring(e).ifPresent(item::setDocumentation);
item.setInsertText(name); // TODO
item.setSortText(sortText);
item.setFilterText(name);
return Stream.of(item);
}
case CONSTRUCTOR: {
ExecutableElement method = (ExecutableElement) e;
CompletionItem item = new CompletionItem();
String insertText = name;
if (!method.getTypeParameters().isEmpty())
insertText += "<>";
item.setKind(CompletionItemKind.Constructor);
item.setLabel(Hovers.methodSignature(method));
docstring(e).ifPresent(item::setDocumentation);
item.setInsertText(insertText);
item.setSortText(sortText);
item.setFilterText(name);
return Stream.of(item);
}
case STATIC_INIT:
case INSTANCE_INIT:
case OTHER:
case RESOURCE_VARIABLE:
default:
// Nothing user-enterable
// Nothing user-enterable
return Stream.empty();
}
}
private boolean isAccessible(Element e, Scope scope) {
TypeMirror enclosing = e.getEnclosingElement().asType();
if (enclosing instanceof DeclaredType)
return trees.isAccessible(scope, e, (DeclaredType) enclosing);
else
return true;
}
private Optional<String> docstring(Element e) {
return Optional.ofNullable(elements.getDocComment(e));
}
}
|
package com.conveyal.r5.analyst.scenario;
import com.conveyal.r5.transit.PickDropType;
import com.conveyal.r5.transit.TransitLayer;
import com.conveyal.r5.transit.TransportNetwork;
import com.conveyal.r5.transit.TripPattern;
import com.conveyal.r5.transit.TripSchedule;
import gnu.trove.list.TIntList;
import gnu.trove.list.array.TIntArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Insert one or more stops into some trip patterns.
* This splices a new chunk of timetable into an existing route.
* If both fromStop and toStop are specified, the part of the timetable in between those stops is replaced.
* If fromStop is null, then the whole timetable is replaced up to the toStop.
* If toStop in null, then the whole timetable is replaced after fromStop.
* One dwell time should be supplied for each new stop.
* When both fromStop and toStop are specified, there should be one more hop time than there are new stops.
* If one of fromStop or toStop is not specified, then there should be the same number of hop times as stops.
* Inserting stops into some trips but not others on a pattern could create new patterns. Therefore we only allow
* applying this modification to entire routes, which ensures that it is applied to entire patterns.
*/
public class AddStops extends Modification {
public static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(AddStops.class);
/** On which routes the stop should be inserted. */
public Set<String> routes;
/** Stop after which to insert the new stops. */
public String fromStop;
/** Stop before which to insert the new stops. */
public String toStop;
/** Stops to insert, replacing everything between fromStop and toStop in the given routes. */
public List<StopSpec> stops;
/** Number of seconds the vehicle will remain immobile at each of the new stops. */
public int[] dwellTimes;
/**
* Number of seconds the vehicle will spend traveling between each of the new stops.
* There should be one more hop time than dwell times if both of fromStop and toStop are specified.
*/
public int[] hopTimes;
/* The internal integer ID of the stop is looked up only once and cached before the modification is applied. */
private int intFromStop = -1;
/* The internal integer ID of the stop is looked up only once and cached before the modification is applied. */
private int intToStop = -1;
/**
* The internal integer IDs of all the new stops to be added.
* These are looked up or created and cached before the modification is applied.
*/
private TIntList intNewStops = new TIntArrayList();
@Override
public String getType() {
return "add-stops";
}
@Override
public boolean resolve (TransportNetwork network) {
if (fromStop == null && toStop == null) {
warnings.add("At least one of from and to stop must be supplied.");
}
if (fromStop != null) {
intFromStop = network.transitLayer.indexForStopId.get(fromStop);
if (intFromStop == -1) {
warnings.add("Could not find fromStop with GTFS ID " + fromStop);
}
}
if (toStop != null) {
intToStop = network.transitLayer.indexForStopId.get(toStop);
if (intToStop == -1) {
warnings.add("Could not find toStop with GTFS ID " + toStop);
}
}
// It is fine to add no new stops,
// as long as there is a single hop expressing the travel time from fromStop to toStop.
if (stops == null) {
stops = new ArrayList<>();
}
if (dwellTimes == null) {
dwellTimes = new int[0];
}
if (dwellTimes.length != stops.size()) {
warnings.add("The number of dwell times must exactly match the number of new stops.");
}
if (hopTimes == null) {
warnings.add("You must always supply some hop times.");
} else {
// In the case where a from or to stop is not spcified for the insertion.
int expectedHops = stops.size();
// Adjust for the case where we are not inserting at the beginning or end of a pattern.
if (fromStop != null && toStop != null) {
expectedHops += 1;
}
if (hopTimes.length != expectedHops) {
warnings.add("The number of hops must equal the number of new stops (one less if fromStop or toStop is not specified).");
}
}
intNewStops = findOrCreateStops(stops, network);
return warnings.size() > 0;
}
@Override
public boolean apply(TransportNetwork network) {
network.transitLayer.tripPatterns = network.transitLayer.tripPatterns.stream()
.map(this::processTripPattern)
.collect(Collectors.toList());
return warnings.size() > 0;
}
/**
* Given a single TripPattern, if this Modification changes that TripPattern, return a modified copy of it.
* Otherwise return the original, unchanged and uncopied TripPattern.
*/
private TripPattern processTripPattern (TripPattern originalTripPattern) {
if (routes != null && !routes.contains(originalTripPattern.routeId)) {
// This pattern is not on one of the specified routes. The trip pattern should remain unchanged.
return originalTripPattern;
}
// The number of elements to copy from the original stops array before the new segment is spliced in.
// That is, the first element in the output stops array that will contain a stop from the new segment.
int insertBeginIndex = -1;
// The element of the original stops array at which copying resumes after the new segment is spliced in.
int insertEndIndex = -1;
for (int s = 0; s < originalTripPattern.stops.length; s++) {
if (originalTripPattern.stops[s] == intFromStop) {
insertBeginIndex = s + 1;
}
if (originalTripPattern.stops[s] == intToStop) {
insertEndIndex = s;
}
}
if (intFromStop == -1) {
insertBeginIndex = 0;
}
if (intToStop == -1) {
insertEndIndex = originalTripPattern.stops.length;
}
if (insertBeginIndex == -1 || insertEndIndex == -1) {
// We are missing either the beginning or the end of the insertion slice. This TripPattern does not match.
return originalTripPattern;
}
if (insertEndIndex < insertBeginIndex) {
warnings.add("The end of the insertion region must be at or after its beginning.");
return originalTripPattern;
}
// Create a protective copy of this TripPattern whose arrays are shorter or longer as needed.
TripPattern pattern = originalTripPattern.clone();
int nStopsToRemove = insertEndIndex - insertBeginIndex;
int oldLength = pattern.stops.length;
int newLength = (oldLength + intNewStops.size()) - nStopsToRemove;
pattern.stops = new int[newLength];
pattern.pickups = new PickDropType[newLength];
pattern.dropoffs = new PickDropType[newLength];
pattern.wheelchairAccessible = new BitSet(newLength);
// Copy the original pattern to the new one, inserting or leaving out stops as necessary.
// This is copying the stops, PickDropTypes, etc. for the whole pattern.
// Trip timetables will be modified separately below.
// i is the index within the source (original) pattern, j is the index within the target (new) pattern.
LOG.info("Old stop sequence: {}", originalTripPattern.stops);
for (int i = 0, j = 0; i < oldLength; i++) {
if (i == insertBeginIndex) {
// Splice in the new schedule fragment here.
for (int ns = 0; ns < intNewStops.size(); ns++) {
pattern.stops[j] = intNewStops.get(ns);
pattern.pickups[j] = PickDropType.SCHEDULED;
pattern.dropoffs[j] = PickDropType.SCHEDULED;
// Assume newly created stops are wheelchair accessible
// FIXME but we should be copying wheelchair accessibility value for existing inserted stops
pattern.wheelchairAccessible.set(j, true);
j++;
}
}
if (i >= insertBeginIndex && i < insertEndIndex) {
// Skip over the stops in the original (source) trip pattern that are to be replaced.
continue;
}
pattern.stops[j] = originalTripPattern.stops[i];
pattern.pickups[j] = originalTripPattern.pickups[i];
pattern.dropoffs[j] = originalTripPattern.dropoffs[i];
pattern.wheelchairAccessible.set(j, originalTripPattern.wheelchairAccessible.get(i));
j++;
}
LOG.info("New stop sequence: {}", pattern.stops);
// Perform the same splicing operation for every trip on this pattern.
// Here we have to deal with both stops and the hops between them.
pattern.tripSchedules = new ArrayList<>();
for (TripSchedule originalSchedule : originalTripPattern.tripSchedules) {
// Make a protective copy of this TripSchedule, changing the length of its arrays as needed.
TripSchedule schedule = originalSchedule.clone();
pattern.tripSchedules.add(schedule);
schedule.arrivals = new int[newLength];
schedule.departures = new int[newLength];
// Track the departure time from the last written stop in the output across iterations.
int prevOutputDeparture = 0;
// TODO calculate all arrivals and departures zero-based, and then shift them at the end to maintain fixed-point stop.
// The fixed-point stop should be different depending on whether we are splicing onto the beginning or end of the route
// Iterate over all stops in the source pattern. We have an arrival and departure time for each of them.
for (int ss = 0, ts = 0; ss < oldLength; ss++) {
// At stop zero, there is no preceding hop.
int hopTime = originalSchedule.arrivals[ss];
if (ss > 0) {
hopTime -= originalSchedule.departures[ss - 1];
}
// This arrival time will be superseded where the new segment is spliced into the pattern.
int arrivalTime = prevOutputDeparture + hopTime;
// Splice in the new schedule fragment when we reach the right place in the source pattern.
// NOTE dwellTimes[hop] is not always the dwell after hopTimes[hop].
// Either keep two different indexes or pop element 0 off the dwellTimes as needed.
// The number of dwells is always equal to the number of hops or one less, so we iterate over all hops
// but track the dwell index separately.
if (ss == insertBeginIndex) {
int hop = 0, dwell = 0;
while (hop < hopTimes.length) {
if (ss == 0 && dwell == 0) {
// Inserting at the beginning of the route. On the first stop there is no preceding hop.
schedule.arrivals[ts] = originalSchedule.arrivals[0];
schedule.departures[ts] = schedule.arrivals[ts] + dwellTimes[dwell];
prevOutputDeparture = schedule.departures[ts];
dwell++;
ts++;
// Hop is not incremented because we did not consume one.
continue;
}
// Always consume a hop, but only save arrival and departure times if there's a dwell.
arrivalTime = prevOutputDeparture + hopTimes[hop];
hop++;
// There will only be a final dwell if we're splicing onto the end of the pattern.
if (dwell < dwellTimes.length) {
schedule.arrivals[ts] = arrivalTime;
schedule.departures[ts] = schedule.arrivals[ts] + dwellTimes[dwell];
prevOutputDeparture = schedule.departures[ts];
dwell++;
ts++;
}
}
if (hop != hopTimes.length || dwell != dwellTimes.length) {
throw new AssertionError("Hop and dwell arrays with validated lengths were not exhausted. THIS IS A BUG");
}
}
// Skip over the part of the source pattern that was replaced by the new schedule fragment.
// We don't use 'continue' to do this because we want to retain the arrivalTime set during insertion.
while (ss >= insertBeginIndex && ss < insertEndIndex) {
ss++;
}
// Accumulate the remaining ride and dwell times from the source schedule.
// This block will be run unless we're splicing onto the end of the pattern.
if (ts < schedule.arrivals.length) {
schedule.arrivals[ts] = arrivalTime;
int dwellTime = originalSchedule.departures[ss] - originalSchedule.arrivals[ss];
schedule.departures[ts] = schedule.arrivals[ts] + dwellTime;
prevOutputDeparture = schedule.departures[ts];
ts++;
}
}
LOG.info("Original arrivals: {}", originalSchedule.arrivals);
LOG.info("Original departures: {}", originalSchedule.departures);
LOG.info("Modified arrivals: {}", schedule.arrivals);
LOG.info("Modified departures: {}", schedule.departures);
}
return pattern;
}
@Override
public boolean affectsStreetLayer() {
return stops.stream().anyMatch(s -> s.id == null);
}
}
|
package org.javacs;
import java.net.URI;
import java.util.*;
import java.io.*;
import java.nio.file.*;
import java.util.logging.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.lang.model.element.ElementKind;
import javax.tools.*;
import javax.tools.JavaFileObject;
import com.sun.tools.javac.tree.*;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Name;
import io.typefox.lsapi.*;
import io.typefox.lsapi.impl.*;
/**
* Global index of exported symbol declarations and references.
* such as classes, methods, and fields.
*/
public class SymbolIndex {
private static final Logger LOG = Logger.getLogger("main");
/**
* Completes when initial index is done. Useful for testing.
*/
public final CompletableFuture<Void> initialIndexComplete = new CompletableFuture<>();
/**
* Contains all symbol declarations and referencs in a single source file
*/
private static class SourceFileIndex {
private final EnumMap<ElementKind, Map<String, SymbolInformation>> declarations = new EnumMap<>(ElementKind.class);
private final EnumMap<ElementKind, Map<String, Set<Location>>> references = new EnumMap<>(ElementKind.class);
}
/**
* Source path files, for which we support methods and classes
*/
private Map<URI, SourceFileIndex> sourcePath = new HashMap<>();
/**
* Files that are open in the editor. Some functions need to access these.
*/
private Map<URI, JCTree.JCCompilationUnit> activeDocuments = new HashMap<>();
public SymbolIndex(Set<Path> classPath,
Set<Path> sourcePath,
Path outputDirectory) {
JavacHolder compiler = new JavacHolder(classPath, sourcePath, outputDirectory);
Indexer indexer = new Indexer(compiler.context);
// Index exported declarations and references for all files on the source path
// This may take a while, so we'll do it on an extra thread
Thread worker = new Thread("InitialIndex") {
List<JCTree.JCCompilationUnit> parsed = new ArrayList<>();
List<Path> paths = new ArrayList<>();
@Override
public void run() {
// Parse each file
sourcePath.forEach(s -> parseAll(s, parsed, paths));
// Compile all parsed files
compiler.compile(parsed);
parsed.forEach(p -> p.accept(indexer));
// TODO minimize memory use during this process
// Instead of doing parse-all / compile-all,
// queue all files, then do parse / compile on each
// If invoked correctly, javac should avoid reparsing the same file twice
// Then, use the same mechanism as the desugar / generate phases to remove method bodies,
// to reclaim memory as we go
initialIndexComplete.complete(null);
// TODO verify that compiler and all its resources get destroyed
}
/**
* Look for .java files and invalidate them
*/
private void parseAll(Path path, List<JCTree.JCCompilationUnit> trees, List<Path> paths) {
if (Files.isDirectory(path)) try {
Files.list(path).forEach(p -> parseAll(p, trees, paths));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
else if (path.getFileName().toString().endsWith(".java")) {
LOG.info("Index " + path);
JavaFileObject file = compiler.fileManager.getRegularFile(path.toFile());
trees.add(compiler.parse(file));
paths.add(path);
}
}
};
worker.start();
}
/**
* Search all indexed symbols
*/
public Stream<? extends SymbolInformation> search(String query) {
Stream<SymbolInformation> classes = allSymbols(ElementKind.CLASS);
Stream<SymbolInformation> methods = allSymbols(ElementKind.METHOD);
return Stream.concat(classes, methods)
.filter(s -> containsCharsInOrder(s.getName(), query));
}
/**
* Get all symbols in an open file
*/
public Stream<? extends SymbolInformation> allInFile(URI source) {
SourceFileIndex index = sourcePath.getOrDefault(source, new SourceFileIndex());
return index.declarations.values().stream().flatMap(map -> map.values().stream());
}
private Stream<SymbolInformation> allSymbols(ElementKind kind) {
return sourcePath.values().stream().flatMap(f -> allSymbolsInFile(f, kind));
}
private Stream<SymbolInformation> allSymbolsInFile(SourceFileIndex f, ElementKind kind) {
return f.declarations.getOrDefault(kind, Collections.emptyMap())
.values()
.stream();
}
/**
* Find all references to a symbol
*/
public Stream<? extends Location> references(Symbol symbol) {
// For indexed symbols, just look up the precomputed references
if (shouldIndex(symbol)) {
String key = uniqueName(symbol);
return sourcePath.values().stream().flatMap(f -> {
Map<String, Set<Location>> bySymbol = f.references.getOrDefault(symbol.getKind(), Collections.emptyMap());
Set<Location> locations = bySymbol.getOrDefault(key, Collections.emptySet());
return locations.stream();
});
}
// For non-indexed symbols, scan the active set
else {
return activeDocuments.values().stream().flatMap(compilationUnit -> {
List<LocationImpl> references = new ArrayList<>();
compilationUnit.accept(new TreeScanner() {
@Override
public void visitSelect(JCTree.JCFieldAccess tree) {
super.visitSelect(tree);
if (tree.sym != null && tree.sym.equals(symbol))
references.add(location(tree, compilationUnit));
}
@Override
public void visitReference(JCTree.JCMemberReference tree) {
super.visitReference(tree);
if (tree.sym != null && tree.sym.equals(symbol))
references.add(location(tree, compilationUnit));
}
@Override
public void visitIdent(JCTree.JCIdent tree) {
super.visitIdent(tree);
if (tree.sym != null && tree.sym.equals(symbol))
references.add(location(tree, compilationUnit));
}
});
return references.stream();
});
}
}
public Optional<SymbolInformation> findSymbol(Symbol symbol) {
ElementKind kind = symbol.getKind();
String key = uniqueName(symbol);
for (SourceFileIndex f : sourcePath.values()) {
Map<String, SymbolInformation> withKind = f.declarations.getOrDefault(kind, Collections.emptyMap());
if (withKind.containsKey(key))
return Optional.of(withKind.get(key));
}
for (JCTree.JCCompilationUnit compilationUnit : activeDocuments.values()) {
JCTree symbolTree = TreeInfo.declarationFor(symbol, compilationUnit);
if (symbolTree != null)
return Optional.of(symbolInformation(symbolTree, symbol, compilationUnit));
}
return Optional.empty();
}
/**
* Check if name contains all the characters of query in order.
* For example, name 'FooBar' contains query 'FB', but not 'BF'
*/
private boolean containsCharsInOrder(String name, String query) {
int iName = 0, iQuery = 0;
while (iName < name.length() && iQuery < query.length()) {
// If query matches name, consume a character of query and of name
if (name.charAt(iName) == query.charAt(iQuery)) {
iName++;
iQuery++;
}
// Otherwise consume a character of name
else {
iName++;
}
}
// If the entire query was consumed, we found what we were looking for
return iQuery == query.length();
}
private class Indexer extends BaseScanner {
private SourceFileIndex index;
public Indexer(Context context) {
super(context);
}
@Override
public void visitTopLevel(JCTree.JCCompilationUnit tree) {
URI uri = tree.getSourceFile().toUri();
index = new SourceFileIndex();
sourcePath.put(uri, index);
super.visitTopLevel(tree);
}
@Override
public void visitClassDef(JCTree.JCClassDecl tree) {
super.visitClassDef(tree);
addDeclaration(tree, tree.sym);
}
@Override
public void visitMethodDef(JCTree.JCMethodDecl tree) {
super.visitMethodDef(tree);
addDeclaration(tree, tree.sym);
}
@Override
public void visitVarDef(JCTree.JCVariableDecl tree) {
super.visitVarDef(tree);
addDeclaration(tree, tree.sym);
}
@Override
public void visitSelect(JCTree.JCFieldAccess tree) {
super.visitSelect(tree);
addReference(tree, tree.sym);
}
@Override
public void visitReference(JCTree.JCMemberReference tree) {
super.visitReference(tree);
addReference(tree, tree.sym);
}
@Override
public void visitIdent(JCTree.JCIdent tree) {
addReference(tree, tree.sym);
}
@Override
public void visitNewClass(JCTree.JCNewClass tree) {
super.visitNewClass(tree);
addReference(tree, tree.constructor);
}
private void addDeclaration(JCTree tree, Symbol symbol) {
if (symbol != null && onSourcePath(symbol) && shouldIndex(symbol)) {
String key = uniqueName(symbol);
SymbolInformationImpl info = symbolInformation(tree, symbol, compilationUnit);
Map<String, SymbolInformation> withKind = index.declarations.computeIfAbsent(symbol.getKind(), newKind -> new HashMap<>());
withKind.put(key, info);
}
}
private void addReference(JCTree tree, Symbol symbol) {
if (symbol != null && onSourcePath(symbol) && shouldIndex(symbol)) {
String key = uniqueName(symbol);
Map<String, Set<Location>> withKind = index.references.computeIfAbsent(symbol.getKind(), newKind -> new HashMap<>());
Set<Location> locations = withKind.computeIfAbsent(key, newName -> new HashSet<>());
LocationImpl location = location(tree, compilationUnit);
locations.add(location);
}
}
}
private static boolean shouldIndex(Symbol symbol) {
ElementKind kind = symbol.getKind();
switch (kind) {
case ENUM:
case ANNOTATION_TYPE:
case INTERFACE:
case ENUM_CONSTANT:
case FIELD:
case METHOD:
return true;
case CLASS:
return !symbol.isAnonymous();
case CONSTRUCTOR:
// TODO also skip generated constructors
return !symbol.getEnclosingElement().isAnonymous();
default:
return false;
}
}
private static SymbolInformationImpl symbolInformation(JCTree tree, Symbol symbol, JCTree.JCCompilationUnit compilationUnit) {
LocationImpl location = location(tree, compilationUnit);
SymbolInformationImpl info = new SymbolInformationImpl();
info.setContainerName(symbol.getEnclosingElement().getQualifiedName().toString());
info.setKind(symbolInformationKind(symbol.getKind()));
// Constructors have name <init>, use class name instead
if (symbol.getKind() == ElementKind.CONSTRUCTOR)
info.setName(symbol.getEnclosingElement().getSimpleName().toString());
else
info.setName(symbol.getSimpleName().toString());
info.setLocation(location);
return info;
}
private static LocationImpl location(JCTree tree, JCTree.JCCompilationUnit compilationUnit) {
try {
// Declaration should include offset
int offset = tree.pos;
int end = tree.getEndPosition(null);
// If symbol is a class, offset points to 'class' keyword, not name
// Find the name by searching the text of the source, starting at the 'class' keyword
if (tree instanceof JCTree.JCClassDecl) {
Symbol.ClassSymbol symbol = ((JCTree.JCClassDecl) tree).sym;
offset = offset(compilationUnit, symbol, offset);
end = offset + symbol.name.length();
}
else if (tree instanceof JCTree.JCMethodDecl) {
Symbol.MethodSymbol symbol = ((JCTree.JCMethodDecl) tree).sym;
offset = offset(compilationUnit, symbol, offset);
end = offset + symbol.name.length();
}
else if (tree instanceof JCTree.JCVariableDecl) {
Symbol.VarSymbol symbol = ((JCTree.JCVariableDecl) tree).sym;
offset = offset(compilationUnit, symbol, offset);
end = offset + symbol.name.length();
}
RangeImpl position = JavaLanguageServer.findPosition(compilationUnit.getSourceFile(),
offset,
end);
LocationImpl location = new LocationImpl();
location.setUri(compilationUnit.getSourceFile().toUri().toString());
location.setRange(position);
return location;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static int offset(JCTree.JCCompilationUnit compilationUnit,
Symbol symbol,
int estimate) throws IOException {
CharSequence content = compilationUnit.sourcefile.getCharContent(false);
Name name = symbol.getSimpleName();
estimate = indexOf(content, name, estimate);
return estimate;
}
/**
* Adapted from java.util.String.
*
* The source is the character array being searched, and the target
* is the string being searched for.
*
* @param source the characters being searched.
* @param target the characters being searched for.
* @param fromIndex the index to begin searching from.
*/
private static int indexOf(CharSequence source, CharSequence target, int fromIndex) {
int sourceOffset = 0, sourceCount = source.length(), targetOffset = 0, targetCount = target.length();
if (fromIndex >= sourceCount) {
return (targetCount == 0 ? sourceCount : -1);
}
if (fromIndex < 0) {
fromIndex = 0;
}
if (targetCount == 0) {
return fromIndex;
}
char first = target.charAt(targetOffset);
int max = sourceOffset + (sourceCount - targetCount);
for (int i = sourceOffset + fromIndex; i <= max; i++) {
/* Look for first character. */
if (source.charAt(i) != first) {
while (++i <= max && source.charAt(i) != first);
}
/* Found first character, now look at the rest of v2 */
if (i <= max) {
int j = i + 1;
int end = j + targetCount - 1;
for (int k = targetOffset + 1; j < end && source.charAt(j) == target.charAt(k); j++, k++);
if (j == end) {
/* Found whole string. */
return i - sourceOffset;
}
}
}
return -1;
}
private static boolean onSourcePath(Symbol symbol) {
return true; // TODO
}
private static String uniqueName(Symbol s) {
StringJoiner acc = new StringJoiner(".");
createUniqueName(s, acc);
return acc.toString();
}
private static void createUniqueName(Symbol s, StringJoiner acc) {
if (s != null) {
createUniqueName(s.owner, acc);
if (!s.getSimpleName().isEmpty())
acc.add(s.getSimpleName().toString());
}
}
private static SymbolKind symbolInformationKind(ElementKind kind) {
switch (kind) {
case PACKAGE:
return SymbolKind.Package;
case ENUM:
case ENUM_CONSTANT:
return SymbolKind.Enum;
case CLASS:
return SymbolKind.Class;
case ANNOTATION_TYPE:
case INTERFACE:
return SymbolKind.Interface;
case FIELD:
return SymbolKind.Property;
case PARAMETER:
case LOCAL_VARIABLE:
case EXCEPTION_PARAMETER:
case TYPE_PARAMETER:
return SymbolKind.Variable;
case METHOD:
case STATIC_INIT:
case INSTANCE_INIT:
return SymbolKind.Method;
case CONSTRUCTOR:
return SymbolKind.Constructor;
case OTHER:
case RESOURCE_VARIABLE:
default:
return SymbolKind.String;
}
}
public void update(JCTree.JCCompilationUnit tree, Context context) {
Indexer indexer = new Indexer(context);
tree.accept(indexer);
activeDocuments.put(tree.getSourceFile().toUri(), tree);
}
public void clear(URI sourceFile) {
sourcePath.remove(sourceFile);
activeDocuments.remove(sourceFile);
}
}
|
package org.jpmml.sklearn;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.xml.transform.stream.StreamResult;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import net.razorvine.pickle.objects.ClassDict;
import org.dmg.pmml.PMML;
import org.jpmml.model.JAXBUtil;
import sklearn.Estimator;
import sklearn_pandas.DataFrameMapper;
public class Main {
@Parameter (
names = {"--pkl-input", "--pkl-estimator-input"},
description = "Estimator pickle input file",
required = true
)
private File estimatorInput = null;
@Parameter (
names = "--help",
description = "Show the list of configuration options and exit",
help = true
)
private boolean help = false;
@Parameter (
names = "--pkl-mapper-input",
description = "DataFrameMapper pickle input file",
required = false
)
private File mapperInput = null;
@Parameter (
names = "--pmml-output",
description = "PMML output file",
required = true
)
private File output = null;
static
public void main(String... args) throws Exception {
Main main = new Main();
JCommander commander = new JCommander(main);
commander.setProgramName(Main.class.getName());
try {
commander.parse(args);
} catch(ParameterException pe){
commander.usage();
System.exit(-1);
}
if(main.help){
commander.usage();
System.exit(0);
}
main.run();
}
private void run() throws Exception {
PMML pmml = convert();
OutputStream os = new FileOutputStream(this.output);
try {
JAXBUtil.marshalPMML(pmml, new StreamResult(os));
} finally {
os.close();
}
}
public PMML convert() throws IOException {
PMML pmml;
Storage estimatorStorage = PickleUtil.createStorage(this.estimatorInput);
try {
Object object = PickleUtil.unpickle(estimatorStorage);
if(!(object instanceof Estimator)){
throw new IllegalArgumentException("The unpickled estimator object (" + getClass(object) + ") is not an Estimator or is not a supported Estimator subclass");
}
Estimator estimator = (Estimator)object;
pmml = estimator.encodePMML();
} finally {
estimatorStorage.close();
}
if(this.mapperInput != null){
Storage mapperStorage = PickleUtil.createStorage(this.mapperInput);
try {
Object object = PickleUtil.unpickle(mapperStorage);
if(!(object instanceof DataFrameMapper)){
throw new IllegalArgumentException("The unpickled mapper object (" + getClass(object) + ") is not a DataFrameMapper");
}
DataFrameMapper mapper = (DataFrameMapper)object;
mapper.updatePMML(pmml);
} finally {
mapperStorage.close();
}
}
return pmml;
}
public File getEstimatorInput(){
return this.estimatorInput;
}
public void setEstimatorInput(File estimatorInput){
this.estimatorInput = estimatorInput;
}
public File getMapperInput(){
return this.mapperInput;
}
public void setMapperInput(File mapperInput){
this.mapperInput = mapperInput;
}
public File getOutput(){
return this.output;
}
public void setOutput(File output){
this.output = output;
}
static
private String getClass(Object object){
if(object instanceof ClassDict){
ClassDict classDict = (ClassDict)object;
String clazz = (String)classDict.get("__class__");
return "Python class " + clazz;
}
Class<?> clazz = object.getClass();
return "Java class " + clazz.getName();
}
}
|
package com.demigodsrpg.stoa.model;
import com.censoredsoftware.library.util.CommonSymbol;
import com.demigodsrpg.stoa.Stoa;
import com.demigodsrpg.stoa.StoaPlugin;
import com.demigodsrpg.stoa.StoaServer;
import com.demigodsrpg.stoa.battle.Participant;
import com.demigodsrpg.stoa.deity.Ability;
import com.demigodsrpg.stoa.deity.Alliance;
import com.demigodsrpg.stoa.deity.Deity;
import com.demigodsrpg.stoa.event.StoaChatEvent;
import com.demigodsrpg.stoa.util.*;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.iciql.Db;
import com.iciql.Iciql;
import org.bukkit.*;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.potion.PotionEffect;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
@Iciql.IQTable(name = "dg_characters")
public class CharacterModel implements Participant {
// -- MODEL META -- //
@Iciql.IQColumn(name = "id", primaryKey = true)
public String uuid = UUID.randomUUID().toString();
// -- DATA -- //
@Iciql.IQColumn
public String name;
@Iciql.IQColumn
public String deity;
@Iciql.IQColumn
public Boolean alive;
@Iciql.IQColumn
public Boolean active;
@Iciql.IQColumn
public Boolean usable;
@Iciql.IQColumn
public Integer hunger;
@Iciql.IQColumn
public Integer level;
@Iciql.IQColumn(name = "kill_count")
public Integer killCount;
@Iciql.IQColumn
public Double health;
@Iciql.IQColumn
public Float experience;
@Iciql.IQEnum
@Iciql.IQColumn(name = "game_mode")
public GameMode gameMode;
// -- ADDITIONAL DATA -- //
@Iciql.IQColumn
public Integer favor;
@Iciql.IQColumn(name = "max_favor")
public Integer maxFavor;
@Iciql.IQColumn(name = "skill_points")
public Integer skillPoints;
// -- FOREIGN DATA -- //
@Iciql.IQColumn(nullable = false, name = "player_id")
public String playerId;
@Iciql.IQColumn(name = "last_location")
public String lastLocation;
@Iciql.IQColumn
public String bedSpawn;
// -- DEFAULT CONSTRUCTOR -- //
public CharacterModel() {
}
// -- PRACTICAL CONSTRUCTOR -- //
public CharacterModel(final PlayerModel player, final String charName, final Deity deity) {
// Set name
name = charName;
// Defaults
this.deity = deity.getName();
alive = true;
active = false;
usable = true;
hunger = 20;
level = 0;
killCount = 0;
health = deity.getMaxHealth();
experience = 0.0F;
gameMode = GameMode.SURVIVAL;
// Additional Defaults
favor = deity.getMaxFavor();
maxFavor = deity.getMaxFavor();
skillPoints = StoaPlugin.config().getInt("skillPoints");
// Foreign Keys
playerId = player.mojangAccount;
}
public String getId() {
return uuid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Boolean getAlive() {
return alive;
}
public void setAlive(Boolean alive) {
this.alive = alive;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public Boolean getUsable() {
return usable;
}
public void setUsable(Boolean usable) {
this.usable = usable;
}
public Integer getHunger() {
return hunger;
}
public void setHunger(Integer hunger) {
this.hunger = hunger;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
public Integer getKillCount() {
return killCount;
}
public void addKill() {
killCount++;
}
public int getDeathCount() {
return getDeaths().size();
}
public void addDeath() {
DeathModel death = new DeathModel(this);
Db db = StoaServer.openDb();
db.insert(death);
db.close();
}
public void addDeath(CharacterModel attacker) {
DeathModel death = new DeathModel(this, attacker);
Db db = StoaServer.openDb();
db.insert(death);
db.close();
}
public List<DeathModel> getDeaths() {
DeathModel alias = new DeathModel();
Db db = StoaServer.openDb();
try {
return db.from(alias).where(alias.victimId).is(uuid).select();
} finally {
db.close();
}
}
public Double getHealth() {
return health;
}
public void setHealth(Double health) {
this.health = health;
}
public Float getExperience() {
return experience;
}
public void setExperience(Float experience) {
this.experience = experience;
}
public GameMode getGameMode() {
return gameMode;
}
public void setGameMode(GameMode gameMode) {
this.gameMode = gameMode;
}
public Integer getFavor() {
return favor;
}
public void setFavor(Integer favor) {
this.favor = favor;
}
public void addFavor(Integer add) {
this.favor += add;
}
public void removeFavor(Integer remove) {
this.favor -= remove;
}
public Integer getMaxFavor() {
return maxFavor;
}
public void setMaxFavor(Integer maxFavor) {
this.maxFavor = maxFavor;
}
public Integer getSkillPoints() {
return skillPoints;
}
public void setSkillPoints(Integer skillPoints) {
this.skillPoints = skillPoints;
}
public void addSkillPoints(Integer add) {
skillPoints += add;
}
public void minusSkillPoints(Integer minus) {
skillPoints -= minus;
}
public String getPlayerId() {
return playerId;
}
public void setPlayerId(String playerId) {
this.playerId = playerId;
}
public PlayerInventoryModel getInventory() {
return ItemUtil2.playerInvFromOwnerId(uuid);
}
public EnderChestInventoryModel getEnderInventory() {
return ItemUtil2.enderInvFromOwnerId(uuid);
}
public Location getLastLocation() {
return LocationUtil.locationFromString(lastLocation);
}
public void setLastLocation(Location location) {
this.lastLocation = LocationUtil.stringFromLocation(location);
}
public Location getBedSpawn() {
return LocationUtil.locationFromString(bedSpawn);
}
public void setBedSpawn(Location bedSpawn) {
this.bedSpawn = LocationUtil.stringFromLocation(bedSpawn);
}
public List<PotionEffect> getPotionEffects() {
PotionEffectModel alias = new PotionEffectModel();
Db db = StoaServer.openDb();
try {
return db.from(alias).where(alias.id).is(uuid).selectFirst().getPotionEffects();
} finally {
db.close();
}
}
public void setPotionEffects(Collection<PotionEffect> effects) {
PotionEffectModel alias = new PotionEffectModel();
Db db = StoaServer.openDb();
PotionEffectModel model = db.from(alias).where(alias.id).is(uuid).selectFirst();
if (model != null) {
db.delete(model);
}
model = new PotionEffectModel(uuid, effects);
db.insert(model);
db.close();
}
public Collection<Deity> getMinorDeities() {
// TODO
return null;
}
public boolean isDeity(String name) {
return deity.equals(name);
}
public Deity getDeity() {
return Stoa.getMythos().getDeity(deity);
}
public void setDeity(String deity) {
this.deity = deity;
}
public Alliance getAlliance() {
return getDeity().getAlliance();
}
public List<StructureModel> getOwnedStructures() {
StructureModel alias = new StructureModel();
Db db = StoaServer.openDb();
try {
return db.from(alias).where(alias.getOwnerId()).is(uuid).select();
} finally {
db.close();
}
}
public List<StructureModel> getOwnedStructures(final String type) {
StructureModel alias = new StructureModel();
Db db = StoaServer.openDb();
try {
return db.from(alias).where(alias.getOwnerId()).is(uuid).and(alias.typeName).is(type).select();
} finally {
db.close();
}
}
public int getFavorRegen() {
SkillModel alias = new SkillModel();
Db db = StoaServer.openDb();
SkillModel found = Iterables.getFirst(db.from(alias).where(alias.type).is(SkillModel.Type.FAVOR_REGEN).and(alias.characterId).is(uuid).select(), null);
int favorRegenSkill = found != null ? 4 * found.level : 0;
int regenRate = (int) Math.ceil(StoaPlugin.config().getDouble("multipliers.favor") * (getDeity().getFavorRegen() + favorRegenSkill));
if (regenRate < 30) regenRate = 30;
return regenRate;
}
public void setCanPvp(boolean pvp) {
Db db = StoaServer.openDb();
PlayerModel player = PlayerUtil.fromId(playerId);
player.setCanPvp(pvp);
db.update(player);
db.close();
}
public List<SkillModel> getSkills() {
SkillModel alias = new SkillModel();
Db db = StoaServer.openDb();
try {
return db.from(alias).where(alias.characterId).is(uuid).select();
} finally {
db.close();
}
}
public int getIndividualSkillCap() {
int total = 0;
for (SkillModel skill : getSkills())
total += skill.getLevel();
return getOverallSkillCap() - total;
}
public int getOverallSkillCap() {
// This is done this way so it can easily be manipulated later
return StoaPlugin.config().getInt("caps.skills");
}
public void updateUseable() {
usable = getDeity() != null && getDeity().getFlags().contains(Deity.Flag.PLAYABLE);
}
public boolean alliedTo(Participant participant) {
return getAlliance().equals(participant.getCharacter().getAlliance());
}
public Collection<TameableModel> getPets() {
return TameableUtil.findByOwner(uuid);
}
public void remove() {
Db db = StoaServer.openDb();
// Define controller
PlayerModel player = PlayerUtil.fromId(playerId);
// Switch the player to mortal
if (getEntity() != null && player.currentCharacterId.equals(uuid)) {
player.setToMortal();
player.resetCurrent();
}
for (StructureModel structure : StructureUtil.getStructuresWithFlag(StructureModel.Flag.DELETE_WITH_OWNER))
if (structure.getOwnerId() != null && structure.getOwnerId().equals(uuid)) structure.remove();
// for(StoaPotionEffect potion : getPotionEffects())
// potion.remove();
db.delete(getInventory());
db.delete(getEnderInventory());
db.delete(this);
}
public List<Ability> getAbilities() {
List<Ability> list = Lists.newArrayList();
list.addAll(getDeity().getAbilities());
for (Deity minorDeity : getMinorDeities())
list.addAll(minorDeity.getAbilities());
return list;
}
public CharacterModel sendAllianceMessage(String message) {
StoaChatEvent chatEvent = new StoaChatEvent(message, Stoa.getServer().getOnlineCharactersWithAlliance(getAlliance()));
Bukkit.getPluginManager().callEvent(chatEvent);
if (!chatEvent.isCancelled()) for (Player player : chatEvent.getRecipients())
player.sendMessage(message);
return this;
}
public CharacterModel chatWithAlliance(String message) {
sendAllianceMessage(" " + ChatColor.GRAY + getAlliance() + "s " + ChatColor.DARK_GRAY + "" + CommonSymbol.BLACK_FLAG + " " + getDeity().getColor() + name + ChatColor.GRAY + ": " + ChatColor.RESET + message);
MessageUtil.info("[" + getAlliance() + "]" + name + ": " + message);
return this;
}
public void saveInventory() {
Db db = StoaServer.openDb();
PlayerInventoryModel inventoryModel = getInventory();
PlayerInventory inventory = getEntity().getInventory();
inventoryModel.setArmor(inventory.getArmorContents());
inventoryModel.setContents(inventory.getContents());
db.update(inventoryModel);
EnderChestInventoryModel enderChestInventoryModel = getEnderInventory();
Inventory enderChestInventory = getEntity().getEnderChest();
enderChestInventoryModel.setContents(enderChestInventory.getContents());
db.update(enderChestInventoryModel);
db.close();
}
public CharacterModel applyToPlayer(final Player player) {
// Define variables
PlayerModel playerSave = PlayerUtil.fromId(playerId);
// Set character to active
setActive(true);
if (playerSave.getMortalInventory() != null) {
playerSave.setMortalName(player.getDisplayName());
playerSave.setMortalListName(player.getPlayerListName());
}
// Update their inventory
if (playerSave.getCharacters().size() == 1) saveInventory();
else player.getEnderChest().clear();
getInventory().setToPlayer(player);
getEnderInventory().setToPlayer(player);
// Update health, experience
player.setMaxHealth(getDeity().getMaxHealth());
player.setHealth(health >= getDeity().getMaxHealth() ? getDeity().getMaxHealth() : health);
player.setFoodLevel(hunger);
player.setExp(experience);
player.setLevel(level);
for (PotionEffect potion : player.getActivePotionEffects())
player.removePotionEffect(potion.getType());
List<PotionEffect> potionEffects = getPotionEffects();
if (!potionEffects.isEmpty()) player.addPotionEffects(potionEffects);
/*
Bukkit.getScheduler().scheduleSyncDelayedTask(StoaPlugin.getInst(), new BukkitRunnable()
{
@Override
public void run()
{
if(getBedSpawn() != null) player.setBedSpawnLocation(getBedSpawn());
}
}, 1);
*/
if (gameMode != null) player.setGameMode(gameMode);
// Set player display name
player.setDisplayName(getDeity().getColor() + name);
player.setPlayerListName(getDeity().getColor() + name); // FIXME
// Re-own pets
// StoaTameable.reownPets(player, this);
return this;
}
public int getAscensions() {
double total = 0.0;
for (SkillModel skill : getSkills())
total += skill.getLevel();
return (int) Math.ceil(total / getSkills().size());
}
@Override
public CharacterModel getCharacter() {
return this;
}
@Override
public OfflinePlayer getOfflinePlayer() {
return Bukkit.getOfflinePlayer(UUID.fromString(playerId));
}
@Override
public boolean hasCharacter() {
return true;
}
@Override
public boolean canPvp() {
return PlayerUtil.fromId(playerId).canPvp();
}
@Override
public Location getCurrentLocation() {
return PlayerUtil.fromId(playerId).getCurrentLocation();
}
@Override
public Player getEntity() {
return PlayerUtil.fromId(playerId).getEntity();
}
}
|
package org.lantern.state;
import java.net.URI;
import java.util.Locale;
import org.apache.commons.lang3.time.FastDateFormat;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.codehaus.jackson.map.annotate.JsonView;
import org.lantern.LanternClientConstants;
import org.lantern.LanternRosterEntry;
import org.lantern.event.Events;
import org.lantern.state.Model.Persistent;
import org.lantern.state.Model.Run;
import org.lantern.util.LanternTrafficCounter;
/**
* Class containing data for an individual peer, including active connections,
* IP address, etc.
*/
public class Peer {
private String peerid = "";
private String country = "";
public enum Type {
pc,
cloud,
laeproxy
}
//private final Collection<PeerSocketWrapper> sockets =
// new HashSet<PeerSocketWrapper>();
//private final String base64Cert;
private double lat = 0.0;
private double lon = 0.0;
private String type;
private boolean online;
private boolean mapped;
private String ip = "";
private Mode mode;
private boolean incoming;
private LanternTrafficCounter trafficCounter;
private long bytesUp;
private long bytesDn;
private String version = "";
private long lastConnectedLong;
private LanternRosterEntry rosterEntry;
private int port;
public Peer() {
}
public Peer(final URI peerId,final String countryCode,
final boolean mapped, final double latitude,
final double longitude, final Type type,
final String ip, final int port, final Mode mode, final boolean incoming,
final LanternTrafficCounter trafficCounter,
final LanternRosterEntry rosterEntry) {
this.mapped = mapped;
this.lat = latitude;
this.lon = longitude;
this.port = port;
this.rosterEntry = rosterEntry;
this.peerid = peerId.toASCIIString();
this.ip = ip;
this.mode = mode;
this.incoming = incoming;
this.type = type.toString();
this.country = countryCode.toUpperCase(Locale.US);
this.trafficCounter = trafficCounter;
// Peers are online when constructed this way (because we presumably
// just received some type of message from them).
this.online = true;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public double getLat() {
if (lat == 0.0) {
return Double.MAX_VALUE;
}
return lat;
}
public void setLat(double latitude) {
this.lat = latitude;
}
public double getLon() {
if (lon == 0.0) {
return Double.MAX_VALUE;
}
return lon;
}
public void setLon(double longitude) {
this.lon = longitude;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public boolean isOnline() {
return online;
}
public void setOnline(boolean online) {
this.online = online;
}
public boolean isMapped() {
return mapped;
}
public void setMapped(boolean mapped) {
this.mapped = mapped;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public Mode getMode() {
return mode;
}
public void setMode(Mode mode) {
this.mode = mode;
}
@JsonView({Run.class})
public boolean isConnected() {
if (this.trafficCounter == null) {
return false;
}
if (!this.trafficCounter.isConnected()) {
return getBpsUpDn() > 0L;
}
return true;
}
public boolean isIncoming() {
return incoming;
}
public void setIncoming(boolean incoming) {
this.incoming = incoming;
}
@JsonView({Run.class})
public long getBpsUp() {
if (this.trafficCounter != null) {
return trafficCounter.getCurrentWrittenBytes() *
LanternClientConstants.SYNC_INTERVAL_SECONDS;
}
return 0L;
}
@JsonView({Run.class})
public long getBpsDown() {
if (this.trafficCounter != null) {
return trafficCounter.getCurrentReadBytes() *
LanternClientConstants.SYNC_INTERVAL_SECONDS;
}
return 0L;
}
@JsonView({Run.class})
public long getBpsUpDn() {
return getBpsUp() + getBpsDown();
}
public long getBytesUp() {
if (this.trafficCounter != null) {
return bytesUp +
//trafficCounter.getTrafficCounter().getCumulativeWrittenBytes();
trafficCounter.getCumulativeWrittenBytes();
}
return this.bytesUp;
}
public void setBytesUp(long bytesUp) {
this.bytesUp = bytesUp;
}
public long getBytesDn() {
if (this.trafficCounter != null) {
return bytesDn +
//trafficCounter.getTrafficCounter().getCumulativeReadBytes();
trafficCounter.getCumulativeReadBytes();
}
return this.bytesDn;
}
public void setBytesDn(long bytesDn) {
this.bytesDn = bytesDn;
}
@JsonView({Run.class})
public long getBytesUpDn() {
if (this.trafficCounter != null) {
return getBytesUp() + getBytesDn();
}
return 0L;
}
@JsonIgnore
public LanternTrafficCounter getTrafficCounter() {
return trafficCounter;
}
public void setTrafficCounter(
final LanternTrafficCounter trafficCounter) {
this.trafficCounter = trafficCounter;
}
@JsonView({Run.class})
public int getNSockets() {
if (this.trafficCounter != null) {
return trafficCounter.getNumSockets();
}
return 0;
}
@JsonView({Run.class})
@JsonSerialize(include=Inclusion.NON_NULL)
public String getLastConnected() {
long lastConnected = getLastConnectedLong();
if (lastConnected == 0) {
return null;
}
return FastDateFormat.getInstance("yyyy-MM-dd' 'HH:mm:ss").format(
lastConnected);
}
@JsonView({Persistent.class})
public long getLastConnectedLong() {
if (this.trafficCounter != null) {
final long last = trafficCounter.getLastConnected();
// Only use the counter data if it has connected.
if (last > 0L) return last;
}
return this.lastConnectedLong;
}
public void setLastConnectedLong(final long lastConnectedLong) {
this.lastConnectedLong = lastConnectedLong;
Events.eventBus().post(new PeerLastConnectedChangedEvent(this));
}
public String getPeerid() {
return peerid;
}
public void setPeerid(String peerid) {
this.peerid = peerid;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
@JsonSerialize(include=Inclusion.NON_NULL)
@JsonView({Run.class})
public LanternRosterEntry getRosterEntry() {
return rosterEntry;
}
public void setRosterEntry(LanternRosterEntry rosterEntry) {
this.rosterEntry = rosterEntry;
}
@Override
public String toString() {
return "Peer [peerid=" + peerid + ", country=" + country + ", lat="
+ lat + ", lon=" + lon + ", type=" + type + ", online="
+ online + ", mapped=" + mapped + ", ip=" + ip + ", mode="
+ mode + ", incoming=" + incoming + ", trafficCounter="
+ trafficCounter + ", bytesUp=" + bytesUp + ", bytesDn="
+ bytesDn + ", version=" + version + ", lastConnectedLong="
+ lastConnectedLong + ", rosterEntry=" + rosterEntry + "]";
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
}
|
package net.lightbody.bmp;
import net.lightbody.bmp.core.har.Har;
import net.lightbody.bmp.filters.RequestFilter;
import net.lightbody.bmp.filters.ResponseFilter;
import net.lightbody.bmp.proxy.BlacklistEntry;
import net.lightbody.bmp.proxy.CaptureType;
import net.lightbody.bmp.proxy.auth.AuthType;
import net.lightbody.bmp.proxy.dns.AdvancedHostResolver;
import org.littleshoot.proxy.HttpFiltersSource;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Collection;
import java.util.EnumSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
public interface BrowserMobProxy {
void start();
void start(int port);
void start(int port, InetAddress bindAddress);
void start(int port, InetAddress clientBindAddress, InetAddress serverBindAddress);
/**
* Returns true if the proxy is started and listening for connections, otherwise false.
*/
boolean isStarted();
void stop();
void abort();
/**
* Returns the address of the network interface on which the proxy is listening for client connections.
*
* @return the client bind address, or null if the proxy has not been started
*/
InetAddress getClientBindAddress();
int getPort();
/**
* Returns the address address of the network interface the proxy will use to initiate upstream connections. If no server bind address
* has been set, this method returns null, even if the proxy has been started.
*
* @return server bind address if one has been set, otherwise null
*/
InetAddress getServerBindAddress();
/**
* Retrieves the current HAR.
*
* @return current HAR, or null if HAR capture is not enabled
*/
Har getHar();
/**
* Starts a new HAR file with the default page name (see {@link #newPage()}. Enables HAR capture if it was not previously enabled.
*
* @return existing HAR file, or null if none exists or HAR capture was disabled
*/
Har newHar();
/**
* Starts a new HAR file with the specified initialPageRef as the page name and page title. Enables HAR capture if it was not previously enabled.
*
* @param initialPageRef initial page name of the new HAR file
* @return existing HAR file, or null if none exists or HAR capture was disabled
*/
Har newHar(String initialPageRef);
/**
* Starts a new HAR file with the specified page name and page title. Enables HAR capture if it was not previously enabled.
*
* @param initialPageRef initial page name of the new HAR file
* @param initialPageTitle initial page title of the new HAR file
* @return existing HAR file, or null if none exists or HAR capture was disabled
*/
Har newHar(String initialPageRef, String initialPageTitle);
/**
* Sets the data types that will be captured in the HAR file for future requests. Replaces any existing capture types with the specified
* capture types. A null or empty set will not disable HAR capture, but will disable collection of
* additional {@link net.lightbody.bmp.proxy.CaptureType} data types. {@link net.lightbody.bmp.proxy.CaptureType} provides several
* convenience methods to retrieve commonly-used capture settings.
* <p/>
* <b>Note:</b> HAR capture must still be explicitly enabled via {@link #newHar()} or {@link #newHar(String)} to begin capturing
* any request and response contents.
*
* @param captureTypes HAR data types to capture
*/
void setHarCaptureTypes(Set<CaptureType> captureTypes);
/**
* @return A copy of HAR capture types currently in effect. The EnumSet cannot be used to modify the HAR capture types currently in effect.
*/
EnumSet<CaptureType> getHarCaptureTypes();
/**
* Enables the specified HAR capture types. Does not replace or disable any other capture types that may already be enabled.
*
* @param captureTypes capture types to enable
*/
void enableHarCaptureTypes(Set<CaptureType> captureTypes);
/**
* Disables the specified HAR capture types. Does not replace or disable any other capture types that may already be enabled.
*
* @param captureTypes capture types to disable
*/
void disableHarCaptureTypes(Set<CaptureType> captureTypes);
Har newPage();
Har newPage(String pageRef);
Har newPage(String pageRef, String pageTitle);
/**
* Stops capturing traffic in the HAR. Populates the {@link net.lightbody.bmp.core.har.HarPageTimings#onLoad} value for the current page
* based on the amount of time it has been captured.
*
* @return the existing HAR
*/
Har endHar();
/**
* Sets the maximum bandwidth to consume when reading server responses.
*
* @param bytesPerSecond maximum bandwidth, in bytes per second
*/
void setReadBandwidthLimit(long bytesPerSecond);
/**
* Sets the maximum bandwidth to consume when sending requests to servers.
*
* @param bytesPerSecond maximum bandwidth, in bytes per second
*/
void setWriteBandwidthLimit(long bytesPerSecond);
/**
* The minimum amount of time that will elapse between the time the proxy begins receiving a response from the server and the time the
* proxy begins sending the response to the client.
*
* @param latency minimum latency, or 0 for no minimum
* @param timeUnit TimeUnit for the latency
*/
void setLatency(long latency, TimeUnit timeUnit);
/**
* Maximum amount of time to wait to establish a connection to a remote server. If the connection has not been established within the
* specified time, the proxy will respond with an HTTP 502 Bad Gateway. The default value is 60 seconds.
*
* @param connectionTimeout maximum time to wait to establish a connection to a server, or 0 to wait indefinitely
* @param timeUnit TimeUnit for the connectionTimeout
*/
void setConnectTimeout(int connectionTimeout, TimeUnit timeUnit);
/**
* Maximum amount of time to allow a connection to remain idle. A connection becomes idle when it has not received data from a server
* within the the specified timeout. If the proxy has not yet begun to forward the response to the client, the proxy
* will respond with an HTTP 504 Gateway Timeout. If the proxy has already started forwarding the response to the client, the
* connection to the client <i>may</i> be closed abruptly. The default value is 60 seconds.
*
* @param idleConnectionTimeout maximum time to allow a connection to remain idle, or 0 to wait indefinitely.
* @param timeUnit TimeUnit for the idleConnectionTimeout
*/
void setIdleConnectionTimeout(int idleConnectionTimeout, TimeUnit timeUnit);
/**
* Maximum amount of time to wait for an HTTP response from the remote server after the request has been sent in its entirety. The HTTP
* request must complete within the specified time. If the proxy has not yet begun to forward the response to the client, the proxy
* will respond with an HTTP 504 Gateway Timeout. If the proxy has already started forwarding the response to the client, the
* connection to the client <i>may</i> be closed abruptly. The default value is 0 (wait indefinitely).
*
* @param requestTimeout maximum time to wait for an HTTP response, or 0 to wait indefinitely
* @param timeUnit TimeUnit for the requestTimeout
*/
void setRequestTimeout(int requestTimeout, TimeUnit timeUnit);
/**
* Enables automatic authorization for the specified domain and auth type. Every request sent to the specified domain will contain the
* specified authorization information.
*
* @param domain domain automatically send authorization information to
* @param username authorization username
* @param password authorization password
* @param authType authorization type
*/
void autoAuthorization(String domain, String username, String password, AuthType authType);
/**
* Stops automatic authorization for the specified domain.
*
* @param domain domain to stop automatically sending authorization information to
*/
void stopAutoAuthorization(String domain);
void rewriteUrl(String urlPattern, String replacementExpression);
/**
* Replaces existing rewrite rules with the specified patterns and replacement expressions. The rules will be applied in the order
* specified by the Map's iterator.
* <p/>
* See {@link #rewriteUrl(String, String)} for details on the format of the rewrite rules.
*
* @param rewriteRules {@code Map<urlPattern, replacementExpression>}
*/
void rewriteUrls(Map<String, String> rewriteRules);
/**
* Returns all rewrite rules currently in effect. Iterating over the returned Map is guaranteed to return rewrite rules
* in the order in which the rules are actually applied.
*
* @return {@code Map<URL-matching regex, replacement expression>}
*/
Map<String, String> getRewriteRules();
/**
* Removes an existing rewrite rule whose urlPattern matches the specified pattern.
*
* @param urlPattern rewrite rule pattern to remove
*/
void removeRewriteRule(String urlPattern);
/**
* Clears all existing rewrite rules.
*/
void clearRewriteRules();
void blacklistRequests(String urlPattern, int statusCode);
/**
* Adds a URL-matching regular expression to the blacklist. Requests that match a blacklisted URL will return the specified HTTP
* statusCode only when the request's HTTP method (GET, POST, PUT, etc.) matches the specified httpMethodPattern regular expression.
* If there are existing patterns on the blacklist, the urlPattern will be evaluated last, after the URL is checked against all
* other blacklist entries.
* <p/>
* See {@link #blacklistRequests(String, int)} for details on the URL the urlPattern will match.
*
* @param urlPattern URL-matching regular expression to blacklist
* @param statusCode HTTP status code to return
* @param httpMethodPattern regular expression matching a request's HTTP method
*/
void blacklistRequests(String urlPattern, int statusCode, String httpMethodPattern);
/**
* Replaces any existing blacklist with the specified blacklist. URLs will be evaluated against the blacklist in the order
* specified by the Collection's iterator.
*
* @param blacklist new blacklist entries
*/
void setBlacklist(Collection<BlacklistEntry> blacklist);
/**
* Returns all blacklist entries currently in effect. Iterating over the returned Collection is guaranteed to return
* blacklist entries in the order in which URLs are actually evaluated against the blacklist.
*
* @return blacklist entries, or an empty collection if none exist
*/
Collection<BlacklistEntry> getBlacklist();
/**
* Clears any existing blacklist.
*/
void clearBlacklist();
void whitelistRequests(Collection<String> urlPatterns, int statusCode);
void addWhitelistPattern(String urlPattern);
/**
* Enables the whitelist, but with no matching URLs. All requests will generated the specified HTTP statusCode.
*
* @param statusCode HTTP status code to return to clients on all requests
*/
void enableEmptyWhitelist(int statusCode);
/**
* Clears any existing whitelist and disables whitelisting.
*/
void disableWhitelist();
/**
* Returns the URL-matching regular expressions currently in effect. If the whitelist is disabled, this method always returns an empty collection.
* If the whitelist is enabled but empty, this method return an empty collection.
*
* @return whitelist currently in effect, or an empty collection if the whitelist is disabled or empty
*/
Collection<String> getWhitelistUrls();
/**
* Returns the status code returned for all URLs that do not match the whitelist. If the whitelist is not currently enabled, returns -1.
*
* @return HTTP status code returned for non-whitelisted URLs, or -1 if the whitelist is disabled.
*/
int getWhitelistStatusCode();
/**
* Returns true if the whitelist is enabled, otherwise false.
*/
boolean isWhitelistEnabled();
/**
* Adds the specified HTTP headers to every request. Replaces any existing additional headers with the specified headers.
*
* @param headers {@code Map<header name, header value>} to append to every request.
*/
void addHeaders(Map<String, String> headers);
/**
* Adds a new HTTP header to every request. If the header already exists on the request, it will be replaced with the specified header.
*
* @param name name of the header to add
* @param value new header's value
*/
void addHeader(String name, String value);
/**
* Removes a header previously added with {@link #addHeader(String name, String value)}.
*
* @param name previously-added header's name
*/
void removeHeader(String name);
/**
* Removes all headers previously added with {@link #addHeader(String name, String value)}.
*/
void removeAllHeaders();
/**
* Returns all headers previously added with {@link #addHeader(String name, String value)}.
*
* @return {@code Map<header name, header value>}
*/
Map<String, String> getAllHeaders();
/**
* Sets the resolver that will be used to look up host names. To chain multiple resolvers, wrap a list
* of resolvers in a {@link net.lightbody.bmp.proxy.dns.ChainedHostResolver}.
*
* @param resolver host name resolver
*/
void setHostNameResolver(AdvancedHostResolver resolver);
/**
* Returns the current host name resolver.
*
* @return current host name resolver
*/
AdvancedHostResolver getHostNameResolver();
/**
* Waits for existing network traffic to stop, and for the specified quietPeriod to elapse. Returns true if there is no network traffic
* for the quiet period within the specified timeout, otherwise returns false.
*
* @param quietPeriod amount of time after which network traffic will be considered "stopped"
* @param timeout maximum amount of time to wait for network traffic to stop
* @param timeUnit TimeUnit for the quietPeriod and timeout
* @return true if network traffic is stopped, otherwise false
*/
boolean waitForQuiescence(long quietPeriod, long timeout, TimeUnit timeUnit);
/**
* Sets an upstream proxy that this proxy will use to connect to external hosts.
*
* @param chainedProxyAddress address and port of the upstream proxy, or null to remove an upstream proxy
*/
void setChainedProxy(InetSocketAddress chainedProxyAddress);
/**
* Returns the address and port of the upstream proxy.
*
* @return address and port of the upstream proxy, or null of there is none.
*/
InetSocketAddress getChainedProxy();
void addFirstHttpFilterFactory(HttpFiltersSource filterFactory);
void addLastHttpFilterFactory(HttpFiltersSource filterFactory);
/**
* Adds a new ResponseFilter that can be used to examine and manipulate the response before sending it to the client.
*
* @param filter filter instance
*/
void addResponseFilter(ResponseFilter filter);
/**
* Adds a new RequestFilter that can be used to examine and manipulate the request before sending it to the server.
*
* @param filter filter instance
*/
void addRequestFilter(RequestFilter filter);
void setMitmDisabled(boolean mitmDisabled);
}
|
package com.elmakers.mine.bukkit.utility;
import com.elmakers.mine.bukkit.block.Schematic;
import org.bukkit.Bukkit;
import org.bukkit.DyeColor;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.block.BlockFace;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Vector;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* Contains some raw methods for doing some simple NMS utilities.
*
* This is not meant to be a replacement for full-on NMS or Protocol libs,
* but it is enough for Magic to use internally without requiring any
* external dependencies.
*
* Use any of this at your own risk!
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public class NMSUtils {
protected static boolean failed = false;
protected static String versionPrefix = "";
protected final static int NBT_TYPE_COMPOUND = 10;
protected final static int NBT_TYPE_INT_ARRAY= 11;
protected final static int NBT_TYPE_DOUBLE = 6;
protected final static int NBT_TYPE_FLOAT = 5;
protected final static int NBT_TYPE_STRING = 8;
protected static int WITHER_SKULL_TYPE = 66;
protected static int FIREWORK_TYPE = 76;
protected static Class<?> class_ItemStack;
protected static Class<?> class_NBTBase;
protected static Class<?> class_NBTTagCompound;
protected static Class<?> class_NBTTagList;
protected static Class<?> class_NBTTagByte;
protected static Class<?> class_NBTTagString;
protected static Class<?> class_CraftTask;
protected static Class<?> class_CraftInventoryCustom;
protected static Class<?> class_CraftItemStack;
protected static Class<?> class_CraftBlockState;
protected static Class<?> class_CraftLivingEntity;
protected static Class<?> class_CraftWorld;
protected static Class<?> class_Entity;
protected static Class<?> class_EntityCreature;
protected static Class<?> class_EntityLiving;
protected static Class<?> class_DataWatcher;
protected static Class<?> class_DamageSource;
protected static Class<?> class_EntityDamageSource;
protected static Class<?> class_World;
protected static Class<?> class_WorldServer;
protected static Class<?> class_Packet;
protected static Class<Enum> class_EnumSkyBlock;
protected static Class<?> class_PacketPlayOutMapChunkBulk;
protected static Class<?> class_EntityPainting;
protected static Class<?> class_EntityItemFrame;
protected static Class<?> class_EntityMinecartRideable;
protected static Class<?> class_EntityTNTPrimed;
protected static Class<?> class_AxisAlignedBB;
protected static Class<?> class_PathPoint;
protected static Class<?> class_PathEntity;
protected static Class<?> class_EntityFirework;
protected static Class<?> class_CraftSkull;
protected static Class<?> class_CraftBanner;
protected static Class<?> class_CraftMetaSkull;
protected static Class<?> class_CraftMetaBanner;
protected static Class<?> class_GameProfile;
protected static Class<?> class_GameProfileProperty;
protected static Class<?> class_BlockPosition;
protected static Class<?> class_NBTCompressedStreamTools;
protected static Class<?> class_TileEntity;
protected static Class<?> class_TileEntitySign;
protected static Class<?> class_TileEntityContainer;
protected static Class<?> class_ChestLock;
protected static Class<Enum> class_EnumDirection;
protected static Class<?> class_EntityHorse;
protected static Class<?> class_EntityWitherSkull;
protected static Class<?> class_PacketPlayOutAttachEntity;
protected static Class<?> class_PacketPlayOutEntityDestroy;
protected static Class<?> class_PacketPlayOutSpawnEntity;
protected static Class<?> class_PacketPlayOutSpawnEntityLiving;
protected static Class<?> class_PacketPlayOutEntityMetadata;
protected static Class<?> class_PacketPlayOutEntityStatus;
protected static Class<?> class_EntityFallingBlock;
protected static Class<?> class_EntityArmorStand;
protected static Class<?> class_EntityPlayer;
protected static Class<?> class_PlayerConnection;
protected static Class<?> class_Chunk;
protected static Class<?> class_CraftPlayer;
protected static Class<?> class_CraftChunk;
protected static Class<?> class_CraftEntity;
protected static Class<?> class_EntityProjectile;
protected static Class<?> class_EntityFireball;
protected static Class<?> class_EntityArrow;
protected static Class<?> class_CraftArrow;
protected static Method class_NBTTagList_addMethod;
protected static Method class_NBTTagList_getMethod;
protected static Method class_NBTTagList_getDoubleMethod;
protected static Method class_NBTTagList_sizeMethod;
protected static Method class_NBTTagCompound_setMethod;
protected static Method class_DataWatcher_watchMethod;
protected static Method class_World_getEntitiesMethod;
protected static Method class_Entity_setSilentMethod;
protected static Method class_Entity_setYawPitchMethod;
protected static Method class_Entity_getBukkitEntityMethod;
protected static Method class_EntityLiving_damageEntityMethod;
protected static Method class_DamageSource_getMagicSourceMethod;
protected static Method class_EntityDamageSource_setThornsMethod;
protected static Method class_AxisAlignedBB_createBBMethod;
protected static Method class_World_explodeMethod;
protected static Method class_NBTTagCompound_setBooleanMethod;
protected static Method class_NBTTagCompound_setStringMethod;
protected static Method class_NBTTagCompound_setIntMethod;
protected static Method class_NBTTagCompound_removeMethod;
protected static Method class_NBTTagCompound_getStringMethod;
protected static Method class_NBTTagCompound_getIntMethod;
protected static Method class_NBTTagCompound_getByteMethod;
protected static Method class_NBTTagCompound_getMethod;
protected static Method class_NBTTagCompound_getCompoundMethod;
protected static Method class_NBTTagCompound_getShortMethod;
protected static Method class_NBTTagCompound_getByteArrayMethod;
protected static Method class_NBTTagCompound_getListMethod;
protected static Method class_TileEntity_loadMethod;
protected static Method class_TileEntity_saveMethod;
protected static Method class_TileEntity_updateMethod;
protected static Method class_World_addEntityMethod;
protected static Method class_CraftMetaBanner_getPatternsMethod;
protected static Method class_CraftMetaBanner_setPatternsMethod;
protected static Method class_CraftMetaBanner_getBaseColorMethod;
protected static Method class_CraftMetaBanner_setBaseColorMethod;
protected static Method class_CraftBanner_getPatternsMethod;
protected static Method class_CraftBanner_setPatternsMethod;
protected static Method class_CraftBanner_getBaseColorMethod;
protected static Method class_CraftBanner_setBaseColorMethod;
protected static Method class_NBTCompressedStreamTools_loadFileMethod;
protected static Method class_ItemStack_createStackMethod;
protected static Method class_CraftItemStack_asBukkitCopyMethod;
protected static Method class_CraftItemStack_copyMethod;
protected static Method class_CraftItemStack_mirrorMethod;
protected static Method class_NBTTagCompound_hasKeyMethod;
protected static Method class_CraftWorld_getTileEntityAtMethod;
protected static Method class_Entity_setLocationMethod;
protected static Method class_Entity_getIdMethod;
protected static Method class_Entity_getDataWatcherMethod;
protected static Method class_Server_getOnlinePlayers;
protected static Method class_Entity_getBoundingBox;
protected static Method class_TileEntityContainer_setLock;
protected static Method class_TileEntityContainer_getLock;
protected static Method class_ChestLock_isEmpty;
protected static Method class_ChestLock_getString;
protected static Method class_ArmorStand_setInvisible;
protected static Method class_ArmorStand_setMarker;
protected static Method class_ArmorStand_setGravity;
protected static Method class_ArmorStand_setSmall;
protected static Method class_CraftPlayer_getHandleMethod;
protected static Method class_CraftChunk_getHandleMethod;
protected static Method class_CraftEntity_getHandleMethod;
protected static Method class_CraftLivingEntity_getHandleMethod;
protected static Method class_CraftWorld_getHandleMethod;
protected static Method class_EntityPlayer_openSignMethod;
protected static Constructor class_NBTTagList_consructor;
protected static Constructor class_NBTTagList_legacy_consructor;
protected static Constructor class_CraftInventoryCustom_constructor;
protected static Constructor class_NBTTagByte_constructor;
protected static Constructor class_NBTTagByte_legacy_constructor;
protected static Constructor class_EntityFireworkConstructor;
protected static Constructor class_EntityPaintingConstructor;
protected static Constructor class_EntityItemFrameConstructor;
protected static Constructor class_BlockPositionConstructor;
protected static Constructor class_PacketSpawnEntityConstructor;
protected static Constructor class_PacketSpawnLivingEntityConstructor;
protected static Constructor class_PacketPlayOutEntityMetadata_Constructor;
protected static Constructor class_PacketPlayOutEntityStatus_Constructor;
protected static Constructor class_PacketPlayOutEntityDestroy_Constructor;
protected static Constructor class_ChestLock_Constructor;
protected static Constructor class_ArmorStand_Constructor;
protected static Field class_Entity_invulnerableField;
protected static Field class_Entity_motXField;
protected static Field class_Entity_motYField;
protected static Field class_Entity_motZField;
protected static Field class_WorldServer_entitiesByUUIDField;
protected static Field class_ItemStack_tagField;
protected static Field class_DamageSource_MagicField;
protected static Field class_Firework_ticksFlownField;
protected static Field class_Firework_expectedLifespanField;
protected static Field class_CraftSkull_profile;
protected static Field class_CraftMetaSkull_profile;
protected static Field class_GameProfile_properties;
protected static Field class_GameProfileProperty_value;
protected static Field class_ItemStack_count;
protected static Field class_EntityTNTPrimed_source;
protected static Field class_NBTTagList_list;
protected static Field class_AxisAlignedBB_minXField;
protected static Field class_AxisAlignedBB_minYField;
protected static Field class_AxisAlignedBB_minZField;
protected static Field class_AxisAlignedBB_maxXField;
protected static Field class_AxisAlignedBB_maxYField;
protected static Field class_AxisAlignedBB_maxZField;
protected static Field class_EntityFallingBlock_hurtEntitiesField;
protected static Field class_EntityFallingBlock_fallHurtMaxField;
protected static Field class_EntityFallingBlock_fallHurtAmountField;
protected static Field class_EntityArmorStand_disabledSlotsField;
protected static Field class_EntityPlayer_playerConnectionField;
protected static Field class_PlayerConnection_floatCountField;
protected static Field class_Chunk_doneField;
protected static Field class_CraftItemStack_getHandleField;
protected static Field class_EntityArrow_lifeField = null;
protected static Field class_EntityArrow_fromPlayerField;
protected static Field class_EntityArrow_damageField;
protected static Field class_CraftWorld_environmentField;
static
{
// Find classes Bukkit hides from us. :-D
// Much thanks to @DPOHVAR for sharing the PowerNBT code that powers the reflection approach.
String className = Bukkit.getServer().getClass().getName();
String[] packages = className.split("\\.");
if (packages.length == 5) {
versionPrefix = packages[3] + ".";
}
try {
class_Entity = fixBukkitClass("net.minecraft.server.Entity");
class_EntityLiving = fixBukkitClass("net.minecraft.server.EntityLiving");
class_ItemStack = fixBukkitClass("net.minecraft.server.ItemStack");
class_DataWatcher = fixBukkitClass("net.minecraft.server.DataWatcher");
class_NBTBase = fixBukkitClass("net.minecraft.server.NBTBase");
class_NBTTagCompound = fixBukkitClass("net.minecraft.server.NBTTagCompound");
class_NBTTagList = fixBukkitClass("net.minecraft.server.NBTTagList");
class_NBTTagString = fixBukkitClass("net.minecraft.server.NBTTagString");
class_NBTTagByte = fixBukkitClass("net.minecraft.server.NBTTagByte");
class_CraftWorld = fixBukkitClass("org.bukkit.craftbukkit.CraftWorld");
class_CraftInventoryCustom = fixBukkitClass("org.bukkit.craftbukkit.inventory.CraftInventoryCustom");
class_CraftItemStack = fixBukkitClass("org.bukkit.craftbukkit.inventory.CraftItemStack");
class_CraftBlockState = fixBukkitClass("org.bukkit.craftbukkit.block.CraftBlockState");
class_CraftTask = fixBukkitClass("org.bukkit.craftbukkit.scheduler.CraftTask");
class_CraftLivingEntity = fixBukkitClass("org.bukkit.craftbukkit.entity.CraftLivingEntity");
class_Packet = fixBukkitClass("net.minecraft.server.Packet");
class_World = fixBukkitClass("net.minecraft.server.World");
class_WorldServer = fixBukkitClass("net.minecraft.server.WorldServer");
class_EnumSkyBlock = (Class<Enum>)fixBukkitClass("net.minecraft.server.EnumSkyBlock");
class_EntityPainting = fixBukkitClass("net.minecraft.server.EntityPainting");
class_EntityCreature = fixBukkitClass("net.minecraft.server.EntityCreature");
class_EntityItemFrame = fixBukkitClass("net.minecraft.server.EntityItemFrame");
class_EntityMinecartRideable = fixBukkitClass("net.minecraft.server.EntityMinecartRideable");
class_EntityTNTPrimed = fixBukkitClass("net.minecraft.server.EntityTNTPrimed");
class_AxisAlignedBB = fixBukkitClass("net.minecraft.server.AxisAlignedBB");
class_DamageSource = fixBukkitClass("net.minecraft.server.DamageSource");
class_EntityDamageSource = fixBukkitClass("net.minecraft.server.EntityDamageSource");
class_PathEntity = fixBukkitClass("net.minecraft.server.PathEntity");
class_PathPoint = fixBukkitClass("net.minecraft.server.PathPoint");
class_EntityFirework = fixBukkitClass("net.minecraft.server.EntityFireworks");
class_CraftSkull = fixBukkitClass("org.bukkit.craftbukkit.block.CraftSkull");
class_CraftMetaSkull = fixBukkitClass("org.bukkit.craftbukkit.inventory.CraftMetaSkull");
class_NBTCompressedStreamTools = fixBukkitClass("net.minecraft.server.NBTCompressedStreamTools");
class_TileEntity = fixBukkitClass("net.minecraft.server.TileEntity");
class_EntityHorse = fixBukkitClass("net.minecraft.server.EntityHorse");
class_EntityWitherSkull = fixBukkitClass("net.minecraft.server.EntityWitherSkull");
class_PacketPlayOutAttachEntity = fixBukkitClass("net.minecraft.server.PacketPlayOutAttachEntity");
class_PacketPlayOutEntityDestroy = fixBukkitClass("net.minecraft.server.PacketPlayOutEntityDestroy");
class_PacketPlayOutSpawnEntity = fixBukkitClass("net.minecraft.server.PacketPlayOutSpawnEntity");
class_PacketPlayOutSpawnEntityLiving = fixBukkitClass("net.minecraft.server.PacketPlayOutSpawnEntityLiving");
class_PacketPlayOutEntityMetadata = fixBukkitClass("net.minecraft.server.PacketPlayOutEntityMetadata");
class_PacketPlayOutEntityStatus = fixBukkitClass("net.minecraft.server.PacketPlayOutEntityStatus");
class_EntityFallingBlock = fixBukkitClass("net.minecraft.server.EntityFallingBlock");
class_EntityArmorStand = fixBukkitClass("net.minecraft.server.EntityArmorStand");
class_EntityPlayer = fixBukkitClass("net.minecraft.server.EntityPlayer");
class_PlayerConnection = fixBukkitClass("net.minecraft.server.PlayerConnection");
class_Chunk = fixBukkitClass("net.minecraft.server.Chunk");
class_CraftPlayer = fixBukkitClass("org.bukkit.craftbukkit.entity.CraftPlayer");
class_CraftChunk = fixBukkitClass("org.bukkit.craftbukkit.CraftChunk");
class_CraftEntity = fixBukkitClass("org.bukkit.craftbukkit.entity.CraftEntity");
class_TileEntitySign = fixBukkitClass("net.minecraft.server.TileEntitySign");
class_EntityProjectile = NMSUtils.getBukkitClass("net.minecraft.server.EntityProjectile");
class_EntityFireball = NMSUtils.getBukkitClass("net.minecraft.server.EntityFireball");
class_EntityArrow = NMSUtils.getBukkitClass("net.minecraft.server.EntityArrow");
class_CraftArrow = NMSUtils.getBukkitClass("org.bukkit.craftbukkit.entity.CraftArrow");
class_NBTTagList_addMethod = class_NBTTagList.getMethod("add", class_NBTBase);
class_NBTTagList_getMethod = class_NBTTagList.getMethod("get", Integer.TYPE);
class_NBTTagList_getDoubleMethod = class_NBTTagList.getMethod("d", Integer.TYPE);
class_NBTTagList_sizeMethod = class_NBTTagList.getMethod("size");
class_NBTTagCompound_setMethod = class_NBTTagCompound.getMethod("set", String.class, class_NBTBase);
class_DataWatcher_watchMethod = class_DataWatcher.getMethod("watch", Integer.TYPE, Object.class);
class_World_getEntitiesMethod = class_World.getMethod("getEntities", class_Entity, class_AxisAlignedBB);
class_CraftWorld_getTileEntityAtMethod = class_CraftWorld.getMethod("getTileEntityAt", Integer.TYPE, Integer.TYPE, Integer.TYPE);
class_Entity_getBukkitEntityMethod = class_Entity.getMethod("getBukkitEntity");
class_Entity_setYawPitchMethod = class_Entity.getDeclaredMethod("setYawPitch", Float.TYPE, Float.TYPE);
class_Entity_setYawPitchMethod.setAccessible(true);
class_Entity_setSilentMethod = class_Entity.getDeclaredMethod("b", Boolean.TYPE);
class_AxisAlignedBB_createBBMethod = class_AxisAlignedBB.getMethod("a", Double.TYPE, Double.TYPE, Double.TYPE, Double.TYPE, Double.TYPE, Double.TYPE);
class_World_explodeMethod = class_World.getMethod("createExplosion", class_Entity, Double.TYPE, Double.TYPE, Double.TYPE, Float.TYPE, Boolean.TYPE, Boolean.TYPE);
class_NBTTagCompound_setBooleanMethod = class_NBTTagCompound.getMethod("setBoolean", String.class, Boolean.TYPE);
class_NBTTagCompound_setStringMethod = class_NBTTagCompound.getMethod("setString", String.class, String.class);
class_NBTTagCompound_setIntMethod = class_NBTTagCompound.getMethod("setInt", String.class, Integer.TYPE);
class_NBTTagCompound_removeMethod = class_NBTTagCompound.getMethod("remove", String.class);
class_NBTTagCompound_getStringMethod = class_NBTTagCompound.getMethod("getString", String.class);
class_NBTTagCompound_getShortMethod = class_NBTTagCompound.getMethod("getShort", String.class);
class_NBTTagCompound_getIntMethod = class_NBTTagCompound.getMethod("getInt", String.class);
class_NBTTagCompound_getByteMethod = class_NBTTagCompound.getMethod("getByte", String.class);
class_NBTTagCompound_getByteArrayMethod = class_NBTTagCompound.getMethod("getByteArray", String.class);
class_NBTTagCompound_getListMethod = class_NBTTagCompound.getMethod("getList", String.class, Integer.TYPE);
class_CraftItemStack_copyMethod = class_CraftItemStack.getMethod("asNMSCopy", org.bukkit.inventory.ItemStack.class);
class_CraftItemStack_asBukkitCopyMethod = class_CraftItemStack.getMethod("asBukkitCopy", class_ItemStack);
class_CraftItemStack_mirrorMethod = class_CraftItemStack.getMethod("asCraftMirror", class_ItemStack);
class_ItemStack_createStackMethod = class_ItemStack.getMethod("createStack", class_NBTTagCompound);
class_NBTTagCompound_hasKeyMethod = class_NBTTagCompound.getMethod("hasKey", String.class);
class_NBTTagCompound_getMethod = class_NBTTagCompound.getMethod("get", String.class);
class_NBTTagCompound_getCompoundMethod = class_NBTTagCompound.getMethod("getCompound", String.class);
class_EntityLiving_damageEntityMethod = class_EntityLiving.getMethod("damageEntity", class_DamageSource, Float.TYPE);
class_DamageSource_getMagicSourceMethod = class_DamageSource.getMethod("b", class_Entity, class_Entity);
class_World_addEntityMethod = class_World.getMethod("addEntity", class_Entity, CreatureSpawnEvent.SpawnReason.class);
class_NBTCompressedStreamTools_loadFileMethod = class_NBTCompressedStreamTools.getMethod("a", InputStream.class);
class_TileEntity_loadMethod = class_TileEntity.getMethod("a", class_NBTTagCompound);
class_TileEntity_saveMethod = class_TileEntity.getMethod("b", class_NBTTagCompound);
class_TileEntity_updateMethod = class_TileEntity.getMethod("update");
class_Entity_setLocationMethod = class_Entity.getMethod("setLocation", Double.TYPE, Double.TYPE, Double.TYPE, Float.TYPE, Float.TYPE);
class_Entity_getIdMethod = class_Entity.getMethod("getId");
class_Entity_getDataWatcherMethod = class_Entity.getMethod("getDataWatcher");
class_Server_getOnlinePlayers = Server.class.getMethod("getOnlinePlayers");
class_ArmorStand_setInvisible = class_EntityArmorStand.getDeclaredMethod("setInvisible", Boolean.TYPE);
class_ArmorStand_setGravity = class_EntityArmorStand.getDeclaredMethod("setGravity", Boolean.TYPE);
class_ArmorStand_setSmall = class_EntityArmorStand.getDeclaredMethod("setSmall", Boolean.TYPE);
class_ArmorStand_setMarker = class_EntityArmorStand.getDeclaredMethod("n", Boolean.TYPE);
class_ArmorStand_setMarker.setAccessible(true);
class_CraftPlayer_getHandleMethod = class_CraftPlayer.getMethod("getHandle");
class_CraftChunk_getHandleMethod = class_CraftChunk.getMethod("getHandle");
class_CraftEntity_getHandleMethod = class_CraftEntity.getMethod("getHandle");
class_CraftLivingEntity_getHandleMethod = class_CraftLivingEntity.getMethod("getHandle");
class_CraftWorld_getHandleMethod = class_CraftWorld.getMethod("getHandle");
class_EntityPlayer_openSignMethod = class_EntityPlayer.getMethod("openSign", class_TileEntitySign);
class_CraftInventoryCustom_constructor = class_CraftInventoryCustom.getConstructor(InventoryHolder.class, Integer.TYPE, String.class);
class_EntityFireworkConstructor = class_EntityFirework.getConstructor(class_World, Double.TYPE, Double.TYPE, Double.TYPE, class_ItemStack);
class_PacketSpawnEntityConstructor = class_PacketPlayOutSpawnEntity.getConstructor(class_Entity, Integer.TYPE);
class_PacketSpawnLivingEntityConstructor = class_PacketPlayOutSpawnEntityLiving.getConstructor(class_EntityLiving);
class_PacketPlayOutEntityMetadata_Constructor = class_PacketPlayOutEntityMetadata.getConstructor(Integer.TYPE, class_DataWatcher, Boolean.TYPE);
class_PacketPlayOutEntityStatus_Constructor = class_PacketPlayOutEntityStatus.getConstructor(class_Entity, Byte.TYPE);
class_PacketPlayOutEntityDestroy_Constructor = class_PacketPlayOutEntityDestroy.getConstructor(int[].class);
class_CraftWorld_environmentField = class_CraftWorld.getDeclaredField("environment");
class_CraftWorld_environmentField.setAccessible(true);
class_Entity_invulnerableField = class_Entity.getDeclaredField("invulnerable");
class_Entity_invulnerableField.setAccessible(true);
class_Entity_motXField = class_Entity.getDeclaredField("motX");
class_Entity_motXField.setAccessible(true);
class_Entity_motYField = class_Entity.getDeclaredField("motY");
class_Entity_motYField.setAccessible(true);
class_Entity_motZField = class_Entity.getDeclaredField("motZ");
class_Entity_motZField.setAccessible(true);
class_WorldServer_entitiesByUUIDField = class_WorldServer.getDeclaredField("entitiesByUUID");
class_WorldServer_entitiesByUUIDField.setAccessible(true);
class_ItemStack_tagField = class_ItemStack.getDeclaredField("tag");
class_ItemStack_tagField.setAccessible(true);
class_DamageSource_MagicField = class_DamageSource.getField("MAGIC");
class_EntityTNTPrimed_source = class_EntityTNTPrimed.getDeclaredField("source");
class_EntityTNTPrimed_source.setAccessible(true);
class_AxisAlignedBB_minXField = class_AxisAlignedBB.getField("a");
class_AxisAlignedBB_minYField = class_AxisAlignedBB.getField("b");
class_AxisAlignedBB_minZField = class_AxisAlignedBB.getField("c");
class_AxisAlignedBB_maxXField = class_AxisAlignedBB.getField("d");
class_AxisAlignedBB_maxYField = class_AxisAlignedBB.getField("e");
class_AxisAlignedBB_maxZField = class_AxisAlignedBB.getField("f");
class_EntityArmorStand_disabledSlotsField = class_EntityArmorStand.getDeclaredField("bi");
class_EntityArmorStand_disabledSlotsField.setAccessible(true);
class_EntityPlayer_playerConnectionField = class_EntityPlayer.getDeclaredField("playerConnection");
class_PlayerConnection_floatCountField = class_PlayerConnection.getDeclaredField("g");
class_PlayerConnection_floatCountField.setAccessible(true);
class_Firework_ticksFlownField = class_EntityFirework.getDeclaredField("ticksFlown");
class_Firework_ticksFlownField.setAccessible(true);
class_Firework_expectedLifespanField = class_EntityFirework.getDeclaredField("expectedLifespan");
class_Firework_expectedLifespanField.setAccessible(true);
class_NBTTagList_consructor = class_NBTTagString.getConstructor(String.class);
class_NBTTagByte_constructor = class_NBTTagByte.getConstructor(Byte.TYPE);
class_ItemStack_count = class_ItemStack.getDeclaredField("count");
class_ItemStack_count.setAccessible(true);
class_NBTTagList_list = class_NBTTagList.getDeclaredField("list");
class_NBTTagList_list.setAccessible(true);
class_EntityFallingBlock_hurtEntitiesField = class_EntityFallingBlock.getDeclaredField("hurtEntities");
class_EntityFallingBlock_hurtEntitiesField.setAccessible(true);
class_EntityFallingBlock_fallHurtAmountField = class_EntityFallingBlock.getDeclaredField("fallHurtAmount");
class_EntityFallingBlock_fallHurtAmountField.setAccessible(true);
class_EntityFallingBlock_fallHurtMaxField = class_EntityFallingBlock.getDeclaredField("fallHurtMax");
class_EntityFallingBlock_fallHurtMaxField.setAccessible(true);
class_Chunk_doneField = class_Chunk.getDeclaredField("done");
class_Chunk_doneField.setAccessible(true);
class_CraftItemStack_getHandleField = class_CraftItemStack.getDeclaredField("handle");
class_CraftItemStack_getHandleField.setAccessible(true);
class_TileEntityContainer = fixBukkitClass("net.minecraft.server.TileEntityContainer");
class_ChestLock = fixBukkitClass("net.minecraft.server.ChestLock");
class_TileEntityContainer_setLock = class_TileEntityContainer.getMethod("a", class_ChestLock);
class_TileEntityContainer_getLock = class_TileEntityContainer.getMethod("i");
class_ChestLock_isEmpty = class_ChestLock.getMethod("a");
class_ChestLock_getString = class_ChestLock.getMethod("b");
class_Entity_getBoundingBox = class_Entity.getMethod("getBoundingBox");
class_GameProfile = getClass("com.mojang.authlib.GameProfile");
class_GameProfileProperty = getClass("com.mojang.authlib.properties.Property");
class_CraftSkull_profile = class_CraftSkull.getDeclaredField("profile");
class_CraftSkull_profile.setAccessible(true);
class_CraftMetaSkull_profile = class_CraftMetaSkull.getDeclaredField("profile");
class_CraftMetaSkull_profile.setAccessible(true);
class_GameProfile_properties = class_GameProfile.getDeclaredField("properties");
class_GameProfile_properties.setAccessible(true);
class_GameProfileProperty_value = class_GameProfileProperty.getDeclaredField("value");
class_GameProfileProperty_value.setAccessible(true);
class_CraftMetaBanner = fixBukkitClass("org.bukkit.craftbukkit.inventory.CraftMetaBanner");
class_CraftMetaBanner_getBaseColorMethod = class_CraftMetaBanner.getMethod("getBaseColor");
class_CraftMetaBanner_getPatternsMethod = class_CraftMetaBanner.getMethod("getPatterns");
class_CraftMetaBanner_setPatternsMethod = class_CraftMetaBanner.getMethod("setPatterns", List.class);
class_CraftMetaBanner_setBaseColorMethod = class_CraftMetaBanner.getMethod("setBaseColor", DyeColor.class);
class_CraftBanner = fixBukkitClass("org.bukkit.craftbukkit.block.CraftBanner");
class_CraftBanner_getBaseColorMethod = class_CraftBanner.getMethod("getBaseColor");
class_CraftBanner_getPatternsMethod = class_CraftBanner.getMethod("getPatterns");
class_CraftBanner_setPatternsMethod = class_CraftBanner.getMethod("setPatterns", List.class);
class_CraftBanner_setBaseColorMethod = class_CraftBanner.getMethod("setBaseColor", DyeColor.class);
class_EntityDamageSource_setThornsMethod = class_EntityDamageSource.getMethod("v");
class_BlockPosition = fixBukkitClass("net.minecraft.server.BlockPosition");
class_EnumDirection = (Class<Enum>)fixBukkitClass("net.minecraft.server.EnumDirection");
class_BlockPositionConstructor = class_BlockPosition.getConstructor(Double.TYPE, Double.TYPE, Double.TYPE);
class_EntityPaintingConstructor = class_EntityPainting.getConstructor(class_World, class_BlockPosition, class_EnumDirection);
class_EntityItemFrameConstructor = class_EntityItemFrame.getConstructor(class_World, class_BlockPosition, class_EnumDirection);
class_ChestLock_Constructor = class_ChestLock.getConstructor(String.class);
class_ArmorStand_Constructor = class_EntityArmorStand.getConstructor(class_World);
class_PacketPlayOutMapChunkBulk = getVersionedBukkitClass("net.minecraft.server.PacketPlayOutMapChunkBulk", "net.minecraft.server.Packet56MapChunkBulk");
try {
class_EntityArrow_fromPlayerField = class_EntityArrow.getField("fromPlayer");
class_EntityArrow_damageField = class_EntityArrow.getDeclaredField("damage");
class_EntityArrow_damageField.setAccessible(true);
// This is kinda hacky, like fer reals :\
try {
// 1.8.3
class_EntityArrow_lifeField = class_EntityArrow.getDeclaredField("ar");
} catch (Throwable ignore3) {
try {
class_EntityArrow_lifeField = class_EntityArrow.getDeclaredField("ap");
} catch (Throwable ignore2) {
try {
class_EntityArrow_lifeField = class_EntityArrow.getDeclaredField("at");
} catch (Throwable ignore) {
// Prior
class_EntityArrow_lifeField = class_EntityArrow.getDeclaredField("j");
}
}
}
} catch (Throwable ex) {
class_EntityArrow_lifeField = null;
}
if (class_EntityArrow_lifeField != null)
{
class_EntityArrow_lifeField.setAccessible(true);
}
}
catch (Throwable ex) {
failed = true;
ex.printStackTrace();
}
}
public static boolean getFailed() {
return failed;
}
public static Class<?> getVersionedBukkitClass(String newVersion, String oldVersion) {
Class<?> c = getBukkitClass(newVersion);
if (c == null) {
c = getBukkitClass(oldVersion);
if (c == null) {
Bukkit.getLogger().warning("Could not bind to " + newVersion + " or " + oldVersion);
}
}
return c;
}
public static Class<?> getClass(String className) {
Class<?> result = null;
try {
result = NMSUtils.class.getClassLoader().loadClass(className);
} catch (Exception ex) {
result = null;
}
return result;
}
public static Class<?> getBukkitClass(String className) {
Class<?> result = null;
try {
result = fixBukkitClass(className);
} catch (Exception ex) {
result = null;
}
return result;
}
public static Class<?> fixBukkitClass(String className) throws ClassNotFoundException {
if (!versionPrefix.isEmpty()) {
className = className.replace("org.bukkit.craftbukkit.", "org.bukkit.craftbukkit." + versionPrefix);
className = className.replace("net.minecraft.server.", "net.minecraft.server." + versionPrefix);
}
return NMSUtils.class.getClassLoader().loadClass(className);
}
public static Object getHandle(org.bukkit.inventory.ItemStack stack) {
Object handle = null;
try {
handle = class_CraftItemStack_getHandleField.get(stack);
} catch (Throwable ex) {
handle = null;
}
return handle;
}
public static Object getHandle(org.bukkit.World world) {
if (world == null) return null;
Object handle = null;
try {
handle = class_CraftWorld_getHandleMethod.invoke(world);
} catch (Throwable ex) {
ex.printStackTrace();
}
return handle;
}
public static Object getHandle(org.bukkit.entity.Entity entity) {
if (entity == null) return null;
Object handle = null;
try {
handle = class_CraftEntity_getHandleMethod.invoke(entity);
} catch (Throwable ex) {
ex.printStackTrace();
}
return handle;
}
public static Object getHandle(org.bukkit.entity.LivingEntity entity) {
if (entity == null) return null;
Object handle = null;
try {
handle = class_CraftLivingEntity_getHandleMethod.invoke(entity);
} catch (Throwable ex) {
ex.printStackTrace();
}
return handle;
}
public static boolean isDone(org.bukkit.Chunk chunk) {
Object chunkHandle = getHandle(chunk);
boolean done = false;
try {
done = (Boolean)class_Chunk_doneField.get(chunkHandle);
} catch (Throwable ex) {
ex.printStackTrace();
}
return done;
}
public static Object getHandle(org.bukkit.Chunk chunk) {
Object handle = null;
try {
handle = class_CraftChunk_getHandleMethod.invoke(chunk);
} catch (Throwable ex) {
ex.printStackTrace();
}
return handle;
}
public static Object getHandle(org.bukkit.entity.Player player) {
Object handle = null;
try {
handle = class_CraftPlayer_getHandleMethod.invoke(player);
} catch (Throwable ex) {
ex.printStackTrace();
}
return handle;
}
protected static void sendPacket(Server server, Location source, Collection<? extends Player> players, Object packet) throws Exception {
players = ((players != null && players.size() > 0) ? players : server.getOnlinePlayers());
int viewDistance = Bukkit.getServer().getViewDistance() * 16;
int viewDistanceSquared = viewDistance * viewDistance;
World sourceWorld = source.getWorld();
for (Player player : players) {
Location location = player.getLocation();
if (!location.getWorld().equals(sourceWorld)) continue;
if (location.distanceSquared(source) <= viewDistanceSquared) {
sendPacket(player, packet);
}
}
}
protected static void sendPacket(Player player, Object packet) throws Exception {
Object playerHandle = getHandle(player);
Field connectionField = playerHandle.getClass().getField("playerConnection");
Object connection = connectionField.get(playerHandle);
Method sendPacketMethod = connection.getClass().getMethod("sendPacket", class_Packet);
sendPacketMethod.invoke(connection, packet);
}
public static int getFacing(BlockFace direction)
{
int dir;
switch (direction) {
case SOUTH:
default:
dir = 0;
break;
case WEST:
dir = 1;
break;
case NORTH:
dir = 2;
break;
case EAST:
dir = 3;
break;
}
return dir;
}
public static org.bukkit.entity.Entity getBukkitEntity(Object entity)
{
if (entity == null) return null;
try {
Method getMethod = entity.getClass().getMethod("getBukkitEntity");
Object bukkitEntity = getMethod.invoke(entity);
if (!(bukkitEntity instanceof org.bukkit.entity.Entity)) return null;
return (org.bukkit.entity.Entity)bukkitEntity;
} catch (Throwable ex) {
ex.printStackTrace();
}
return null;
}
public static Object getTag(Object mcItemStack) {
Object tag = null;
try {
tag = class_ItemStack_tagField.get(mcItemStack);
} catch (Throwable ex) {
ex.printStackTrace();
}
return tag;
}
protected static Object getNMSCopy(ItemStack stack) {
Object nms = null;
try {
nms = class_CraftItemStack_copyMethod.invoke(null, stack);
} catch (Throwable ex) {
ex.printStackTrace();
}
return nms;
}
public static ItemStack getCopy(ItemStack stack) {
if (stack == null) return null;
try {
Object craft = getNMSCopy(stack);
stack = (ItemStack)class_CraftItemStack_mirrorMethod.invoke(null, craft);
} catch (Throwable ex) {
stack = null;
}
return stack;
}
public static ItemStack makeReal(ItemStack stack) {
if (stack == null) return null;
Object nmsStack = getHandle(stack);
if (nmsStack == null) {
stack = getCopy(stack);
nmsStack = getHandle(stack);
}
if (nmsStack == null) {
return null;
}
try {
Object tag = class_ItemStack_tagField.get(nmsStack);
if (tag == null) {
class_ItemStack_tagField.set(nmsStack, class_NBTTagCompound.newInstance());
}
} catch (Throwable ex) {
ex.printStackTrace();
return null;
}
return stack;
}
public static String getMeta(ItemStack stack, String tag, String defaultValue) {
String result = getMeta(stack, tag);
return result == null ? defaultValue : result;
}
public static boolean hasMeta(ItemStack stack, String tag) {
return getNode(stack, tag) != null;
}
public static Object getNode(ItemStack stack, String tag) {
if (stack == null) return null;
Object meta = null;
try {
Object craft = getHandle(stack);
if (craft == null) return null;
Object tagObject = getTag(craft);
if (tagObject == null) return null;
meta = class_NBTTagCompound_getMethod.invoke(tagObject, tag);
} catch (Throwable ex) {
ex.printStackTrace();
}
return meta;
}
public static boolean containsNode(Object nbtBase, String tag) {
if (nbtBase == null) return false;
Boolean result = false;
try {
result = (Boolean)class_NBTTagCompound_hasKeyMethod.invoke(nbtBase, tag);
} catch (Throwable ex) {
ex.printStackTrace();
}
return result;
}
public static Object getNode(Object nbtBase, String tag) {
if (nbtBase == null) return null;
Object meta = null;
try {
meta = class_NBTTagCompound_getMethod.invoke(nbtBase, tag);
} catch (Throwable ex) {
ex.printStackTrace();
}
return meta;
}
public static Object createNode(Object nbtBase, String tag) {
if (nbtBase == null) return null;
Object meta = null;
try {
meta = class_NBTTagCompound_getCompoundMethod.invoke(nbtBase, tag);
class_NBTTagCompound_setMethod.invoke(nbtBase, tag, meta);
} catch (Throwable ex) {
ex.printStackTrace();
}
return meta;
}
public static Object createNode(ItemStack stack, String tag) {
if (stack == null) return null;
Object outputObject = getNode(stack, tag);
if (outputObject == null) {
try {
Object craft = getHandle(stack);
if (craft == null) return null;
Object tagObject = getTag(craft);
if (tagObject == null) return null;
outputObject = class_NBTTagCompound.newInstance();
class_NBTTagCompound_setMethod.invoke(tagObject, tag, outputObject);
} catch (Throwable ex) {
ex.printStackTrace();
}
}
return outputObject;
}
public static String getMeta(Object node, String tag, String defaultValue) {
String meta = getMeta(node, tag);
return meta == null || meta.length() == 0 ? defaultValue : meta;
}
public static String getMeta(Object node, String tag) {
if (node == null || !class_NBTTagCompound.isInstance(node)) return null;
String meta = null;
try {
meta = (String)class_NBTTagCompound_getStringMethod.invoke(node, tag);
} catch (Throwable ex) {
ex.printStackTrace();
}
return meta;
}
public static Byte getMetaByte(Object node, String tag) {
if (node == null || !class_NBTTagCompound.isInstance(node)) return null;
Byte meta = null;
try {
meta = (Byte)class_NBTTagCompound_getByteMethod.invoke(node, tag);
} catch (Throwable ex) {
ex.printStackTrace();
}
return meta;
}
public static Integer getMetaInt(Object node, String tag) {
if (node == null || !class_NBTTagCompound.isInstance(node)) return null;
Integer meta = null;
try {
meta = (Integer)class_NBTTagCompound_getIntMethod.invoke(node, tag);
} catch (Throwable ex) {
ex.printStackTrace();
}
return meta;
}
public static void setMeta(Object node, String tag, String value) {
if (node == null|| !class_NBTTagCompound.isInstance(node)) return;
try {
if (value == null || value.length() == 0) {
class_NBTTagCompound_removeMethod.invoke(node, tag);
} else {
class_NBTTagCompound_setStringMethod.invoke(node, tag, value);
}
} catch (Throwable ex) {
ex.printStackTrace();
}
}
public static void removeMeta(Object node, String tag) {
if (node == null|| !class_NBTTagCompound.isInstance(node)) return;
try {
class_NBTTagCompound_removeMethod.invoke(node, tag);
} catch (Throwable ex) {
ex.printStackTrace();
}
}
public static void removeMeta(ItemStack stack, String tag) {
if (stack == null) return;
try {
Object craft = getHandle(stack);
if (craft == null) return;
Object tagObject = getTag(craft);
if (tagObject == null) return;
removeMeta(tagObject, tag);
} catch (Throwable ex) {
ex.printStackTrace();
}
}
public static String getMeta(ItemStack stack, String tag) {
if (stack == null) return null;
String meta = null;
try {
Object craft = getHandle(stack);
if (craft == null) return null;
Object tagObject = getTag(craft);
if (tagObject == null) return null;
meta = (String)class_NBTTagCompound_getStringMethod.invoke(tagObject, tag);
} catch (Throwable ex) {
ex.printStackTrace();
}
return meta;
}
public static void setMeta(ItemStack stack, String tag, String value) {
if (stack == null) return;
try {
Object craft = getHandle(stack);
if (craft == null) return;
Object tagObject = getTag(craft);
if (tagObject == null) return;
class_NBTTagCompound_setStringMethod.invoke(tagObject, tag, value);
} catch (Throwable ex) {
ex.printStackTrace();
}
}
public static void addGlow(ItemStack stack) {
if (stack == null) return;
try {
Object craft = getHandle(stack);
if (craft == null) return;
Object tagObject = getTag(craft);
if (tagObject == null) return;
final Object enchList = class_NBTTagList.newInstance();
class_NBTTagCompound_setMethod.invoke(tagObject, "ench", enchList);
// Testing Glow API based on ItemMetadata storage
Object bukkitData = createNode(stack, "bukkit");
class_NBTTagCompound_setBooleanMethod.invoke(bukkitData, "glow", true);
} catch (Throwable ex) {
}
}
public static void removeGlow(ItemStack stack) {
if (stack == null) return;
Collection<Enchantment> enchants = stack.getEnchantments().keySet();
for (Enchantment enchant : enchants) {
stack.removeEnchantment(enchant);
}
try {
Object craft = getHandle(stack);
if (craft == null) return;
Object tagObject = getTag(craft);
if (tagObject == null) return;
// Testing Glow API based on ItemMetadata storage
Object bukkitData = getNode(stack, "bukkit");
if (bukkitData != null) {
class_NBTTagCompound_setBooleanMethod.invoke(bukkitData, "glow", false);
}
} catch (Throwable ex) {
}
}
public static void makeUnbreakable(ItemStack stack) {
if (stack == null) return;
try {
Object craft = getHandle(stack);
if (craft == null) return;
Object tagObject = getTag(craft);
if (tagObject == null) return;
Object unbreakableFlag = null;
if (class_NBTTagByte_constructor != null) {
unbreakableFlag = class_NBTTagByte_constructor.newInstance((byte) 1);
} else {
unbreakableFlag = class_NBTTagByte_legacy_constructor.newInstance("", (byte) 1);
}
class_NBTTagCompound_setMethod.invoke(tagObject, "Unbreakable", unbreakableFlag);
} catch (Throwable ex) {
}
}
public static void removeUnbreakable(ItemStack stack) {
removeMeta(stack, "Unbreakable");
}
public static void hideFlags(ItemStack stack, byte flags) {
if (stack == null) return;
try {
Object craft = getHandle(stack);
if (craft == null) return;
Object tagObject = getTag(craft);
if (tagObject == null) return;
Object hideFlag = null;
if (class_NBTTagByte_constructor != null) {
hideFlag = class_NBTTagByte_constructor.newInstance(flags);
} else {
hideFlag = class_NBTTagByte_legacy_constructor.newInstance("", flags);
}
class_NBTTagCompound_setMethod.invoke(tagObject, "HideFlags", hideFlag);
} catch (Throwable ex) {
}
}
public static boolean createExplosion(Entity entity, World world, double x, double y, double z, float power, boolean setFire, boolean breakBlocks) {
boolean result = false;
if (world == null) return false;
try {
Object worldHandle = getHandle(world);
if (worldHandle == null) return false;
Object entityHandle = entity == null ? null : getHandle(entity);
Object explosion = class_World_explodeMethod.invoke(worldHandle, entityHandle, x, y, z, power, setFire, breakBlocks);
Field cancelledField = explosion.getClass().getDeclaredField("wasCanceled");
result = (Boolean)cancelledField.get(explosion);
} catch (Throwable ex) {
ex.printStackTrace();
result = false;
}
return result;
}
public static void makeTemporary(ItemStack itemStack, String message) {
setMeta(itemStack, "temporary", message);
}
public static boolean isTemporary(ItemStack itemStack) {
return hasMeta(itemStack, "temporary");
}
public static void makeUnplaceable(ItemStack itemStack) {
setMeta(itemStack, "unplaceable", "true");
}
public static boolean isUnplaceable(ItemStack itemStack) {
return hasMeta(itemStack, "unplaceable");
}
public static String getTemporaryMessage(ItemStack itemStack) {
return getMeta(itemStack, "temporary");
}
public static void setReplacement(ItemStack itemStack, ItemStack replacement) {
YamlConfiguration configuration = new YamlConfiguration();
configuration.set("item", replacement);
setMeta(itemStack, "replacement", configuration.saveToString());
}
public static ItemStack getReplacement(ItemStack itemStack) {
String serialized = getMeta(itemStack, "replacement");
if (serialized == null || serialized.isEmpty()) {
return null;
}
YamlConfiguration configuration = new YamlConfiguration();
ItemStack replacement = null;
try {
configuration.loadFromString(serialized);
replacement = configuration.getItemStack("item");
} catch (Exception ex) {
ex.printStackTrace();
}
return replacement;
}
protected static Object getTagString(String value) {
try {
if (class_NBTTagList_legacy_consructor != null) {
return class_NBTTagList_legacy_consructor.newInstance("", value);
}
return class_NBTTagList_consructor.newInstance(value);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static Object setStringList(Object nbtBase, String tag, Collection<String> values) {
if (nbtBase == null) return null;
Object listMeta = null;
try {
listMeta = class_NBTTagList.newInstance();
for (String value : values) {
Object nbtString = getTagString(value);
class_NBTTagList_addMethod.invoke(listMeta, nbtString);
}
class_NBTTagCompound_setMethod.invoke(nbtBase, tag, listMeta);
} catch (Throwable ex) {
ex.printStackTrace();
return null;
}
return listMeta;
}
public static ItemStack getItem(Object itemTag) {
if (itemTag == null) return null;
ItemStack item = null;
try {
Object nmsStack = class_ItemStack_createStackMethod.invoke(null, itemTag);
item = (ItemStack)class_CraftItemStack_mirrorMethod.invoke(null, nmsStack);
} catch (Exception ex) {
ex.printStackTrace();
}
return item;
}
public static ItemStack[] getItems(Object rootTag, String tagName) {
try {
Object itemList = class_NBTTagCompound_getListMethod.invoke(rootTag, tagName, NBT_TYPE_COMPOUND);
Integer size = (Integer)class_NBTTagList_sizeMethod.invoke(itemList);
ItemStack[] items = new ItemStack[size];
for (int i = 0; i < size; i++) {
try {
Object itemData = class_NBTTagList_getMethod.invoke(itemList, i);
if (itemData != null) {
items[i] = getItem(itemData);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
return items;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static boolean loadSchematic(File inputFile, Schematic schematic) {
if (inputFile == null || !inputFile.exists() || schematic == null) {
return false;
}
InputStream inputStream = null;
try {
inputStream = new FileInputStream(inputFile);
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
return loadSchematic(inputStream, schematic);
}
public static boolean loadSchematic(InputStream input, Schematic schematic) {
if (input == null || schematic == null) return false;
try {
Object nbtData = class_NBTCompressedStreamTools_loadFileMethod.invoke(null, input);
if (nbtData == null) {
return false;
}
// Version check
String materials = (String)class_NBTTagCompound_getStringMethod.invoke(nbtData, "Materials");
if (!materials.equals("Alpha")) {
Bukkit.getLogger().warning("Schematic is not in Alpha format");
return false;
}
short width = (Short)class_NBTTagCompound_getShortMethod.invoke(nbtData, "Width");
short height = (Short)class_NBTTagCompound_getShortMethod.invoke(nbtData, "Height");
short length = (Short)class_NBTTagCompound_getShortMethod.invoke(nbtData, "Length");
byte[] blockIds = (byte[])class_NBTTagCompound_getByteArrayMethod.invoke(nbtData, "Blocks");
// Have to combine block ids to get 12 bits of ids
// Thanks to the WorldEdit team for showing me how to do this.
short[] blocks = new short[blockIds.length];
byte[] addBlocks = new byte[0];
if ((Boolean)class_NBTTagCompound_hasKeyMethod.invoke(nbtData, "AddBlocks")) {
addBlocks = (byte[])class_NBTTagCompound_getByteArrayMethod.invoke(nbtData, "AddBlocks");
}
for (int index = 0; index < blocks.length; index++) {
if ((index >> 1) >= addBlocks.length) {
blocks[index] = (short) (blockIds[index] & 0xFF);
} else {
if ((index & 1) == 0) {
blocks[index] = (short) (((addBlocks[index >> 1] & 0x0F) << 8) + (blockIds[index] & 0xFF));
} else {
blocks[index] = (short) (((addBlocks[index >> 1] & 0xF0) << 4) + (blockIds[index] & 0xFF));
}
}
}
byte[] data = (byte[])class_NBTTagCompound_getByteArrayMethod.invoke(nbtData, "Data");
Collection<Object> tileEntityData = new ArrayList<Object>();
Collection<Object> entityData = new ArrayList<Object>();
Object entityList = class_NBTTagCompound_getListMethod.invoke(nbtData, "Entities", NBT_TYPE_COMPOUND);
Object tileEntityList = class_NBTTagCompound_getListMethod.invoke(nbtData, "TileEntities", NBT_TYPE_COMPOUND);
if (entityList != null) {
int size = (Integer)class_NBTTagList_sizeMethod.invoke(entityList);
for (int i = 0; i < size; i++) {
Object entity = class_NBTTagList_getMethod.invoke(entityList, i);
entityData.add(entity);
}
}
if (tileEntityList != null) {
int size = (Integer)class_NBTTagList_sizeMethod.invoke(tileEntityList);
for (int i = 0; i < size; i++) {
Object tileEntity = class_NBTTagList_getMethod.invoke(tileEntityList, i);
tileEntityData.add(tileEntity);
}
}
int originX = (Integer)class_NBTTagCompound_getIntMethod.invoke(nbtData, "WEOriginX");
int originY = (Integer)class_NBTTagCompound_getIntMethod.invoke(nbtData, "WEOriginY");
int originZ = (Integer)class_NBTTagCompound_getIntMethod.invoke(nbtData, "WEOriginZ");
int offsetX = (Integer)class_NBTTagCompound_getIntMethod.invoke(nbtData, "WEOffsetX");
int offsetY = (Integer)class_NBTTagCompound_getIntMethod.invoke(nbtData, "WEOffsetY");
int offsetZ = (Integer)class_NBTTagCompound_getIntMethod.invoke(nbtData, "WEOffsetZ");
schematic.load(width, height, length, blocks, data, tileEntityData, entityData, new Vector(originX, originY, originZ), new Vector(offsetX, offsetY, offsetZ));
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
public static Object getTileEntityData(Location location) {
Object data = null;
try {
World world = location.getWorld();
Object tileEntity = class_CraftWorld_getTileEntityAtMethod.invoke(world, location.getBlockX(), location.getBlockY(), location.getBlockZ());
if (tileEntity != null) {
data = class_NBTTagCompound.newInstance();
class_TileEntity_saveMethod.invoke(tileEntity, data);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return data;
}
public static Object getTileEntity(Location location) {
Object tileEntity = null;
try {
World world = location.getWorld();
tileEntity = class_CraftWorld_getTileEntityAtMethod.invoke(world, location.getBlockX(), location.getBlockY(), location.getBlockZ());
} catch (Exception ex) {
ex.printStackTrace();
}
return tileEntity;
}
public static void clearItems(Location location) {
if (location == null) return;
try {
World world = location.getWorld();
if (world == null) return;
Object tileEntity = class_CraftWorld_getTileEntityAtMethod.invoke(world, location.getBlockX(), location.getBlockY(), location.getBlockZ());
if (tileEntity != null) {
Object entityData = class_NBTTagCompound.newInstance();
class_TileEntity_saveMethod.invoke(tileEntity, entityData);
Object itemList = class_NBTTagCompound_getListMethod.invoke(entityData, "Items", NBT_TYPE_COMPOUND);
if (itemList != null) {
List items = (List)class_NBTTagList_list.get(itemList);
items.clear();
class_TileEntity_loadMethod.invoke(tileEntity, entityData);
class_TileEntity_updateMethod.invoke(tileEntity);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void setTileEntityData(Location location, Object data) {
if (location == null || data == null) return;
try {
World world = location.getWorld();
if (world == null) return;
Object tileEntity = class_CraftWorld_getTileEntityAtMethod.invoke(world, location.getBlockX(), location.getBlockY(), location.getBlockZ());
if (tileEntity == null) return;
class_NBTTagCompound_setIntMethod.invoke(data, "x", location.getBlockX());
class_NBTTagCompound_setIntMethod.invoke(data, "y", location.getBlockY());
class_NBTTagCompound_setIntMethod.invoke(data, "z", location.getBlockZ());
class_TileEntity_loadMethod.invoke(tileEntity, data);
class_TileEntity_updateMethod.invoke(tileEntity);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static Vector getPosition(Object entityData, String tag) {
try {
Object posList = class_NBTTagCompound_getListMethod.invoke(entityData, tag, NBT_TYPE_DOUBLE);
Double x = (Double)class_NBTTagList_getDoubleMethod.invoke(posList, 0);
Double y = (Double)class_NBTTagList_getDoubleMethod.invoke(posList, 1);
Double z = (Double)class_NBTTagList_getDoubleMethod.invoke(posList, 2);
if (x != null && y != null && z != null) {
return new Vector(x, y, z);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static Entity getEntity(World world, UUID uuid) {
try {
Object worldHandle = getHandle(world);
final Map<UUID, Entity> entityMap = (Map<UUID, Entity>)class_WorldServer_entitiesByUUIDField.get(worldHandle);
if (entityMap != null) {
Object nmsEntity = entityMap.get(uuid);
if (nmsEntity != null) {
return getBukkitEntity(nmsEntity);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static void setEnvironment(World world, World.Environment environment) {
try {
class_CraftWorld_environmentField.set(world, environment);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
|
package org.mvel;
import org.mvel.integration.Interceptor;
import org.mvel.ast.LineLabel;
import java.util.*;
import java.io.Serializable;
import java.lang.reflect.Method;
/**
* The ParserContext is the main enviroment object used for sharing state throughout the entire
* parser/compile process.
*/
public class ParserContext implements Serializable {
private String sourceFile;
private int lineCount = 1;
private int lineOffset;
protected Map<String, Object> imports;
protected Set<String> packageImports;
protected Map<String, Interceptor> interceptors;
private Map<String, Class> variables;
private Map<String, Class> inputs;
private List<ErrorDetail> errorList;
private Map<String, Set<Integer>> sourceMap;
private LineLabel firstLineLabel;
private Object rootParser;
private boolean compiled = false;
private boolean strictTypeEnforcement = false;
private boolean fatalError = false;
private boolean retainParserState = false;
private boolean debugSymbols = false;
public ParserContext() {
}
public ParserContext(boolean debugSymbols) {
this.debugSymbols = debugSymbols;
}
public ParserContext(Object rootParser) {
this.rootParser = rootParser;
}
public ParserContext(Map<String, Object> imports, Map<String, Interceptor> interceptors, String sourceFile) {
this.imports = imports;
this.interceptors = interceptors;
this.sourceFile = sourceFile;
}
public boolean hasVarOrInput(String name) {
return (variables != null && variables.containsKey(name))
|| (inputs != null && inputs.containsKey(name));
}
public Class getVarOrInputType(String name) {
if (variables != null && variables.containsKey(name)) {
return variables.get(name);
}
else if (inputs != null && inputs.containsKey(name)) {
return inputs.get(name);
}
return Object.class;
}
public int getLineCount() {
return lineCount;
}
public void setLineCount(int lineCount) {
this.lineCount = lineCount;
}
public int getLineOffset() {
return lineOffset;
}
public void setLineOffset(int lineOffset) {
this.lineOffset = lineOffset;
}
public void setLineAndOffset(int lineCount, int lineOffset) {
this.lineCount = lineCount;
this.lineOffset = lineOffset;
}
public Class getImport(String name) {
return (imports != null && imports.containsKey(name) ? (Class) imports.get(name) : (Class) AbstractParser.LITERALS.get(name));
}
public Method getStaticImport(String name) {
return imports != null ? (Method) imports.get(name) : null;
}
public void addPackageImport(String packageName) {
if (packageImports == null) packageImports = new HashSet<String>();
packageImports.add(packageName);
}
private boolean checkForDynamicImport(String className) {
if (packageImports == null) return false;
int found = 0;
Class cls = null;
for (String pkg : packageImports) {
try {
cls = Class.forName(pkg + "." + className);
found++;
}
catch (ClassNotFoundException e) {
// do nothing.
}
}
if (found > 1) {
throw new CompileException("ambiguous class name: " + className);
}
else if (found == 1) {
addImport(className, cls);
return true;
}
else {
return false;
}
}
public boolean hasImport(String name) {
return (imports != null && imports.containsKey(name)) || (!"this".equals(name) && !"self".equals(name) && !"empty".equals(name)
&& AbstractParser.LITERALS.containsKey(name))
|| checkForDynamicImport(name);
}
public void addImport(String name, Class cls) {
if (this.imports == null) this.imports = new HashMap<String, Object>();
this.imports.put(name, cls);
}
public void addImport(String name, Method method) {
if (this.imports == null) this.imports = new HashMap<String, Object>();
this.imports.put(name, method);
}
public void initializeTables() {
if (variables == null) variables = new HashMap<String, Class>();
if (inputs == null) inputs = new HashMap<String, Class>();
}
public void addVariable(String name, Class type) {
if (variables.containsKey(name)) return;
if (type == null) type = Object.class;
variables.put(name, type);
}
public void addInput(String name, Class type) {
if (inputs == null) inputs = new HashMap<String, Class>();
if (inputs.containsKey(name)) return;
if (type == null) type = Object.class;
inputs.put(name, type);
}
public void processTables() {
for (String name : variables.keySet()) {
inputs.remove(name);
}
}
// accessors -- start here
public Map<String, Class> getInputs() {
return inputs;
}
public void setInputs(Map<String, Class> inputs) {
this.inputs = inputs;
}
public List<ErrorDetail> getErrorList() {
return errorList;
}
public void setErrorList(List<ErrorDetail> errorList) {
this.errorList = errorList;
}
public void addError(ErrorDetail errorDetail) {
if (errorList == null) errorList = new ArrayList<ErrorDetail>();
if (errorDetail.isCritical()) fatalError = true;
errorList.add(errorDetail);
}
public boolean isFatalError() {
return fatalError;
}
public void setFatalError(boolean fatalError) {
this.fatalError = fatalError;
}
public boolean isStrictTypeEnforcement() {
return strictTypeEnforcement;
}
public void setStrictTypeEnforcement(boolean strictTypeEnforcement) {
this.strictTypeEnforcement = strictTypeEnforcement;
}
public boolean isRetainParserState() {
return retainParserState;
}
public void setRetainParserState(boolean retainParserState) {
this.retainParserState = retainParserState;
}
public Object getRootParser() {
return rootParser;
}
public void setRootParser(Object rootParser) {
this.rootParser = rootParser;
}
public String getSourceFile() {
return sourceFile;
}
public void setSourceFile(String sourceFile) {
if (sourceFile != null)
this.sourceFile = sourceFile;
}
public Map<String, Interceptor> getInterceptors() {
return interceptors;
}
public void setInterceptors(Map<String, Interceptor> interceptors) {
this.interceptors = interceptors;
}
public Map<String, Object> getImports() {
return imports;
}
public void setImports(Map<String, Object> imports) {
if (imports == null) return;
if (this.imports != null) {
this.imports.putAll(imports);
}
else {
this.imports = imports;
}
}
public Map<String, Class> getVariables() {
return variables;
}
public void setVariables(Map<String, Class> variables) {
this.variables = variables;
}
public boolean isCompiled() {
return compiled;
}
public void setCompiled(boolean compiled) {
this.compiled = compiled;
}
public boolean isDebugSymbols() {
return debugSymbols;
}
public void setDebugSymbols(boolean debugSymbols) {
this.debugSymbols = debugSymbols;
}
public boolean isKnownLine(String sourceName, int lineNumber) {
return sourceMap != null && sourceMap.containsKey(sourceName) && sourceMap.get(sourceName).contains(lineNumber);
}
public void addKnownLine(String sourceName, int lineNumber) {
if (sourceMap == null) sourceMap = new HashMap<String, Set<Integer>>();
if (!sourceMap.containsKey(sourceName)) sourceMap.put(sourceName, new HashSet<Integer>());
sourceMap.get(sourceName).add(lineNumber);
}
public LineLabel getFirstLineLabel() {
return firstLineLabel;
}
public void setFirstLineLabel(LineLabel firstLineLabel) {
this.firstLineLabel = firstLineLabel;
}
public boolean hasImports() {
return (imports != null && imports.size() != 0) || (packageImports != null && packageImports.size() != 0);
}
}
|
package org.bedework.webclient;
//import org.bedework.calfacade.BwDateTime;
import org.bedework.appcommon.FormattedFreeBusy;
import org.bedework.appcommon.MyCalendarVO;
import org.bedework.appcommon.TimeView;
import org.bedework.calfacade.BwDuration;
import org.bedework.calfacade.BwFreeBusy;
import org.bedework.calfacade.BwUser;
import org.bedework.calfacade.CalFacadeAccessException;
import org.bedework.calfacade.CalFacadeUtil;
import org.bedework.calfacade.ifs.CalTimezones;
import org.bedework.calsvci.CalSvcI;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
/**
* Action to fetch free busy information
* <p>Request parameters - all optional:<ul>
* <li> userid: whose free busy we want - default to current user</li>.
* <li> calendar: name of the calendar - default to subscriptions
* specified by user</li>.
* <li> start: start of period - default to beginning of this week</li>.
* <li> end: end of period - default to end of this week</li>.
* <li> interval: default entire period or a multiplier</li>.
* <li> intunit: default to hours, "minutes", "hours, "days", "weeks"
* "months"</li>.
* </ul>
* <p>e.g interval=30 and intunit="minutes" means half hour intervals
* <p>Forwards to:<ul>
* <li>"doNothing" input error or we want to ignore the request.</li>
* <li>"noAccess" No acccess to free busy</li>
* <li>"notFound" event not found.</li>
* <li>"error" input error - correct and retry.</li>
* <li>"success" fetched OK.</li>
* </ul>
*
* <p>If no period is given return this week. If no interval and intunit is
* supplied default to 1 hour intervals during the workday.
*
* @author Mike Douglass douglm @ rpi.edu
*/
public class BwFreeBusyAction extends BwCalAbstractAction {
/* (non-Javadoc)
* @see org.bedework.webclient.BwCalAbstractAction#doAction(javax.servlet.http.HttpServletRequest, org.bedework.webclient.BwActionForm)
*/
public String doAction(HttpServletRequest request,
BwActionForm form) throws Throwable {
BwUser user;
CalSvcI svci = form.fetchSvci();
String userId = getReqPar(request, "userid");
if (userId != null) {
user = svci.findUser(userId);
if (user == null) {
form.getErr().emit("org.bedework.client.error.usernotfound");
return "notFound";
}
} else {
user = svci.getUser();
}
MyCalendarVO scal;
Calendar start;
Calendar end;
Calendar endDay;
String st = getReqPar(request, "start");
if (st == null) {
/* Set period and start from the current timeview */
TimeView tv = form.getCurTimeView();
scal = tv.getFirstDay();
start = scal.getCalendar();
end = tv.getLastDay().getTomorrow().getCalendar();
} else {
Locale loc = Locale.getDefault(); // XXX Locale
Date jdt = CalFacadeUtil.fromISODate(st);
scal = new MyCalendarVO(jdt, loc);
scal = scal.getFirstDayOfThisWeek();
start = scal.getCalendar();
//BwDateTime startDt = form.getEventStartDate().getDateTime();
end = scal.getNextWeek().getCalendar();
}
endDay = scal.getTomorrow().getCalendar();
int interval = getIntReqPar(request, "interval", 1);
if (interval <= 0) {
form.getErr().emit("org.bedework.client.error.badinterval");
return "error";
}
String intunitStr = getReqPar(request, "intunit");
BwDuration dur = new BwDuration();
if (intunitStr != null) {
if ("minutes".equals(intunitStr)) {
dur.setMinutes(interval);
} else if ("hours".equals(intunitStr)) {
dur.setHours(interval);
} else if ("days".equals(intunitStr)) {
dur.setDays(interval);
} else if ("weeks".equals(intunitStr)) {
dur.setWeeks(interval);
} else {
form.getErr().emit("org.bedework.client.error.badintervalunit");
return "error";
}
} else {
dur.setHours(interval);
}
//int maxRequests = 1000;
CalTimezones tzs = svci.getTimezones();
Collection freeBusy = new ArrayList();
/* Get the free busy in daily chunks and process for display
*/
while (start.before(end)) {
Date sdt = start.getTime();
Date edt = endDay.getTime();
if (debug) {
debugMsg("getFreeBusy for start = " + sdt +
" end = " + edt);
}
try {
BwFreeBusy fb = svci.getFreeBusy(null, user,
CalFacadeUtil.getDateTime(sdt, false, false, tzs),
CalFacadeUtil.getDateTime(edt, false, false, tzs),
dur, true);
FormattedFreeBusy ffb = new FormattedFreeBusy(fb);
freeBusy.add(ffb);
start.add(Calendar.DAY_OF_MONTH, 1);
endDay.add(Calendar.DAY_OF_MONTH, 1);
} catch (CalFacadeAccessException cfae) {
return "noAccess";
}
}
form.assignFreeBusy(freeBusy);
return "success";
}
}
|
package ucar.unidata.geoloc.projection;
import org.junit.Assert;
import org.junit.Test;
import ucar.unidata.geoloc.*;
public class SinusoidalTest {
// If we want all of the x-coords in the geographic region to be positive, use this.
// Will be roughly 20015.8.
private static final double false_easting = new Sinusoidal().latLonToProj(0, 180).getX();
// If we want all of the y-coords in the geographic region to be positive, use this.
// Will be roughly 10007.9.
private static final double false_northing = new Sinusoidal().latLonToProj(90, 0).getY();
@Test
public void projToLatLonBB_typical() {
// All 4 corners of the bounding box are on the earth.
// Values come from visual inspection in ToolsUI->Grid Viewer
// Upper left: -2201 1111 -> 10.0N 20.1W
// Upper right: 2982 111 -> 10.0N 27.23E
// Lower left: -2201 -4446 -> 40.0S 25.84W
// Lower right: 2982 -4446 -> 40.0S 35.0E
ProjectionPoint upperLeft = new ProjectionPointImpl(-2201, 1111);
ProjectionPoint lowerRight = new ProjectionPointImpl(2982, -4446);
Sinusoidal proj = new Sinusoidal();
ProjectionRect projBB = new ProjectionRect(upperLeft, lowerRight);
LatLonRect latLonBB = proj.projToLatLonBB(projBB);
Assert.assertEquals(-25.84, latLonBB.getLonMin(), 0.1);
Assert.assertEquals(35.0, latLonBB.getLonMax(), 0.1);
Assert.assertEquals(-40.0, latLonBB.getLatMin(), 0.1);
Assert.assertEquals(10.0, latLonBB.getLatMax(), 0.1);
}
@Test // Reproduces issue from ETO-719860
public void projToLatLonBB_validBottom() {
// Bottom 2 corners of bounding box are on the earth. Box intercepts earth's edge at 2 places.
// These values come from the dataset referenced in ETO-719860.
double minX = 7783.190324950472;
double minY = 6672.166430716527;
double maxX = 8895.140844616471;
double maxY = 7784.116950383528;
Sinusoidal proj = new Sinusoidal();
ProjectionRect projBB = new ProjectionRect(minX, minY, maxX, maxY);
LatLonRect latLonBB = proj.projToLatLonBB(projBB);
// Values come from visual inspection in ToolsUI->Grid Viewer
Assert.assertEquals(140.0, latLonBB.getLonMin(), 0.1);
Assert.assertEquals(180.0, latLonBB.getLonMax(), 0.1);
Assert.assertEquals(60.0, latLonBB.getLatMin(), 0.1);
Assert.assertEquals(67.11, latLonBB.getLatMax(), 0.1);
}
@Test
public void projToLatLonBB_validTop() {
// Top 2 corners of bounding box are on the earth. Box intercepts earth's edge at 2 places.
// Values come from visual inspection in ToolsUI->Grid Viewer
// Upper left: -9070 -2780 -> 25.002S 90.004W
// Upper right: -3603 -2780 -> 25.002S 35.761W
// Lower right: -3603 -8854 -> 79.627S 179.99W
// But let's use false_easting = 20015.8 and false_northing = 10007.9
ProjectionPoint upperLeft = new ProjectionPointImpl(false_easting + -9070, false_northing + -2780);
ProjectionPoint lowerRight = new ProjectionPointImpl(false_easting + -3603, false_northing + -10000);
Sinusoidal proj = new Sinusoidal(0, false_easting, false_northing, ProjectionImpl.EARTH_RADIUS);
ProjectionRect projBB = new ProjectionRect(upperLeft, lowerRight);
LatLonRect latLonBB = proj.projToLatLonBB(projBB);
Assert.assertEquals(-180.0, latLonBB.getLonMin(), 0.1);
Assert.assertEquals(-35.761, latLonBB.getLonMax(), 0.1);
Assert.assertEquals(-79.627, latLonBB.getLatMin(), 0.1);
Assert.assertEquals(-25.002, latLonBB.getLatMax(), 0.1);
}
@Test
public void projToLatLonBB_validLeft() {
// Left 2 corners of bounding box are on the earth. Box intercepts earth's edge at 2 places.
// Values come from visual inspection in ToolsUI->Grid Viewer
// Upper left: 14480 -2228 -> 20.037S 138.62E
// Lower left: 14480 -4361 -> 39.224S 168.10E
// Upper right: 18803 -2228 -> 20.037S 179.99E
// But let's use false_easting = 20015.8 and false_northing = 10007.9
ProjectionPoint upperLeft = new ProjectionPointImpl(false_easting + 14480, false_northing + -2228);
ProjectionPoint lowerRight = new ProjectionPointImpl(false_easting + 20000, false_northing + -4361);
Sinusoidal proj = new Sinusoidal(0, false_easting, false_northing, ProjectionImpl.EARTH_RADIUS);
ProjectionRect projBB = new ProjectionRect(upperLeft, lowerRight);
LatLonRect latLonBB = proj.projToLatLonBB(projBB);
Assert.assertEquals(138.62, latLonBB.getLonMin(), 0.1);
Assert.assertEquals(180.0 , latLonBB.getLonMax(), 0.1);
Assert.assertEquals(-39.224, latLonBB.getLatMin(), 0.1);
Assert.assertEquals(-20.037, latLonBB.getLatMax(), 0.1);
}
@Test
public void projToLatLonBB_validRight() {
// Right 2 corners of bounding box are on the earth. Box intercepts earth's edge at 2 places.
// Values come from visual inspection in ToolsUI->Grid Viewer
// Lower right: -9370 4446 -> 39.985N 109.99W
// Upper right: -9370 6278 -> 56.465N 152.54W
// Lower left: -15334 4446 -> 39.985N 179.99W
// But let's use false_easting = 20015.8 and false_northing = 10007.9
ProjectionPoint lowerRight = new ProjectionPointImpl(false_easting + -9370, false_northing + 4446);
ProjectionPoint upperLeft = new ProjectionPointImpl(false_easting + -17500, false_northing + 6278);
Sinusoidal proj = new Sinusoidal(0, false_easting, false_northing, ProjectionImpl.EARTH_RADIUS);
ProjectionRect projBB = new ProjectionRect(upperLeft, lowerRight);
LatLonRect latLonBB = proj.projToLatLonBB(projBB);
Assert.assertEquals(-180.0, latLonBB.getLonMin(), 0.1);
Assert.assertEquals(-109.99, latLonBB.getLonMax(), 0.1);
Assert.assertEquals(39.985, latLonBB.getLatMin(), 0.1);
Assert.assertEquals(56.465, latLonBB.getLatMax(), 0.1);
}
@Test
public void projToLatLonBB_partiallyValidTop() {
// The bottom corners are on the earth, the top corners are not. However, the line formed by the top corners
// intersects the earth. As a result, the bounding box intersects the earth's edge at 4 places.
// Values come from visual inspection in ToolsUI->Grid Viewer
// Lower left : -4166 8342 -> 75.0N 145.0W
// Lower right: 4021 8342 -> 75.0N 140.0E
// Upper 1st-from-left: -4166 8671 -> 77.985N 180.0W
// Upper 2nd-from-left: -1744 9451 -> 85.0N 180.0W
// Upper 3rd-from-left: 1743 9451 -> 85.0N 180.0E
// Upper 4th-from-left: 4021 8718 -> 78.404N 180.0E
ProjectionPoint lowerLeft = new ProjectionPointImpl(-4166, 8342);
ProjectionPoint upperRight = new ProjectionPointImpl(4021, 9451);
Sinusoidal proj = new Sinusoidal();
ProjectionRect projBB = new ProjectionRect(lowerLeft, upperRight);
LatLonRect latLonBB = proj.projToLatLonBB(projBB);
Assert.assertEquals(-180.0, latLonBB.getLonMin(), 0.1);
Assert.assertEquals(180.0, latLonBB.getLonMax(), 0.1);
Assert.assertEquals(75.0, latLonBB.getLatMin(), 0.1);
Assert.assertEquals(85.0, latLonBB.getLatMax(), 0.1);
}
@Test
public void projToLatLonBB_onlyIntercepts() {
// Same bounding box as projToLatLonBB_partiallyValidTop(), but the left and right sides have been
// extended completely off the earth. None of its corners are on the earth, but it intersects it at 4 places.
ProjectionPoint lowerLeft = new ProjectionPointImpl(-13000, 8342);
ProjectionPoint upperRight = new ProjectionPointImpl(15000, 9451);
Sinusoidal proj = new Sinusoidal();
ProjectionRect projBB = new ProjectionRect(lowerLeft, upperRight);
LatLonRect latLonBB = proj.projToLatLonBB(projBB);
Assert.assertEquals(-180.0, latLonBB.getLonMin(), 0.1);
Assert.assertEquals(180.0, latLonBB.getLonMax(), 0.1);
Assert.assertEquals(75.0, latLonBB.getLatMin(), 0.1);
Assert.assertEquals(85.0, latLonBB.getLatMax(), 0.1);
}
@Test
public void projToLatLonBB_includesNorthPole() {
// It intersects the earth at 2 places and includes the north pole.
ProjectionPoint lowerLeft = new ProjectionPointImpl(-4166, 8342);
ProjectionPoint upperRight = new ProjectionPointImpl(4021, 11111);
Sinusoidal proj = new Sinusoidal();
ProjectionRect projBB = new ProjectionRect(lowerLeft, upperRight);
LatLonRect latLonBB = proj.projToLatLonBB(projBB);
Assert.assertEquals(-180.0, latLonBB.getLonMin(), 0.1);
Assert.assertEquals(180.0, latLonBB.getLonMax(), 0.1);
Assert.assertEquals(75.0, latLonBB.getLatMin(), 0.1);
Assert.assertEquals(90.0, latLonBB.getLatMax(), 0.1);
}
@Test
public void projToLatLonBB_onlyInterceptsAndPole() {
// Same bounding box as projToLatLonBB_partiallyValidTop(), but the left, right, and top sides have been
// extended completely off the earth. None of its corners are on the earth, but it intersects it at 2 places
// and includes the north pole.
ProjectionPoint lowerLeft = new ProjectionPointImpl(-13000, 8342);
ProjectionPoint upperRight = new ProjectionPointImpl(15000, 11111);
Sinusoidal proj = new Sinusoidal();
ProjectionRect projBB = new ProjectionRect(lowerLeft, upperRight);
LatLonRect latLonBB = proj.projToLatLonBB(projBB);
Assert.assertEquals(-180.0, latLonBB.getLonMin(), 0.1);
Assert.assertEquals(180.0, latLonBB.getLonMax(), 0.1);
Assert.assertEquals(75.0, latLonBB.getLatMin(), 0.1);
Assert.assertEquals(90.0, latLonBB.getLatMax(), 0.1);
}
@Test
public void projToLatLonBB_poleAndOneCorner() {
// The bounding box includes the south pole and only 1 corner is on the earth.
// It intersects the the earth's edges at 2 places.
// Values come from visual inspection in ToolsUI->Grid Viewer
// Upper left: -1388 -6673 -> 60.0S 25.0W
// Upper right: 10003 -6673 -> 60.0S 180.0E
// Lower left: -1388 -9565 -> 86.0S 180.0W
ProjectionPoint upperLeft = new ProjectionPointImpl(-1388, -6673);
ProjectionPoint lowerRight = new ProjectionPointImpl(12000, -12000);
Sinusoidal proj = new Sinusoidal();
ProjectionRect projBB = new ProjectionRect(upperLeft, lowerRight);
LatLonRect latLonBB = proj.projToLatLonBB(projBB);
Assert.assertEquals(-180.0, latLonBB.getLonMin(), 0.1);
Assert.assertEquals(180.0, latLonBB.getLonMax(), 0.1);
Assert.assertEquals(60.0, latLonBB.getLatMin(), 0.1);
Assert.assertEquals(90.0, latLonBB.getLatMax(), 0.1);
}
@Test(expected = IllegalArgumentException.class)
public void projToLatLonBB_completelyOffTheEarth() {
// None of the corners are on the earth and none of the sides intersect its edge.
ProjectionPoint upperLeft = new ProjectionPointImpl(10000, -7000);
ProjectionPoint lowerRight = new ProjectionPointImpl(3000, 3000);
Sinusoidal proj = new Sinusoidal();
ProjectionRect projBB = new ProjectionRect(upperLeft, lowerRight);
proj.projToLatLonBB(projBB);
}
}
|
package com.fwdekker.randomness.word;
import com.fwdekker.randomness.Settings;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.util.xmlb.XmlSerializerUtil;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Contains settings for generating random words.
*/
@State(
name = "WordSettings",
storages = @Storage("$APP_CONFIG$/randomness.xml")
)
public final class WordSettings extends Settings implements PersistentStateComponent<WordSettings> {
private static final int DEFAULT_MIN_LENGTH = 3;
private static final int DEFAULT_MAX_LENGTH = 8;
/**
* The minimum length of a generated word, inclusive.
*/
private int minLength = DEFAULT_MIN_LENGTH;
/**
* The maximum length of a generated word, inclusive.
*/
private int maxLength = DEFAULT_MAX_LENGTH;
/**
* The string that encloses the generated word on both sides.
*/
private String enclosure = "\"";
/**
* The way in which the generated word should be capitalized.
*/
private CapitalizationMode capitalization = CapitalizationMode.NORMAL;
/**
* The list of all dictionaries provided by the plugin.
*/
private Set<String> bundledDictionaries = new HashSet<>(Arrays.asList(Dictionary.DEFAULT_DICTIONARY_FILE));
/**
* The list of all dictionaries registered by the user.
*/
private Set<String> userDictionaries = new HashSet<>();
/**
* The list of bundled dictionaries that are currently active.
*/
private Set<String> activeBundledDictionaries = new HashSet<>(Arrays.asList(Dictionary.DEFAULT_DICTIONARY_FILE));
/**
* The list of user dictionaries that are currently active.
*/
private Set<String> activeUserDictionaries = new HashSet<>();
/**
* Returns the singleton {@code WordSettings} instance.
*
* @return the singleton {@code WordSettings} instance
*/
public static WordSettings getInstance() {
return ServiceManager.getService(WordSettings.class);
}
@Override
public WordSettings getState() {
return this;
}
@Override
public void loadState(final @NotNull WordSettings state) {
XmlSerializerUtil.copyBean(state, this);
}
/**
* Returns the minimum length of a generated word, inclusive.
*
* @return the minimum length of a generated word, inclusive
*/
public int getMinLength() {
return minLength;
}
/**
* Sets the minimum length of a generated word, inclusive.
*
* @param minLength the minimum length of a generated word, inclusive
*/
public void setMinLength(final int minLength) {
this.minLength = minLength;
}
/**
* Returns the maximum length of a generated word, inclusive.
*
* @return the maximum length of a generated word, inclusive
*/
public int getMaxLength() {
return maxLength;
}
/**
* Sets the maximum length of a generated word, inclusive.
*
* @param maxLength the maximum length of a generated word, inclusive
*/
public void setMaxLength(final int maxLength) {
this.maxLength = maxLength;
}
/**
* Returns the string that encloses the generated word on both sides.
*
* @return the string that encloses the generated word on both sides
*/
public String getEnclosure() {
return enclosure;
}
/**
* Sets the string that encloses the generated word on both sides.
*
* @param enclosure the string that encloses the generated word on both sides
*/
public void setEnclosure(final String enclosure) {
this.enclosure = enclosure;
}
/**
* Returns the way in which the generated word should be capitalized.
*
* @return the way in which the generated word should be capitalized
*/
public CapitalizationMode getCapitalization() {
return capitalization;
}
/**
* Sets the way in which the generated word should be capitalized.
*
* @param capitalization the way in which the generated word should be capitalized
*/
public void setCapitalization(final CapitalizationMode capitalization) {
this.capitalization = capitalization;
}
/**
* Returns the list of all dictionaries provided by the plugin.
*
* @return the list of all dictionaries provided by the plugin
*/
public Set<String> getBundledDictionaries() {
return bundledDictionaries;
}
/**
* Sets the list of all dictionaries provided by the plugin.
*
* @param bundledDictionaries the list of all dictionaries provided by the plugin
*/
public void setBundledDictionaries(final Set<String> bundledDictionaries) {
this.bundledDictionaries = bundledDictionaries;
}
/**
* Returns the list of all dictionaries registered by the user.
*
* @return the list of all dictionaries registered by the user
*/
public Set<String> getUserDictionaries() {
return userDictionaries;
}
/**
* Sets the list of all dictionaries registered by the user.
*
* @param userDictionaries the list of all dictionaries registered by the user
*/
public void setUserDictionaries(final Set<String> userDictionaries) {
this.userDictionaries = userDictionaries;
}
/**
* Returns the list of bundled dictionaries that are currently active.
*
* @return the list of bundled dictionaries that are currently active
*/
public Set<String> getActiveBundledDictionaries() {
return activeBundledDictionaries;
}
/**
* Sets the list of bundled dictionaries that are currently active.
*
* @param activeBundledDictionaries the list of bundled dictionaries that are currently active
*/
public void setActiveBundledDictionaries(final Set<String> activeBundledDictionaries) {
this.activeBundledDictionaries = activeBundledDictionaries;
}
/**
* Returns the list of user dictionaries that are currently active.
*
* @return the list of user dictionaries that are currently active
*/
public Set<String> getActiveUserDictionaries() {
return activeUserDictionaries;
}
/**
* Sets the list of user dictionaries that are currently active.
*
* @param activeUserDictionaries the list of user dictionaries that are currently active
*/
public void setActiveUserDictionaries(final Set<String> activeUserDictionaries) {
this.activeUserDictionaries = activeUserDictionaries;
}
/**
* Returns the list of all dictionaries.
*
* @return the list of all dictionaries
*/
public List<Dictionary> getDictionaries() {
final List<Dictionary> dictionaries = new ArrayList<>();
dictionaries.addAll(bundledDictionaries.stream()
.map(Dictionary.BundledDictionary::get)
.collect(Collectors.toList()));
dictionaries.addAll(userDictionaries.stream()
.map(Dictionary.UserDictionary::get)
.collect(Collectors.toList()));
return dictionaries;
}
/**
* Returns the list of all dictionaries that are currently active.
*
* @return the list of all dictionaries that are currently active
*/
public List<Dictionary> getActiveDictionaries() {
final List<Dictionary> dictionaries = new ArrayList<>();
dictionaries.addAll(activeBundledDictionaries.stream()
.map(Dictionary.BundledDictionary::get)
.collect(Collectors.toList()));
dictionaries.addAll(activeUserDictionaries.stream()
.map(Dictionary.UserDictionary::get)
.collect(Collectors.toList()));
return dictionaries;
}
}
|
package pig.ml.reco.cf.udf;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import org.apache.pig.AccumulatorEvalFunc;
import org.apache.pig.backend.executionengine.ExecException;
import org.apache.pig.data.BagFactory;
import org.apache.pig.data.DataBag;
import org.apache.pig.data.DataType;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
import org.apache.pig.impl.logicalLayer.FrontendException;
import org.apache.pig.impl.logicalLayer.schema.Schema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pig.ml.reco.cf.sim.Similarity;
import com.google.common.base.Preconditions;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
public class SIM extends AccumulatorEvalFunc<DataBag> {
private static final Logger logger = LoggerFactory.getLogger(SIM.class);
private static final String PKGPREFIX = "pig.ml.reco.cf.sim.";
private Similarity similarity;
private int threshold;
DataBag prodSimilarities = BagFactory.getInstance().newSortedBag(bagComparator1);
static private final Comparator<Tuple> bagComparator1 = new Comparator<Tuple>() {
@Override
public int compare(Tuple o1, Tuple o2) {
try {
Object p11 = o1.get(0);
Object p12 = o1.get(1);
Object p21 = o2.get(0);
Object p22 = o2.get(1);
if(p11.equals(p22) && p12.equals(p21)) {
return 0;
}
} catch (ExecException e) {
logger.error(e.getMessage(), e);
}
return -1;
}
};
static private final Comparator<Tuple> bagComparator2 = new Comparator<Tuple>() {
@Override
public int compare(Tuple o1, Tuple o2) {
try {
Object p11 = o1.get(0);
Object p12 = o1.get(2);
Object p21 = o2.get(0);
Object p22 = o2.get(2);
if(p11.equals(p22) && p12.equals(p21)) {
return 0;
}
} catch (ExecException e) {
logger.error(e.getMessage(), e);
}
return -1;
}
};
public SIM(String threshold, String similarityClass) throws ExecException {
this.threshold = Integer.parseInt(threshold);
Class<?> similarityKlass = null;
try {
similarityKlass = Class.forName(PKGPREFIX + (String) similarityClass);
Preconditions.checkArgument(Similarity.class.isAssignableFrom(similarityKlass));
similarity = (Similarity) similarityKlass.newInstance();
logger.debug("Similarity Class configured is {} ", similarity.getClass());
} catch (Exception e) {
throw new ExecException(e.getMessage(), e);
}
}
private DataBag getSimilarityBag(Tuple input) throws IOException {
try {
Object object = input.get(0);
Preconditions.checkArgument(object instanceof DataBag);
DataBag inputBag = (DataBag) object;
Tuple tupleSimilarity = null;
Multimap<Object, Number> userWeightMap = ArrayListMultimap.create();
for (Tuple inputTuple : inputBag) {
Preconditions.checkArgument(inputTuple.size() == 4);
Object product1 = inputTuple.get(0);
Object product2 = inputTuple.get(2);
if (product1.equals(product2)) {
continue;
}
tupleSimilarity = TupleFactory.getInstance().newTuple(3);
tupleSimilarity.set(0, product1);
tupleSimilarity.set(1, product2);
tupleSimilarity.set(2, 0.0d);
Object dataBagObj1 = inputTuple.get(1);
Preconditions.checkArgument(dataBagObj1 instanceof DataBag);
DataBag bag1 = (DataBag) dataBagObj1;
Object dataBagObj2 = inputTuple.get(3);
Preconditions.checkArgument(dataBagObj2 instanceof DataBag);
DataBag bag2 = (DataBag) dataBagObj2;
for (Tuple t : bag1) {
userWeightMap.put(t.get(0), (Number) t.get(2));
}
if (userWeightMap.keySet().size() < threshold) {
userWeightMap.clear();
continue;
}
for (Tuple t : bag2) {
userWeightMap.put(t.get(0), (Number) t.get(2));
}
List<Number> weightsList1 = new ArrayList<Number>();
List<Number> weightsList2 = new ArrayList<Number>();
for (Entry<Object, Collection<Number>> entry : userWeightMap.asMap().entrySet()) {
Collection<Number> weightsByUser = entry.getValue();
if (weightsByUser.size() < 2) {
continue;
}
Iterator<Number> valueItr = weightsByUser.iterator();
weightsList1.add(valueItr.next());
weightsList2.add(valueItr.next());
}
if (weightsList1.size() >= threshold) {
tupleSimilarity.set(2, similarity.getSimilarity(weightsList1, weightsList2));
prodSimilarities.add(tupleSimilarity);
}
userWeightMap.clear();
}
return prodSimilarities;
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new ExecException(e.getMessage(), e);
}
}
@Override
public DataBag exec(Tuple input) throws IOException {
if (input == null || input.size() == 0 || input.isNull(0) == true) {
throw new ExecException("Input is not provided.");
}
return getSimilarityBag(input);
}
@Override
public Schema outputSchema(Schema input) {
Schema fieldSchema = new Schema();
fieldSchema.add(new Schema.FieldSchema("item1", DataType.CHARARRAY));
fieldSchema.add(new Schema.FieldSchema("item2", DataType.CHARARRAY));
fieldSchema.add(new Schema.FieldSchema("similarity", DataType.DOUBLE));
try {
return new Schema(new Schema.FieldSchema("tuple", fieldSchema, DataType.TUPLE));
} catch (FrontendException e) {
throw new RuntimeException(e);
}
}
DataBag intermediateBag = BagFactory.getInstance().newSortedBag(bagComparator2);
@Override
public void accumulate(Tuple input) throws IOException {
try {
Object object = input.get(0);
Preconditions.checkArgument(object instanceof DataBag);
DataBag inputBag = (DataBag) object;
for (Tuple inputTuple : inputBag) {
Preconditions.checkArgument(inputTuple.size() == 4);
Object product1 = inputTuple.get(0);
Object product2 = inputTuple.get(2);
if (product1.equals(product2)) {
continue;
}
intermediateBag.add(inputTuple);
}
} catch(Exception e) {
logger.error(e.getMessage(), e);
throw new ExecException(e.getMessage(), e);
}
}
@Override
public void cleanup() {
intermediateBag.clear();
}
@Override
public DataBag getValue() {
try {
Tuple tupleSimilarity = null;
Multimap<Object, Number> userWeightMap = ArrayListMultimap.create();
for (Tuple inputTuple : intermediateBag) {
Object product1 = inputTuple.get(0);
Object product2 = inputTuple.get(2);
tupleSimilarity = TupleFactory.getInstance().newTuple(3);
tupleSimilarity.set(0, product1);
tupleSimilarity.set(1, product2);
tupleSimilarity.set(2, 0.0d);
Object dataBagObj1 = inputTuple.get(1);
Preconditions.checkArgument(dataBagObj1 instanceof DataBag);
DataBag bag1 = (DataBag) dataBagObj1;
Object dataBagObj2 = inputTuple.get(3);
Preconditions.checkArgument(dataBagObj2 instanceof DataBag);
DataBag bag2 = (DataBag) dataBagObj2;
for (Tuple t : bag1) {
userWeightMap.put(t.get(0), (Number) t.get(2));
}
if (userWeightMap.keySet().size() < threshold) {
userWeightMap.clear();
continue;
}
for (Tuple t : bag2) {
userWeightMap.put(t.get(0), (Number) t.get(2));
}
List<Number> weightsList1 = new ArrayList<Number>();
List<Number> weightsList2 = new ArrayList<Number>();
for (Entry<Object, Collection<Number>> entry : userWeightMap.asMap().entrySet()) {
Collection<Number> weightsByUser = entry.getValue();
if (weightsByUser.size() < 2) {
continue;
}
Iterator<Number> valueItr = weightsByUser.iterator();
weightsList1.add(valueItr.next());
weightsList2.add(valueItr.next());
}
if (weightsList1.size() >= threshold) {
tupleSimilarity.set(2, similarity.getSimilarity(weightsList1, weightsList2));
prodSimilarities.add(tupleSimilarity);
}
userWeightMap.clear();
}
return prodSimilarities;
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new RuntimeException(e.getMessage(), e);
}
}
}
|
package com.collective.celos;
import junit.framework.Assert;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import java.io.IOException;
import java.net.ServerSocket;
public class JettyServerTest {
@Test
public void testServerStarts() throws Exception {
JettyServer jettyServer = new JettyServer();
int port = jettyServer.start();
HttpClient httpClient = new DefaultHttpClient();
HttpGet workflowListGet = new HttpGet("http://localhost:" + port);
HttpResponse response = httpClient.execute(workflowListGet);
EntityUtils.consume(response.getEntity());
Assert.assertEquals(response.getStatusLine().getStatusCode(), 403);
}
@Test(expected = HttpHostConnectException.class)
public void testServerStops() throws Exception {
JettyServer jettyServer = new JettyServer();
int port = jettyServer.start();
HttpClient httpClient = new DefaultHttpClient();
HttpGet workflowListGet = new HttpGet("http://localhost:" + port);
HttpResponse response = httpClient.execute(workflowListGet);
Assert.assertEquals(response.getStatusLine().getStatusCode(), 403);
EntityUtils.consume(response.getEntity());
jettyServer.stop();
httpClient.execute(workflowListGet);
}
@Test
public void testServerStartsSpecifyPort() throws Exception {
int port = getFreePort();
JettyServer jettyServer = new JettyServer();
jettyServer.start(port);
HttpClient httpClient = new DefaultHttpClient();
HttpGet workflowListGet = new HttpGet("http://localhost:" + port);
HttpResponse response = httpClient.execute(workflowListGet);
EntityUtils.consume(response.getEntity());
Assert.assertEquals(response.getStatusLine().getStatusCode(), 403);
}
@Test(expected = HttpHostConnectException.class)
public void testServerStopsSpecifyPort() throws Exception {
int port = getFreePort();
JettyServer jettyServer = new JettyServer();
jettyServer.start(port);
HttpClient httpClient = new DefaultHttpClient();
HttpGet workflowListGet = new HttpGet("http://localhost:" + port);
HttpResponse response = httpClient.execute(workflowListGet);
Assert.assertEquals(response.getStatusLine().getStatusCode(), 403);
EntityUtils.consume(response.getEntity());
jettyServer.stop();
httpClient.execute(workflowListGet);
}
private int getFreePort() throws IOException {
ServerSocket s = new ServerSocket(0);
int port = s.getLocalPort();
s.close();
return port;
}
}
|
package com.github.ahitrin.jqexample;
import java.lang.Math;
import java.util.ArrayList;
import java.util.List;
/**
* @author Andrey Hitrin
* @since 25.09.14
*/
public class PrimeFactors
{
public static List<Integer> extract(Integer number)
{
List<Integer> factors = new ArrayList<>();
for (int divisor = 2; divisor < Math.sqrt(number) - 2; divisor++) {
while ((number > divisor) && (number % divisor == 0)) {
factors.add(divisor);
number = number / divisor;
}
}
factors.add(number);
return factors;
}
}
|
package com.github.apixandru.games.rummikub;
import java.util.Collection;
import java.util.HashSet;
/**
* @author Alexandru-Constantin Bledea
* @since Sep 16, 2015
*/
final class Cards {
private Cards() {
}
/**
* @return
*/
static boolean isDifferentColors(final Collection<Card> cards) {
final Collection<Color> colors = new HashSet<>();
for (final Card card : cards) {
final Color cardColor = card.getColor();
if (null == cardColor) {
continue;
}
if (colors.contains(cardColor)) {
return false;
}
colors.add(cardColor);
}
return true;
}
/**
* @param cards
* @return
*/
static boolean isSameRanks(final Collection<Card> cards) {
final Rank rank = getFirstRank(cards);
for (final Card card : cards) {
final Rank cardRank = card.getRank();
if (null != cardRank && rank != cardRank) {
return false;
}
}
return true;
}
/**
* @param cards
* @return
*/
public static boolean isAscendingRanks(final Collection<Card> cards) {
Rank expected = null;
boolean first = true;
for (final Card card : cards) {
final Rank rank = card.getRank();
if (first) {
expected = rank;
first = false;
}
// if rank is null then joker, matches
if (rank != null && expected != rank) {
return false;
}
expected = Rank.next(expected);
}
return true;
}
/**
* @param cards
* @return
*/
private static Rank getFirstRank(final Collection<Card> cards) {
for (final Card card : cards) {
final Rank rank = card.getRank();
if (null != rank) {
return rank;
}
}
return null;
}
}
|
package seedu.task.ui;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import seedu.task.model.task.ReadOnlyTask;
//@@author A0146757R
public class TaskCard extends UiPart<Region> {
private static final String FXML = "TaskListCard.fxml";
@FXML
private HBox cardPane;
@FXML
private Label taskName;
@FXML
private Label id;
@FXML
private Label taskDate;
@FXML
private Label taskTime;
@FXML
private Label taskDescription;
@FXML
private Label taskStatus;
@FXML
private FlowPane tags;
public TaskCard(ReadOnlyTask task, int displayedIndex) {
super(FXML);
id.setText(displayedIndex + ". ");
if (task.getTaskName() != null) {
taskName.setText(task.getTaskName().toString());
}
if (task.getTaskDate() != null) {
taskDate.setText("Date : " + task.getTaskDate().toString());
} else
taskDate.setText("Date: -");
if (task.getTaskStartTime() != null && task.getTaskEndTime() != null) {
taskTime.setText("Time: " + task.getTaskStartTime().toString() + "-" + task.getTaskEndTime());
} else if (task.getTaskStartTime() != null) {
taskTime.setText("Start Time: "+task.getTaskStartTime().toString());
} else if (task.getTaskEndTime() != null) {
taskTime.setText("End Time: "+task.getTaskEndTime().toString());
} else
taskTime.setText("Time: -");
if (task.getTaskDescription() != null) {
taskDescription.setText("Description: " + task.getTaskDescription().toString());
} else
taskDescription.setText("Description: -");
taskStatus.setText("Task Status: " + task.getTaskStatus().toString() );
initTags(task);
}
//@@author
private void initTags(ReadOnlyTask task) {
task.getTags().forEach(tag -> tags.getChildren().add(new Label(tag.tagName)));
}
}
|
package water.api;
import hex.Summary2;
import water.*;
import water.util.Log;
import water.util.RString;
import water.fvec.*;
import water.util.Utils;
import java.util.Iterator;
public class SummaryPage2 extends Request2 {
static final int API_WEAVER=1; // This file has auto-gen'd doc & json fields
static public DocGen.FieldDoc[] DOC_FIELDS; // Initialized from Auto-Gen code.
// This Request supports the HTML 'GET' command, and this is the help text
// for GET.
static final String DOC_GET = "Returns a summary of a fluid-vec frame";
@API(help="An existing H2O Frame key.", required=true, filter=Default.class)
Frame source;
class colsFilter1 extends MultiVecSelect { public colsFilter1() { super("source");} }
@API(help = "Select columns", filter=colsFilter1.class)
int[] cols;
@API(help = "Maximum columns to show summaries of", filter = Default.class, lmin = 1, lmax = 1000)
int max_ncols = 1000;
@API(help = "Column summaries.")
Summary2[] summaries;
public static String link(Key k, String content) {
RString rs = new RString("<a href='SummaryPage2.query?source=%$key'>"+content+"</a>");
rs.replace("key", k.toString());
return rs.toString();
}
@Override protected Response serve() {
if( source == null ) return RequestServer._http404.serve();
// select all columns by default
if( cols == null ) {
cols = new int[Math.min(source.vecs().length,max_ncols)];
for(int i = 0; i < cols.length; i++) cols[i] = i;
}
Vec[] vecs = new Vec[cols.length];
String[] names = new String[cols.length];
for (int i = 0; i < cols.length; i++) {
vecs[i] = source.vecs()[cols[i]];
names[i] = source._names[cols[i]];
}
Frame fr = new Frame(names, vecs);
summaries = new SummaryTask2().doAll(fr)._summaries;
if (summaries != null)
for( Summary2 s2 : summaries ) s2.finishUp();
return new Response(Response.Status.done, this, -1, -1, null);
}
private static class SummaryTask2 extends MRTask2<SummaryTask2> {
Summary2 _summaries[];
@Override public void map(Chunk[] cs) {
_summaries = new Summary2[cs.length];
for (int i = 0; i < cs.length; i++) {
(_summaries[i]=new Summary2(_fr.vecs()[i], _fr.names()[i])).add(cs[i]);
}
}
@Override public void reduce(SummaryTask2 other) {
for (int i = 0; i < _summaries.length; i++)
_summaries[i].add(other._summaries[i]);
}
}
@Override public boolean toHTML( StringBuilder sb ) {
sb.append("<div class=container-fluid'>");
sb.append("<div class='row-fluid'>");
sb.append("<div class='span2' style='overflow-y:scroll;height:100%;left:0;position:fixed;text-align:right;overflow-x:scroll;'><h5>Columns</h5>");
if (summaries != null && summaries.length > max_ncols)
sb.append("<div class='alert'>Too many columns were selected. "+max_ncols+" of them are shown!</div>");
StringBuilder innerPageBdr = null;
if (summaries != null) {
innerPageBdr = new StringBuilder("<div class='span10' style='float:right;height:90%;overflow-y:scroll'>");
for( int i = 0; i < Math.min(summaries.length,max_ncols); i++) {
String cname = source._names[cols[i]];
Summary2 s2 = summaries[i];
s2.toHTML(source.vecs()[cols[i]],cname,innerPageBdr);
sb.append("<div><a href='#col_" + cname + "'>" + cname + "</a></div>");
}
innerPageBdr.append("</div>");
}
sb.append("</div>");
sb.append("</div>");
if (summaries != null) sb.append(innerPageBdr);
sb.append("</div>");
return true;
}
}
|
package com.github.dozedoff.commonj.file;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class FileUtil {
private static final String[] ILLEGAL_FILENAME_CHARS = {"/", "\\", ":", "?", "\"", "<", ">", "|"};
public static File WorkingDir(){
return new File( System.getProperty("user.dir") );
}
public static List<String> pathTokenList(String path){
LinkedList<String> resultList = new LinkedList<String>();
Scanner scanner = new Scanner(path);
scanner.useDelimiter("\\\\");
//to handle network paths
if(path.startsWith("\\\\")){
int endPos = path.indexOf("\\", 2);
resultList.add(path.substring(0, endPos));
scanner.next();
scanner.next();
}
while(scanner.hasNext()){
resultList.add(scanner.next());
}
//check if the last entry (filename) has an extension, if so, split them
if(resultList.peekLast() != null && resultList.peekLast().contains(".")){
String lastEntry = resultList.pollLast();
int dotPosition = lastEntry.lastIndexOf(".");
String filename = lastEntry.substring(0, dotPosition);
String extension = lastEntry.substring(dotPosition);
resultList.add(filename);
resultList.add(extension);
}
scanner.close();
return resultList;
}
/**
* Move a directory, sub-directories and files to the new location.
* src\a , dst will result in dst\a
*
* @param source the path of the source directory
* @param destination the path of the destination directory
* @throws IOException
*/
public static void moveDirectory(Path source, Path destination) throws IOException{
Files.walkFileTree(source, new DirectoryMover(source, destination));
}
public static void moveFileWithStructure(Path source, Path dstDirectory) throws IOException{
Path relativeSource = source.getRoot().relativize(source);
Path destinationPath = dstDirectory.resolve(relativeSource);
Files.createDirectories(destinationPath.getParent());
Files.move(source, destinationPath);
}
static public String convertDirPathToString(Path directory){
if(directory == null){
return null;
}else if((directory.getRoot() != null) && (directory.getRoot().equals(directory))){
return directory.toString().toLowerCase();
}else{
return directory.toString().toLowerCase()+"\\";
}
}
/**
* Remove the root component from the path, returning a relative path.
* If the path is already relative, it will not be changed.
* C:\temp\ becomes \temp\
* @param path path to remove root from
* @return a relative path
*/
static public Path removeDriveLetter(Path path){
if(path == null){
return null;
}
if(path.isAbsolute()){
return Paths.get(path.getRoot().relativize(path).toString());
}else{
return path;
}
}
static public String removeDriveLetter(String path) {
if (path == null) {
return null;
}
Path relPath = removeDriveLetter(Paths.get(path));
String filename = relPath.getFileName().toString();
if (filename.contains(".")) {
return relPath.toString();
} else {
return relPath.toString() + "\\";
}
}
static public boolean hasValidWindowsFilename(File fullpath) {
String filename = fullpath.getName();
if (filename.isEmpty()) {
return false;
}
for (String illegalChar : ILLEGAL_FILENAME_CHARS) {
if (filename.contains(illegalChar)) {
return false;
}
}
return true;
}
static class DirectoryMover extends SimpleFileVisitor<Path>{
Path currMoveDir, dstDir, srcDir;
public DirectoryMover(Path srcDir, Path dstDir) {
this.dstDir = dstDir;
this.srcDir = srcDir.getParent();
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
File f = new File(dstDir.toFile(),srcDir.relativize(dir).toString());
f.mkdirs(); // create new directory with identical name in the destination directory
currMoveDir = f.toPath();
return super.preVisitDirectory(dir, attrs);
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.move(file, currMoveDir.resolve(file.getFileName())); // move files
return super.visitFile(file, attrs);
}
@Override
public FileVisitResult postVisitDirectory(Path arg0, IOException arg1) throws IOException {
Files.delete(arg0); // delete the source directory when done
return super.postVisitDirectory(arg0, arg1);
}
}
}
|
package com.github.martincooper.datatable;
import io.vavr.control.Try;
public class DataRow {
private final DataTable table;
private final Integer rowIdx;
/**
* Private DataRow constructor.
* Use 'build' to create instance.
*
* @param table The DataTable the DataRow is pointing to.
* @param rowIdx The row index.
*/
private DataRow(DataTable table, Integer rowIdx) {
this.table = table;
this.rowIdx = rowIdx;
}
/**
* Returns the underlying Data Table for this row.
*
* @return Returns the Data Table for this row .
*/
public DataTable table() {
return this.table;
}
/**
* Gets the row index.
*
* @return Returns the row index.
*/
public Integer rowIdx() {
return this.rowIdx;
}
/**
* Returns the data as an array for this row.
*
* @return Returns the data for this row in an array.
*/
public Object[] data() {
return this.table.columns()
.map(col -> col.data().get(this.rowIdx))
.toJavaArray();
}
/**
* Returns the data at the specified column index, returning as an object.
*
* @param colIndex The column index to return the value of.
* @return Returns the value of the row at the specified column.
*/
public Try<Object> get(Integer colIndex) {
return columnToValue(this.table.columns().tryGet(colIndex));
}
/**
* Returns the data in the specified column name, returning as an object.
*
* @param colName The column to return the value of.
* @return Returns the value of the row at the specified column.
*/
public Try<Object> get(String colName) {
return columnToValue(this.table.columns().tryGet(colName));
}
/**
* Returns the value of a particular row column as a specific type.
* This method makes no bounds checks or type checks, so any failures
* will result in an exception being thrown.
*
* @param type The data type.
* @param idx The index of the column.
* @param <T> The value type.
* @return Returns the value at the specified index.
*/
public <T> T getAs(Class<T> type, Integer idx) {
Try<DataColumn<T>> col = this.table.columns().get(idx).asType(type);
return col.get().valueAt(this.rowIdx);
}
/**
* Returns the value of a particular row column as a specific type.
* This method makes no bounds checks or type checks, so any failures
* will result in an exception being thrown.
*
* @param type The data type.
* @param colName The name of the column.
* @param <T> The value type.
* @return Returns the value at the specified index.
*/
public <T> T getAs(Class<T> type, String colName) {
Try<DataColumn<T>> col = this.table.columns().get(colName).asType(type);
return col.get().valueAt(this.rowIdx);
}
/**
* Returns the value of a particular row column as a specific type.
* This method performs bounds checks and type checks. Any errors
* will return a Try.failure.
*
* @param type The data type.
* @param idx The index of the column.
* @param <T> The value type.
* @return Returns the value at the specified index.
*/
public <T> Try<T> tryGetAs(Class<T> type, Integer idx) {
// Get the column as it's typed version.
Try<DataColumn<T>> col = this.table.columns()
.tryGet(idx)
.flatMap(c -> c.asType(type));
return col.isFailure()
? Try.failure(col.getCause())
: Try.success(col.get().valueAt(this.rowIdx));
}
/**
* Returns the value of a particular row column as a specific type.
* This method performs bounds checks and type checks. Any errors
* will return a Try.failure.
*
* @param type The data type.
* @param colName The name of the column.
* @param <T> The value type.
* @return Returns the value at the specified index.
*/
public <T> Try<T> tryGetAs(Class<T> type, String colName) {
// Get the column as it's typed version.
Try<DataColumn<T>> col = this.table.columns()
.tryGet(colName)
.flatMap(c -> c.asType(type));
return col.isFailure()
? Try.failure(col.getCause())
: Try.success(col.get().valueAt(this.rowIdx));
}
private Try<Object> columnToValue(Try<IDataColumn> column) {
return column.isSuccess()
? Try.success(column.get().valueAt(this.rowIdx))
: Try.failure(column.getCause());
}
/**
* Builds an instance of a DataRow.
* Row Index is validated before creation, returning a Failure on error.
*
* @param table The DataTable the DataRow is pointing to.
* @param rowIdx The row index.
* @return Returns a DataRow wrapped in a Try.
*/
public static Try<DataRow> build(DataTable table, Integer rowIdx) {
Guard.notNull(table, "table");
// Check row index bounds, and return new DataRow if success.
return VectorExtensions.outOfBounds(table.rowCount(), rowIdx)
? DataTableException.tryError("Invalid row index for DataRow.")
: Try.success(new DataRow(table, rowIdx));
}
}
|
package com.github.pagehelper.util;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageException;
import org.apache.ibatis.reflection.MetaObject;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
*
*
* @author liuzh
*/
public abstract class PageObjectUtil {
//request
protected static Boolean hasRequest;
protected static Class<?> requestClass;
protected static Method getParameterMap;
protected static Map<String, String> PARAMS = new HashMap<String, String>(6, 1);
static {
try {
requestClass = Class.forName("javax.servlet.ServletRequest");
getParameterMap = requestClass.getMethod("getParameterMap", new Class[]{});
hasRequest = true;
} catch (Throwable e) {
hasRequest = false;
}
PARAMS.put("pageNum", "pageNum");
PARAMS.put("pageSize", "pageSize");
PARAMS.put("count", "countSql");
PARAMS.put("orderBy", "orderBy");
PARAMS.put("reasonable", "reasonable");
PARAMS.put("pageSizeZero", "pageSizeZero");
}
/**
*
*
* @param params
* @return
*/
public static <T> Page<T> getPageFromObject(Object params, boolean required) {
int pageNum;
int pageSize;
MetaObject paramsObject = null;
if (params == null) {
throw new PageException("!");
}
if (hasRequest && requestClass.isAssignableFrom(params.getClass())) {
try {
paramsObject = MetaObjectUtil.forObject(getParameterMap.invoke(params, new Object[]{}));
} catch (Exception e) {
}
} else {
paramsObject = MetaObjectUtil.forObject(params);
}
if (paramsObject == null) {
throw new PageException("!");
}
Object orderBy = getParamValue(paramsObject, "orderBy", false);
boolean hasOrderBy = false;
if (orderBy != null && orderBy.toString().length() > 0) {
hasOrderBy = true;
}
try {
Object _pageNum = getParamValue(paramsObject, "pageNum", required);
Object _pageSize = getParamValue(paramsObject, "pageSize", required);
if (_pageNum == null || _pageSize == null) {
if(hasOrderBy){
Page page = new Page();
page.setOrderBy(orderBy.toString());
page.setOrderByOnly(true);
return page;
}
return null;
}
pageNum = Integer.parseInt(String.valueOf(_pageNum));
pageSize = Integer.parseInt(String.valueOf(_pageSize));
} catch (NumberFormatException e) {
throw new PageException("!");
}
Page page = new Page(pageNum, pageSize);
//count
Object _count = getParamValue(paramsObject, "count", false);
if (_count != null) {
page.setCount(Boolean.valueOf(String.valueOf(_count)));
}
if (hasOrderBy) {
page.setOrderBy(orderBy.toString());
}
Object reasonable = getParamValue(paramsObject, "reasonable", false);
if (reasonable != null) {
page.setReasonable(Boolean.valueOf(String.valueOf(reasonable)));
}
Object pageSizeZero = getParamValue(paramsObject, "pageSizeZero", false);
if (pageSizeZero != null) {
page.setPageSizeZero(Boolean.valueOf(String.valueOf(pageSizeZero)));
}
return page;
}
/**
*
*
* @param paramsObject
* @param paramName
* @param required
* @return
*/
protected static Object getParamValue(MetaObject paramsObject, String paramName, boolean required) {
Object value = null;
if (paramsObject.hasGetter(PARAMS.get(paramName))) {
value = paramsObject.getValue(PARAMS.get(paramName));
}
if (value != null && value.getClass().isArray()) {
Object[] values = (Object[]) value;
if (values.length == 0) {
value = null;
} else {
value = values[0];
}
}
if (required && value == null) {
throw new PageException(":" + PARAMS.get(paramName));
}
return value;
}
public static void setParams(String params) {
if (StringUtil.isNotEmpty(params)) {
String[] ps = params.split("[;|,|&]");
for (String s : ps) {
String[] ss = s.split("[=|:]");
if (ss.length == 2) {
PARAMS.put(ss[0], ss[1]);
}
}
}
}
}
|
package mondrian.rolap.sql;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import mondrian.olap.MondrianDef;
import mondrian.olap.MondrianProperties;
import mondrian.olap.Util;
import org.eigenbase.util.property.Property;
import org.eigenbase.util.property.Trigger;
/**
* <code>SqlQuery</code> allows us to build a <code>select</code>
* statement and generate it in database-specific SQL syntax.
*
* <p> Notable differences in database syntax are:<dl>
*
* <dt> Identifier quoting </dt>
* <dd> Oracle (and all JDBC-compliant drivers) uses double-quotes,
* for example <code>select * from "emp"</code>. Access prefers brackets,
* for example <code>select * from [emp]</code>. mySQL allows single- and
* double-quotes for string literals, and therefore does not allow
* identifiers to be quoted, for example <code>select 'foo', "bar" from
* emp</code>. </dd>
*
* <dt> AS in from clause </dt>
* <dd> Oracle doesn't like AS in the from * clause, for example
* <code>select from emp as e</code> vs. <code>select * from emp
* e</code>. </dd>
*
* <dt> Column aliases </dt>
* <dd> Some databases require that every column in the select list
* has a valid alias. If the expression is an expression containing
* non-alphanumeric characters, an explicit alias is needed. For example,
* Oracle will barfs at <code>select empno + 1 from emp</code>. </dd>
*
* <dt> Parentheses around table names </dt>
* <dd> Oracle doesn't like <code>select * from (emp)</code> </dd>
*
* <dt> Queries in FROM clause </dt>
* <dd> PostgreSQL and hsqldb don't allow, for example, <code>select * from
* (select * from emp) as e</code>.</dd>
*
* <dt> Uniqueness of index names </dt>
* <dd> In PostgreSQL and Oracle, index names must be unique within the
* database; in Access and hsqldb, they must merely be unique within their
* table </dd>
*
* <dt> Datatypes </dt>
* <dd> In Oracle, BIT is CHAR(1), TIMESTAMP is DATE.
* In PostgreSQL, DOUBLE is DOUBLE PRECISION, BIT is BOOL. </dd>
* </ul>
*
* <p>
* NOTE: Instances of this class are NOT thread safe so the user must make
* sure this is accessed by only one thread at a time.
*
* @author jhyde
* @version $Id$
*/
public class SqlQuery
{
/** This static variable controls the formatting of the sql string. */
private static boolean generateFormattedSql =
MondrianProperties.instance().GenerateFormattedSql.get();
static {
// Trigger is used to lookup and change the value of the
// variable that controls formatting.
// Using a trigger means we don't have to look up the property eveytime.
MondrianProperties.instance().GenerateFormattedSql.addTrigger(
new Trigger() {
public boolean isPersistent() {
return true;
}
public int phase() {
return Trigger.PRIMARY_PHASE;
}
public void execute(Property property, String value) {
generateFormattedSql = property.booleanValue();
}
}
);
}
private boolean distinct;
private final ClauseList select;
private final ClauseList from;
private final ClauseList where;
private final ClauseList groupBy;
private final ClauseList having;
private final ClauseList orderBy;
/**
* This list is used to keep track of what aliases have been used in the
* FROM clause. One might think that a java.util.Set would be a more
* appropriate Collection type, but if you only have a couple of "from
* aliases", then iterating over a list is faster than doing a hash lookup
* (as is used in java.util.HashSet).
*/
private final List<String> fromAliases;
/** The SQL dialect this query is to be generated in. */
private final Dialect dialect;
/** Scratch buffer. Clear it before use. */
private final StringBuilder buf;
/**
* Base constructor used by all other constructors to create an empty
* instance.
*/
public SqlQuery(Dialect dialect) {
// both select and from allow duplications
this.select = new ClauseList(true);
this.from = new ClauseList(true);
this.where = new ClauseList(false);
this.groupBy = new ClauseList(false);
this.having = new ClauseList(false);
this.orderBy = new ClauseList(false);
this.fromAliases = new ArrayList<String>();
this.buf = new StringBuilder(128);
this.dialect = dialect;
}
/**
* Creates a <code>SqlQuery</code>
*
* @param databaseMetaData used to determine which dialect of
* SQL to generate. Must not be held beyond the constructor.
*/
public SqlQuery(final DatabaseMetaData databaseMetaData) {
this(Dialect.create(databaseMetaData));
}
/**
* Creates an empty <code>SqlQuery</code> with the same environment as this
* one. (As per the Gang of Four 'prototype' pattern.)
*/
public SqlQuery cloneEmpty()
{
return new SqlQuery(dialect);
}
public void setDistinct(final boolean distinct) {
this.distinct = distinct;
}
/**
* The size required to add quotes around a string - this ought to be
* large enough to prevent a reallocation.
*/
private static final int SINGLE_QUOTE_SIZE = 10;
/**
* Two strings are quoted and the character '.' is placed between them.
*/
private static final int DOUBLE_QUOTE_SIZE = 2 * SINGLE_QUOTE_SIZE + 1;
/**
* Adds a subquery to the FROM clause of this Query with a given alias.
* If the query already exists it either, depending on
* <code>failIfExists</code>, throws an exception or does not add the query
* and returns false.
*
* @param query
* @param alias (if not null, must not be zero length).
* @param failIfExists if true, throws exception if alias already exists
* @return true if query *was* added
*
* @pre alias != null
*/
public boolean addFromQuery(final String query,
final String alias,
final boolean failIfExists) {
Util.assertPrecondition(alias != null);
if (fromAliases.contains(alias)) {
if (failIfExists) {
throw Util.newInternal(
"query already contains alias '" + alias + "'");
} else {
return false;
}
}
buf.setLength(0);
buf.append('(');
buf.append(query);
buf.append(')');
if (alias != null) {
Util.assertTrue(alias.length() > 0);
if (dialect.allowsAs()) {
buf.append(" as ");
} else {
buf.append(' ');
}
dialect.quoteIdentifier(alias, buf);
fromAliases.add(alias);
}
from.add(buf.toString());
return true;
}
/**
* Adds <code>[schema.]table AS alias</code> to the FROM clause.
*
* @param schema schema name; may be null
* @param table table name
* @param alias table alias, may not be null
* (if not null, must not be zero length).
* @param failIfExists
*
* @pre alias != null
* @return true if table *was* added
*/
private boolean addFromTable(final String schema,
final String table,
final String alias,
final String filter,
final boolean failIfExists) {
if (fromAliases.contains(alias)) {
if (failIfExists) {
throw Util.newInternal(
"query already contains alias '" + alias + "'");
} else {
return false;
}
}
buf.setLength(0);
dialect.quoteIdentifier(schema, table, buf);
if (alias != null) {
Util.assertTrue(alias.length() > 0);
if (dialect.allowsAs()) {
buf.append(" as ");
} else {
buf.append(' ');
}
dialect.quoteIdentifier(alias, buf);
fromAliases.add(alias);
}
from.add(buf.toString());
if (filter != null) {
// append filter condition to where clause
addWhere("(", filter, ")");
}
return true;
}
public void addFrom(final SqlQuery sqlQuery,
final String alias,
final boolean failIfExists)
{
addFromQuery(sqlQuery.toString(), alias, failIfExists);
}
/**
* Adds a relation to a query, adding appropriate join conditions, unless
* it is already present.
*
* <p>Returns whether the relation was added to the query.
*
* @param relation Relation to add
* @param alias Alias of relation. If null, uses relation's alias.
* @param failIfExists Whether to fail if relation is already present
* @return true, if relation *was* added to query
*/
public boolean addFrom(final MondrianDef.Relation relation,
final String alias,
final boolean failIfExists)
{
if (relation instanceof MondrianDef.View) {
final MondrianDef.View view = (MondrianDef.View) relation;
final String viewAlias = (alias == null)
? view.getAlias()
: alias;
final String sqlString = dialect.chooseQuery(view.selects);
return addFromQuery(sqlString, viewAlias, false);
} else if (relation instanceof MondrianDef.Table) {
final MondrianDef.Table table = (MondrianDef.Table) relation;
final String tableAlias = (alias == null)
? table.getAlias()
: alias;
return addFromTable(table.schema, table.name, tableAlias,
table.getFilter(), failIfExists);
} else if (relation instanceof MondrianDef.Join) {
final MondrianDef.Join join = (MondrianDef.Join) relation;
final String leftAlias = join.getLeftAlias();
final String rightAlias = join.getRightAlias();
boolean addLeft = addFrom(join.left, leftAlias, failIfExists);
boolean addRight = addFrom(join.right, rightAlias, failIfExists);
boolean added = addLeft || addRight;
if (added) {
buf.setLength(0);
dialect.quoteIdentifier(leftAlias, join.leftKey, buf);
buf.append(" = ");
dialect.quoteIdentifier(rightAlias, join.rightKey, buf);
addWhere(buf.toString());
}
return added;
} else {
throw Util.newInternal("bad relation type " + relation);
}
}
/**
* Adds an expression to the select clause, automatically creating a
* column alias.
*/
public void addSelect(final String expression) {
// Some DB2 versions (AS/400) throw an error if a column alias is
// *not* used in a subsequent order by (Group by).
// Derby fails on 'SELECT... HAVING' if column has alias.
if (dialect.isAS400() || dialect.isDerby()) {
addSelect(expression, null);
} else {
addSelect(expression, nextColumnAlias());
}
}
public String nextColumnAlias() {
return "c" + select.size();
}
/** Adds an expression to the select clause, with a specified column
* alias. */
public void addSelect(final String expression, final String alias) {
buf.setLength(0);
buf.append(expression);
if (alias != null) {
buf.append(" as ");
dialect.quoteIdentifier(alias, buf);
}
select.add(buf.toString());
}
public void addWhere(
final String exprLeft,
final String exprMid,
final String exprRight)
{
int len = exprLeft.length() + exprMid.length() + exprRight.length();
StringBuilder buf = new StringBuilder(len);
buf.append(exprLeft);
buf.append(exprMid);
buf.append(exprRight);
addWhere(buf.toString());
}
public void addWhere(final String expression)
{
where.add(expression);
}
public void addGroupBy(final String expression)
{
groupBy.add(expression);
}
public void addHaving(final String expression)
{
having.add(expression);
}
/**
* Adds an item to the ORDER BY clause.
*
* @param expr the expr to order by
* @param ascending sort direction
* @param prepend whether to prepend to the current list of items
* @param nullable whether the expression might be null
*/
public void addOrderBy(
String expr,
boolean ascending,
boolean prepend,
boolean nullable)
{
if (nullable && !dialect.isNullsCollateLast()) {
expr = dialect.forceNullsCollateLast(expr);
}
if (ascending) {
expr = expr + " ASC";
} else {
expr = expr + " DESC";
}
if (prepend) {
orderBy.add(0, expr);
} else {
orderBy.add(expr);
}
}
public String toString()
{
if (generateFormattedSql) {
StringWriter sw = new StringWriter(256);
PrintWriter pw = new PrintWriter(sw);
print(pw, "");
pw.flush();
return sw.toString();
} else {
buf.setLength(0);
select.toBuffer(buf,
distinct ? "select distinct " : "select ", ", ");
from.toBuffer(buf, " from ", ", ");
where.toBuffer(buf, " where ", " and ");
groupBy.toBuffer(buf, " group by ", ", ");
having.toBuffer(buf, " having ", " and ");
orderBy.toBuffer(buf, " order by ", ", ");
return buf.toString();
}
}
public void print(PrintWriter pw, String prefix) {
// This <CR> is added to the front because the part of the code
// that prints out the sql (if the trace level is non-zero),
// RolapUtil, does not print the sql at the start of a new line.
pw.println();
select.print(pw, prefix,
distinct ? "select distinct " : "select ", ", ");
from.print(pw, prefix, "from ", ", ");
where.print(pw, prefix, "where ", " and ");
groupBy.print(pw, prefix, "group by ", ", ");
having.print(pw, prefix, "having ", " and ");
orderBy.print(pw, prefix, "order by ", ", ");
}
public Dialect getDialect() {
return dialect;
}
private class ClauseList extends ArrayList<String> {
private final boolean allowDups;
ClauseList(final boolean allowDups) {
this.allowDups = allowDups;
}
/**
* Parameter element is added if either duplicates are allowed or if
* it has not already been added.
*
* @param element
*/
public boolean add(final String element) {
if (allowDups || !contains(element)) {
return super.add(element);
}
return false;
}
void toBuffer(final StringBuilder buf,
final String first,
final String sep) {
Iterator it = iterator();
boolean firstTime = true;
while (it.hasNext()) {
String s = (String) it.next();
if (firstTime) {
buf.append(first);
firstTime = false;
} else {
buf.append(sep);
}
buf.append(s);
}
}
void print(final PrintWriter pw,
final String prefix,
final String first,
final String sep) {
String subprefix = prefix + " ";
boolean firstTime = true;
for (Iterator it = iterator(); it.hasNext(); ) {
String s = (String) it.next();
if (firstTime) {
pw.print(prefix);
pw.print(first);
firstTime = false;
} else {
pw.print(sep);
}
pw.println();
pw.print(subprefix);
pw.print(s);
}
if (! firstTime) {
pw.println();
}
}
}
/**
* Description of a SQL dialect. It is immutable.
*/
public static class Dialect {
private final String quoteIdentifierString;
private final String productName;
private final String productVersion;
Dialect(
String quoteIdentifierString,
String productName,
String productVersion) {
this.quoteIdentifierString = quoteIdentifierString;
this.productName = productName;
this.productVersion = productVersion;
}
/**
* Creates a {@link SqlQuery.Dialect} from a {@link DatabaseMetaData}.
*/
public static Dialect create(final DatabaseMetaData databaseMetaData) {
String productName;
try {
productName = databaseMetaData.getDatabaseProductName();
} catch (SQLException e1) {
throw Util.newInternal(e1, "while detecting database product");
}
String quoteIdentifierString;
try {
quoteIdentifierString =
databaseMetaData.getIdentifierQuoteString();
} catch (SQLException e) {
throw Util.newInternal(e, "while quoting identifier");
}
if ((quoteIdentifierString == null) ||
(quoteIdentifierString.trim().length() == 0)) {
if (productName.toUpperCase().equals("MYSQL")) {
// mm.mysql.2.0.4 driver lies. We know better.
quoteIdentifierString = "`";
} else {
// Quoting not supported
quoteIdentifierString = null;
}
}
String productVersion;
try {
productVersion = databaseMetaData.getDatabaseProductVersion();
} catch (SQLException e11) {
throw Util.newInternal(e11,
"while detecting database product version");
}
return new Dialect(
quoteIdentifierString,
productName,
productVersion);
}
// -- detect various databases --
public boolean isAccess() {
return productName.equals("ACCESS");
}
public boolean isDerby() {
return productName.trim().toUpperCase().equals("APACHE DERBY");
}
public boolean isCloudscape() {
return productName.trim().toUpperCase().equals("DBMS:CLOUDSCAPE");
}
public boolean isDB2() {
// DB2 on NT returns "DB2/NT"
return productName.startsWith("DB2");
}
public boolean isAS400() {
// DB2/AS400 Product String = "DB2 UDB for AS/400"
return productName.startsWith("DB2 UDB for AS/400");
}
public boolean isOldAS400() {
if (!isAS400()) {
return false;
}
// TB "04.03.0000 V4R3m0"
// this version cannot handle subqueries and is considered "old"
// DEUKA "05.01.0000 V5R1m0" is ok
String[] version_release = productVersion.split("\\.", 3);
/*
if ( version_release.length > 2 &&
"04".compareTo(version_release[0]) > 0 ||
("04".compareTo(version_release[0]) == 0
&& "03".compareTo(version_release[1]) >= 0) )
return true;
*/
// assume, that version <= 04 is "old"
return ("04".compareTo(version_release[0]) >= 0);
}
// Note: its not clear that caching the best name would actually save
// very much time, so we do not do so.
private String getBestName() {
String best;
if (isOracle()) {
best = "oracle";
} else if (isMSSQL()) {
best = "mssql";
} else if (isMySQL()) {
best = "mysql";
} else if (isAccess()) {
best = "access";
} else if (isPostgres()) {
best = "postgres";
} else if (isSybase()) {
best = "sybase";
} else if (isCloudscape() || isDerby()) {
best = "derby";
} else if (isDB2()) {
best = "db2";
} else if (isFirebird()) {
best = "firebird";
} else if (isInterbase()) {
best = "interbase";
} else if (isIngres()) {
best = "ingres";
} else if (isLucidDB()) {
best = "luciddb";
} else if (isTeradata()) {
best = "teradata";
} else {
best = "generic";
}
return best;
}
/**
* @return SQL syntax that converts <code>expr</code>
* into upper case.
*/
public String toUpper(String expr) {
if (isDB2() || isAccess())
return "UCASE(" + expr + ")";
return "UPPER(" + expr + ")";
}
public String caseWhenElse(String cond, String thenExpr, String elseExpr) {
if (isAccess()) {
return "IIF(" + cond + "," + thenExpr + "," + elseExpr + ")";
}
return "CASE WHEN " + cond + " THEN " + thenExpr + " ELSE " + elseExpr + " END";
}
/**
* Encloses an identifier in quotation marks appropriate for the
* current SQL dialect. For example,
* <code>quoteIdentifier("emp")</code> yields a string containing
* <code>"emp"</code> in Oracle, and a string containing
* <code>[emp]</code> in Access.
*/
public String quoteIdentifier(final String val) {
int size = val.length() + SINGLE_QUOTE_SIZE;
StringBuilder buf = new StringBuilder(size);
quoteIdentifier(val, buf);
return buf.toString();
}
/**
* Appends to a buffer an identifier, quoted appropriately for this
* Dialect.
*
* @param val identifier to quote (must not be null).
* @param buf Buffer
*/
public void quoteIdentifier(final String val, final StringBuilder buf) {
String q = getQuoteIdentifierString();
if (q == null) {
// quoting is not supported
buf.append(val);
return;
}
// if the value is already quoted, do nothing
// if not, then check for a dot qualified expression
// like "owner.table".
// In that case, prefix the single parts separately.
if (val.startsWith(q) && val.endsWith(q)) {
// already quoted - nothing to do
buf.append(val);
return;
}
int k = val.indexOf('.');
if (k > 0) {
// qualified
String val1 = Util.replace(val.substring(0,k), q, q + q);
String val2 = Util.replace(val.substring(k+1), q, q + q);
buf.append(q);
buf.append(val1);
buf.append(q);
buf.append(".");
buf.append(q);
buf.append(val2);
buf.append(q);
} else {
// not Qualified
String val2 = Util.replace(val, q, q + q);
buf.append(q);
buf.append(val2);
buf.append(q);
}
}
/**
* Encloses an identifier in quotation marks appropriate for the
* current SQL dialect. For example, in Oracle, where the identifiers
* are quoted using double-quotes,
* <code>quoteIdentifier("schema","table")</code> yields a string
* containing <code>"schema"."table"</code>.
*
* @param qual Qualifier. If it is not null,
* <code>"<em>qual</em>".</code> is prepended.
* @param name Name to be quoted.
*/
public String quoteIdentifier(final String qual, final String name) {
// We know if the qalifier is null, then only the name is going
// to be quoted.
int size = name.length()
+ ((qual == null)
? SINGLE_QUOTE_SIZE
: (qual.length() + DOUBLE_QUOTE_SIZE));
StringBuilder buf = new StringBuilder(size);
quoteIdentifier(qual, name, buf);
return buf.toString();
}
/**
* Appends to a buffer an identifier and optional qualifier, quoted
* appropriately for this Dialect.
*
* @param qual optional qualifier to be quoted.
* @param name name to be quoted (must not be null).
* @param buf Buffer
*/
public void quoteIdentifier(
final String qual,
final String name,
final StringBuilder buf)
{
if (qual == null) {
quoteIdentifier(name, buf);
} else {
Util.assertTrue(
(qual.length() != 0),
"qual should probably be null, not empty");
quoteIdentifier(qual, buf);
buf.append('.');
quoteIdentifier(name, buf);
}
}
/**
* Returns the character which is used to quote identifiers, or null
* if quoting is not supported.
*/
public String getQuoteIdentifierString() {
if (isDB2()) {
return "";
} else {
return quoteIdentifierString;
}
}
/**
* Appends to a buffer a single-quoted SQL string.
*
* <p>For example, in the default dialect,
* <code>quoteStringLiteral(buf, "Can't")</code> appends
* "<code>'Can''t'</code>" to <code>buf</code>.
*/
public void quoteStringLiteral(StringBuilder buf, String s) {
Util.singleQuoteString(s, buf);
}
/**
* Appends to a buffer a numeric literal.
*
* <p>In the default dialect, numeric literals are printed as is.
*/
public void quoteNumericLiteral(StringBuilder buf, String value) {
buf.append(value);
}
/**
* Appends to a buffer a boolean literal.
*
* <p>In the default dialect, boolean literals are printed as is.
*/
public void quoteBooleanLiteral(StringBuilder buf, String value) {
buf.append(value);
}
/**
* Appends to a buffer a date literal.
*
* <p>For example, in the default dialect,
* <code>quoteStringLiteral(buf, "1969-03-17")</code>
* appends <code>DATE '1969-03-17'</code>.
*/
public void quoteDateLiteral(StringBuilder buf, String value) {
buf.append("DATE ");
Util.singleQuoteString(value, buf);
}
/**
* Appends to a buffer a time literal.
*
* <p>For example, in the default dialect,
* <code>quoteStringLiteral(buf, "12:34:56")</code>
* appends <code>TIME '12:34:56'</code>.
*/
public void quoteTimeLiteral(StringBuilder buf, String value) {
buf.append("TIME ");
Util.singleQuoteString(value, buf);
}
/**
* Appends to a buffer a timestamp literal.
*
* <p>For example, in the default dialect,
* <code>quoteStringLiteral(buf, "1969-03-17 12:34:56")</code>
* appends <code>TIMESTAMP '1969-03-17 12:34:56'</code>.
*/
public void quoteTimestampLiteral(StringBuilder buf, String value) {
buf.append("TIMESTAMP ");
Util.singleQuoteString(value, buf);
}
/**
* Returns whether the underlying database is Firebird.
*/
public boolean isFirebird() {
return productName.toUpperCase().indexOf("FIREBIRD") >= 0;
}
/**
* Returns whether the underlying database is Informix.
*/
public boolean isInformix() {
return productName.startsWith("Informix");
}
/**
* Returns whether the underlying database is Ingres.
*/
public boolean isIngres() {
return productName.toUpperCase().equals("INGRES");
}
/**
* Returns whether the underlying database is Interbase.
*/
public boolean isInterbase() {
return productName.equals("Interbase");
}
/**
* Returns whether the underlying database is LucidDB.
*/
public boolean isLucidDB() {
return productName.toUpperCase().equals("LUCIDDB");
}
/**
* Returns whether the underlying database is Microsoft SQL Server.
*/
public boolean isMSSQL() {
return productName.toUpperCase().indexOf("SQL SERVER") >= 0;
}
/**
* Returns whether the underlying database is Oracle.
*/
public boolean isOracle() {
return productName.equals("Oracle");
}
/**
* Returns whether the underlying database is Postgres.
*/
public boolean isPostgres() {
return productName.toUpperCase().indexOf("POSTGRE") >= 0;
}
/**
* Returns whether the underlying database is MySQL.
*/
public boolean isMySQL() {
return productName.toUpperCase().equals("MYSQL");
}
/**
* Returns whether the underlying database is Sybase.
*/
public boolean isSybase() {
return productName.toUpperCase().indexOf("SYBASE") >= 0;
}
/**
* Returns whether the underlying database is Teradata.
*/
public boolean isTeradata() {
return productName.toUpperCase().indexOf("SYBASE") >= 0;
}
// -- behaviors --
protected boolean requiresAliasForFromItems() {
return isPostgres();
}
/**
* Returns whether the SQL dialect allows "AS" in the FROM clause.
* If so, "SELECT * FROM t AS alias" is a valid query.
*/
protected boolean allowsAs() {
return !isOracle() && !isSybase() && !isFirebird() &&
!isInterbase();
}
/**
* Whether "select * from (select * from t)" is OK.
*/
public boolean allowsFromQuery() {
// older versions of AS400 do not allow FROM subqueries
return !isMySQL() && !isOldAS400() && !isInformix() &&
!isSybase() && !isInterbase();
}
/**
* Whether "select count(distinct x, y) from t" is OK.
*/
public boolean allowsCompoundCountDistinct() {
return isMySQL();
}
/**
* Whether "select count(distinct x) from t" is OK.
*/
public boolean allowsCountDistinct() {
return !isAccess();
}
/**
* Chooses the variant within an array of
* {@link mondrian.olap.MondrianDef.SQL} which best matches the current
* SQL dialect.
*/
public String chooseQuery(final MondrianDef.SQL[] sqls) {
String best = getBestName();
String generic = null;
for (MondrianDef.SQL sql : sqls) {
if (sql.dialect.equals(best)) {
return sql.cdata;
}
if (sql.dialect.equals("generic")) {
generic = sql.cdata;
}
}
if (generic == null) {
throw Util.newError("View has no 'generic' variant");
}
return generic;
}
/**
* Generates a SQL statement to represent an inline dataset.
*
* <p>For example, for Oracle, generates
*
* <pre>
* SELECT 1 AS FOO, 'a' AS BAR FROM dual
* UNION ALL
* SELECT 2 AS FOO, 'b' AS BAR FROM dual
* </pre>
*
* <p>For ANSI SQL, generates:
*
* <pre>
* VALUES (1, 'a'), (2, 'b')
* </pre>
*
* @param columnNames List of column names
* @param columnTypes List of column types ("String" or "Numeric")
* @param valueList List of rows values
* @return SQL string
*/
public String generateInline(
List<String> columnNames,
List<String> columnTypes,
List<String[]> valueList) {
if (isOracle()) {
return generateInlineGeneric(
columnNames, columnTypes, valueList,
"from dual");
} else if (isAccess()) {
// Fall back to using the FoodMart 'days' table, because
// Access SQL has no way to generate values not from a table.
return generateInlineGeneric(
columnNames, columnTypes, valueList,
"from [days] where [day] = 1");
} else if (isMySQL()) {
return generateInlineGeneric(
columnNames, columnTypes, valueList, null);
} else if (isLucidDB()) {
// TODO jvs 26-Nov-2006: Eliminate this once LucidDB
// can support applying column names to a VALUES clause
// (needed by generateInlineForAnsi).
return generateInlineGeneric(
columnNames, columnTypes, valueList,
" from (values(0))");
} else {
return generateInlineForAnsi("t", columnNames, columnTypes, valueList);
}
}
/**
* Generic algorithm to generate inline values list,
* using an optional FROM clause, specified by the caller of this
* method, appropriate to the dialect of SQL.
*/
private String generateInlineGeneric(
List<String> columnNames,
List<String> columnTypes,
List<String[]> valueList,
String fromClause) {
final StringBuilder buf = new StringBuilder();
for (int i = 0; i < valueList.size(); i++) {
if (i > 0) {
buf.append(" union all ");
}
String[] values = valueList.get(i);
buf.append("select ");
for (int j = 0; j < values.length; j++) {
String value = values[j];
if (j > 0) {
buf.append(", ");
}
final String columnType = columnTypes.get(j);
final String columnName = columnNames.get(j);
Datatype datatype = Datatype.valueOf(columnType);
quote(buf, value, datatype);
if (allowsAs()) {
buf.append(" as ");
} else {
buf.append(' ');
}
quoteIdentifier(columnName, buf);
}
if (fromClause != null) {
buf.append(fromClause);
}
}
return buf.toString();
}
/**
* Generates inline values list using ANSI 'VALUES' syntax.
* For example,
*
* <blockquote><code>SELECT * FROM
* (VALUES (1, 'a'), (2, 'b')) AS t(x, y)</code></blockquote>
*
* <p>If NULL values are present, we use a CAST to ensure that they
* have the same type as other columns:
*
* <blockquote><code>SELECT * FROM
* (VALUES (1, 'a'), (2, CASE(NULL AS VARCHAR(1)))) AS t(x, y)
* </code></blockquote>
*
* <p>This syntax is known to work on Derby, but not Oracle 10 or
* Access.
*/
private String generateInlineForAnsi(
String alias,
List<String> columnNames,
List<String> columnTypes,
List<String[]> valueList) {
final StringBuilder buf = new StringBuilder();
buf.append("SELECT * FROM (VALUES ");
// Derby pads out strings to a common length, so we cast the
// string values to avoid this. Determine the cast type for each
// column.
String[] castTypes = null;
if (isDerby()) {
castTypes = new String[columnNames.size()];
for (int i = 0; i < columnNames.size(); i++) {
String columnType = columnTypes.get(i);
if (columnType.equals("String")) {
castTypes[i] =
guessSqlType(columnType, valueList, i);
}
}
}
for (int i = 0; i < valueList.size(); i++) {
if (i > 0) {
buf.append(", ");
}
String[] values = valueList.get(i);
buf.append("(");
for (int j = 0; j < values.length; j++) {
String value = values[j];
if (j > 0) {
buf.append(", ");
}
final String columnType = columnTypes.get(j);
Datatype datatype = Datatype.valueOf(columnType);
if (value == null) {
String sqlType =
guessSqlType(columnType, valueList, j);
buf.append("CAST(NULL AS ")
.append(sqlType)
.append(")");
} else if (isDerby() && castTypes[j] != null) {
buf.append("CAST(");
quote(buf, value, datatype);
buf.append(" AS ")
.append(castTypes[j])
.append(")");
} else {
quote(buf, value, datatype);
}
}
buf.append(")");
}
buf.append(") AS ");
quoteIdentifier(alias, buf);
buf.append(" (");
for (int j = 0; j < columnNames.size(); j++) {
final String columnName = columnNames.get(j);
if (j > 0) {
buf.append(", ");
}
quoteIdentifier(columnName, buf);
}
buf.append(")");
return buf.toString();
}
/**
* Appends to a buffer a value quoted for its type.
*/
public void quote(StringBuilder buf, Object value, Datatype datatype) {
if (value == null) {
buf.append("null");
} else {
datatype.quoteValue(buf, this, value.toString());
}
}
/**
* Guesses the type of a column based upon (a) its basic type,
* (b) a list of values.
*/
private static String guessSqlType(
String basicType, List<String[]> valueList, int column) {
if (basicType.equals("String")) {
int maxLen = 1;
for (String[] values : valueList) {
final String value = values[column];
if (value == null) {
continue;
}
maxLen = Math.max(maxLen, value.length());
}
return "VARCHAR(" + maxLen + ")";
} else {
return "INTEGER";
}
}
/**
* Returns whether this dialect supports common SQL Data Definition
* Language (DDL) statements such as <code>CREATE TABLE</code> and
* <code>DROP INDEX</code>.
*/
public boolean allowsDdl() {
return !isAccess();
}
/**
* Returns whether NULL values appear last when sorted using ORDER BY.
* According to the SQL standard, this is implementation-specific.
*/
public boolean isNullsCollateLast() {
if (isMySQL()) {
return false;
}
return true;
}
/**
* Modifies an expression in the ORDER BY clause to ensure that NULL
* values collate after all non-NULL values.
* If {@link #isNullsCollateLast()} is true, there's nothing to do.
*/
public String forceNullsCollateLast(String expr) {
// If we need to support other DBMSes, note that the SQL standard
// provides the syntax 'ORDER BY x ASC NULLS LAST'.
if (isMySQL()) {
String addIsNull = "ISNULL(" + expr + "), ";
expr = addIsNull + expr;
}
return expr;
}
/**
* Returns whether this Dialect supports expressions in the GROUP BY
* clause. Derby/Cloudscape do not.
*
* @return Whether this Dialect allows expressions in the GROUP BY
* clause
*/
public boolean supportsGroupByExpressions() {
return !(isDerby() || isCloudscape());
}
public boolean requiresOrderByAlias() {
return isMySQL() || isDB2() || isIngres();
}
/**
* Returns true if this dialect supports multi-value IN expressions.
* E.g.,
*
* <code>WHERE (col1, col2) IN ((val1a, val2a), (val1b, val2b))</code>
*
* @return true if the dialect supports multi-value IN expressions
*/
public boolean supportsMultiValueInExpr() {
return isLucidDB() || isMySQL();
}
}
/**
* Datatype of a column.
*/
public enum Datatype {
String {
public void quoteValue(StringBuilder buf, Dialect dialect, String value) {
dialect.quoteStringLiteral(buf, value);
}
},
Numeric {
public void quoteValue(StringBuilder buf, Dialect dialect, String value) {
dialect.quoteNumericLiteral(buf, value);
}
public boolean isNumeric() {
return true;
}
},
Integer {
public void quoteValue(StringBuilder buf, Dialect dialect, String value) {
dialect.quoteNumericLiteral(buf, value);
}
public boolean isNumeric() {
return true;
}
},
Boolean {
public void quoteValue(StringBuilder buf, Dialect dialect, String value) {
dialect.quoteBooleanLiteral(buf, value);
}
},
Date {
public void quoteValue(StringBuilder buf, Dialect dialect, String value) {
dialect.quoteDateLiteral(buf, value);
}
},
Time {
public void quoteValue(StringBuilder buf, Dialect dialect, String value) {
dialect.quoteTimeLiteral(buf, value);
}
},
Timestamp {
public void quoteValue(StringBuilder buf, Dialect dialect, String value) {
dialect.quoteTimestampLiteral(buf, value);
}
};
/**
* Appends to a buffer a value of this type, in the appropriate format
* for this dialect.
*
* @param buf Buffer
* @param dialect Dialect
* @param value Value
*/
public abstract void quoteValue(
StringBuilder buf,
Dialect dialect,
String value);
public boolean isNumeric() {
return false;
}
}
}
// End SqlQuery.java
|
package com.hankcs.hanlp.summary;
import com.hankcs.hanlp.corpus.tag.Nature;
import com.hankcs.hanlp.dictionary.stopword.CoreStopWordDictionary;
import com.hankcs.hanlp.seg.common.Term;
import com.hankcs.hanlp.tokenizer.StandardTokenizer;
import java.util.*;
import java.util.regex.*;
/**
* TextRank
* @author hankcs
*/
public class TextRankSentence
{
/**
* 0.85
*/
final static double d = 0.85;
final static int max_iter = 200;
final static double min_diff = 0.001;
int D;
List<List<String>> docs;
/**
* score <-> index
*/
TreeMap<Double, Integer> top;
double[][] weight;
double[] weight_sum;
double[] vertex;
/**
* BM25
*/
BM25 bm25;
public TextRankSentence(List<List<String>> docs)
{
this.docs = docs;
bm25 = new BM25(docs);
D = docs.size();
weight = new double[D][D];
weight_sum = new double[D];
vertex = new double[D];
top = new TreeMap<Double, Integer>(Collections.reverseOrder());
solve();
}
private void solve()
{
int cnt = 0;
for (List<String> sentence : docs)
{
double[] scores = bm25.simAll(sentence);
// System.out.println(Arrays.toString(scores));
weight[cnt] = scores;
weight_sum[cnt] = sum(scores) - scores[cnt];
vertex[cnt] = 1.0;
++cnt;
}
for (int _ = 0; _ < max_iter; ++_)
{
double[] m = new double[D];
double max_diff = 0;
for (int i = 0; i < D; ++i)
{
m[i] = 1 - d;
for (int j = 0; j < D; ++j)
{
if (j == i || weight_sum[j] == 0) continue;
m[i] += (d * weight[j][i] / weight_sum[j] * vertex[j]);
}
double diff = Math.abs(m[i] - vertex[i]);
if (diff > max_diff)
{
max_diff = diff;
}
}
vertex = m;
if (max_diff <= min_diff) break;
}
for (int i = 0; i < D; ++i)
{
top.put(vertex[i], i);
}
}
/**
*
* @param size
* @return
*/
public int[] getTopSentence(int size)
{
Collection<Integer> values = top.values();
size = Math.min(size, values.size());
int[] indexArray = new int[size];
Iterator<Integer> it = values.iterator();
for (int i = 0; i < size; ++i)
{
indexArray[i] = it.next();
}
return indexArray;
}
/**
*
* @param array
* @return
*/
private static double sum(double[] array)
{
double total = 0;
for (double v : array)
{
total += v;
}
return total;
}
public static void main(String[] args)
{
String document = "\n" +
"\n" +
"\n" +
"\n" +
"";
System.out.println(TextRankSentence.getTopSentenceList(document, 3));
}
/**
*
* @param document
* @return
*/
static List<String> spiltSentence(String document)
{
List<String> sentences = new ArrayList<String>();
for (String line : document.split("[\r\n]"))
{
line = line.trim();
if (line.length() == 0) continue;
for (String sent : line.split("[]"))
{
sent = sent.trim();
if (sent.length() == 0) continue;
sentences.add(sent);
}
}
int length = sentences.size();
for (int i = 0; i < length; i++)
{
String buffer = sentences.get(i);
if (!buffer.contains(""))
{
buffer = buffer + "";
sentences.set(i, buffer);
}
}
return sentences;
}
/**
* List<List<String>>
* @param termList
* @return docs
*/
static List<List<String>> termSpiltSentence(List<Term> termList)
{
List<List<String>> docs = new ArrayList<List<String>>();
List<String> sentences = new ArrayList<String>();
for (Term term : termList)
{
if (!term.word.equals(""))
{
if ((!term.word.equals(" "))&&
(!term.word.equals("\r")) &&
(!term.word.equals("\n"))&&
term.word.length()>0)
{
if (CoreStopWordDictionary.shouldInclude(term))
{
sentences.add(term.word);
}
}
}
else {
docs.add(sentences);
sentences = new ArrayList<String>();
}
}
return docs;
}
/**
*
* @param document
* @param size
* @return
*/
public static List<String> getTopSentenceList(String document, int size)
{
List<String> sentenceList = spiltSentence(document);
List<List<String>> docs = new ArrayList<List<String>>();
for (String sentence : sentenceList)
{
List<Term> termList = StandardTokenizer.segment(sentence.toCharArray());
List<String> wordList = new LinkedList<String>();
for (Term term : termList)
{
if (CoreStopWordDictionary.shouldInclude(term))
{
wordList.add(term.word);
}
}
docs.add(wordList);
// System.out.println(wordList);
}
TextRankSentence textRank = new TextRankSentence(docs);
int[] topSentence = textRank.getTopSentence(size);
List<String> resultList = new LinkedList<String>();
for (int i : topSentence)
{
resultList.add(sentenceList.get(i));
}
return resultList;
}
/**
*
* @param termList
* @param max_length
* @param document
* @return
*/
public static String taikorGetSummary(String document, List<Term> termList, int max_length)
{
List<String> sentenceList = spiltSentence(document);
List<List<String>> docs = termSpiltSentence(termList);
int document_length = document.length();
int sentence_count = sentenceList.size();
int sentence_length_avg = document_length/sentence_count;
int size = max_length/sentence_length_avg + 1;
TextRankSentence textRank = new TextRankSentence(docs);
int[] topSentence = textRank.getTopSentence(size);
List<String> resultList = new LinkedList<String>();
for (int i : topSentence)
{
resultList.add(sentenceList.get(i));
}
resultList = permutation(resultList, sentenceList);
resultList = pick_sentences(resultList, max_length);
//String summary = String.join("", resultList); // incompatible with .net in Storm clusters
String summary = "";
for(String temp : resultList)
{
summary += patch_quote(temp);
}
return summary;
}
/**
*
* @param termString
* @param max_length
* @param document
* @return
*/
public static String taikorGetSummary(String document, String termString, int max_length)
{
List<Term> termList = string2term(termString);
List<String> sentenceList = spiltSentence(document);
List<List<String>> docs = termSpiltSentence(termList);
int document_length = document.length();
int sentence_count = sentenceList.size();
int sentence_length_avg = document_length/sentence_count;
int size = max_length/sentence_length_avg + 1;
TextRankSentence textRank = new TextRankSentence(docs);
int[] topSentence = textRank.getTopSentence(size);
List<String> resultList = new LinkedList<String>();
for (int i : topSentence)
{
resultList.add(sentenceList.get(i));
}
resultList = permutation(resultList, sentenceList);
resultList = pick_sentences(resultList, max_length);
//String summary = String.join("", resultList); // incompatible with .net in Storm clusters
String summary = "";
for(String temp : resultList)
{
summary += patch_quote(temp);
}
return summary;
}
/**
*
* @param document
* @param max_length
* @return
*/
public static String getSummary(String document, int max_length)
{
List<String> sentenceList = spiltSentence(document);
int sentence_count = sentenceList.size();
int document_length = document.length();
int sentence_length_avg = document_length/sentence_count;
int size = max_length/sentence_length_avg + 1;
List<List<String>> docs = new ArrayList<List<String>>();
for (String sentence : sentenceList)
{
List<Term> termList = StandardTokenizer.segment(sentence.toCharArray());
List<String> wordList = new LinkedList<String>();
for (Term term : termList)
{
if (CoreStopWordDictionary.shouldInclude(term))
{
wordList.add(term.word);
}
}
docs.add(wordList);
// System.out.println(wordList);
}
TextRankSentence textRank = new TextRankSentence(docs);
int[] topSentence = textRank.getTopSentence(size);
List<String> resultList = new LinkedList<String>();
for (int i : topSentence)
{
resultList.add(sentenceList.get(i));
}
resultList = permutation(resultList, sentenceList);
resultList = pick_sentences(resultList, max_length);
/*
String summary = String.join("", resultList);
incompatible with .net in Storm clusters
*/
String summary = "";
for(String temp : resultList)
{
summary += patch_quote(temp);
}
return summary;
}
public static String patch_quote(String sentence)
{
if((sentence.charAt(0)=='“')&&(sentence.charAt(sentence.length()-1)!='”'))
{
sentence += "”";
}
else if((sentence.charAt(0)=='"')&&(sentence.charAt(sentence.length()-1)!='"'))
{
sentence += "\"";
}
return sentence;
}
public static List<String> permutation(List<String> resultList, List<String> sentenceList)
{
int index_buffer_x;
int index_buffer_y;
String sen_x;
String sen_y;
int length = resultList.size();
// bubble sort derivative
for (int i = 0; i < length; i++)
for (int offset=0; offset < length - i; offset++)
{
sen_x = resultList.get(i);
sen_y = resultList.get(i + offset);
index_buffer_x = sentenceList.indexOf(sen_x);
index_buffer_y = sentenceList.indexOf(sen_y);
// if the sentence order in sentenceList does not conform that is in resultList, reverse it
if (index_buffer_x > index_buffer_y)
{
resultList.set(i, sen_y);
resultList.set(i+offset, sen_x);
}
}
return resultList;
}
public static List<String> pick_sentences(List<String> resultList, int max_length)
{
int length_counter = 0;
int length_buffer;
int length_jump;
List<String> resultBuffer = new LinkedList<String>();
for(int i = 0; i < resultList.size(); i++)
{
length_buffer = length_counter + resultList.get(i).length();
if (length_buffer <= max_length)
{
resultBuffer.add(resultList.get(i));
length_counter += resultList.get(i).length();
}
else if (i < (resultList.size()-1)) {
length_jump = length_counter + resultList.get(i+1).length();
if (length_jump <= max_length) {
resultBuffer.add(resultList.get(i + 1));
length_counter += resultList.get(i + 1).length();
i++;
}
}
}
return resultBuffer;
}
public static List<Term> string2term(String seg_str){
if (seg_str.charAt(0)=='[') {
seg_str = seg_str.substring(1, seg_str.length() - 1);
}
String[] items = seg_str.split("[ ]");
List<Term> termList = new ArrayList<Term>();
for (int i=0; i< items.length; i++)
{
String item = items[i];
if (item.length()==0){
continue;
}
if (item.charAt(0)=='/'){
continue;
}
String[] temp = item.split("/");
String word = temp[0];
String nature_str = temp[1];
if (nature_str.charAt(nature_str.length()-1)==','){
nature_str = nature_str.substring(0, nature_str.length()-1);
}
try {
Nature nature = Nature.valueOf(nature_str);
Term term = new Term(word, nature);
termList.add(term);
}
catch (Exception e){
System.out.println("Nature Value Illegal (Not Listed in Nature.java)");
}
}
return termList;
}
}
|
package com.ids1024.whitakerswords;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.File;
import java.io.Serializable;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import android.app.ListActivity;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuInflater;
import android.view.inputmethod.EditorInfo;
import android.view.KeyEvent;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.EditText;
import android.widget.ToggleButton;
import android.os.Bundle;
import android.content.Intent;
import android.content.res.AssetManager;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.StyleSpan;
import android.text.style.ForegroundColorSpan;
import android.graphics.Typeface;
import android.graphics.Color;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class WhitakersWords extends ListActivity {
String search_term;
boolean english_to_latin;
ArrayList<SpannableStringBuilder> results;
ListView list_view;
EditText search_term_view;
ToggleButton english_to_latin_view;
public void copyFiles() throws IOException {
for (String filename: getAssets().list("words")) {
InputStream ins = getAssets().open("words/" + filename);
byte[] buffer = new byte[4096];
FileOutputStream fos = openFileOutput(filename, MODE_PRIVATE);
for (int read = 0; read >= 0; read = ins.read(buffer)) {
fos.write(buffer, 0, read);
}
ins.close();
fos.close();
}
getFileStreamPath("words").setExecutable(true);
}
public String executeWords(String text, boolean fromenglish) {
String wordspath = getFilesDir().getPath() + "/words";
Process process;
try {
String[] command;
if (fromenglish) {
command = new String[] {wordspath, "~E", text};
} else {
command = new String[] {wordspath, text};
}
process = Runtime.getRuntime().exec(command, null, getFilesDir());
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
for (int read = 0; read >= 0; read = reader.read(buffer)) {
output.append(buffer, 0, read);
}
reader.close();
process.waitFor();
return output.toString();
} catch(IOException | InterruptedException e) {
throw new RuntimeException(e.getMessage());
}
}
public void searchWord() {
results.clear();
String result = executeWords(search_term, english_to_latin);
SpannableStringBuilder processed_result = new SpannableStringBuilder();
int prev_code = 0;
for (String line: result.split("\n")) {
String[] words = line.split(" +");
String handled_line = TextUtils.join(" ", words);
int pearse_code = 0;
if (words[0].length() == 2) {
try {
pearse_code = Integer.parseInt(words[0]);
handled_line = handled_line.substring(3);
} catch (NumberFormatException e) {}
}
// Indent meanings
if (pearse_code == 3) {
handled_line = " " + handled_line;
}
if (line.isEmpty() || line.equals("*")) {
if (line.equals("*")) {
processed_result.append("*");
}
String finalresult = processed_result.toString().trim();
if (!finalresult.isEmpty()) {
results.add(processed_result);
}
processed_result = new SpannableStringBuilder();
continue;
}
int startindex = processed_result.length();
processed_result.append(handled_line + "\n");
Object span = null;
int endindex = processed_result.length();
switch (pearse_code) {
// Forms
case 1:
span = new StyleSpan(Typeface.BOLD);
endindex = startindex + words[1].length();
break;
// Dictionary forms
case 2:
// A HACK(?) for parsing output of searches like
// "quod", which show shorter output for dictionary forms
if (words[1].startsWith("[")) {
break;
}
int index = 1;
endindex = startindex;
do {
endindex += words[index].length() + 1;
index += 1;
} while (words[index-1].endsWith(","));
span = new StyleSpan(Typeface.BOLD);
break;
// Meaning
case 3:
span = new StyleSpan(Typeface.ITALIC);
break;
// Not found
case 4:
span = new ForegroundColorSpan(Color.RED);
break;
// Addons
case 5:
break;
// Tricks/syncope/addons?
case 6:
break;
}
processed_result.setSpan(span, startindex, endindex, 0);
prev_code = pearse_code;
}
String finalresult = processed_result.toString().trim();
if (!finalresult.isEmpty()) {
results.add(processed_result);
}
ArrayAdapter<SpannableStringBuilder> itemsAdapter =
new ArrayAdapter<SpannableStringBuilder>(getApplicationContext(), R.layout.result, results);
list_view.setAdapter(itemsAdapter);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
copyFiles();
} catch(IOException e) {
throw new RuntimeException(e.getMessage());
}
setContentView(R.layout.main);
list_view = (ListView)findViewById(android.R.id.list);
search_term_view = (EditText)findViewById(R.id.search_term);
english_to_latin_view = (ToggleButton)findViewById(R.id.english_to_latin);
search_term_view.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
boolean handled = false;
if ((actionId == EditorInfo.IME_ACTION_SEARCH) ||
(actionId==EditorInfo.IME_NULL &&
event.getAction()==KeyEvent.ACTION_DOWN)) {
search_term = search_term_view.getText().toString();
english_to_latin = english_to_latin_view.isChecked();
searchWord();
v.setText("");
handled = true;
}
return handled;
}
});
results = new ArrayList<SpannableStringBuilder>();
if (savedInstanceState != null) {
search_term = savedInstanceState.getString("search_term");
english_to_latin = savedInstanceState.getBoolean("english_to_latin");
english_to_latin_view.setChecked(english_to_latin);
searchWord();
ArrayAdapter<SpannableStringBuilder> itemsAdapter =
new ArrayAdapter<SpannableStringBuilder>(getApplicationContext(), R.layout.result, results);
list_view.setAdapter(itemsAdapter);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString("search_term", search_term);
outState.putBoolean("english_to_latin", english_to_latin);
super.onSaveInstanceState(outState);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent = new Intent(this, WhitakersSettings.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
|
package com.kaishiyoku.youtubedownloadhelper;
import com.kaishiyoku.youtubedownloadhelper.models.Channel;
import de.vandermeer.asciitable.AT_Context;
import de.vandermeer.asciitable.AsciiTable;
import de.vandermeer.asciithemes.TA_GridThemes;
import de.vandermeer.skb.interfaces.transformers.textformat.TextAlignment;
import org.pmw.tinylog.Logger;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.util.*;
import java.util.stream.Stream;
import static com.kaishiyoku.youtubedownloadhelper.helper.ConsoleHelper.*;
public class Main {
private final static long MAX_AGE_OF_YOUTUBE_DL_FILE_IN_DAYS = 30;
private static List<Channel> channels = new ArrayList<>();
private static Map<Integer, String> options = new LinkedHashMap<Integer, String>() {{
put(1, "List channels");
put(2, "Add channel");
put(3, "Remove channel");
put(4, "Start download");
put(5, "Download single channel");
put(-1, "");
put(0, "Exit");
}};
public static void main(String[] args) {
downloadYoutubeDlIfNeeded();
createChannelConfigIfNeeded();
loadChannelConfig();
cls();
int status = 1;
while (status == 1) {
int option = showMenuOptions();
cls();
try {
switch (option) {
case 1:
listChannels();
break;
case 2:
addChannel();
break;
case 3:
removeChannel();
break;
case 4:
startDownload();
break;
case 5:
startDownloadSingle();
break;
case 0:
status = 0;
break;
default:
println("Invalid option.");
}
} catch (Exception e) {
Logger.error(e);
}
println();
println();
}
System.exit(0);
}
private static int showMenuOptions() {
Scanner scanner = new Scanner(System.in);
AT_Context ctx = new AT_Context();
ctx.setGridTheme(TA_GridThemes.INSIDE_HORIZONTAL);
ctx.setWidth(30);
AsciiTable at = new AsciiTable(ctx);
at.addRule();
at.addRow("Options:");
at.addRule();
for (Map.Entry<Integer, String> option : options.entrySet()) {
if (option.getKey() == -1) {
at.addRow(option.getValue());
} else {
at.addRow(option.getKey() + ": " + option.getValue());
}
}
at.addRule();
render(at.render());
println();
print("> ");
int option = scanner.nextInt();
return option;
}
private static void loadChannelConfig() {
try {
File channelConfigFile = new File("config/channels.txt");
BufferedReader reader = new BufferedReader(new FileReader(channelConfigFile));
String line;
while ((line = reader.readLine()) != null) {
if (!line.startsWith("
channels.add(new Channel(line));
}
}
} catch (FileNotFoundException e) {
Logger.error(e);
} catch (IOException e) {
Logger.error(e);
}
}
private static void createChannelConfigIfNeeded() {
File dir = new File("config");
dir.mkdirs();
try {
File channelConfigFile = new File("config/channels.txt");
if (!channelConfigFile.exists()) {
PrintWriter writer = new PrintWriter(channelConfigFile, "UTF-8");
writer.println("# Enter here the YouTube channels you want to download in the following format, one channel per row:");
writer.println("# The description field is for visibility only and will not be used by the downloader.");
writer.println("# <DESCRIPTION>;<URL>;<LOCAL_PATH>");
writer.close();
}
} catch (IOException e) {
Logger.error(e);
}
}
private static void listChannels() {
AT_Context ctx = new AT_Context();
ctx.setGridTheme(TA_GridThemes.FULL);
ctx.setWidth(95);
AsciiTable at = new AsciiTable(ctx);
at.setTextAlignment(TextAlignment.LEFT);
at.addRule();
at.addRow("# | DESCRIPTION", "URL", "LOCAL PATH");
at.addRule();
if (channels.size() == 0) {
at.addRow(null, null, "no channels yet");
}
int i = 1;
for (Channel channel : channels) {
at.addRow(i + " | " + channel.getDescription(), channel.getUrl(), channel.getLocalPath());
if (i < channels.size()) {
at.addRule();
}
i++;
}
at.addRule();
render(at.render());
}
private static void addChannel() {
Scanner scanner = new Scanner(System.in);
print("Description: ");
String description = scanner.nextLine();
print("URL: ");
String url = scanner.nextLine();
print("Local path: ");
String localPath = scanner.nextLine();
Channel channel = new Channel(description, url, localPath);
channels.add(channel);
saveChannels(channel);
println("Channel added.");
}
private static void removeChannel() {
listChannels();
Scanner scanner = new Scanner(System.in);
print("Remove channel
int channelNumber = scanner.nextInt();
channels.remove(channelNumber - 1);
saveChannels();
println("Channel removed.");
listChannels();
}
private static void saveChannels() {
saveChannels(null);
}
private static void saveChannels(Channel channel) {
// save to file
File channelConfigFile = new File("config/channels.txt");
PrintWriter writer = null;
List<String> channelLines = new ArrayList<>();
try (Stream<String> lines = Files.lines(channelConfigFile.toPath())) {
lines.forEach(channelLines::add);
} catch (IOException e) {
Logger.error(e);
}
if (channel != null) {
channelLines.add(channel.toConfigLine());
}
try {
writer = new PrintWriter(channelConfigFile);
for (String line : channelLines) {
writer.println(line);
}
} catch (FileNotFoundException e) {
Logger.error(e);
} finally {
writer.close();
}
}
private static void downloadYoutubeDlIfNeeded() {
File dir = new File("third_party");
dir.mkdirs();
String baseUrl = "https://yt-dl.org/downloads/latest/";
// check if file already exists
File youtubeDlFile = new File("third_party/" + getYoutubeDlFileName());
long ageOfFile = new Date().getTime() - youtubeDlFile.lastModified();
boolean fileNotExistsOrIsVeryOld = !youtubeDlFile.exists();
if (!fileNotExistsOrIsVeryOld && ageOfFile > MAX_AGE_OF_YOUTUBE_DL_FILE_IN_DAYS * 24 * 60 * 60 * 1000) {
fileNotExistsOrIsVeryOld = true;
}
if (fileNotExistsOrIsVeryOld) {
println("Downloading youtube-dl tool from https://rg3.github.io/youtube-dl/...");
URL url;
try {
url = new URL(baseUrl + getYoutubeDlFileName());
URLConnection connection = url.openConnection();
InputStream in = connection.getInputStream();
FileOutputStream fos = new FileOutputStream(new File("third_party/" + getYoutubeDlFileName()));
byte[] buf = new byte[512];
while (true) {
int len = in.read(buf);
if (len == -1) {
break;
}
fos.write(buf, 0, len);
}
in.close();
fos.flush();
fos.close();
println("...done.");
pressToContinue();
} catch (MalformedURLException e) {
Logger.error(e);
} catch (FileNotFoundException e) {
Logger.error(e);
} catch (IOException e) {
Logger.error(e);
}
}
}
private static void startDownloadSingle() {
listChannels();
Scanner scanner = new Scanner(System.in);
println("Select the channel # to be downloaded.");
print("> ");
int channelNumber = scanner.nextInt();
try {
println();
downloadChannel(channels.get(channelNumber - 1), getYoutubeDlFile());
} catch (IndexOutOfBoundsException e) {
println("Invalid channel
}
}
private static File getYoutubeDlFile() {
return new File("third_party/" + getYoutubeDlFileName());
}
private static void startDownload() {
File youtubeDlFile = getYoutubeDlFile();
for (Channel channel : channels) {
downloadChannel(channel, youtubeDlFile);
}
}
private static void downloadChannel(Channel channel, File youtubeDlFile) {
Process p;
try {
println("Starting downloads for \"" + channel.getDescription() + "\".");
println();
List<String> newParams = new ArrayList<>();
if (isWindows()) {
newParams.add("cmd");
newParams.add("/c");
}
newParams.add(youtubeDlFile.getAbsolutePath());
newParams.add("--yes-playlist");
newParams.add("--output");
newParams.add(channel.getLocalPath() + "/%(title)s.%(ext)s");
newParams.add("--ignore-errors");
newParams.add("--no-overwrites");
newParams.add(channel.getUrl());
ProcessBuilder builder = new ProcessBuilder(newParams);
builder.redirectErrorStream(true);
p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while (true) {
line = r.readLine();
if (line == null) {
break;
}
Logger.info(line);
}
println();
println();
} catch (IOException e) {
Logger.error(e);
}
}
private static String getYoutubeDlFileName() {
String fileName = "youtube-dl";
if (isWindows()) {
fileName += ".exe";
}
return fileName;
}
}
|
package com.maksofrol.gameoflife.forms;
import com.maksofrol.gameoflife.controller.LifeController;
import javax.swing.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
/**
* TO DO
*/
public class FieldPanel extends JPanel {
private final JFrame rootFrame;
private final JPanel field;
private final JButton addB;
private final JButton startB;
private final JButton stopB;
private final JButton exitB;
private final JButton clearB;
private final JTextField xText;
private final JTextField yText;
private final JLabel xyLabel;
private final ListenersFactory factory = new ListenersFactory();
private final LifeController controller;
private final Timer startGame;
private final JLabel version;
private long delay;
public FieldPanel(JFrame rootFrame) {
controller = LifeController.getInstance();
this.rootFrame = rootFrame;
setLayout(null);
field = new Canvas(0, 0, 1006, 1006);
addB = new JButton();
startB = new JButton();
stopB = new JButton();
exitB = new JButton();
clearB = new JButton();
addB.setText("Add cell");
addB.setBounds(1040, 150, 110, 30);
clearB.setFont(new Font("Verdana", Font.PLAIN, 12));
clearB.setText("Clear field");
clearB.setBounds(1040, 190, 110, 40);
addB.setFont(new Font("Verdana", Font.PLAIN, 12));
startB.setText("Start game!");
startB.setBounds(1040, 300, 110, 40);
startB.setFont(new Font("Verdana", Font.PLAIN, 12));
stopB.setText("Stop");
stopB.setBounds(1040, 350, 110, 40);
stopB.setFont(new Font("Verdana", Font.PLAIN, 12));
exitB.setText("Exit");
exitB.setBounds(1040, 600, 110, 40);
exitB.setFont(new Font("Verdana", Font.PLAIN, 12));
xText = new JTextField();
xText.setBounds(1040, 120, 50, 20);
xText.setFont(new Font("Verdana", Font.PLAIN, 12));
yText = new JTextField();
yText.setBounds(1095, 120, 50, 20);
yText.setFont(new Font("Verdana", Font.PLAIN, 12));
xyLabel = new JLabel();
xyLabel.setBounds(1040, 102, 110, 20);
xyLabel.setFont(new Font("Verdana", Font.PLAIN, 12));
xyLabel.setText("X: Y:");
version = new JLabel();
version.setText("version 0.4.2");
version.setBounds(1100, 950, 100, 50);
version.setFont(new Font("Verdana", Font.PLAIN, 10));
version.setEnabled(false);
startGame = new Timer(0, factory.getTimerListener());
init();
}
private void textLimit(JTextField textField, int limit, String charLimit) {
textField.setDocument(new PlainDocument() {
@Override
public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
if (str == null || !charLimit.contains(str))
return;
if ((getLength() + str.length()) <= limit) {
super.insertString(offset, str, attr);
}
}
});
}
private void init() {
add(field);
add(addB);
add(clearB);
add(startB);
add(stopB);
add(exitB);
add(xText);
add(yText);
add(xyLabel);
add(version);
textLimit(xText, 3, "1234567890");
textLimit(yText, 3, "1234567890");
stopB.setEnabled(false);
addB.addActionListener(factory.getAddListener());
exitB.addActionListener(factory.getExitListener());
clearB.addActionListener(factory.getClearFListener());
startB.addActionListener(factory.getStartListener());
stopB.addActionListener(factory.getStopListener());
field.addMouseListener(factory.getTouchListener());
field.addMouseMotionListener(factory.getMouseMListener());
}
private class ListenersFactory {
private ActionListener getTimerListener() {
return e -> {
delay = System.currentTimeMillis();
try {
controller.checkCells();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
field.repaint();
delay = System.currentTimeMillis() - delay;
delay = delay > 50 ? 0 : 50 - delay;
startGame.setDelay((int) delay);
};
}
private ActionListener getAddListener() {
return e -> {
String x1 = xText.getText();
String y1 = yText.getText();
if (x1.equals("") || y1.equals("") || Integer.parseInt(x1) > 500 || Integer.parseInt(y1) > 500) {
JOptionPane.showMessageDialog(rootFrame, "Wrong parameters. Please choose coordinates from 0 to 500.");
return;
}
controller.addAliveCell(Integer.parseInt(x1), Integer.parseInt(y1));
field.repaint();
};
}
private ActionListener getExitListener() {
return e -> {
System.exit(0);
};
}
private ActionListener getClearFListener() {
return e -> {
controller.clearActiveCells();
field.repaint();
};
}
private ActionListener getStartListener() {
return e -> {
xText.setEnabled(false);
yText.setEnabled(false);
addB.setEnabled(false);
clearB.setEnabled(false);
startB.setEnabled(false);
stopB.setEnabled(true);
startGame.start();
};
}
private ActionListener getStopListener() {
return e -> {
startGame.stop();
xText.setEnabled(true);
yText.setEnabled(true);
addB.setEnabled(true);
clearB.setEnabled(true);
stopB.setEnabled(false);
startB.setEnabled(true);
};
}
private MouseMotionListener getMouseMListener() {
return new MouseMotionListener() {
@Override
public void mouseDragged(MouseEvent e) {
int x = e.getX() / 2 - 1;
int y = e.getY() / 2 - 1;
if (x >= 0 && x <= 500 && y >= 0 && y <= 500) {
controller.addAliveCell(x, y);
}
field.repaint();
}
@Override
public void mouseMoved(MouseEvent e) {
}
};
}
private MouseListener getTouchListener() {
return new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
int x = e.getX() / 2 - 1;
int y = e.getY() / 2 - 1;
controller.addAliveCell(x, y);
field.repaint();
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
};
}
}
}
|
package com.openlattice.postgres;
//@formatter:off
//@formatter:on
public enum PostgresDatatype {
SMALLINT, SMALLINT_ARRAY,
INTEGER, INTEGER_ARRAY,
BIGINT, BIGINT_ARRAY,
DECIMAL,
NUMERIC,
DOUBLE, DOUBLE_ARRAY,
SERIAL,
BIGSERIAL,
BYTEA,
BOOLEAN,
TIMESTAMPTZ, TIMESTAMPTZ_ARRAY,
UUID, UUID_ARRAY, UUID_ARRAY_ARRAY,
TEXT, TEXT_ARRAY;
private static final EnumSet<PostgresDatatype> ARRAY_TYPES = EnumSet
.of( SMALLINT_ARRAY,
INTEGER_ARRAY,
BIGINT_ARRAY,
DOUBLE_ARRAY,
TIMESTAMPTZ_ARRAY,
UUID_ARRAY,
UUID_ARRAY_ARRAY,
TEXT_ARRAY );
public String sql() {
return ARRAY_TYPES.contains( this ) ? name().replace( "_ARRAY", "[]" ) : name();
}
}
|
package com.panzareon.spellcircles.item;
import com.panzareon.spellcircles.init.ModBlocks;
import com.panzareon.spellcircles.tileentity.TileEntitySpellCircle;
import com.panzareon.spellcircles.tileentity.TileEntitySpellCircleGag;
import net.minecraft.block.Block;
import net.minecraft.block.BlockStoneBrick;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.registry.GameRegistry;
public class ItemChalk extends SpellCirclesItem
{
public ItemChalk()
{
super();
this.setUnlocalizedName("chalk");
this.setHasSubtypes(true);
this.setMaxDamage(64);
this.maxStackSize = 1;
}
@Override
public boolean onItemUse(ItemStack stack, EntityPlayer playerIn, World worldIn, BlockPos pos, EnumFacing side, float hitX, float hitY, float hitZ) {
if(side == EnumFacing.UP)
{
int y = pos.getY() + 1;
int yDown = pos.getY();
//Todo: check max space / size
IBlockState state;
int radius = 0;
boolean increase = true;
Block lapis = Blocks.lapis_block;
Block stone = Blocks.stonebrick;
//check if 3x3 fits
for(int x = pos.getX() - 1; x <= pos.getX() + 1; x++)
{
for(int z = pos.getZ() - 1; z <= pos.getZ() + 1; z++)
{
if(!worldIn.isAirBlock(new BlockPos(x, y, z)))
{
increase = false;
}
state = worldIn.getBlockState(new BlockPos(x, yDown, z));
boolean xSame = x == pos.getX();
boolean zSame = z == pos.getZ();
if(xSame ^ zSame)
{
if(state.getBlock() != lapis)
{
increase = false;
}
}
if(!xSame && !zSame)
{
if(state.getBlock() != stone || state.getValue(BlockStoneBrick.VARIANT) != BlockStoneBrick.EnumType.CHISELED)
{
increase = false;
}
}
}
}
if(increase)
{
radius = 1;
//Todo: check if bigger Spellcircle possible
}
int damage = radius * 2 + 1;
damage = damage * damage;
stack.damageItem(damage, playerIn);
TileEntitySpellCircleGag teGag;
for(int x = pos.getX() - radius; x <= pos.getX() + radius; x++)
{
for(int z = pos.getZ() - radius; z <= pos.getZ() + radius; z++)
{
BlockPos posAt = new BlockPos(x,y,z);
if(x != pos.getX() || z != pos.getZ())
{
worldIn.setBlockState(posAt, ModBlocks.spellCircleGag.getDefaultState());
teGag = (TileEntitySpellCircleGag) worldIn.getTileEntity(posAt);
teGag.primaryPos = pos.up();
}
else
{
worldIn.setBlockState(posAt, ModBlocks.spellCircle.getDefaultState());
TileEntitySpellCircle te = (TileEntitySpellCircle) worldIn.getTileEntity(posAt);
te.radius = radius + 1;
}
}
}
}
return false;
}
}
|
package com.pollistics.controllers;
import com.pollistics.models.Poll;
import com.pollistics.services.PollService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
@Controller
public class PollController {
@Autowired
private PollService pollService;
@GetMapping(value = {"/polls/{pollId}", "/{pollId}"})
public String greeting(@PathVariable String pollId, Model model, HttpServletResponse response) {
Poll poll = pollService.getPoll(pollId);
if(poll == null) {
response.setStatus(404);
return "error/404";
}
model.addAttribute("poll", pollService.getPoll(pollId));
return "polls/detail";
}
@PostMapping(value = "/polls/create")
public String createPoll(HttpServletRequest request, Model model) {
String title = request.getParameter("title");
String option1 = request.getParameter("option1");
String option2 = request.getParameter("option2");
String option3 = request.getParameter("option3");
HashMap<String, Integer> options = new HashMap<>();
options.put(option1, 0);
options.put(option2, 0);
options.put(option3, 0);
String id = pollService.createPoll(title, options);
return "redirect:/" + id;
}
@PostMapping(value = "/polls/vote/{pollId}")
public String voteOptions(@PathVariable String pollId, HttpServletRequest request, Model model) {
String option = request.getParameter("option");
Poll p = pollService.getPoll(pollId);
pollService.voteOption(p, option);
return "redirect:/" + pollId;
}
}
|
package com.rarchives.ripme.ripper;
import java.awt.Desktop;
import java.io.*;
import java.lang.reflect.Constructor;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.jsoup.HttpStatusException;
import com.rarchives.ripme.ui.RipStatusComplete;
import com.rarchives.ripme.ui.RipStatusHandler;
import com.rarchives.ripme.ui.RipStatusMessage;
import com.rarchives.ripme.ui.RipStatusMessage.STATUS;
import com.rarchives.ripme.utils.Utils;
import java.io.File;
import java.util.Scanner;
public abstract class AbstractRipper
extends Observable
implements RipperInterface, Runnable {
protected static final Logger logger = Logger.getLogger(AbstractRipper.class);
private final String URLHistoryFile = Utils.getURLHistoryFile();
public static final String USER_AGENT =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36";
protected URL url;
protected File workingDir;
DownloadThreadPool threadPool;
RipStatusHandler observer = null;
private boolean completed = true;
public abstract void rip() throws IOException;
public abstract String getHost();
public abstract String getGID(URL url) throws MalformedURLException;
public boolean hasASAPRipping() { return false; }
// Everytime addUrlToDownload skips a already downloaded url this increases by 1
public int alreadyDownloadedUrls = 0;
private boolean shouldStop = false;
private boolean thisIsATest = false;
public void stop() {
shouldStop = true;
}
public boolean isStopped() {
return shouldStop;
}
protected void stopCheck() throws IOException {
if (shouldStop) {
throw new IOException("Ripping interrupted");
}
}
private void writeDownloadedURL(String downloadedURL) throws IOException {
BufferedWriter bw = null;
FileWriter fw = null;
try {
File file = new File(URLHistoryFile);
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
fw = new FileWriter(file.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
bw.write(downloadedURL);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
/**
* Checks to see if Ripme has already downloaded a URL
* @param url URL to check if downloaded
* @return
* Returns true if previously downloaded.
* Returns false if not yet downloaded.
*/
private boolean hasDownloadedURL(String url) {
File file = new File(URLHistoryFile);
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if (lineFromFile.equals(url)) {
return true;
}
}
} catch (FileNotFoundException e) {
return false;
}
return false;
}
/**
* Ensures inheriting ripper can rip this URL, raises exception if not.
* Otherwise initializes working directory and thread pool.
*
* @param url
* URL to rip.
* @throws IOException
* If anything goes wrong.
*/
public AbstractRipper(URL url) throws IOException {
if (!canRip(url)) {
throw new MalformedURLException("Unable to rip url: " + url);
}
this.url = sanitizeURL(url);
}
/**
* Sets ripper's:
* Working directory
* Logger (for debugging)
* FileAppender
* Threadpool
* @throws IOException
* Always be prepared.
*/
public void setup() throws IOException {
setWorkingDir(this.url);
Logger rootLogger = Logger.getRootLogger();
FileAppender fa = (FileAppender) rootLogger.getAppender("FILE");
if (fa != null) {
fa.setFile(this.workingDir + File.separator + "log.txt");
fa.activateOptions();
}
this.threadPool = new DownloadThreadPool();
}
public void setObserver(RipStatusHandler obs) {
this.observer = obs;
}
/**
* Queues image to be downloaded and saved.
* @param url
* URL of the file
* @param saveAs
* Path of the local file to save the content to.
* @return True on success, flase on failure.
*/
public abstract boolean addURLToDownload(URL url, File saveAs);
/**
* Queues image to be downloaded and saved.
* @param url
* URL of the file
* @param saveAs
* Path of the local file to save the content to.
* @param referrer
* The HTTP referrer to use while downloading this file.
* @param cookies
* The cookies to send to the server while downloading this file.
* @return
* True if downloaded successfully
* False if failed to download
*/
protected abstract boolean addURLToDownload(URL url, File saveAs, String referrer, Map<String, String> cookies);
/**
* Queues image to be downloaded and saved.
* @param url
* URL of the file
* @param prefix
* Prefix for the downloaded file
* @param subdirectory
* Path to get to desired directory from working directory
* @param referrer
* The HTTP referrer to use while downloading this file.
* @param cookies
* The cookies to send to the server while downloading this file.
* @return
* True if downloaded successfully
* False if failed to download
*/
protected boolean addURLToDownload(URL url, String prefix, String subdirectory, String referrer, Map<String, String> cookies) {
// Don't re-add the url if it was downloaded in a previous rip
if (Utils.getConfigBoolean("remember.url_history", true) && !isThisATest()) {
if (hasDownloadedURL(url.toExternalForm())) {
sendUpdate(STATUS.DOWNLOAD_WARN, "Already downloaded " + url.toExternalForm());
alreadyDownloadedUrls += 1;
return false;
}
}
try {
stopCheck();
} catch (IOException e) {
logger.debug("Ripper has been stopped");
return false;
}
logger.debug("url: " + url + ", prefix: " + prefix + ", subdirectory" + subdirectory + ", referrer: " + referrer + ", cookies: " + cookies);
String saveAs = url.toExternalForm();
saveAs = saveAs.substring(saveAs.lastIndexOf('/')+1);
if (saveAs.indexOf('?') >= 0) { saveAs = saveAs.substring(0, saveAs.indexOf('?')); }
if (saveAs.indexOf('#') >= 0) { saveAs = saveAs.substring(0, saveAs.indexOf('#')); }
if (saveAs.indexOf('&') >= 0) { saveAs = saveAs.substring(0, saveAs.indexOf('&')); }
if (saveAs.indexOf(':') >= 0) { saveAs = saveAs.substring(0, saveAs.indexOf(':')); }
File saveFileAs;
try {
if (!subdirectory.equals("")) {
subdirectory = File.separator + subdirectory;
}
prefix = Utils.filesystemSanitized(prefix);
saveFileAs = new File(
workingDir.getCanonicalPath()
+ subdirectory
+ File.separator
+ prefix
+ saveAs);
} catch (IOException e) {
logger.error("[!] Error creating save file path for URL '" + url + "':", e);
return false;
}
logger.debug("Downloading " + url + " to " + saveFileAs);
if (!saveFileAs.getParentFile().exists()) {
logger.info("[+] Creating directory: " + Utils.removeCWD(saveFileAs.getParent()));
saveFileAs.getParentFile().mkdirs();
}
if (Utils.getConfigBoolean("remember.url_history", true) && !isThisATest()) {
try {
writeDownloadedURL(url.toExternalForm() + "\n");
} catch (IOException e) {
logger.debug("Unable to write URL history file");
}
}
return addURLToDownload(url, saveFileAs, referrer, cookies);
}
/**
* Queues file to be downloaded and saved. With options.
* @param url
* URL to download.
* @param prefix
* Prefix to prepend to the saved filename.
* @param subdirectory
* Sub-directory of the working directory to save the images to.
* @return True on success, flase on failure.
*/
protected boolean addURLToDownload(URL url, String prefix, String subdirectory) {
return addURLToDownload(url, prefix, subdirectory, null, null);
}
/**
* Queues image to be downloaded and saved.
* Uses filename from URL (and 'prefix') to decide filename.
* @param url
* URL to download
* @param prefix
* Text to append to saved filename.
* @return True on success, flase on failure.
*/
protected boolean addURLToDownload(URL url, String prefix) {
// Use empty subdirectory
return addURLToDownload(url, prefix, "");
}
/**
* Waits for downloading threads to complete.
*/
protected void waitForThreads() {
logger.debug("Waiting for threads to finish");
completed = false;
threadPool.waitForThreads();
checkIfComplete();
}
/**
* Notifies observers that source is being retrieved.
* @param url
* URL being retrieved
*/
public void retrievingSource(String url) {
RipStatusMessage msg = new RipStatusMessage(STATUS.LOADING_RESOURCE, url);
if (observer != null) {
observer.update(this, msg);
}
}
/**
* Notifies observers that a file download has completed.
* @param url
* URL that was completed.
* @param saveAs
* Where the downloaded file is stored.
*/
public abstract void downloadCompleted(URL url, File saveAs);
/**
* Notifies observers that a file could not be downloaded (includes a reason).
* @param url
* @param reason
*/
public abstract void downloadErrored(URL url, String reason);
/**
* Notify observers that a download could not be completed,
* but was not technically an "error".
* @param url
* @param file
*/
public abstract void downloadExists(URL url, File file);
/**
* @return Number of files downloaded.
*/
int getCount() {
return 1;
}
/**
* Notifies observers and updates state if all files have been ripped.
*/
void checkIfComplete() {
if (observer == null) {
logger.debug("observer is null");
return;
}
if (!completed) {
completed = true;
logger.info(" Rip completed!");
RipStatusComplete rsc = new RipStatusComplete(workingDir, getCount());
RipStatusMessage msg = new RipStatusMessage(STATUS.RIP_COMPLETE, rsc);
observer.update(this, msg);
Logger rootLogger = Logger.getRootLogger();
FileAppender fa = (FileAppender) rootLogger.getAppender("FILE");
if (fa != null) {
logger.debug("Changing log file back to 'ripme.log'");
fa.setFile("ripme.log");
fa.activateOptions();
}
if (Utils.getConfigBoolean("urls_only.save", false)) {
String urlFile = this.workingDir + File.separator + "urls.txt";
try {
Desktop.getDesktop().open(new File(urlFile));
} catch (IOException e) {
logger.warn("Error while opening " + urlFile, e);
}
}
}
}
/**
* Gets URL
* @return
* Returns URL that wants to be downloaded.
*/
public URL getURL() {
return url;
}
/**
* @return
* Path to the directory in which all files
* ripped via this ripper will be stored.
*/
public File getWorkingDir() {
return workingDir;
}
@Override
public abstract void setWorkingDir(URL url) throws IOException;
/**
*
* @param url
* The URL you want to get the title of.
* @return
* host_URLid
* e.g. (for a reddit post)
* reddit_post_7mg2ur
* @throws MalformedURLException
* If any of those damned URLs gets malformed.
*/
public String getAlbumTitle(URL url) throws MalformedURLException {
return getHost() + "_" + getGID(url);
}
/**
* Finds, instantiates, and returns a compatible ripper for given URL.
* @param url
* URL to rip.
* @return
* Instantiated ripper ready to rip given URL.
* @throws Exception
* If no compatible rippers can be found.
*/
public static AbstractRipper getRipper(URL url) throws Exception {
for (Constructor<?> constructor : getRipperConstructors("com.rarchives.ripme.ripper.rippers")) {
try {
AlbumRipper ripper = (AlbumRipper) constructor.newInstance(url); // by design: can throw ClassCastException
logger.debug("Found album ripper: " + ripper.getClass().getName());
return ripper;
} catch (Exception e) {
// Incompatible rippers *will* throw exceptions during instantiation.
}
}
for (Constructor<?> constructor : getRipperConstructors("com.rarchives.ripme.ripper.rippers.video")) {
try {
VideoRipper ripper = (VideoRipper) constructor.newInstance(url); // by design: can throw ClassCastException
logger.debug("Found video ripper: " + ripper.getClass().getName());
return ripper;
} catch (Exception e) {
// Incompatible rippers *will* throw exceptions during instantiation.
}
}
throw new Exception("No compatible ripper found");
}
/**
* @param pkg
* The package name.
* @return
* List of constructors for all eligible Rippers.
* @throws Exception
*/
public static List<Constructor<?>> getRipperConstructors(String pkg) throws Exception {
List<Constructor<?>> constructors = new ArrayList<>();
for (Class<?> clazz : Utils.getClassesForPackage(pkg)) {
if (AbstractRipper.class.isAssignableFrom(clazz)) {
constructors.add(clazz.getConstructor(URL.class));
}
}
return constructors;
}
/**
* Sends an update message to the relevant observer(s) on this ripper.
* @param status
* @param message
*/
public void sendUpdate(STATUS status, Object message) {
if (observer == null) {
return;
}
observer.update(this, new RipStatusMessage(status, message));
}
/**
* Get the completion percentage.
* @return
* Percentage complete
*/
public abstract int getCompletionPercentage();
/**
* @return
* Text for status
*/
public abstract String getStatusText();
/**
* Rips the album when the thread is invoked.
*/
public void run() {
try {
rip();
} catch (HttpStatusException e) {
logger.error("Got exception while running ripper:", e);
waitForThreads();
sendUpdate(STATUS.RIP_ERRORED, "HTTP status code " + e.getStatusCode() + " for URL " + e.getUrl());
} catch (Exception e) {
logger.error("Got exception while running ripper:", e);
waitForThreads();
sendUpdate(STATUS.RIP_ERRORED, e.getMessage());
} finally {
cleanup();
}
}
/**
* Tries to delete any empty directories
*/
private void cleanup() {
if (this.workingDir.list().length == 0) {
// No files, delete the dir
logger.info("Deleting empty directory " + this.workingDir);
boolean deleteResult = this.workingDir.delete();
if (!deleteResult) {
logger.error("Unable to delete empty directory " + this.workingDir);
}
}
}
/**
* Pauses thread for a set amount of time.
* @param milliseconds
* Amount of time (in milliseconds) that the thread gets paused for
* @return
* True if paused successfully
* False if failed to pause/got interrupted.
*/
protected boolean sleep(int milliseconds) {
try {
logger.debug("Sleeping " + milliseconds + "ms");
Thread.sleep(milliseconds);
return true;
} catch (InterruptedException e) {
logger.error("Interrupted while waiting to load next page", e);
return false;
}
}
public void setBytesTotal(int bytes) {
// Do nothing
}
public void setBytesCompleted(int bytes) {
// Do nothing
}
/** Methods for detecting when we're running a test. */
public void markAsTest() {
logger.debug("THIS IS A TEST RIP");
thisIsATest = true;
}
protected boolean isThisATest() {
return thisIsATest;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.