lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
lgpl-2.1
cf5a75c5fa38cdb5bd1ad13008aa5e2cdf900591
0
CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine
/* * jETeL/CloverETL - Java based ETL application framework. * Copyright (c) Javlin, a.s. ([email protected]) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.jetel.graph; import java.io.IOException; import org.apache.commons.logging.LogFactory; import org.jetel.data.DataRecord; import org.jetel.data.Defaults; import org.jetel.data.DynamicRecordBuffer; import org.jetel.util.bytes.CloverBuffer; /** * A class that represents Edge - data connection between two NODEs. * <p> * This EDGE buffers data in-memory and if this buffer is exhausted then * on disk to allow unlimited buffering for writer. * <p> * It internally allocates two buffers (for reading, writing) of * <code>BUFFERED_EDGE_INTERNAL_BUFFER_SIZE</code>. * * @author David Pavlis, Javlin a.s. &lt;[email protected]&gt; * * @see InputPort * @see OutputPort * * @revision $Revision$ */ public class BufferedEdge extends EdgeBase { private int outputRecordCounter; private int inputRecordCounter; private long byteCounter; private int internalBufferSize; private DynamicRecordBuffer recordBuffer; /** * Constructs an <code>Edge</code> with default internal buffer size. * * @param proxy edge proxy object */ public BufferedEdge(Edge proxy) { this(proxy, Defaults.Graph.BUFFERED_EDGE_INTERNAL_BUFFER_SIZE); } /** * Constructs an <code>Edge</code> with desired internal buffer size. * * @param proxy edge proxy object * @param internalBufferSize the desired size of the internal buffer used for buffering data records */ public BufferedEdge(Edge proxy, int internalBufferSize) { super(proxy); this.internalBufferSize = internalBufferSize; } @Override public int getOutputRecordCounter() { return outputRecordCounter; } @Override public int getInputRecordCounter() { return inputRecordCounter; } @Override public long getOutputByteCounter(){ return byteCounter; } @Override public long getInputByteCounter(){ return byteCounter; } @Override public int getBufferedRecords(){ return recordBuffer.getBufferedRecords(); } @Override public int getUsedMemory() { return recordBuffer.getBufferSize(); } @Override public void init() throws IOException { recordBuffer = new DynamicRecordBuffer(internalBufferSize); recordBuffer.init(); } @Override public void preExecute() { super.preExecute(); outputRecordCounter = 0; inputRecordCounter = 0; byteCounter = 0; } @Override public void postExecute() { super.postExecute(); recordBuffer.reset(); } @Override public DataRecord readRecord(DataRecord record) throws IOException, InterruptedException { DataRecord ret = recordBuffer.readRecord(record); if (ret != null) { inputRecordCounter++; } return ret; } @Override public boolean readRecordDirect(CloverBuffer record) throws IOException, InterruptedException { boolean ret = recordBuffer.readRecord(record); if (ret) { inputRecordCounter++; } return ret; } @Override public void writeRecord(DataRecord record) throws IOException, InterruptedException { byteCounter += recordBuffer.writeRecord(record); outputRecordCounter++; } @Override public void writeRecordDirect(CloverBuffer record) throws IOException, InterruptedException { byteCounter += recordBuffer.writeRecord(record); outputRecordCounter++; } @Override public void eof() throws InterruptedException { try { recordBuffer.setEOF(); } catch (IOException ex) { throw new RuntimeException("Error when closing BufferedEdge: " + ex.getMessage(), ex); } } @Override public boolean isEOF() { return recordBuffer.isClosed(); } @Override public void free() { try { recordBuffer.close(); } catch (IOException ex) { LogFactory.getLog(getClass()).warn("Error closing the record buffer!", ex); } } @Override public boolean hasData() { return recordBuffer.hasData(); } public void setInternalBufferSize(int internalBufferSize) { if (internalBufferSize > Defaults.Graph.BUFFERED_EDGE_INTERNAL_BUFFER_SIZE) { this.internalBufferSize = internalBufferSize; } } }
cloveretl.engine/src/org/jetel/graph/BufferedEdge.java
/* * jETeL/CloverETL - Java based ETL application framework. * Copyright (c) Javlin, a.s. ([email protected]) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.jetel.graph; import java.io.IOException; import org.apache.commons.logging.LogFactory; import org.jetel.data.DataRecord; import org.jetel.data.Defaults; import org.jetel.data.DynamicRecordBuffer; import org.jetel.util.bytes.CloverBuffer; /** * A class that represents Edge - data connection between two NODEs. * <p> * This EDGE buffers data in-memory and if this buffer is exhausted then * on disk to allow unlimited buffering for writer. * <p> * It internally allocates two buffers (for reading, writing) of * <code>BUFFERED_EDGE_INTERNAL_BUFFER_SIZE</code>. * * @author David Pavlis, Javlin a.s. &lt;[email protected]&gt; * * @see InputPort * @see OutputPort * * @revision $Revision$ */ public class BufferedEdge extends EdgeBase { private int outputRecordCounter; private int inputRecordCounter; private long byteCounter; private int internalBufferSize; private DynamicRecordBuffer recordBuffer; /** * Constructs an <code>Edge</code> with default internal buffer size. * * @param proxy edge proxy object */ public BufferedEdge(Edge proxy) { this(proxy, Defaults.Graph.BUFFERED_EDGE_INTERNAL_BUFFER_SIZE); } /** * Constructs an <code>Edge</code> with desired internal buffer size. * * @param proxy edge proxy object * @param internalBufferSize the desired size of the internal buffer used for buffering data records */ public BufferedEdge(Edge proxy, int internalBufferSize) { super(proxy); this.internalBufferSize = internalBufferSize; } @Override public int getOutputRecordCounter() { return outputRecordCounter; } @Override public int getInputRecordCounter() { return inputRecordCounter; } @Override public long getOutputByteCounter(){ return byteCounter; } @Override public long getInputByteCounter(){ return byteCounter; } @Override public int getBufferedRecords(){ return recordBuffer.getBufferedRecords(); } @Override public int getUsedMemory() { return recordBuffer.getBufferSize(); } @Override public void init() throws IOException { recordBuffer = new DynamicRecordBuffer(internalBufferSize); recordBuffer.init(); outputRecordCounter = 0; inputRecordCounter = 0; byteCounter = 0; } @Override public void reset() { recordBuffer.reset(); outputRecordCounter = 0; inputRecordCounter = 0; byteCounter = 0; } @Override public DataRecord readRecord(DataRecord record) throws IOException, InterruptedException { DataRecord ret = recordBuffer.readRecord(record); if (ret != null) { inputRecordCounter++; } return ret; } @Override public boolean readRecordDirect(CloverBuffer record) throws IOException, InterruptedException { boolean ret = recordBuffer.readRecord(record); if (ret) { inputRecordCounter++; } return ret; } @Override public void writeRecord(DataRecord record) throws IOException, InterruptedException { byteCounter += recordBuffer.writeRecord(record); outputRecordCounter++; } @Override public void writeRecordDirect(CloverBuffer record) throws IOException, InterruptedException { byteCounter += recordBuffer.writeRecord(record); outputRecordCounter++; } @Override public void eof() throws InterruptedException { try { recordBuffer.setEOF(); } catch (IOException ex) { throw new RuntimeException("Error when closing BufferedEdge: " + ex.getMessage(), ex); } } @Override public boolean isEOF() { return recordBuffer.isClosed(); } @Override public void free() { try { recordBuffer.close(); } catch (IOException ex) { LogFactory.getLog(getClass()).warn("Error closing the record buffer!", ex); } } @Override public boolean hasData() { return recordBuffer.hasData(); } public void setInternalBufferSize(int internalBufferSize) { if (internalBufferSize > Defaults.Graph.BUFFERED_EDGE_INTERNAL_BUFFER_SIZE) { this.internalBufferSize = internalBufferSize; } } }
FIX: CL-2693 BufferedEdge leaves open files after postExecute() BufferedEdge.reset() code has been moved to BufferedEdge.preExecute() and to BufferedEdge.postExecute() git-svn-id: ea4e32a9c087aaafabd002c256df6ce060387585@13610 a09ad3ba-1a0f-0410-b1b9-c67202f10d70
cloveretl.engine/src/org/jetel/graph/BufferedEdge.java
FIX: CL-2693 BufferedEdge leaves open files after postExecute()
<ide><path>loveretl.engine/src/org/jetel/graph/BufferedEdge.java <ide> public void init() throws IOException { <ide> recordBuffer = new DynamicRecordBuffer(internalBufferSize); <ide> recordBuffer.init(); <add> } <add> <add> @Override <add> public void preExecute() { <add> super.preExecute(); <add> <ide> outputRecordCounter = 0; <ide> inputRecordCounter = 0; <ide> byteCounter = 0; <ide> } <add> <add> @Override <add> public void postExecute() { <add> super.postExecute(); <ide> <del> @Override <del> public void reset() { <del> recordBuffer.reset(); <del> outputRecordCounter = 0; <del> inputRecordCounter = 0; <del> byteCounter = 0; <add> recordBuffer.reset(); <ide> } <del> <add> <ide> @Override <ide> public DataRecord readRecord(DataRecord record) throws IOException, InterruptedException { <ide> DataRecord ret = recordBuffer.readRecord(record);
Java
apache-2.0
29dfe2bcb8f01a2f004c40f5613116946b47b173
0
ahb0327/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,semonte/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,clumsy/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,semonte/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,holmes/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,ibinti/intellij-community,samthor/intellij-community,fnouama/intellij-community,slisson/intellij-community,youdonghai/intellij-community,caot/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,diorcety/intellij-community,joewalnes/idea-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,joewalnes/idea-community,blademainer/intellij-community,slisson/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,fnouama/intellij-community,kool79/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,signed/intellij-community,jagguli/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,Lekanich/intellij-community,consulo/consulo,wreckJ/intellij-community,ahb0327/intellij-community,da1z/intellij-community,slisson/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,da1z/intellij-community,petteyg/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,retomerz/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,FHannes/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,ryano144/intellij-community,hurricup/intellij-community,ernestp/consulo,michaelgallacher/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,da1z/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,apixandru/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,kdwink/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,hurricup/intellij-community,caot/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,hurricup/intellij-community,retomerz/intellij-community,kool79/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,holmes/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,amith01994/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,joewalnes/idea-community,joewalnes/idea-community,signed/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,dslomov/intellij-community,robovm/robovm-studio,dslomov/intellij-community,fitermay/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,apixandru/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,semonte/intellij-community,caot/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,samthor/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,ernestp/consulo,allotria/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,robovm/robovm-studio,kdwink/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,joewalnes/idea-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,asedunov/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,joewalnes/idea-community,SerCeMan/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,kool79/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,nicolargo/intellij-community,samthor/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,izonder/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,fnouama/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,signed/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,joewalnes/idea-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,holmes/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,joewalnes/idea-community,jagguli/intellij-community,fitermay/intellij-community,ryano144/intellij-community,asedunov/intellij-community,kool79/intellij-community,FHannes/intellij-community,ernestp/consulo,amith01994/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,fitermay/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,nicolargo/intellij-community,slisson/intellij-community,signed/intellij-community,diorcety/intellij-community,petteyg/intellij-community,da1z/intellij-community,amith01994/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,samthor/intellij-community,ibinti/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,da1z/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,izonder/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,supersven/intellij-community,adedayo/intellij-community,semonte/intellij-community,kdwink/intellij-community,retomerz/intellij-community,signed/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,ernestp/consulo,semonte/intellij-community,TangHao1987/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,clumsy/intellij-community,kool79/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,consulo/consulo,michaelgallacher/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,apixandru/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,diorcety/intellij-community,diorcety/intellij-community,caot/intellij-community,signed/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,allotria/intellij-community,allotria/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,hurricup/intellij-community,asedunov/intellij-community,clumsy/intellij-community,ryano144/intellij-community,signed/intellij-community,supersven/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,caot/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,apixandru/intellij-community,caot/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,robovm/robovm-studio,hurricup/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,slisson/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,holmes/intellij-community,vvv1559/intellij-community,izonder/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,fitermay/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,slisson/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,signed/intellij-community,blademainer/intellij-community,consulo/consulo,clumsy/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,caot/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,samthor/intellij-community,vladmm/intellij-community,ryano144/intellij-community,da1z/intellij-community,caot/intellij-community,dslomov/intellij-community,fnouama/intellij-community,amith01994/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,signed/intellij-community,ibinti/intellij-community,izonder/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,allotria/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,samthor/intellij-community,FHannes/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,asedunov/intellij-community,da1z/intellij-community,Lekanich/intellij-community,consulo/consulo,semonte/intellij-community,clumsy/intellij-community,supersven/intellij-community,slisson/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,holmes/intellij-community,robovm/robovm-studio,vladmm/intellij-community,diorcety/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,joewalnes/idea-community,robovm/robovm-studio,clumsy/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,caot/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,ernestp/consulo,retomerz/intellij-community,izonder/intellij-community,semonte/intellij-community,caot/intellij-community,retomerz/intellij-community,fitermay/intellij-community,diorcety/intellij-community,allotria/intellij-community,izonder/intellij-community,fitermay/intellij-community,signed/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,izonder/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,ernestp/consulo,samthor/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,da1z/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,kool79/intellij-community,ryano144/intellij-community,caot/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,FHannes/intellij-community,blademainer/intellij-community,clumsy/intellij-community,consulo/consulo,wreckJ/intellij-community,xfournet/intellij-community,jagguli/intellij-community,semonte/intellij-community,samthor/intellij-community,holmes/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,amith01994/intellij-community,ryano144/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,slisson/intellij-community,fitermay/intellij-community,asedunov/intellij-community,xfournet/intellij-community,ibinti/intellij-community,robovm/robovm-studio,hurricup/intellij-community,semonte/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,consulo/consulo,ol-loginov/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,supersven/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,allotria/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,akosyakov/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,xfournet/intellij-community
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.testFramework; import com.intellij.ProjectTopics; import com.intellij.codeHighlighting.HighlightDisplayLevel; import com.intellij.codeInsight.completion.CompletionProgressIndicator; import com.intellij.codeInsight.daemon.HighlightDisplayKey; import com.intellij.codeInsight.lookup.LookupManager; import com.intellij.codeInspection.InspectionProfileEntry; import com.intellij.codeInspection.LocalInspectionTool; import com.intellij.codeInspection.ex.InspectionProfileImpl; import com.intellij.codeInspection.ex.InspectionTool; import com.intellij.codeInspection.ex.LocalInspectionToolWrapper; import com.intellij.codeInspection.ex.ToolsImpl; import com.intellij.ide.highlighter.ProjectFileType; import com.intellij.ide.startup.impl.StartupManagerImpl; import com.intellij.idea.IdeaLogger; import com.intellij.idea.IdeaTestApplication; import com.intellij.lang.injection.InjectedLanguageManager; import com.intellij.openapi.actionSystem.DataProvider; import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.impl.UndoManagerImpl; import com.intellij.openapi.command.undo.UndoManager; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.impl.FileDocumentManagerImpl; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.module.EmptyModuleType; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.module.ModuleType; import com.intellij.openapi.project.ModuleListener; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.project.ex.ProjectEx; import com.intellij.openapi.project.ex.ProjectManagerEx; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.*; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.encoding.EncodingManager; import com.intellij.openapi.vfs.encoding.EncodingManagerImpl; import com.intellij.openapi.vfs.newvfs.ManagingFS; import com.intellij.openapi.vfs.newvfs.persistent.PersistentFS; import com.intellij.profile.codeInspection.InspectionProfileManager; import com.intellij.profile.codeInspection.InspectionProjectProfileManager; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.psi.impl.PsiDocumentManagerImpl; import com.intellij.psi.impl.PsiManagerImpl; import com.intellij.psi.impl.source.tree.injected.InjectedLanguageManagerImpl; import com.intellij.util.IncorrectOperationException; import com.intellij.util.LocalTimeCounter; import com.intellij.util.indexing.FileBasedIndex; import com.intellij.util.indexing.IndexableFileSet; import com.intellij.util.messages.MessageBusConnection; import gnu.trove.THashMap; import junit.framework.TestCase; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; /** * @author yole */ public abstract class LightPlatformTestCase extends UsefulTestCase implements DataProvider { public static final String PROFILE = "Configurable"; private static IdeaTestApplication ourApplication; protected static Project ourProject; private static Module ourModule; private static PsiManager ourPsiManager; private static boolean ourAssertionsInTestDetected; private static VirtualFile ourSourceRoot; private static TestCase ourTestCase = null; public static Thread ourTestThread; private static LightProjectDescriptor ourProjectDescriptor; private final Map<String, InspectionTool> myAvailableInspectionTools = new THashMap<String, InspectionTool>(); private static boolean ourHaveShutdownHook; private ThreadTracker myThreadTracker; /** * @return Project to be used in tests for example for project components retrieval. */ public static Project getProject() { return ourProject; } /** * @return Module to be used in tests for example for module components retrieval. */ public static Module getModule() { return ourModule; } /** * Shortcut to PsiManager.getInstance(getProject()) */ public static PsiManager getPsiManager() { if (ourPsiManager == null) { ourPsiManager = PsiManager.getInstance(ourProject); } return ourPsiManager; } public static void initApplication(final DataProvider dataProvider) throws Exception { ourApplication = IdeaTestApplication.getInstance(null); ourApplication.setDataProvider(dataProvider); } public static IdeaTestApplication getApplication() { return ourApplication; } protected void resetAllFields() { resetClassFields(getClass()); } private void resetClassFields(final Class<?> aClass) { try { UsefulTestCase.clearDeclaredFields(this, aClass); } catch (IllegalAccessException e) { throw new RuntimeException(e); } if (aClass == LightPlatformTestCase.class) return; resetClassFields(aClass.getSuperclass()); } private static void cleanPersistedVFSContent() { ((PersistentFS)ManagingFS.getInstance()).cleanPersistedContents(); } private static void initProject(final LightProjectDescriptor descriptor) throws Exception { ourProjectDescriptor = descriptor; final File projectFile = File.createTempFile("lighttemp", ProjectFileType.DOT_DEFAULT_EXTENSION); ApplicationManager.getApplication().runWriteAction(new Runnable() { @SuppressWarnings({"AssignmentToStaticFieldFromInstanceMethod"}) public void run() { if (ourProject != null) { closeAndDeleteProject(); } else { cleanPersistedVFSContent(); } LocalFileSystem.getInstance().refreshAndFindFileByIoFile(projectFile); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); new Throwable(projectFile.getPath()).printStackTrace(new PrintStream(buffer)); ourProject = PlatformTestCase.createProject(projectFile, buffer.toString()); if (!ourHaveShutdownHook) { ourHaveShutdownHook = true; registerShutdownHook(); } ourPsiManager = null; ourModule = createMainModule(descriptor.getModuleType()); //ourSourceRoot = DummyFileSystem.getInstance().createRoot("src"); final VirtualFile dummyRoot = VirtualFileManager.getInstance().findFileByUrl("temp:///"); dummyRoot.refresh(false, false); try { ourSourceRoot = dummyRoot.createChildDirectory(this, "src"); } catch (IOException e) { throw new RuntimeException(e); } FileBasedIndex.getInstance().registerIndexableSet(new IndexableFileSet() { public boolean isInSet(final VirtualFile file) { return ourSourceRoot != null && file.getFileSystem() == ourSourceRoot.getFileSystem(); } public void iterateIndexableFilesIn(final VirtualFile file, final ContentIterator iterator) { if (file.isDirectory()) { for (VirtualFile child : file.getChildren()) { iterateIndexableFilesIn(child, iterator); } } else { iterator.processFile(file); } } }); final ModuleRootManager rootManager = ModuleRootManager.getInstance(ourModule); final ModifiableRootModel rootModel = rootManager.getModifiableModel(); if (descriptor.getSdk() != null) { rootModel.setSdk(descriptor.getSdk()); } final ContentEntry contentEntry = rootModel.addContentEntry(ourSourceRoot); contentEntry.addSourceFolder(ourSourceRoot, false); descriptor.configureModule(ourModule, rootModel, contentEntry); rootModel.commit(); final MessageBusConnection connection = ourProject.getMessageBus().connect(); connection.subscribe(ProjectTopics.PROJECT_ROOTS, new ModuleRootListener() { public void beforeRootsChange(ModuleRootEvent event) { if (!event.isCausedByFileTypesChange()) { fail("Root modification in LightIdeaTestCase is not allowed."); } } public void rootsChanged(ModuleRootEvent event) {} }); connection.subscribe(ProjectTopics.MODULES, new ModuleListener() { public void moduleAdded(Project project, Module module) { fail("Adding modules is not permitted in LightIdeaTestCase."); } public void beforeModuleRemoved(Project project, Module module) {} public void moduleRemoved(Project project, Module module) {} public void modulesRenamed(Project project, List<Module> modules) {} }); ((StartupManagerImpl)StartupManager.getInstance(getProject())).runStartupActivities(); } }); } protected static Module createMainModule(final ModuleType moduleType) { return ApplicationManager.getApplication().runWriteAction(new Computable<Module>() { public Module compute() { return ModuleManager.getInstance(ourProject).newModule("light_idea_test_case.iml", moduleType); } }); } /** * @return The only source root */ public static VirtualFile getSourceRoot() { return ourSourceRoot; } protected void setUp() throws Exception { super.setUp(); initApplication(this); doSetup(new SimpleLightProjectDescriptor(getModuleType(), getProjectJDK()), configureLocalInspectionTools(), myAvailableInspectionTools); ((InjectedLanguageManagerImpl)InjectedLanguageManager.getInstance(getProject())).pushInjectors(); storeSettings(); myThreadTracker = new ThreadTracker(); } public static void doSetup(final LightProjectDescriptor descriptor, final LocalInspectionTool[] localInspectionTools, final Map<String, InspectionTool> availableInspectionTools) throws Exception { assertNull("Previous test " + ourTestCase + " hasn't called tearDown(). Probably overriden without super call.", ourTestCase); IdeaLogger.ourErrorsOccurred = null; if (ourProject == null || !ourProjectDescriptor.equals(descriptor)) { initProject(descriptor); } ProjectManagerEx.getInstanceEx().setCurrentTestProject(ourProject); ((PsiDocumentManagerImpl)PsiDocumentManager.getInstance(getProject())).clearUncommitedDocuments(); for (LocalInspectionTool tool : localInspectionTools) { enableInspectionTool(availableInspectionTools, new LocalInspectionToolWrapper(tool)); } final InspectionProfileImpl profile = new InspectionProfileImpl("Configurable") { @NotNull public InspectionProfileEntry[] getInspectionTools(PsiElement element) { if (availableInspectionTools != null){ final Collection<InspectionTool> tools = availableInspectionTools.values(); return tools.toArray(new InspectionTool[tools.size()]); } return new InspectionTool[0]; } @Override public List<ToolsImpl> getAllEnabledInspectionTools() { List<ToolsImpl> result = new ArrayList<ToolsImpl>(); for (InspectionProfileEntry entry : getInspectionTools(null)) { result.add(new ToolsImpl(entry, entry.getDefaultLevel(), true)); } return result; } public boolean isToolEnabled(HighlightDisplayKey key, PsiElement element) { return key != null && availableInspectionTools.containsKey(key.toString()); } public HighlightDisplayLevel getErrorLevel(@NotNull HighlightDisplayKey key, PsiElement element) { InspectionTool localInspectionTool = availableInspectionTools.get(key.toString()); return localInspectionTool != null ? localInspectionTool.getDefaultLevel() : HighlightDisplayLevel.WARNING; } public InspectionTool getInspectionTool(@NotNull String shortName, @NotNull PsiElement element) { if (availableInspectionTools.containsKey(shortName)) { return availableInspectionTools.get(shortName); } return null; } }; final InspectionProfileManager inspectionProfileManager = InspectionProfileManager.getInstance(); inspectionProfileManager.addProfile(profile); inspectionProfileManager.setRootProfile(profile.getName()); InspectionProjectProfileManager.getInstance(getProject()).updateProfile(profile); InspectionProjectProfileManager.getInstance(getProject()).setProjectProfile(profile.getName()); assertFalse(getPsiManager().isDisposed()); CodeStyleSettingsManager.getInstance(getProject()).setTemporarySettings(new CodeStyleSettings()); } protected void enableInspectionTool(LocalInspectionTool tool){ enableInspectionTool(new LocalInspectionToolWrapper(tool)); } protected void enableInspectionTool(InspectionTool tool){ enableInspectionTool(myAvailableInspectionTools, tool); } private static void enableInspectionTool(final Map<String, InspectionTool> availableLocalTools, InspectionTool wrapper) { final String shortName = wrapper.getShortName(); final HighlightDisplayKey key = HighlightDisplayKey.find(shortName); if (key == null){ HighlightDisplayKey.register(shortName, wrapper.getDisplayName(), wrapper instanceof LocalInspectionToolWrapper ? ((LocalInspectionToolWrapper)wrapper).getTool().getID() : wrapper.getShortName()); } availableLocalTools.put(shortName, wrapper); } protected LocalInspectionTool[] configureLocalInspectionTools() { return new LocalInspectionTool[0]; } protected void tearDown() throws Exception { CodeStyleSettingsManager.getInstance(getProject()).dropTemporarySettings(); checkForSettingsDamage(); doTearDown(getProject(), ourApplication, true); super.tearDown(); myThreadTracker.checkLeak(); checkInjectorsAreDisposed(); } public static void doTearDown(Project project, IdeaTestApplication application, boolean checkForEditors) throws Exception { checkAllTimersAreDisposed(); UsefulTestCase.doPostponedFormatting(project); LookupManager lookupManager = LookupManager.getInstance(project); if (lookupManager != null) { lookupManager.hideActiveLookup(); } ((StartupManagerImpl)StartupManager.getInstance(project)).prepareForNextTest(); InspectionProfileManager.getInstance().deleteProfile(PROFILE); assertNotNull("Application components damaged", ProjectManager.getInstance()); ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { if (ourSourceRoot != null) { try { final VirtualFile[] children = ourSourceRoot.getChildren(); for (VirtualFile child : children) { child.delete(this); } } catch (IOException e) { //noinspection CallToPrintStackTrace e.printStackTrace(); } } EncodingManager encodingManager = EncodingManager.getInstance(); if (encodingManager instanceof EncodingManagerImpl) ((EncodingManagerImpl)encodingManager).drainDocumentQueue(); FileDocumentManager manager = FileDocumentManager.getInstance(); if (manager instanceof FileDocumentManagerImpl) { ((FileDocumentManagerImpl)manager).dropAllUnsavedDocuments(); } ApplicationManager.getApplication().runWriteAction(EmptyRunnable.getInstance()); // Flash posponed formatting if any. manager.saveAllDocuments(); } }); assertFalse(PsiManager.getInstance(project).isDisposed()); if (!ourAssertionsInTestDetected) { if (IdeaLogger.ourErrorsOccurred != null) { throw IdeaLogger.ourErrorsOccurred; } } ((PsiDocumentManagerImpl)PsiDocumentManager.getInstance(project)).clearUncommitedDocuments(); Runnable runnable = new Runnable() { public void run() { ((UndoManagerImpl)UndoManager.getGlobalInstance()).dropHistoryInTests(); } }; if (ApplicationManager.getApplication().isDispatchThread()) { runnable.run(); } else { SwingUtilities.invokeAndWait(runnable); } ProjectManagerEx.getInstanceEx().setCurrentTestProject(null); application.setDataProvider(null); ourTestCase = null; ((PsiManagerImpl)PsiManager.getInstance(project)).cleanupForNextTest(); CompletionProgressIndicator.cleanupForNextTest(); if (checkForEditors) { checkEditorsReleased(); } } public static void checkEditorsReleased() { final Editor[] allEditors = EditorFactory.getInstance().getAllEditors(); if (allEditors.length > 0) { for (Editor allEditor : allEditors) { EditorFactory.getInstance().releaseEditor(allEditor); } fail("Unreleased editors: " + allEditors.length); } } private static void checkInjectorsAreDisposed() { ((InjectedLanguageManagerImpl)InjectedLanguageManager.getInstance(getProject())).checkInjectorsAreDisposed(); } public final void runBare() throws Throwable { final Throwable[] throwables = new Throwable[1]; SwingUtilities.invokeAndWait(new Runnable() { public void run() { try { ourTestThread = Thread.currentThread(); startRunAndTear(); } catch (Throwable throwable) { throwables[0] = throwable; } finally { ourTestThread = null; try { PlatformTestCase.cleanupApplicationCaches(ourProject); resetAllFields(); } catch (Throwable e) { e.printStackTrace(); } } } }); if (throwables[0] != null) { throw throwables[0]; } // just to make sure all deffered Runnable's to finish SwingUtilities.invokeAndWait(EmptyRunnable.getInstance()); if (IdeaLogger.ourErrorsOccurred != null) { throw IdeaLogger.ourErrorsOccurred; } } private void startRunAndTear() throws Throwable { setUp(); try { ourAssertionsInTestDetected = true; runTest(); ourAssertionsInTestDetected = false; } finally { //try{ tearDown(); //} //catch(Throwable th){ // noinspection CallToPrintStackTrace //th.printStackTrace(); //} } } public Object getData(String dataId) { if (PlatformDataKeys.PROJECT.is(dataId)) { return ourProject; } return null; } protected Sdk getProjectJDK() { return null; } protected ModuleType getModuleType() { return EmptyModuleType.getInstance(); } /** * Creates dummy source file. One is not placed under source root so some PSI functions like resolve to external classes * may not work. Though it works significantly faster and yet can be used if you need to create some PSI structures for * test purposes * * @param fileName - name of the file to create. Extension is used to choose what PSI should be created like java, jsp, aj, xml etc. * @param text - file text. * @return dummy psi file. * @throws com.intellij.util.IncorrectOperationException */ protected static PsiFile createFile(@NonNls String fileName, String text) throws IncorrectOperationException { return createPseudoPhysicalFile(fileName, text); } protected static PsiFile createLightFile(String fileName, String text) throws IncorrectOperationException { return PsiFileFactory.getInstance(getProject()).createFileFromText(fileName, FileTypeManager.getInstance().getFileTypeByFileName( fileName), text, LocalTimeCounter.currentTime(), false); } protected static PsiFile createPseudoPhysicalFile(@NonNls String fileName, String text) throws IncorrectOperationException { FileType fileType = FileTypeManager.getInstance().getFileTypeByFileName(fileName); return PsiFileFactory.getInstance(getProject()).createFileFromText(fileName, fileType, text, LocalTimeCounter.currentTime(), true); } /** * Convinient conversion of testSomeTest -> someTest | SomeTest where testSomeTest is the name of current test. * * @param lowercaseFirstLetter - whether first letter after test should be lowercased. */ protected String getTestName(boolean lowercaseFirstLetter) { String name = getName(); assertTrue("Test name should start with 'test'", name.startsWith("test")); name = name.substring("test".length()); if (lowercaseFirstLetter && !UsefulTestCase.isAllUppercaseName(name)) { name = Character.toLowerCase(name.charAt(0)) + name.substring(1); } return name; } protected static void commitDocument(final Document document) { PsiDocumentManager.getInstance(getProject()).commitDocument(document); } protected static void commitAllDocuments() { PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); } @Override protected CodeStyleSettings getCurrentCodeStyleSettings() { return CodeStyleSettingsManager.getSettings(getProject()); } protected static Document getDocument(final PsiFile file) { return PsiDocumentManager.getInstance(getProject()).getDocument(file); } protected static synchronized void closeAndDeleteProject() { if (ourProject != null) { final VirtualFile projFile = ((ProjectEx)ourProject).getStateStore().getProjectFile(); final File projectFile = projFile == null ? null : VfsUtil.virtualToIoFile(projFile); if (!ourProject.isDisposed()) Disposer.dispose(ourProject); if (projectFile != null) { FileUtil.delete(projectFile); } } } static { System.setProperty("jbdt.test.fixture", "com.intellij.designer.dt.IJTestFixture"); } private static void registerShutdownHook() { ShutDownTracker.getInstance().registerShutdownTask(new Runnable() { public void run() { try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { closeAndDeleteProject(); } }); } catch (InterruptedException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }); } private static class SimpleLightProjectDescriptor implements LightProjectDescriptor { private final ModuleType myModuleType; private final Sdk mySdk; SimpleLightProjectDescriptor(ModuleType moduleType, Sdk sdk) { myModuleType = moduleType; mySdk = sdk; } public ModuleType getModuleType() { return myModuleType; } public Sdk getSdk() { return mySdk; } public void configureModule(Module module, ModifiableRootModel model, ContentEntry contentEntry) { } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SimpleLightProjectDescriptor that = (SimpleLightProjectDescriptor)o; if (myModuleType != null ? !myModuleType.equals(that.myModuleType) : that.myModuleType != null) return false; return !isJDKChanged(that.getSdk()); } @Override public int hashCode() { int result = myModuleType != null ? myModuleType.hashCode() : 0; result = 31 * result + (mySdk != null ? mySdk.hashCode() : 0); return result; } private boolean isJDKChanged(final Sdk newJDK) { if (mySdk == null && newJDK == null) return false; return mySdk == null || newJDK == null || !Comparing.equal(mySdk.getVersionString(), newJDK.getVersionString()); } } }
platform/testFramework/src/com/intellij/testFramework/LightPlatformTestCase.java
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.testFramework; import com.intellij.ProjectTopics; import com.intellij.codeHighlighting.HighlightDisplayLevel; import com.intellij.codeInsight.completion.CompletionProgressIndicator; import com.intellij.codeInsight.daemon.HighlightDisplayKey; import com.intellij.codeInsight.lookup.LookupManager; import com.intellij.codeInspection.InspectionProfileEntry; import com.intellij.codeInspection.LocalInspectionTool; import com.intellij.codeInspection.ex.InspectionProfileImpl; import com.intellij.codeInspection.ex.InspectionTool; import com.intellij.codeInspection.ex.LocalInspectionToolWrapper; import com.intellij.codeInspection.ex.ToolsImpl; import com.intellij.ide.highlighter.ProjectFileType; import com.intellij.ide.startup.impl.StartupManagerImpl; import com.intellij.idea.IdeaLogger; import com.intellij.idea.IdeaTestApplication; import com.intellij.lang.injection.InjectedLanguageManager; import com.intellij.openapi.actionSystem.DataProvider; import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.impl.UndoManagerImpl; import com.intellij.openapi.command.undo.UndoManager; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.impl.FileDocumentManagerImpl; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.module.EmptyModuleType; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.module.ModuleType; import com.intellij.openapi.project.ModuleListener; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.project.ex.ProjectEx; import com.intellij.openapi.project.ex.ProjectManagerEx; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.*; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.encoding.EncodingManager; import com.intellij.openapi.vfs.encoding.EncodingManagerImpl; import com.intellij.openapi.vfs.newvfs.ManagingFS; import com.intellij.openapi.vfs.newvfs.persistent.PersistentFS; import com.intellij.profile.codeInspection.InspectionProfileManager; import com.intellij.profile.codeInspection.InspectionProjectProfileManager; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.psi.impl.PsiDocumentManagerImpl; import com.intellij.psi.impl.PsiManagerImpl; import com.intellij.psi.impl.source.tree.injected.InjectedLanguageManagerImpl; import com.intellij.util.IncorrectOperationException; import com.intellij.util.LocalTimeCounter; import com.intellij.util.indexing.FileBasedIndex; import com.intellij.util.indexing.IndexableFileSet; import com.intellij.util.messages.MessageBusConnection; import gnu.trove.THashMap; import junit.framework.TestCase; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; /** * @author yole */ public abstract class LightPlatformTestCase extends UsefulTestCase implements DataProvider { public static final String PROFILE = "Configurable"; private static IdeaTestApplication ourApplication; protected static Project ourProject; private static Module ourModule; private static PsiManager ourPsiManager; private static boolean ourAssertionsInTestDetected; private static VirtualFile ourSourceRoot; private static TestCase ourTestCase = null; public static Thread ourTestThread; private static LightProjectDescriptor ourProjectDescriptor; private final Map<String, InspectionTool> myAvailableInspectionTools = new THashMap<String, InspectionTool>(); private static boolean ourHaveShutdownHook; private ThreadTracker myThreadTracker; /** * @return Project to be used in tests for example for project components retrieval. */ public static Project getProject() { return ourProject; } /** * @return Module to be used in tests for example for module components retrieval. */ public static Module getModule() { return ourModule; } /** * Shortcut to PsiManager.getInstance(getProject()) */ public static PsiManager getPsiManager() { if (ourPsiManager == null) { ourPsiManager = PsiManager.getInstance(ourProject); } return ourPsiManager; } public static void initApplication(final DataProvider dataProvider) throws Exception { ourApplication = IdeaTestApplication.getInstance(null); ourApplication.setDataProvider(dataProvider); } public static IdeaTestApplication getApplication() { return ourApplication; } protected void resetAllFields() { resetClassFields(getClass()); } private void resetClassFields(final Class<?> aClass) { try { UsefulTestCase.clearDeclaredFields(this, aClass); } catch (IllegalAccessException e) { throw new RuntimeException(e); } if (aClass == LightPlatformTestCase.class) return; resetClassFields(aClass.getSuperclass()); } private static void cleanPersistedVFSContent() { ((PersistentFS)ManagingFS.getInstance()).cleanPersistedContents(); } private static void initProject(final LightProjectDescriptor descriptor) throws Exception { ourProjectDescriptor = descriptor; final File projectFile = File.createTempFile("lighttemp", ProjectFileType.DOT_DEFAULT_EXTENSION); ApplicationManager.getApplication().runWriteAction(new Runnable() { @SuppressWarnings({"AssignmentToStaticFieldFromInstanceMethod"}) public void run() { if (ourProject != null) { closeAndDeleteProject(); } else { cleanPersistedVFSContent(); } LocalFileSystem.getInstance().refreshAndFindFileByIoFile(projectFile); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); new Throwable(projectFile.getPath()).printStackTrace(new PrintStream(buffer)); ourProject = PlatformTestCase.createProject(projectFile, buffer.toString()); if (!ourHaveShutdownHook) { ourHaveShutdownHook = true; registerShutdownHook(); } ourPsiManager = null; ourModule = createMainModule(descriptor.getModuleType()); //ourSourceRoot = DummyFileSystem.getInstance().createRoot("src"); final VirtualFile dummyRoot = VirtualFileManager.getInstance().findFileByUrl("temp:///"); dummyRoot.refresh(false, false); try { ourSourceRoot = dummyRoot.createChildDirectory(this, "src"); } catch (IOException e) { throw new RuntimeException(e); } FileBasedIndex.getInstance().registerIndexableSet(new IndexableFileSet() { public boolean isInSet(final VirtualFile file) { return ourSourceRoot != null && file.getFileSystem() == ourSourceRoot.getFileSystem(); } public void iterateIndexableFilesIn(final VirtualFile file, final ContentIterator iterator) { if (file.isDirectory()) { for (VirtualFile child : file.getChildren()) { iterateIndexableFilesIn(child, iterator); } } else { iterator.processFile(file); } } }); final ModuleRootManager rootManager = ModuleRootManager.getInstance(ourModule); final ModifiableRootModel rootModel = rootManager.getModifiableModel(); if (descriptor.getSdk() != null) { rootModel.setSdk(descriptor.getSdk()); } final ContentEntry contentEntry = rootModel.addContentEntry(ourSourceRoot); contentEntry.addSourceFolder(ourSourceRoot, false); descriptor.configureModule(ourModule, rootModel, contentEntry); rootModel.commit(); final MessageBusConnection connection = ourProject.getMessageBus().connect(); connection.subscribe(ProjectTopics.PROJECT_ROOTS, new ModuleRootListener() { public void beforeRootsChange(ModuleRootEvent event) { if (!event.isCausedByFileTypesChange()) { fail("Root modification in LightIdeaTestCase is not allowed."); } } public void rootsChanged(ModuleRootEvent event) {} }); connection.subscribe(ProjectTopics.MODULES, new ModuleListener() { public void moduleAdded(Project project, Module module) { fail("Adding modules is not permitted in LightIdeaTestCase."); } public void beforeModuleRemoved(Project project, Module module) {} public void moduleRemoved(Project project, Module module) {} public void modulesRenamed(Project project, List<Module> modules) {} }); ((StartupManagerImpl)StartupManager.getInstance(getProject())).runStartupActivities(); } }); } protected static Module createMainModule(final ModuleType moduleType) { return ApplicationManager.getApplication().runWriteAction(new Computable<Module>() { public Module compute() { return ModuleManager.getInstance(ourProject).newModule("light_idea_test_case.iml", moduleType); } }); } /** * @return The only source root */ public static VirtualFile getSourceRoot() { return ourSourceRoot; } protected void setUp() throws Exception { super.setUp(); initApplication(this); doSetup(new SimpleLightProjectDescriptor(getModuleType(), getProjectJDK()), configureLocalInspectionTools(), myAvailableInspectionTools); ((InjectedLanguageManagerImpl)InjectedLanguageManager.getInstance(getProject())).pushInjectors(); storeSettings(); myThreadTracker = new ThreadTracker(); } public static void doSetup(final LightProjectDescriptor descriptor, final LocalInspectionTool[] localInspectionTools, final Map<String, InspectionTool> availableInspectionTools) throws Exception { assertNull("Previous test " + ourTestCase + " hasn't called tearDown(). Probably overriden without super call.", ourTestCase); IdeaLogger.ourErrorsOccurred = null; if (ourProject == null || !ourProjectDescriptor.equals(descriptor)) { initProject(descriptor); } ProjectManagerEx.getInstanceEx().setCurrentTestProject(ourProject); ((PsiDocumentManagerImpl)PsiDocumentManager.getInstance(getProject())).clearUncommitedDocuments(); for (LocalInspectionTool tool : localInspectionTools) { enableInspectionTool(availableInspectionTools, new LocalInspectionToolWrapper(tool)); } final InspectionProfileImpl profile = new InspectionProfileImpl("Configurable") { @NotNull public InspectionProfileEntry[] getInspectionTools(PsiElement element) { if (availableInspectionTools != null){ final Collection<InspectionTool> tools = availableInspectionTools.values(); return tools.toArray(new InspectionTool[tools.size()]); } return new InspectionTool[0]; } @Override public List<ToolsImpl> getAllEnabledInspectionTools() { List<ToolsImpl> result = new ArrayList<ToolsImpl>(); for (InspectionProfileEntry entry : getInspectionTools(null)) { result.add(new ToolsImpl(entry, entry.getDefaultLevel(), true)); } return result; } public boolean isToolEnabled(HighlightDisplayKey key, PsiElement element) { return key != null && availableInspectionTools.containsKey(key.toString()); } public HighlightDisplayLevel getErrorLevel(@NotNull HighlightDisplayKey key, PsiElement element) { InspectionTool localInspectionTool = availableInspectionTools.get(key.toString()); return localInspectionTool != null ? localInspectionTool.getDefaultLevel() : HighlightDisplayLevel.WARNING; } public InspectionTool getInspectionTool(@NotNull String shortName, @NotNull PsiElement element) { if (availableInspectionTools.containsKey(shortName)) { return availableInspectionTools.get(shortName); } return null; } }; final InspectionProfileManager inspectionProfileManager = InspectionProfileManager.getInstance(); inspectionProfileManager.addProfile(profile); inspectionProfileManager.setRootProfile(profile.getName()); InspectionProjectProfileManager.getInstance(getProject()).updateProfile(profile); InspectionProjectProfileManager.getInstance(getProject()).setProjectProfile(profile.getName()); assertFalse(getPsiManager().isDisposed()); CodeStyleSettingsManager.getInstance(getProject()).setTemporarySettings(new CodeStyleSettings()); } protected void enableInspectionTool(LocalInspectionTool tool){ enableInspectionTool(new LocalInspectionToolWrapper(tool)); } protected void enableInspectionTool(InspectionTool tool){ enableInspectionTool(myAvailableInspectionTools, tool); } private static void enableInspectionTool(final Map<String, InspectionTool> availableLocalTools, InspectionTool wrapper) { final String shortName = wrapper.getShortName(); final HighlightDisplayKey key = HighlightDisplayKey.find(shortName); if (key == null){ HighlightDisplayKey.register(shortName, wrapper.getDisplayName(), wrapper instanceof LocalInspectionToolWrapper ? ((LocalInspectionToolWrapper)wrapper).getTool().getID() : wrapper.getShortName()); } availableLocalTools.put(shortName, wrapper); } protected LocalInspectionTool[] configureLocalInspectionTools() { return new LocalInspectionTool[0]; } protected void tearDown() throws Exception { CodeStyleSettingsManager.getInstance(getProject()).dropTemporarySettings(); checkForSettingsDamage(); doTearDown(getProject(), ourApplication, true); super.tearDown(); myThreadTracker.checkLeak(); checkInjectorsAreDisposed(); } public static void doTearDown(Project project, IdeaTestApplication application, boolean checkForEditors) throws Exception { checkAllTimersAreDisposed(); UsefulTestCase.doPostponedFormatting(project); LookupManager lookupManager = LookupManager.getInstance(project); if (lookupManager != null) { lookupManager.hideActiveLookup(); } ((StartupManagerImpl)StartupManager.getInstance(project)).prepareForNextTest(); InspectionProfileManager.getInstance().deleteProfile(PROFILE); assertNotNull("Application components damaged", ProjectManager.getInstance()); ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { if (ourSourceRoot != null) { try { final VirtualFile[] children = ourSourceRoot.getChildren(); for (VirtualFile child : children) { child.delete(this); } } catch (IOException e) { //noinspection CallToPrintStackTrace e.printStackTrace(); } } EncodingManager encodingManager = EncodingManager.getInstance(); if (encodingManager instanceof EncodingManagerImpl) ((EncodingManagerImpl)encodingManager).drainDocumentQueue(); FileDocumentManager manager = FileDocumentManager.getInstance(); if (manager instanceof FileDocumentManagerImpl) { ((FileDocumentManagerImpl)manager).dropAllUnsavedDocuments(); } ApplicationManager.getApplication().runWriteAction(EmptyRunnable.getInstance()); // Flash posponed formatting if any. manager.saveAllDocuments(); } }); assertFalse(PsiManager.getInstance(project).isDisposed()); if (!ourAssertionsInTestDetected) { if (IdeaLogger.ourErrorsOccurred != null) { throw IdeaLogger.ourErrorsOccurred; } } ((PsiDocumentManagerImpl)PsiDocumentManager.getInstance(project)).clearUncommitedDocuments(); ((UndoManagerImpl)UndoManager.getGlobalInstance()).dropHistoryInTests(); ProjectManagerEx.getInstanceEx().setCurrentTestProject(null); application.setDataProvider(null); ourTestCase = null; ((PsiManagerImpl)PsiManager.getInstance(project)).cleanupForNextTest(); CompletionProgressIndicator.cleanupForNextTest(); if (checkForEditors) { checkEditorsReleased(); } } public static void checkEditorsReleased() { final Editor[] allEditors = EditorFactory.getInstance().getAllEditors(); if (allEditors.length > 0) { for (Editor allEditor : allEditors) { EditorFactory.getInstance().releaseEditor(allEditor); } fail("Unreleased editors: " + allEditors.length); } } private static void checkInjectorsAreDisposed() { ((InjectedLanguageManagerImpl)InjectedLanguageManager.getInstance(getProject())).checkInjectorsAreDisposed(); } public final void runBare() throws Throwable { final Throwable[] throwables = new Throwable[1]; SwingUtilities.invokeAndWait(new Runnable() { public void run() { try { ourTestThread = Thread.currentThread(); startRunAndTear(); } catch (Throwable throwable) { throwables[0] = throwable; } finally { ourTestThread = null; try { PlatformTestCase.cleanupApplicationCaches(ourProject); resetAllFields(); } catch (Throwable e) { e.printStackTrace(); } } } }); if (throwables[0] != null) { throw throwables[0]; } // just to make sure all deffered Runnable's to finish SwingUtilities.invokeAndWait(EmptyRunnable.getInstance()); if (IdeaLogger.ourErrorsOccurred != null) { throw IdeaLogger.ourErrorsOccurred; } } private void startRunAndTear() throws Throwable { setUp(); try { ourAssertionsInTestDetected = true; runTest(); ourAssertionsInTestDetected = false; } finally { //try{ tearDown(); //} //catch(Throwable th){ // noinspection CallToPrintStackTrace //th.printStackTrace(); //} } } public Object getData(String dataId) { if (PlatformDataKeys.PROJECT.is(dataId)) { return ourProject; } return null; } protected Sdk getProjectJDK() { return null; } protected ModuleType getModuleType() { return EmptyModuleType.getInstance(); } /** * Creates dummy source file. One is not placed under source root so some PSI functions like resolve to external classes * may not work. Though it works significantly faster and yet can be used if you need to create some PSI structures for * test purposes * * @param fileName - name of the file to create. Extension is used to choose what PSI should be created like java, jsp, aj, xml etc. * @param text - file text. * @return dummy psi file. * @throws com.intellij.util.IncorrectOperationException */ protected static PsiFile createFile(@NonNls String fileName, String text) throws IncorrectOperationException { return createPseudoPhysicalFile(fileName, text); } protected static PsiFile createLightFile(String fileName, String text) throws IncorrectOperationException { return PsiFileFactory.getInstance(getProject()).createFileFromText(fileName, FileTypeManager.getInstance().getFileTypeByFileName( fileName), text, LocalTimeCounter.currentTime(), false); } protected static PsiFile createPseudoPhysicalFile(@NonNls String fileName, String text) throws IncorrectOperationException { FileType fileType = FileTypeManager.getInstance().getFileTypeByFileName(fileName); return PsiFileFactory.getInstance(getProject()).createFileFromText(fileName, fileType, text, LocalTimeCounter.currentTime(), true); } /** * Convinient conversion of testSomeTest -> someTest | SomeTest where testSomeTest is the name of current test. * * @param lowercaseFirstLetter - whether first letter after test should be lowercased. */ protected String getTestName(boolean lowercaseFirstLetter) { String name = getName(); assertTrue("Test name should start with 'test'", name.startsWith("test")); name = name.substring("test".length()); if (lowercaseFirstLetter && !UsefulTestCase.isAllUppercaseName(name)) { name = Character.toLowerCase(name.charAt(0)) + name.substring(1); } return name; } protected static void commitDocument(final Document document) { PsiDocumentManager.getInstance(getProject()).commitDocument(document); } protected static void commitAllDocuments() { PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); } @Override protected CodeStyleSettings getCurrentCodeStyleSettings() { return CodeStyleSettingsManager.getSettings(getProject()); } protected static Document getDocument(final PsiFile file) { return PsiDocumentManager.getInstance(getProject()).getDocument(file); } protected static synchronized void closeAndDeleteProject() { if (ourProject != null) { final VirtualFile projFile = ((ProjectEx)ourProject).getStateStore().getProjectFile(); final File projectFile = projFile == null ? null : VfsUtil.virtualToIoFile(projFile); if (!ourProject.isDisposed()) Disposer.dispose(ourProject); if (projectFile != null) { FileUtil.delete(projectFile); } } } static { System.setProperty("jbdt.test.fixture", "com.intellij.designer.dt.IJTestFixture"); } private static void registerShutdownHook() { ShutDownTracker.getInstance().registerShutdownTask(new Runnable() { public void run() { try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { closeAndDeleteProject(); } }); } catch (InterruptedException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }); } private static class SimpleLightProjectDescriptor implements LightProjectDescriptor { private final ModuleType myModuleType; private final Sdk mySdk; SimpleLightProjectDescriptor(ModuleType moduleType, Sdk sdk) { myModuleType = moduleType; mySdk = sdk; } public ModuleType getModuleType() { return myModuleType; } public Sdk getSdk() { return mySdk; } public void configureModule(Module module, ModifiableRootModel model, ContentEntry contentEntry) { } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SimpleLightProjectDescriptor that = (SimpleLightProjectDescriptor)o; if (myModuleType != null ? !myModuleType.equals(that.myModuleType) : that.myModuleType != null) return false; return !isJDKChanged(that.getSdk()); } @Override public int hashCode() { int result = myModuleType != null ? myModuleType.hashCode() : 0; result = 31 * result + (mySdk != null ? mySdk.hashCode() : 0); return result; } private boolean isJDKChanged(final Sdk newJDK) { if (mySdk == null && newJDK == null) return false; return mySdk == null || newJDK == null || !Comparing.equal(mySdk.getVersionString(), newJDK.getVersionString()); } } }
clear UndoManagerHistory on EDT
platform/testFramework/src/com/intellij/testFramework/LightPlatformTestCase.java
clear UndoManagerHistory on EDT
<ide><path>latform/testFramework/src/com/intellij/testFramework/LightPlatformTestCase.java <ide> ((PsiDocumentManagerImpl)PsiDocumentManager.getInstance(project)).clearUncommitedDocuments(); <ide> <ide> <del> ((UndoManagerImpl)UndoManager.getGlobalInstance()).dropHistoryInTests(); <add> Runnable runnable = new Runnable() { <add> public void run() { <add> ((UndoManagerImpl)UndoManager.getGlobalInstance()).dropHistoryInTests(); <add> } <add> }; <add> if (ApplicationManager.getApplication().isDispatchThread()) { <add> runnable.run(); <add> } else { <add> SwingUtilities.invokeAndWait(runnable); <add> } <ide> <ide> ProjectManagerEx.getInstanceEx().setCurrentTestProject(null); <ide> application.setDataProvider(null);
Java
apache-2.0
11475a1b884551619438396d8ffa21379fa87188
0
retomerz/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,petteyg/intellij-community,ernestp/consulo,samthor/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,kdwink/intellij-community,izonder/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,consulo/consulo,xfournet/intellij-community,gnuhub/intellij-community,kool79/intellij-community,signed/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,adedayo/intellij-community,signed/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,holmes/intellij-community,vladmm/intellij-community,fnouama/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,caot/intellij-community,dslomov/intellij-community,allotria/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,xfournet/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,jexp/idea2,akosyakov/intellij-community,samthor/intellij-community,fnouama/intellij-community,clumsy/intellij-community,kool79/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,ibinti/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,clumsy/intellij-community,vladmm/intellij-community,joewalnes/idea-community,supersven/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,joewalnes/idea-community,suncycheng/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,semonte/intellij-community,semonte/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,consulo/consulo,Lekanich/intellij-community,xfournet/intellij-community,slisson/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,adedayo/intellij-community,slisson/intellij-community,FHannes/intellij-community,retomerz/intellij-community,allotria/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,holmes/intellij-community,diorcety/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,consulo/consulo,fitermay/intellij-community,diorcety/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,signed/intellij-community,izonder/intellij-community,clumsy/intellij-community,samthor/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,SerCeMan/intellij-community,signed/intellij-community,da1z/intellij-community,semonte/intellij-community,diorcety/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,retomerz/intellij-community,ernestp/consulo,asedunov/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,signed/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,ernestp/consulo,ahb0327/intellij-community,supersven/intellij-community,apixandru/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,kool79/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,blademainer/intellij-community,da1z/intellij-community,Distrotech/intellij-community,da1z/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,caot/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,fitermay/intellij-community,jexp/idea2,idea4bsd/idea4bsd,FHannes/intellij-community,amith01994/intellij-community,ryano144/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,ernestp/consulo,tmpgit/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,apixandru/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,samthor/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,diorcety/intellij-community,wreckJ/intellij-community,supersven/intellij-community,ibinti/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,signed/intellij-community,semonte/intellij-community,asedunov/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,vladmm/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,consulo/consulo,SerCeMan/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,vvv1559/intellij-community,izonder/intellij-community,FHannes/intellij-community,apixandru/intellij-community,apixandru/intellij-community,joewalnes/idea-community,kdwink/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,izonder/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,retomerz/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,signed/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,jagguli/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,izonder/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,slisson/intellij-community,amith01994/intellij-community,izonder/intellij-community,jagguli/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,vladmm/intellij-community,signed/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,signed/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,jexp/idea2,slisson/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,ibinti/intellij-community,semonte/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,supersven/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,caot/intellij-community,izonder/intellij-community,vvv1559/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,kool79/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,joewalnes/idea-community,diorcety/intellij-community,consulo/consulo,petteyg/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,retomerz/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,blademainer/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,ernestp/consulo,adedayo/intellij-community,petteyg/intellij-community,da1z/intellij-community,kool79/intellij-community,caot/intellij-community,xfournet/intellij-community,holmes/intellij-community,signed/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,blademainer/intellij-community,xfournet/intellij-community,retomerz/intellij-community,hurricup/intellij-community,petteyg/intellij-community,jexp/idea2,akosyakov/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,samthor/intellij-community,FHannes/intellij-community,blademainer/intellij-community,hurricup/intellij-community,samthor/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,signed/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,allotria/intellij-community,allotria/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,fnouama/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,jexp/idea2,fitermay/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,asedunov/intellij-community,semonte/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,retomerz/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,ryano144/intellij-community,amith01994/intellij-community,petteyg/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,tmpgit/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,consulo/consulo,slisson/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,jexp/idea2,TangHao1987/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,holmes/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,slisson/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,lucafavatella/intellij-community,caot/intellij-community,kool79/intellij-community,ryano144/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,ernestp/consulo,clumsy/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,clumsy/intellij-community,joewalnes/idea-community,muntasirsyed/intellij-community,semonte/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,clumsy/intellij-community,vladmm/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,FHannes/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,caot/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,nicolargo/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,apixandru/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,hurricup/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,joewalnes/idea-community,apixandru/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,Distrotech/intellij-community,da1z/intellij-community,hurricup/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,blademainer/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,joewalnes/idea-community,xfournet/intellij-community,kdwink/intellij-community,hurricup/intellij-community,izonder/intellij-community,semonte/intellij-community,slisson/intellij-community,joewalnes/idea-community,mglukhikh/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,xfournet/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,asedunov/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,jexp/idea2,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,robovm/robovm-studio,kdwink/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,holmes/intellij-community,jagguli/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,joewalnes/idea-community,youdonghai/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,allotria/intellij-community,ibinti/intellij-community,amith01994/intellij-community,jexp/idea2,suncycheng/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,caot/intellij-community,holmes/intellij-community,kool79/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,dslomov/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,supersven/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,gnuhub/intellij-community,samthor/intellij-community,da1z/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,caot/intellij-community
package com.intellij.testFramework; import com.intellij.ide.highlighter.ModuleFileType; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.module.ModuleType; import com.intellij.openapi.module.StdModuleTypes; import com.intellij.openapi.module.impl.ModuleImpl; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.impl.ProjectImpl; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.roots.impl.ModuleRootManagerImpl; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import org.jdom.JDOMException; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; public abstract class ModuleTestCase extends IdeaTestCase { protected final Collection<Module> myModulesToDispose = new ArrayList<Module>(); protected void setUp() throws Exception { super.setUp(); myModulesToDispose.clear(); } protected void tearDown() throws Exception { try { final ModuleManager moduleManager = ModuleManager.getInstance(myProject); ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { for (Module module : myModulesToDispose) { String moduleName = module.getName(); if (moduleManager.findModuleByName(moduleName) != null) { moduleManager.disposeModule(module); } } } }); } finally { myModulesToDispose.clear(); super.tearDown(); } } protected Module createModule(final File moduleFile) { return createModule(moduleFile, StdModuleTypes.JAVA); } protected Module createModule(final File moduleFile, final ModuleType moduleType) { final String path = moduleFile.getAbsolutePath(); return createModule(path, moduleType); } protected Module createModule(final String path) { return createModule(path, StdModuleTypes.JAVA); } protected Module createModule(final String path, final ModuleType moduleType) { Module module = ApplicationManager.getApplication().runWriteAction( new Computable<Module>() { public Module compute() { return ModuleManager.getInstance(myProject).newModule(path, moduleType); } } ); myModulesToDispose.add(module); return module; } protected Module loadModule(final File moduleFile) { Module module = ApplicationManager.getApplication().runWriteAction( new Computable<Module>() { public Module compute() { try { return ModuleManager.getInstance(myProject).loadModule(moduleFile.getAbsolutePath()); } catch (Exception e) { LOG.error(e); return null; } } } ); myModulesToDispose.add(module); return module; } public Module loadModule(final String modulePath, Project project) throws InvalidDataException, IOException, JDOMException { return loadModule(new File(modulePath)); } @Nullable protected ModuleImpl loadAllModulesUnder(VirtualFile rootDir) throws Exception { ModuleImpl module = null; final VirtualFile[] children = rootDir.getChildren(); for (VirtualFile child : children) { if (child.isDirectory()) { final ModuleImpl childModule = loadAllModulesUnder(child); if (module == null) module = childModule; } else if (child.getName().endsWith(ModuleFileType.DOT_DEFAULT_EXTENSION)) { String modulePath = child.getPath(); module = (ModuleImpl)loadModule(new File(modulePath)); readJdomExternalizables(module); } } return module; } protected void readJdomExternalizables(ModuleImpl module) { final ProjectImpl project = (ProjectImpl)myProject; project.setOptimiseTestLoadSpeed(false); final ModuleRootManagerImpl moduleRootManager = (ModuleRootManagerImpl)ModuleRootManager.getInstance(module); module.getStateStore().initComponent(moduleRootManager); project.setOptimiseTestLoadSpeed(true); } protected Module createModuleFromTestData(final String dirInTestData, final String newModuleFileName, final ModuleType moduleType, final boolean addSourceRoot) throws IOException { final File dirInTestDataFile = new File(dirInTestData); assertTrue(dirInTestDataFile.isDirectory()); final File moduleDir = createTempDirectory(); FileUtil.copyDir(dirInTestDataFile, moduleDir); final Module module = createModule(moduleDir + "/" + newModuleFileName, moduleType); VirtualFile root = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(moduleDir); if (addSourceRoot) { PsiTestUtil.addSourceContentToRoots(module, root); } else { PsiTestUtil.addContentRoot(module, root); } return module; } }
ExtendedApi/src/com/intellij/testFramework/ModuleTestCase.java
package com.intellij.testFramework; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.module.ModuleType; import com.intellij.openapi.module.StdModuleTypes; import com.intellij.openapi.module.impl.ModuleImpl; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.impl.ProjectImpl; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.roots.impl.ModuleRootManagerImpl; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ide.highlighter.ModuleFileType; import org.jdom.JDOMException; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; public abstract class ModuleTestCase extends IdeaTestCase { protected final Collection<Module> myModulesToDispose = new ArrayList<Module>(); protected void setUp() throws Exception { super.setUp(); myModulesToDispose.clear(); } protected void tearDown() throws Exception { final ModuleManager moduleManager = ModuleManager.getInstance(myProject); ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { for (Module module : myModulesToDispose) { String moduleName = module.getName(); if (moduleManager.findModuleByName(moduleName) != null) { moduleManager.disposeModule(module); } } } }); myModulesToDispose.clear(); super.tearDown(); } protected Module createModule(final File moduleFile) { return createModule(moduleFile, StdModuleTypes.JAVA); } protected Module createModule(final File moduleFile, final ModuleType moduleType) { final String path = moduleFile.getAbsolutePath(); return createModule(path, moduleType); } protected Module createModule(final String path) { return createModule(path, StdModuleTypes.JAVA); } protected Module createModule(final String path, final ModuleType moduleType) { Module module = ApplicationManager.getApplication().runWriteAction( new Computable<Module>() { public Module compute() { return ModuleManager.getInstance(myProject).newModule(path, moduleType); } } ); myModulesToDispose.add(module); return module; } protected Module loadModule(final File moduleFile) { Module module = ApplicationManager.getApplication().runWriteAction( new Computable<Module>() { public Module compute() { try { return ModuleManager.getInstance(myProject).loadModule(moduleFile.getAbsolutePath()); } catch (Exception e) { LOG.error(e); return null; } } } ); myModulesToDispose.add(module); return module; } public Module loadModule(final String modulePath, Project project) throws InvalidDataException, IOException, JDOMException { return loadModule(new File(modulePath)); } @Nullable protected ModuleImpl loadAllModulesUnder(VirtualFile rootDir) throws Exception { ModuleImpl module = null; final VirtualFile[] children = rootDir.getChildren(); for (VirtualFile child : children) { if (child.isDirectory()) { final ModuleImpl childModule = loadAllModulesUnder(child); if (module == null) module = childModule; } else if (child.getName().endsWith(ModuleFileType.DOT_DEFAULT_EXTENSION)) { String modulePath = child.getPath(); module = (ModuleImpl)loadModule(new File(modulePath)); readJdomExternalizables(module); } } return module; } protected void readJdomExternalizables(ModuleImpl module) { final ProjectImpl project = (ProjectImpl)myProject; project.setOptimiseTestLoadSpeed(false); final ModuleRootManagerImpl moduleRootManager = (ModuleRootManagerImpl)ModuleRootManager.getInstance(module); module.getStateStore().initComponent(moduleRootManager); project.setOptimiseTestLoadSpeed(true); } protected Module createModuleFromTestData(final String dirInTestData, final String newModuleFileName, final ModuleType moduleType, final boolean addSourceRoot) throws IOException { final File dirInTestDataFile = new File(dirInTestData); assertTrue(dirInTestDataFile.isDirectory()); final File moduleDir = createTempDirectory(); FileUtil.copyDir(dirInTestDataFile, moduleDir); final Module module = createModule(moduleDir + "/" + newModuleFileName, moduleType); VirtualFile root = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(moduleDir); if (addSourceRoot) { PsiTestUtil.addSourceContentToRoots(module, root); } else { PsiTestUtil.addContentRoot(module, root); } return module; } }
more reliable teardown
ExtendedApi/src/com/intellij/testFramework/ModuleTestCase.java
more reliable teardown
<ide><path>xtendedApi/src/com/intellij/testFramework/ModuleTestCase.java <ide> package com.intellij.testFramework; <ide> <add>import com.intellij.ide.highlighter.ModuleFileType; <ide> import com.intellij.openapi.application.ApplicationManager; <ide> import com.intellij.openapi.module.Module; <ide> import com.intellij.openapi.module.ModuleManager; <ide> import com.intellij.openapi.util.io.FileUtil; <ide> import com.intellij.openapi.vfs.LocalFileSystem; <ide> import com.intellij.openapi.vfs.VirtualFile; <del>import com.intellij.ide.highlighter.ModuleFileType; <ide> import org.jdom.JDOMException; <ide> import org.jetbrains.annotations.Nullable; <ide> <ide> } <ide> <ide> protected void tearDown() throws Exception { <del> final ModuleManager moduleManager = ModuleManager.getInstance(myProject); <del> ApplicationManager.getApplication().runWriteAction(new Runnable() { <del> public void run() { <del> for (Module module : myModulesToDispose) { <del> String moduleName = module.getName(); <del> if (moduleManager.findModuleByName(moduleName) != null) { <del> moduleManager.disposeModule(module); <add> try { <add> final ModuleManager moduleManager = ModuleManager.getInstance(myProject); <add> ApplicationManager.getApplication().runWriteAction(new Runnable() { <add> public void run() { <add> for (Module module : myModulesToDispose) { <add> String moduleName = module.getName(); <add> if (moduleManager.findModuleByName(moduleName) != null) { <add> moduleManager.disposeModule(module); <add> } <ide> } <ide> } <del> } <del> }); <del> myModulesToDispose.clear(); <del> super.tearDown(); <add> }); <add> } <add> finally { <add> myModulesToDispose.clear(); <add> super.tearDown(); <add> } <ide> } <ide> <ide> protected Module createModule(final File moduleFile) {
JavaScript
bsd-3-clause
32b15f5cd07565351683086ed1afd3dae860ec9d
0
maier49/dgrid,maier49/dgrid,dylans/dgrid,kfranqueiro/dgrid,kfranqueiro/dgrid,dylans/dgrid,dylans/dgrid,kfranqueiro/dgrid,maier49/dgrid
define([ 'dojo/_base/declare', 'dojo/_base/lang', 'dojo/dom-class', 'dojo/dom-construct', 'dojo/on', 'dojo/aspect', 'dojo/query', 'dojo/has', './util/misc', 'dojo/_base/sniff' ], function (declare, lang, domClass, domConstruct, on, aspect, query, has, miscUtil) { has.add('event-mousewheel', function (global, document, element) { return 'onmousewheel' in element; }); has.add('event-wheel', function (global, document, element) { return 'onwheel' in element; }); var colsetidAttr = 'data-dgrid-column-set-id'; function adjustScrollLeft(grid, root) { // Adjusts the scroll position of each column set in each row under the given root. // (root can be a row, or e.g. a tree parent row element's connected property to adjust children) var scrollLefts = grid._columnSetScrollLefts; query('.dgrid-column-set', root).forEach(function (element) { element.scrollLeft = scrollLefts[element.getAttribute(colsetidAttr)]; }); } function getColumnSetSubRows(subRows, columnSetId) { // Builds a subRow collection that only contains columns that correspond to // a given column set id. if (!subRows || !subRows.length) { return; } var subset = []; var idPrefix = columnSetId + '-'; for (var i = 0, numRows = subRows.length; i < numRows; i++) { var row = subRows[i]; var subsetRow = []; subsetRow.className = row.className; for (var k = 0, numCols = row.length; k < numCols; k++) { var column = row[k]; // The column id begins with the column set id. if (column.id != null && column.id.indexOf(idPrefix) === 0) { subsetRow.push(column); } } subset.push(subsetRow); } return subset; } function isRootNode(node, rootNode) { // If we've reached the top-level node for the grid then there is no parent column set. // This guard prevents an error when scroll is initated over some node in the grid that is not a descendant of // a column set. This can happen in a grid that has empty space below its rows (grid is taller than the rows). return (rootNode && node === rootNode) || domClass.contains(node, 'dgrid'); } function findParentColumnSet(node, root) { // WebKit will invoke mousewheel handlers with an event target of a text // node; check target and if it's not an element node, start one node higher // in the tree if (node.nodeType !== 1) { node = node.parentNode; } while (node && !query.matches(node, '.dgrid-column-set[' + colsetidAttr + ']', root)) { if (isRootNode(node, root)) { return null; } node = node.parentNode; } return node; } var pointerMap = { start: 'down', end: 'up' }; function getTouchEventName(type) { // Given 'start', 'move', or 'end', returns appropriate touch or pointer event name // based on browser support. (Assumes browser supports touch or pointer.) var hasPointer = has('pointer'); if (hasPointer) { type = pointerMap[type] || type; if (hasPointer.slice(0, 2) === 'MS') { return 'MSPointer' + type.slice(0, 1).toUpperCase() + type.slice(1); } else { return 'pointer' + type; } } return 'touch' + type; } var horizTouchMove = has('touch') && function (grid) { return function (target, listener) { var listeners = [ on(target, getTouchEventName('start'), function (event) { if (!grid._currentlyTouchedColumnSet) { var node = findParentColumnSet(event.target, target); // If handling pointer events, only react to touch; // MSPointerDown (IE10) reports 2, 3, 4 for touch, pen, mouse if (node && (!event.pointerType || event.pointerType === 'touch' || event.pointerType === 2)) { grid._currentlyTouchedColumnSet = node; grid._lastColumnSetTouchX = event.clientX; grid._lastColumnSetTouchY = event.clientY; } } }), on(target, getTouchEventName('move'), function (event) { if (grid._currentlyTouchedColumnSet === null) { return; } var node = findParentColumnSet(event.target); if (!node) { return; } listener.call(null, grid, node, grid._lastColumnSetTouchX - event.clientX); grid._lastColumnSetTouchX = event.clientX; grid._lastColumnSetTouchY = event.clientY; }), on(target, getTouchEventName('end'), function () { grid._currentlyTouchedColumnSet = null; }) ]; return { remove: function () { for (var i = listeners.length; i--;) { listeners[i].remove(); } } }; }; }; var horizMouseWheel = has('event-mousewheel') || has('event-wheel') ? function (grid) { return function (target, listener) { return on(target, has('event-wheel') ? 'wheel' : 'mousewheel', function (event) { var node = findParentColumnSet(event.target, target), deltaX; if (!node) { return; } // Normalize reported delta value: // wheelDeltaX (webkit, mousewheel) needs to be negated and divided by 3 // deltaX (FF17+, wheel) can be used exactly as-is deltaX = event.deltaX || -event.wheelDeltaX / 3; if (deltaX) { // only respond to horizontal movement listener.call(null, grid, node, deltaX); } }); }; } : function (grid) { return function (target, listener) { return on(target, '.dgrid-column-set[' + colsetidAttr + ']:MozMousePixelScroll', function (event) { if (event.axis === 1) { // only respond to horizontal movement listener.call(null, grid, this, event.detail); } }); }; }; function horizMoveHandler(grid, colsetNode, amount) { var id = colsetNode.getAttribute(colsetidAttr), scroller = grid._columnSetScrollers[id], scrollLeft = scroller.scrollLeft + amount; scroller.scrollLeft = scrollLeft < 0 ? 0 : scrollLeft; } return declare(null, { // summary: // Provides column sets to isolate horizontal scroll of sets of // columns from each other. This mainly serves the purpose of allowing for // column locking. postCreate: function () { var self = this; this.inherited(arguments); this.on(horizMouseWheel(this), horizMoveHandler); if (has('touch')) { this.on(horizTouchMove(this), horizMoveHandler); } this.on('.dgrid-column-set:dgrid-cellfocusin', function (event) { self._onColumnSetCellFocus(event, this); }); if (typeof this.expand === 'function') { aspect.after(this, 'expand', function (promise, args) { promise.then(function () { var row = self.row(args[0]); if (self._expanded[row.id]) { // scrollLeft changes can't take effect on collapsed child rows; // ensure they are properly updated once re-expanded. adjustScrollLeft(self, row.element.connected); } }); return promise; }); } }, columnSets: [], createRowCells: function (tag, each, subRows, object) { var row = domConstruct.create('table', { className: 'dgrid-row-table' }); var tbody = domConstruct.create('tbody', null, row); var tr = domConstruct.create('tr', null, tbody); for (var i = 0, l = this.columnSets.length; i < l; i++) { // iterate through the columnSets var cell = domConstruct.create(tag, { className: 'dgrid-column-set-cell dgrid-column-set-' + i }, tr); cell = domConstruct.create('div', { className: 'dgrid-column-set' }, cell); cell.setAttribute(colsetidAttr, i); var subset = getColumnSetSubRows(subRows || this.subRows, i) || this.columnSets[i]; cell.appendChild(this.inherited(arguments, [tag, each, subset, object])); } return row; }, renderArray: function () { var rows = this.inherited(arguments); for (var i = 0; i < rows.length; i++) { adjustScrollLeft(this, rows[i]); } return rows; }, insertRow: function () { var row = this.inherited(arguments); adjustScrollLeft(this, row); return row; }, renderHeader: function () { // summary: // Setup the headers for the grid this.inherited(arguments); var columnSets = this.columnSets, scrollers = this._columnSetScrollers, grid = this, i, l; function reposition() { grid._positionScrollers(); } this._columnSetScrollerContents = {}; this._columnSetScrollLefts = {}; if (scrollers) { // this isn't the first time; destroy existing scroller nodes first for (i in scrollers) { domConstruct.destroy(scrollers[i]); } } else { // first-time-only operations: hook up event/aspected handlers aspect.after(this, 'resize', reposition, true); aspect.after(this, 'styleColumn', reposition, true); this._columnSetScrollerNode = domConstruct.create('div', { className: 'dgrid-column-set-scroller-container' }, this.footerNode, 'after'); } // reset to new object to be populated in loop below scrollers = this._columnSetScrollers = {}; for (i = 0, l = columnSets.length; i < l; i++) { this._putScroller(columnSets[i], i); } this._positionScrollers(); }, styleColumnSet: function (colsetId, css) { // summary: // Dynamically creates a stylesheet rule to alter a columnset's style. var rule = this.addCssRule('#' + miscUtil.escapeCssIdentifier(this.domNode.id) + ' .dgrid-column-set-' + miscUtil.escapeCssIdentifier(colsetId, '-'), css); this._positionScrollers(); return rule; }, _destroyColumns: function () { var columnSetsLength = this.columnSets.length, i, j, k, subRowsLength, len, columnSet, subRow, column; for (i = 0; i < columnSetsLength; i++) { columnSet = this.columnSets[i]; for (j = 0, subRowsLength = columnSet.length; j < subRowsLength; j++) { subRow = columnSet[j]; for (k = 0, len = subRow.length; k < len; k++) { column = subRow[k]; if (typeof column.destroy === 'function') { column.destroy(); } } } } this.inherited(arguments); }, configStructure: function () { // Squash the column sets together so the grid and other dgrid extensions and mixins can // configure the columns and create any needed subrows. this.columns = {}; this.subRows = []; for (var i = 0, l = this.columnSets.length; i < l; i++) { var columnSet = this.columnSets[i]; for (var j = 0; j < columnSet.length; j++) { columnSet[j] = this._configColumns(i + '-' + j + '-', columnSet[j]); } } this.inherited(arguments); }, _positionScrollers: function () { var domNode = this.domNode, scrollers = this._columnSetScrollers, scrollerContents = this._columnSetScrollerContents, columnSets = this.columnSets, scrollerWidth = 0, numScrollers = 0, // tracks number of visible scrollers (sets w/ overflow) i, l, columnSetElement, contentWidth; for (i = 0, l = columnSets.length; i < l; i++) { // iterate through the columnSets columnSetElement = query('.dgrid-column-set[' + colsetidAttr + '="' + i + '"]', domNode)[0]; scrollerWidth = columnSetElement.offsetWidth; contentWidth = columnSetElement.firstChild.offsetWidth; scrollerContents[i].style.width = contentWidth + 'px'; scrollers[i].style.width = scrollerWidth + 'px'; if (has('ie') < 9) { // IE seems to need scroll to be set explicitly scrollers[i].style.overflowX = contentWidth > scrollerWidth ? 'scroll' : 'auto'; } // Keep track of how many scrollbars we're showing if (contentWidth > scrollerWidth) { numScrollers++; } } this._columnSetScrollerNode.style.bottom = this.showFooter ? this.footerNode.offsetHeight + 'px' : '0'; // Align bottom of body node depending on whether there are scrollbars this.bodyNode.style.bottom = numScrollers ? (has('dom-scrollbar-height') + (has('ie') ? 1 : 0) + 'px') : '0'; }, _putScroller: function (columnSet, i) { // function called for each columnSet var scroller = this._columnSetScrollers[i] = domConstruct.create('span', { // IE8 needs dgrid-scrollbar-height class for scrollbar to be visible, // but for some reason IE11's scrollbar arrows become unresponsive, so avoid applying it there className: 'dgrid-column-set-scroller dgrid-column-set-scroller-' + i + (has('ie') < 9 ? ' dgrid-scrollbar-height' : '') }, this._columnSetScrollerNode); scroller.setAttribute(colsetidAttr, i); this._columnSetScrollerContents[i] = domConstruct.create('div', { className: 'dgrid-column-set-scroller-content' }, scroller); on(scroller, 'scroll', lang.hitch(this, '_onColumnSetScroll')); }, _onColumnSetScroll: function (evt) { var scrollLeft = evt.target.scrollLeft, colSetId = evt.target.getAttribute(colsetidAttr), newScrollLeft; if (this._columnSetScrollLefts[colSetId] !== scrollLeft) { query('.dgrid-column-set[' + colsetidAttr + '="' + colSetId + '"],.dgrid-column-set-scroller[' + colsetidAttr + '="' + colSetId + '"]', this.domNode ).forEach(function (element, i) { element.scrollLeft = scrollLeft; if (!i) { // Compute newScrollLeft based on actual resulting // value of scrollLeft, which may be different than // what we assigned under certain circumstances // (e.g. Chrome under 33% / 67% / 90% zoom). // Only need to compute this once, as it will be the // same for every row. newScrollLeft = element.scrollLeft; } }); this._columnSetScrollLefts[colSetId] = newScrollLeft; } }, _setColumnSets: function (columnSets) { this._destroyColumns(); this.columnSets = columnSets; this._updateColumns(); }, _scrollColumnSet: function (nodeOrId, offsetLeft) { var id = nodeOrId.tagName ? nodeOrId.getAttribute(colsetidAttr) : nodeOrId; var scroller = this._columnSetScrollers[id]; scroller.scrollLeft = offsetLeft < 0 ? 0 : offsetLeft; }, _onColumnSetCellFocus: function (event, columnSetNode) { var focusedNode = event.target; var columnSetId = columnSetNode.getAttribute(colsetidAttr); // columnSetNode's offsetLeft is not always correct, // so get the columnScroller to check offsetLeft against var columnScroller = this._columnSetScrollers[columnSetId]; var elementEdge = focusedNode.offsetLeft - columnScroller.scrollLeft + focusedNode.offsetWidth; if (elementEdge > columnSetNode.offsetWidth || columnScroller.scrollLeft > focusedNode.offsetLeft) { this._scrollColumnSet(columnSetNode, focusedNode.offsetLeft); } } }); });
ColumnSet.js
define([ 'dojo/_base/declare', 'dojo/_base/lang', 'dojo/dom-construct', 'dojo/on', 'dojo/aspect', 'dojo/query', 'dojo/has', './util/misc', 'dojo/_base/sniff' ], function (declare, lang, domConstruct, on, aspect, query, has, miscUtil) { has.add('event-mousewheel', function (global, document, element) { return 'onmousewheel' in element; }); has.add('event-wheel', function (global, document, element) { return 'onwheel' in element; }); var colsetidAttr = 'data-dgrid-column-set-id'; function adjustScrollLeft(grid, root) { // Adjusts the scroll position of each column set in each row under the given root. // (root can be a row, or e.g. a tree parent row element's connected property to adjust children) var scrollLefts = grid._columnSetScrollLefts; query('.dgrid-column-set', root).forEach(function (element) { element.scrollLeft = scrollLefts[element.getAttribute(colsetidAttr)]; }); } function getColumnSetSubRows(subRows, columnSetId) { // Builds a subRow collection that only contains columns that correspond to // a given column set id. if (!subRows || !subRows.length) { return; } var subset = []; var idPrefix = columnSetId + '-'; for (var i = 0, numRows = subRows.length; i < numRows; i++) { var row = subRows[i]; var subsetRow = []; subsetRow.className = row.className; for (var k = 0, numCols = row.length; k < numCols; k++) { var column = row[k]; // The column id begins with the column set id. if (column.id != null && column.id.indexOf(idPrefix) === 0) { subsetRow.push(column); } } subset.push(subsetRow); } return subset; } function findParentColumnSet(node, root) { // WebKit will invoke mousewheel handlers with an event target of a text // node; check target and if it's not an element node, start one node higher // in the tree if (node.nodeType !== 1) { node = node.parentNode; } while (node && !query.matches(node, '.dgrid-column-set[' + colsetidAttr + ']', root)) { node = node.parentNode; } return node; } var pointerMap = { start: 'down', end: 'up' }; function getTouchEventName(type) { // Given 'start', 'move', or 'end', returns appropriate touch or pointer event name // based on browser support. (Assumes browser supports touch or pointer.) var hasPointer = has('pointer'); if (hasPointer) { type = pointerMap[type] || type; if (hasPointer.slice(0, 2) === 'MS') { return 'MSPointer' + type.slice(0, 1).toUpperCase() + type.slice(1); } else { return 'pointer' + type; } } return 'touch' + type; } var horizTouchMove = has('touch') && function (grid) { return function (target, listener) { var listeners = [ on(target, getTouchEventName('start'), function (event) { if (!grid._currentlyTouchedColumnSet) { var node = findParentColumnSet(event.target, target); // If handling pointer events, only react to touch; // MSPointerDown (IE10) reports 2, 3, 4 for touch, pen, mouse if (node && (!event.pointerType || event.pointerType === 'touch' || event.pointerType === 2)) { grid._currentlyTouchedColumnSet = node; grid._lastColumnSetTouchX = event.clientX; grid._lastColumnSetTouchY = event.clientY; } } }), on(target, getTouchEventName('move'), function (event) { if (grid._currentlyTouchedColumnSet === null) { return; } var node = findParentColumnSet(event.target); if (!node) { return; } listener.call(null, grid, node, grid._lastColumnSetTouchX - event.clientX); grid._lastColumnSetTouchX = event.clientX; grid._lastColumnSetTouchY = event.clientY; }), on(target, getTouchEventName('end'), function () { grid._currentlyTouchedColumnSet = null; }) ]; return { remove: function () { for (var i = listeners.length; i--;) { listeners[i].remove(); } } }; }; }; var horizMouseWheel = has('event-mousewheel') || has('event-wheel') ? function (grid) { return function (target, listener) { return on(target, has('event-wheel') ? 'wheel' : 'mousewheel', function (event) { var node = findParentColumnSet(event.target, target), deltaX; if (!node) { return; } // Normalize reported delta value: // wheelDeltaX (webkit, mousewheel) needs to be negated and divided by 3 // deltaX (FF17+, wheel) can be used exactly as-is deltaX = event.deltaX || -event.wheelDeltaX / 3; if (deltaX) { // only respond to horizontal movement listener.call(null, grid, node, deltaX); } }); }; } : function (grid) { return function (target, listener) { return on(target, '.dgrid-column-set[' + colsetidAttr + ']:MozMousePixelScroll', function (event) { if (event.axis === 1) { // only respond to horizontal movement listener.call(null, grid, this, event.detail); } }); }; }; function horizMoveHandler(grid, colsetNode, amount) { var id = colsetNode.getAttribute(colsetidAttr), scroller = grid._columnSetScrollers[id], scrollLeft = scroller.scrollLeft + amount; scroller.scrollLeft = scrollLeft < 0 ? 0 : scrollLeft; } return declare(null, { // summary: // Provides column sets to isolate horizontal scroll of sets of // columns from each other. This mainly serves the purpose of allowing for // column locking. postCreate: function () { var self = this; this.inherited(arguments); this.on(horizMouseWheel(this), horizMoveHandler); if (has('touch')) { this.on(horizTouchMove(this), horizMoveHandler); } this.on('.dgrid-column-set:dgrid-cellfocusin', function (event) { self._onColumnSetCellFocus(event, this); }); if (typeof this.expand === 'function') { aspect.after(this, 'expand', function (promise, args) { promise.then(function () { var row = self.row(args[0]); if (self._expanded[row.id]) { // scrollLeft changes can't take effect on collapsed child rows; // ensure they are properly updated once re-expanded. adjustScrollLeft(self, row.element.connected); } }); return promise; }); } }, columnSets: [], createRowCells: function (tag, each, subRows, object) { var row = domConstruct.create('table', { className: 'dgrid-row-table' }); var tbody = domConstruct.create('tbody', null, row); var tr = domConstruct.create('tr', null, tbody); for (var i = 0, l = this.columnSets.length; i < l; i++) { // iterate through the columnSets var cell = domConstruct.create(tag, { className: 'dgrid-column-set-cell dgrid-column-set-' + i }, tr); cell = domConstruct.create('div', { className: 'dgrid-column-set' }, cell); cell.setAttribute(colsetidAttr, i); var subset = getColumnSetSubRows(subRows || this.subRows, i) || this.columnSets[i]; cell.appendChild(this.inherited(arguments, [tag, each, subset, object])); } return row; }, renderArray: function () { var rows = this.inherited(arguments); for (var i = 0; i < rows.length; i++) { adjustScrollLeft(this, rows[i]); } return rows; }, insertRow: function () { var row = this.inherited(arguments); adjustScrollLeft(this, row); return row; }, renderHeader: function () { // summary: // Setup the headers for the grid this.inherited(arguments); var columnSets = this.columnSets, scrollers = this._columnSetScrollers, grid = this, i, l; function reposition() { grid._positionScrollers(); } this._columnSetScrollerContents = {}; this._columnSetScrollLefts = {}; if (scrollers) { // this isn't the first time; destroy existing scroller nodes first for (i in scrollers) { domConstruct.destroy(scrollers[i]); } } else { // first-time-only operations: hook up event/aspected handlers aspect.after(this, 'resize', reposition, true); aspect.after(this, 'styleColumn', reposition, true); this._columnSetScrollerNode = domConstruct.create('div', { className: 'dgrid-column-set-scroller-container' }, this.footerNode, 'after'); } // reset to new object to be populated in loop below scrollers = this._columnSetScrollers = {}; for (i = 0, l = columnSets.length; i < l; i++) { this._putScroller(columnSets[i], i); } this._positionScrollers(); }, styleColumnSet: function (colsetId, css) { // summary: // Dynamically creates a stylesheet rule to alter a columnset's style. var rule = this.addCssRule('#' + miscUtil.escapeCssIdentifier(this.domNode.id) + ' .dgrid-column-set-' + miscUtil.escapeCssIdentifier(colsetId, '-'), css); this._positionScrollers(); return rule; }, _destroyColumns: function () { var columnSetsLength = this.columnSets.length, i, j, k, subRowsLength, len, columnSet, subRow, column; for (i = 0; i < columnSetsLength; i++) { columnSet = this.columnSets[i]; for (j = 0, subRowsLength = columnSet.length; j < subRowsLength; j++) { subRow = columnSet[j]; for (k = 0, len = subRow.length; k < len; k++) { column = subRow[k]; if (typeof column.destroy === 'function') { column.destroy(); } } } } this.inherited(arguments); }, configStructure: function () { // Squash the column sets together so the grid and other dgrid extensions and mixins can // configure the columns and create any needed subrows. this.columns = {}; this.subRows = []; for (var i = 0, l = this.columnSets.length; i < l; i++) { var columnSet = this.columnSets[i]; for (var j = 0; j < columnSet.length; j++) { columnSet[j] = this._configColumns(i + '-' + j + '-', columnSet[j]); } } this.inherited(arguments); }, _positionScrollers: function () { var domNode = this.domNode, scrollers = this._columnSetScrollers, scrollerContents = this._columnSetScrollerContents, columnSets = this.columnSets, scrollerWidth = 0, numScrollers = 0, // tracks number of visible scrollers (sets w/ overflow) i, l, columnSetElement, contentWidth; for (i = 0, l = columnSets.length; i < l; i++) { // iterate through the columnSets columnSetElement = query('.dgrid-column-set[' + colsetidAttr + '="' + i + '"]', domNode)[0]; scrollerWidth = columnSetElement.offsetWidth; contentWidth = columnSetElement.firstChild.offsetWidth; scrollerContents[i].style.width = contentWidth + 'px'; scrollers[i].style.width = scrollerWidth + 'px'; if (has('ie') < 9) { // IE seems to need scroll to be set explicitly scrollers[i].style.overflowX = contentWidth > scrollerWidth ? 'scroll' : 'auto'; } // Keep track of how many scrollbars we're showing if (contentWidth > scrollerWidth) { numScrollers++; } } this._columnSetScrollerNode.style.bottom = this.showFooter ? this.footerNode.offsetHeight + 'px' : '0'; // Align bottom of body node depending on whether there are scrollbars this.bodyNode.style.bottom = numScrollers ? (has('dom-scrollbar-height') + (has('ie') ? 1 : 0) + 'px') : '0'; }, _putScroller: function (columnSet, i) { // function called for each columnSet var scroller = this._columnSetScrollers[i] = domConstruct.create('span', { // IE8 needs dgrid-scrollbar-height class for scrollbar to be visible, // but for some reason IE11's scrollbar arrows become unresponsive, so avoid applying it there className: 'dgrid-column-set-scroller dgrid-column-set-scroller-' + i + (has('ie') < 9 ? ' dgrid-scrollbar-height' : '') }, this._columnSetScrollerNode); scroller.setAttribute(colsetidAttr, i); this._columnSetScrollerContents[i] = domConstruct.create('div', { className: 'dgrid-column-set-scroller-content' }, scroller); on(scroller, 'scroll', lang.hitch(this, '_onColumnSetScroll')); }, _onColumnSetScroll: function (evt) { var scrollLeft = evt.target.scrollLeft, colSetId = evt.target.getAttribute(colsetidAttr), newScrollLeft; if (this._columnSetScrollLefts[colSetId] !== scrollLeft) { query('.dgrid-column-set[' + colsetidAttr + '="' + colSetId + '"],.dgrid-column-set-scroller[' + colsetidAttr + '="' + colSetId + '"]', this.domNode ).forEach(function (element, i) { element.scrollLeft = scrollLeft; if (!i) { // Compute newScrollLeft based on actual resulting // value of scrollLeft, which may be different than // what we assigned under certain circumstances // (e.g. Chrome under 33% / 67% / 90% zoom). // Only need to compute this once, as it will be the // same for every row. newScrollLeft = element.scrollLeft; } }); this._columnSetScrollLefts[colSetId] = newScrollLeft; } }, _setColumnSets: function (columnSets) { this._destroyColumns(); this.columnSets = columnSets; this._updateColumns(); }, _scrollColumnSet: function (nodeOrId, offsetLeft) { var id = nodeOrId.tagName ? nodeOrId.getAttribute(colsetidAttr) : nodeOrId; var scroller = this._columnSetScrollers[id]; scroller.scrollLeft = offsetLeft < 0 ? 0 : offsetLeft; }, _onColumnSetCellFocus: function (event, columnSetNode) { var focusedNode = event.target; var columnSetId = columnSetNode.getAttribute(colsetidAttr); // columnSetNode's offsetLeft is not always correct, // so get the columnScroller to check offsetLeft against var columnScroller = this._columnSetScrollers[columnSetId]; var elementEdge = focusedNode.offsetLeft - columnScroller.scrollLeft + focusedNode.offsetWidth; if (elementEdge > columnSetNode.offsetWidth || columnScroller.scrollLeft > focusedNode.offsetLeft) { this._scrollColumnSet(columnSetNode, focusedNode.offsetLeft); } } }); });
Fix #1179: ColumnSet: Avoid wheel/touch event errors in empty viewport
ColumnSet.js
Fix #1179: ColumnSet: Avoid wheel/touch event errors in empty viewport
<ide><path>olumnSet.js <ide> define([ <ide> 'dojo/_base/declare', <ide> 'dojo/_base/lang', <add> 'dojo/dom-class', <ide> 'dojo/dom-construct', <ide> 'dojo/on', <ide> 'dojo/aspect', <ide> 'dojo/has', <ide> './util/misc', <ide> 'dojo/_base/sniff' <del>], function (declare, lang, domConstruct, on, aspect, query, has, miscUtil) { <add>], function (declare, lang, domClass, domConstruct, on, aspect, query, has, miscUtil) { <ide> has.add('event-mousewheel', function (global, document, element) { <ide> return 'onmousewheel' in element; <ide> }); <ide> return subset; <ide> } <ide> <add> function isRootNode(node, rootNode) { <add> // If we've reached the top-level node for the grid then there is no parent column set. <add> // This guard prevents an error when scroll is initated over some node in the grid that is not a descendant of <add> // a column set. This can happen in a grid that has empty space below its rows (grid is taller than the rows). <add> return (rootNode && node === rootNode) || domClass.contains(node, 'dgrid'); <add> } <add> <ide> function findParentColumnSet(node, root) { <ide> // WebKit will invoke mousewheel handlers with an event target of a text <ide> // node; check target and if it's not an element node, start one node higher <ide> if (node.nodeType !== 1) { <ide> node = node.parentNode; <ide> } <add> <ide> while (node && !query.matches(node, '.dgrid-column-set[' + colsetidAttr + ']', root)) { <add> if (isRootNode(node, root)) { <add> return null; <add> } <ide> node = node.parentNode; <ide> } <add> <ide> return node; <ide> } <ide>
Java
apache-2.0
815b356e61475ede4794ca9a0f5e31feb6104c37
0
cheng-li/pyramid,cheng-li/pyramid
package edu.neu.ccs.pyramid.classification.logistic_regression; import edu.neu.ccs.pyramid.dataset.ClfDataSet; import edu.neu.ccs.pyramid.dataset.DataSet; import edu.neu.ccs.pyramid.dataset.GradientMatrix; import edu.neu.ccs.pyramid.dataset.ProbabilityMatrix; import edu.neu.ccs.pyramid.optimization.Optimizable; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.mahout.math.DenseVector; import org.apache.mahout.math.Vector; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.IntStream; /** * Created by Rainicy on 10/24/15. */ public class LogisticLoss implements Optimizable.ByGradientValue { private static final Logger logger = LogManager.getLogger(); private LogisticRegression logisticRegression; private DataSet dataSet; // instance weights private double[] weights; private double[][] targetDistributions; private Vector empiricalCounts; private Vector predictedCounts; private Vector gradient; private int numParameters; private int numClasses; // size = num classes * num data private double[][] probabilityMatrix; //todo the concept is not unified in logistic regression and gradient boosting /** * actually negative gradient * y_ik - p_k(x_i) * numClasses by numDataPoints */ private GradientMatrix gradientMatrix; private double value; private boolean isGradientCacheValid; private boolean isValueCacheValid; private boolean isParallel = false; private double priorGaussianVariance; public LogisticLoss(LogisticRegression logisticRegression, DataSet dataSet, double[] weights, double[][] targetDistributions, double priorGaussianVariance, boolean parallel) { this.logisticRegression = logisticRegression; this.targetDistributions = targetDistributions; this.isParallel = parallel; numParameters = logisticRegression.getWeights().totalSize(); this.dataSet = dataSet; this.weights = weights; this.priorGaussianVariance = priorGaussianVariance; this.empiricalCounts = new DenseVector(numParameters); this.predictedCounts = new DenseVector(numParameters); this.numClasses = targetDistributions[0].length; this.probabilityMatrix = new double[numClasses][dataSet.getNumDataPoints()]; this.gradientMatrix = new GradientMatrix(dataSet.getNumDataPoints(),numClasses, GradientMatrix.Objective.MAXIMIZE); this.updateEmpricalCounts(); this.isValueCacheValid=false; this.isGradientCacheValid=false; } public LogisticLoss(LogisticRegression logisticRegression, DataSet dataSet, double[][] targetDistributions, double gaussianPriorVariance, boolean parallel) { this(logisticRegression,dataSet,defaultWeights(dataSet.getNumDataPoints()),targetDistributions,gaussianPriorVariance, parallel); } public LogisticLoss(LogisticRegression logisticRegression, ClfDataSet dataSet, double gaussianPriorVariance, boolean parallel){ this(logisticRegression,dataSet,defaultTargetDistribution(dataSet),gaussianPriorVariance, parallel); } public Vector getParameters(){ return logisticRegression.getWeights().getAllWeights(); } public void setParameters(Vector parameters) { this.logisticRegression.getWeights().setWeightVector(parameters); this.isValueCacheValid=false; this.isGradientCacheValid=false; } public double getValue() { if (isValueCacheValid){ return this.value; } double kl = logisticRegression.dataSetKLWeightedDivergence(dataSet, targetDistributions, weights); if (logger.isDebugEnabled()){ logger.debug("kl divergence = "+kl); } this.value = kl + penaltyValue(); this.isValueCacheValid = true; return this.value; } private double penaltyValue(int classIndex){ double square = 0; Vector weightVector = logisticRegression.getWeights().getWeightsWithoutBiasForClass(classIndex); square += weightVector.dot(weightVector); return square/(2*priorGaussianVariance); } // total penalty public double penaltyValue(){ IntStream intStream; if (isParallel){ intStream = IntStream.range(0, numClasses).parallel(); } else { intStream = IntStream.range(0, numClasses); } return intStream.mapToDouble(this::penaltyValue).sum(); } public Vector getGradient(){ if (isGradientCacheValid){ return this.gradient; } updateClassProbMatrix(); updatePredictedCounts(); updateGradient(); this.isGradientCacheValid = true; return this.gradient; } private void updateGradient(){ this.gradient = this.predictedCounts.minus(empiricalCounts).plus(penaltyGradient()); } private Vector penaltyGradient(){ Vector weightsVector = this.logisticRegression.getWeights().getAllWeights(); Vector penalty = new DenseVector(weightsVector.size()); penalty = penalty.plus(weightsVector.divide(priorGaussianVariance)); for (int j:logisticRegression.getWeights().getAllBiasPositions()){ penalty.set(j,0); } return penalty; } //todo removed isParallel private void updateEmpricalCounts(){ IntStream intStream; if (isParallel){ intStream = IntStream.range(0, numParameters).parallel(); } else { intStream = IntStream.range(0, numParameters); } intStream.forEach(i -> this.empiricalCounts.set(i, calEmpricalCount(i))); } private void updatePredictedCounts(){ IntStream intStream; if (isParallel){ intStream = IntStream.range(0,numParameters).parallel(); } else { intStream = IntStream.range(0,numParameters); } intStream.forEach(i -> this.predictedCounts.set(i, calPredictedCount(i))); } private double calEmpricalCount(int parameterIndex){ int classIndex = logisticRegression.getWeights().getClassIndex(parameterIndex); int featureIndex = logisticRegression.getWeights().getFeatureIndex(parameterIndex); double count = 0; //bias if (featureIndex == -1){ for (int i=0;i<dataSet.getNumDataPoints();i++){ count += targetDistributions[i][classIndex]* weights[i]; } } else { Vector featureColumn = dataSet.getColumn(featureIndex); for (Vector.Element element: featureColumn.nonZeroes()){ int dataPointIndex = element.index(); double featureValue = element.get(); count += featureValue*targetDistributions[dataPointIndex][classIndex]* weights[dataPointIndex]; } } return count; } private double calPredictedCount(int parameterIndex){ int classIndex = logisticRegression.getWeights().getClassIndex(parameterIndex); int featureIndex = logisticRegression.getWeights().getFeatureIndex(parameterIndex); double count = 0; double[] probs = this.probabilityMatrix[classIndex]; //bias if (featureIndex == -1){ for (int i=0;i<dataSet.getNumDataPoints();i++){ count += probs[i]* weights[i]; } } else { Vector featureColumn = dataSet.getColumn(featureIndex); for (Vector.Element element: featureColumn.nonZeroes()){ int dataPointIndex = element.index(); double featureValue = element.get(); count += probs[dataPointIndex]*featureValue* weights[dataPointIndex]; } } return count; } private void updateClassProbs(int dataPointIndex){ double[] probs = logisticRegression.predictClassProbs(dataSet.getRow(dataPointIndex)); for (int k=0;k<numClasses;k++){ this.probabilityMatrix[k][dataPointIndex]=probs[k]; } } private void updateClassProbMatrix(){ IntStream intStream; if (isParallel){ intStream = IntStream.range(0,dataSet.getNumDataPoints()).parallel(); } else { intStream = IntStream.range(0,dataSet.getNumDataPoints()); } intStream.forEach(this::updateClassProbs); } public GradientMatrix getGradientMatrix() { return gradientMatrix; } private static double[] defaultWeights(int numDataPoints){ double[] weights = new double[numDataPoints]; Arrays.fill(weights,1.0); return weights; } private static double[][] defaultTargetDistribution(ClfDataSet dataSet){ double[][] targetDistributions = new double[dataSet.getNumDataPoints()][dataSet.getNumClasses()]; int[] labels = dataSet.getLabels(); for (int i=0;i<labels.length;i++){ int label = labels[i]; targetDistributions[i][label]=1; } return targetDistributions; } }
src/main/java/edu/neu/ccs/pyramid/classification/logistic_regression/LogisticLoss.java
package edu.neu.ccs.pyramid.classification.logistic_regression; import edu.neu.ccs.pyramid.dataset.ClfDataSet; import edu.neu.ccs.pyramid.dataset.DataSet; import edu.neu.ccs.pyramid.dataset.GradientMatrix; import edu.neu.ccs.pyramid.dataset.ProbabilityMatrix; import edu.neu.ccs.pyramid.optimization.Optimizable; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.mahout.math.DenseVector; import org.apache.mahout.math.Vector; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.IntStream; /** * Created by Rainicy on 10/24/15. */ public class LogisticLoss implements Optimizable.ByGradientValue { private static final Logger logger = LogManager.getLogger(); private LogisticRegression logisticRegression; private DataSet dataSet; // instance weights private double[] weights; private double[][] targetDistributions; private Vector empiricalCounts; private Vector predictedCounts; private Vector gradient; private int numParameters; private int numClasses; /** * numDataPoints by numClasses; */ private ProbabilityMatrix probabilityMatrix; //todo the concept is not unified in logistic regression and gradient boosting /** * actually negative gradient * y_ik - p_k(x_i) * numClasses by numDataPoints */ private GradientMatrix gradientMatrix; private double value; private boolean isGradientCacheValid; private boolean isValueCacheValid; private boolean isParallel = false; private double priorGaussianVariance; public LogisticLoss(LogisticRegression logisticRegression, DataSet dataSet, double[] weights, double[][] targetDistributions, double priorGaussianVariance, boolean parallel) { this.logisticRegression = logisticRegression; this.targetDistributions = targetDistributions; this.isParallel = parallel; numParameters = logisticRegression.getWeights().totalSize(); this.dataSet = dataSet; this.weights = weights; this.priorGaussianVariance = priorGaussianVariance; this.empiricalCounts = new DenseVector(numParameters); this.predictedCounts = new DenseVector(numParameters); this.numClasses = targetDistributions[0].length; this.probabilityMatrix = new ProbabilityMatrix(dataSet.getNumDataPoints(),numClasses); this.gradientMatrix = new GradientMatrix(dataSet.getNumDataPoints(),numClasses, GradientMatrix.Objective.MAXIMIZE); this.updateEmpricalCounts(); this.isValueCacheValid=false; this.isGradientCacheValid=false; } public LogisticLoss(LogisticRegression logisticRegression, DataSet dataSet, double[][] targetDistributions, double gaussianPriorVariance, boolean parallel) { this(logisticRegression,dataSet,defaultWeights(dataSet.getNumDataPoints()),targetDistributions,gaussianPriorVariance, parallel); } public LogisticLoss(LogisticRegression logisticRegression, ClfDataSet dataSet, double gaussianPriorVariance, boolean parallel){ this(logisticRegression,dataSet,defaultTargetDistribution(dataSet),gaussianPriorVariance, parallel); } public Vector getParameters(){ return logisticRegression.getWeights().getAllWeights(); } public void setParameters(Vector parameters) { this.logisticRegression.getWeights().setWeightVector(parameters); this.isValueCacheValid=false; this.isGradientCacheValid=false; } public double getValue() { if (isValueCacheValid){ return this.value; } double kl = logisticRegression.dataSetKLWeightedDivergence(dataSet, targetDistributions, weights); if (logger.isDebugEnabled()){ logger.debug("kl divergence = "+kl); } this.value = kl + penaltyValue(); this.isValueCacheValid = true; return this.value; } private double penaltyValue(int classIndex){ double square = 0; Vector weightVector = logisticRegression.getWeights().getWeightsWithoutBiasForClass(classIndex); square += weightVector.dot(weightVector); return square/(2*priorGaussianVariance); } // total penalty public double penaltyValue(){ IntStream intStream; if (isParallel){ intStream = IntStream.range(0, numClasses).parallel(); } else { intStream = IntStream.range(0, numClasses); } return intStream.mapToDouble(this::penaltyValue).sum(); } public Vector getGradient(){ if (isGradientCacheValid){ return this.gradient; } updateClassProbMatrix(); updatePredictedCounts(); updateGradient(); this.isGradientCacheValid = true; return this.gradient; } private void updateGradient(){ this.gradient = this.predictedCounts.minus(empiricalCounts).plus(penaltyGradient()); } private Vector penaltyGradient(){ Vector weightsVector = this.logisticRegression.getWeights().getAllWeights(); Vector penalty = new DenseVector(weightsVector.size()); penalty = penalty.plus(weightsVector.divide(priorGaussianVariance)); for (int j:logisticRegression.getWeights().getAllBiasPositions()){ penalty.set(j,0); } return penalty; } //todo removed isParallel private void updateEmpricalCounts(){ IntStream intStream; if (isParallel){ intStream = IntStream.range(0, numParameters).parallel(); } else { intStream = IntStream.range(0, numParameters); } intStream.forEach(i -> this.empiricalCounts.set(i, calEmpricalCount(i))); } private void updatePredictedCounts(){ IntStream intStream; if (isParallel){ intStream = IntStream.range(0,numParameters).parallel(); } else { intStream = IntStream.range(0,numParameters); } intStream.forEach(i -> this.predictedCounts.set(i, calPredictedCount(i))); } private double calEmpricalCount(int parameterIndex){ int classIndex = logisticRegression.getWeights().getClassIndex(parameterIndex); int featureIndex = logisticRegression.getWeights().getFeatureIndex(parameterIndex); double count = 0; //bias if (featureIndex == -1){ for (int i=0;i<dataSet.getNumDataPoints();i++){ count += targetDistributions[i][classIndex]* weights[i]; } } else { Vector featureColumn = dataSet.getColumn(featureIndex); for (Vector.Element element: featureColumn.nonZeroes()){ int dataPointIndex = element.index(); double featureValue = element.get(); count += featureValue*targetDistributions[dataPointIndex][classIndex]* weights[dataPointIndex]; } } return count; } private double calPredictedCount(int parameterIndex){ int classIndex = logisticRegression.getWeights().getClassIndex(parameterIndex); int featureIndex = logisticRegression.getWeights().getFeatureIndex(parameterIndex); double count = 0; double[] probs = this.probabilityMatrix.getProbabilitiesForClass(classIndex); //bias if (featureIndex == -1){ for (int i=0;i<dataSet.getNumDataPoints();i++){ count += probs[i]* weights[i]; } } else { Vector featureColumn = dataSet.getColumn(featureIndex); for (Vector.Element element: featureColumn.nonZeroes()){ int dataPointIndex = element.index(); double featureValue = element.get(); count += probs[dataPointIndex]*featureValue* weights[dataPointIndex]; } } return count; } private void updateClassProbs(int dataPointIndex){ double[] probs = logisticRegression.predictClassProbs(dataSet.getRow(dataPointIndex)); for (int k=0;k<numClasses;k++){ this.probabilityMatrix.setProbability(dataPointIndex,k,probs[k]); } } private void updateClassProbMatrix(){ IntStream intStream; if (isParallel){ intStream = IntStream.range(0,dataSet.getNumDataPoints()).parallel(); } else { intStream = IntStream.range(0,dataSet.getNumDataPoints()); } intStream.forEach(this::updateClassProbs); } public ProbabilityMatrix getProbabilityMatrix() { return probabilityMatrix; } public GradientMatrix getGradientMatrix() { return gradientMatrix; } private static double[] defaultWeights(int numDataPoints){ double[] weights = new double[numDataPoints]; Arrays.fill(weights,1.0); return weights; } private static double[][] defaultTargetDistribution(ClfDataSet dataSet){ double[][] targetDistributions = new double[dataSet.getNumDataPoints()][dataSet.getNumClasses()]; int[] labels = dataSet.getLabels(); for (int i=0;i<labels.length;i++){ int label = labels[i]; targetDistributions[i][label]=1; } return targetDistributions; } }
change ProbabilityMatrix in logistic loss
src/main/java/edu/neu/ccs/pyramid/classification/logistic_regression/LogisticLoss.java
change ProbabilityMatrix in logistic loss
<ide><path>rc/main/java/edu/neu/ccs/pyramid/classification/logistic_regression/LogisticLoss.java <ide> private Vector gradient; <ide> private int numParameters; <ide> private int numClasses; <del> /** <del> * numDataPoints by numClasses; <del> */ <del> private ProbabilityMatrix probabilityMatrix; <add> <add> // size = num classes * num data <add> private double[][] probabilityMatrix; <ide> <ide> //todo the concept is not unified in logistic regression and gradient boosting <ide> <ide> this.empiricalCounts = new DenseVector(numParameters); <ide> this.predictedCounts = new DenseVector(numParameters); <ide> this.numClasses = targetDistributions[0].length; <del> this.probabilityMatrix = new ProbabilityMatrix(dataSet.getNumDataPoints(),numClasses); <add> this.probabilityMatrix = new double[numClasses][dataSet.getNumDataPoints()]; <ide> this.gradientMatrix = new GradientMatrix(dataSet.getNumDataPoints(),numClasses, GradientMatrix.Objective.MAXIMIZE); <ide> this.updateEmpricalCounts(); <ide> this.isValueCacheValid=false; <ide> int classIndex = logisticRegression.getWeights().getClassIndex(parameterIndex); <ide> int featureIndex = logisticRegression.getWeights().getFeatureIndex(parameterIndex); <ide> double count = 0; <del> double[] probs = this.probabilityMatrix.getProbabilitiesForClass(classIndex); <add> double[] probs = this.probabilityMatrix[classIndex]; <ide> //bias <ide> if (featureIndex == -1){ <ide> for (int i=0;i<dataSet.getNumDataPoints();i++){ <ide> private void updateClassProbs(int dataPointIndex){ <ide> double[] probs = logisticRegression.predictClassProbs(dataSet.getRow(dataPointIndex)); <ide> for (int k=0;k<numClasses;k++){ <del> this.probabilityMatrix.setProbability(dataPointIndex,k,probs[k]); <add> this.probabilityMatrix[k][dataPointIndex]=probs[k]; <ide> } <ide> } <ide> <ide> <ide> <ide> <del> <del> public ProbabilityMatrix getProbabilityMatrix() { <del> return probabilityMatrix; <del> } <ide> <ide> public GradientMatrix getGradientMatrix() { <ide> return gradientMatrix;
Java
apache-2.0
error: pathspec 'management/server/core/messenger/messenger-rest/src/test/java/org/safehaus/subutai/core/messenger/rest/RestServiceImplTest.java' did not match any file(s) known to git
c70d2f1f9e18fd6ba9c9a762296a3cda17503212
1
subutai-io/base,subutai-io/base,subutai-io/Subutai,subutai-io/Subutai,subutai-io/Subutai,subutai-io/Subutai,subutai-io/base,subutai-io/base,subutai-io/Subutai,subutai-io/Subutai
package org.safehaus.subutai.core.messenger.rest; import javax.ws.rs.core.Response; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.safehaus.subutai.core.messenger.api.MessageException; import org.safehaus.subutai.core.messenger.api.MessageProcessor; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doThrow; @RunWith( MockitoJUnitRunner.class ) public class RestServiceImplTest { @Mock MessageProcessor messageProcessor; RestServiceImpl restService; @Before public void setUp() throws Exception { restService = new RestServiceImpl( messageProcessor ); } @Test( expected = NullPointerException.class ) public void testConstructor() throws Exception { new RestServiceImpl( null ); } @Test public void testProcessMessage() throws Exception { Response response = restService.processMessage( "" ); assertEquals( Response.Status.ACCEPTED.getStatusCode(), response.getStatus() ); } @Test public void testProcessMessageException() throws Exception { doThrow( new MessageException( "" ) ).when( messageProcessor ).processMessage( anyString() ); Response response = restService.processMessage( "" ); assertEquals( Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus() ); } }
management/server/core/messenger/messenger-rest/src/test/java/org/safehaus/subutai/core/messenger/rest/RestServiceImplTest.java
unit tests for messenger
management/server/core/messenger/messenger-rest/src/test/java/org/safehaus/subutai/core/messenger/rest/RestServiceImplTest.java
unit tests for messenger
<ide><path>anagement/server/core/messenger/messenger-rest/src/test/java/org/safehaus/subutai/core/messenger/rest/RestServiceImplTest.java <add>package org.safehaus.subutai.core.messenger.rest; <add> <add> <add>import javax.ws.rs.core.Response; <add> <add>import org.junit.Before; <add>import org.junit.Test; <add>import org.junit.runner.RunWith; <add>import org.mockito.Mock; <add>import org.mockito.runners.MockitoJUnitRunner; <add>import org.safehaus.subutai.core.messenger.api.MessageException; <add>import org.safehaus.subutai.core.messenger.api.MessageProcessor; <add> <add>import static org.junit.Assert.assertEquals; <add>import static org.mockito.Matchers.anyString; <add>import static org.mockito.Mockito.doThrow; <add> <add> <add>@RunWith( MockitoJUnitRunner.class ) <add>public class RestServiceImplTest <add>{ <add> @Mock <add> MessageProcessor messageProcessor; <add> RestServiceImpl restService; <add> <add> <add> @Before <add> public void setUp() throws Exception <add> { <add> restService = new RestServiceImpl( messageProcessor ); <add> } <add> <add> <add> @Test( expected = NullPointerException.class ) <add> public void testConstructor() throws Exception <add> { <add> new RestServiceImpl( null ); <add> } <add> <add> <add> @Test <add> public void testProcessMessage() throws Exception <add> { <add> Response response = restService.processMessage( "" ); <add> <add> assertEquals( Response.Status.ACCEPTED.getStatusCode(), response.getStatus() ); <add> } <add> <add> <add> @Test <add> public void testProcessMessageException() throws Exception <add> { <add> doThrow( new MessageException( "" ) ).when( messageProcessor ).processMessage( anyString() ); <add> <add> Response response = restService.processMessage( "" ); <add> <add> assertEquals( Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus() ); <add> } <add>}
Java
apache-2.0
9647d174411f229a2a0400c7fe21fff62b11d995
0
MatthewTamlin/AndroidUtilities
/* * Copyright 2016 Matthew Tamlin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.matthewtamlin.android_utilities.library.utilities; /** * Provides access to the UI thread. */ public interface UiThreadUtil { /** * Submits the supplied runnable to the UI thread. * * @param runnable * the runnable to submit, cannot be null */ public void runOnUiThread(Runnable runnable); }
library/src/main/java/com/matthewtamlin/android_utilities/library/utilities/UiThreadUtil.java
/* * Copyright 2016 Matthew Tamlin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.matthewtamlin.android_utilities.library.utilities; /** * Provides access to the UI thread. */ public interface UiThreadUtil { /** * Submits the supplied runnable to the UI thread. * * @param runnable * the runnable to submit, may be null */ public void runOnUiThread(Runnable runnable); }
docs(utilities): fixed Javadoc regarding null condition
library/src/main/java/com/matthewtamlin/android_utilities/library/utilities/UiThreadUtil.java
docs(utilities): fixed Javadoc regarding null condition
<ide><path>ibrary/src/main/java/com/matthewtamlin/android_utilities/library/utilities/UiThreadUtil.java <ide> * Submits the supplied runnable to the UI thread. <ide> * <ide> * @param runnable <del> * the runnable to submit, may be null <add> * the runnable to submit, cannot be null <ide> */ <ide> public void runOnUiThread(Runnable runnable); <ide> }
Java
agpl-3.0
9d06347e9aec28b5a637f2b561d4f7ce9ae3a885
0
Tanaguru/Tanaguru,Tanaguru/Tanaguru,Tanaguru/Tanaguru,Tanaguru/Tanaguru
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.tanaguru.kafka.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.logging.Level; import javax.xml.parsers.ParserConfigurationException; import kafka.consumer.KafkaStream; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.log4j.Logger; import org.hibernate.Hibernate; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.safety.Whitelist; import org.springframework.context.support.ReloadableResourceBundleMessageSource; import org.tanaguru.entity.audit.Audit; import org.tanaguru.entity.audit.AuditStatus; import org.tanaguru.entity.audit.EvidenceElement; import org.tanaguru.entity.audit.ProcessRemark; import org.tanaguru.entity.audit.ProcessResult; import org.tanaguru.entity.audit.SourceCodeRemark; import org.tanaguru.entity.parameterization.Parameter; import org.tanaguru.entity.service.audit.AuditDataService; import org.tanaguru.entity.service.audit.ProcessResultDataService; import org.tanaguru.entity.service.parameterization.ParameterDataService; import org.tanaguru.entity.service.parameterization.ParameterElementDataService; import org.tanaguru.entity.service.audit.ProcessRemarkDataService; import org.tanaguru.entity.service.statistics.WebResourceStatisticsDataService; import org.tanaguru.entity.service.subject.WebResourceDataService; import org.tanaguru.entity.statistics.WebResourceStatistics; import org.tanaguru.kafka.messaging.Consumer; import org.tanaguru.kafka.messaging.MessagesProducer; import org.tanaguru.service.AuditService; import org.tanaguru.service.AuditServiceListener; import org.xml.sax.SAXException; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.tanaguru.entity.audit.Content; import org.tanaguru.entity.audit.RelatedContent; import org.tanaguru.entity.audit.SSP; import org.tanaguru.entity.dao.audit.ContentDAO; import org.tanaguru.entity.service.audit.ContentDataService; import org.tanaguru.entity.service.statistics.TestStatisticsDataService; /** * * @author omokeddem at oceaneconsulting * */ public class AuditPageConsumed implements AuditServiceListener { private ParameterDataService parameterDataService; private AuditService auditService; private ParameterElementDataService parameterElementDataService; private AuditDataService auditDataService; private ProcessResultDataService processResultDataService; private ProcessRemarkDataService processRemarkDataService; private WebResourceStatisticsDataService webResourceStatisticsDataService; private WebResourceDataService webResourceDataService; private ContentDataService contentDataService; private TestStatisticsDataService testStatisticsDataService; private MessagesProducer messagesProducer; private ExposedResourceMessageBundleSource referentialAw22Theme; private ExposedResourceMessageBundleSource referentialAw22Criterion; private ExposedResourceMessageBundleSource referentialAw22Rule; private ExposedResourceMessageBundleSource referentialRgaa2Theme; private ExposedResourceMessageBundleSource referentialRgaa2Criterion; private ExposedResourceMessageBundleSource referentialRgaa2Rule; private ExposedResourceMessageBundleSource referentialRgaa3Theme; private ExposedResourceMessageBundleSource referentialRgaa3Criterion; private ExposedResourceMessageBundleSource referentialRgaa3Rule; private ExposedResourceMessageBundleSource referentialRgaa32016Theme; private ExposedResourceMessageBundleSource referentialRgaa32016Criterion; private ExposedResourceMessageBundleSource referentialRgaa32016Rule; private ExposedResourceMessageBundleSource remarkMessage; private String dbHost; private String dbPort; private String dbUserName; private String dbPassWord; private String dbName; private HashMap<Long, String> auditType = new HashMap<Long, String>(); private HashMap<Long, String> tagsByAudit = new HashMap<Long, String>(); private HashMap<Long, String> auditHash = new HashMap<Long, String>(); private HashMap<Long, String> auditName = new HashMap<Long, String>(); private HashMap<Long, String> auditUrl = new HashMap<Long, String>(); private HashMap<Long, String> auditRef = new HashMap<Long, String>(); private HashMap<Long, String> auditLevel = new HashMap<Long, String>(); private HashMap<Long, String> auditLanguage = new HashMap<Long, String>(); private HashMap<Long, Boolean> auditDescriptionRef = new HashMap<Long, Boolean>(); private HashMap<Long, Integer> auditScreenWidth = new HashMap<Long, Integer>(); private HashMap<Long, Integer> auditScreenHeight = new HashMap<Long, Integer>(); private HashMap<Long, Boolean> auditHtmlTags = new HashMap<Long, Boolean>(); private String compaignHash; private MessageConsumerLimit messageConsumerLimit; private final char Separator = ((char) 007); private static final Logger logger = Logger.getLogger(AuditPageConsumed.class); public void setMessageConsumerLimit(MessageConsumerLimit _messageConsumerLimit) { this.messageConsumerLimit = _messageConsumerLimit; this.messageConsumerLimit.setCurrentNumberMessagesEvent(0); this.messageConsumerLimit.setCurrentNumberMessagesRest(0); } public AuditPageConsumed(ParameterDataService a_parameterDataService, AuditService a_auditService, ParameterElementDataService a_parameterElementDataService, AuditDataService a_auditDataService, ProcessResultDataService a_processResultDataService, WebResourceDataService a_webResourceDataService, WebResourceStatisticsDataService a_webResourceStatisticsDataService, ProcessRemarkDataService a_processRemarkDataService, ContentDataService a_contentDataService, MessagesProducer a_messagesProducer, ExposedResourceMessageBundleSource a_referentialAw22Theme, ExposedResourceMessageBundleSource a_referentialAw22Criterion, ExposedResourceMessageBundleSource a_referentialAw22Rule, ExposedResourceMessageBundleSource a_referentialRgaa2Theme, ExposedResourceMessageBundleSource a_referentialRgaa2Criterion, ExposedResourceMessageBundleSource a_referentialRgaa2Rule, ExposedResourceMessageBundleSource a_referentialRgaa3Theme, ExposedResourceMessageBundleSource a_referentialRgaa3Criterion, ExposedResourceMessageBundleSource a_referentialRgaa3Rule, ExposedResourceMessageBundleSource a_referentialRgaa32016Theme, ExposedResourceMessageBundleSource a_referentialRgaa32016Criterion, ExposedResourceMessageBundleSource a_referentialRgaa32016Rule, ExposedResourceMessageBundleSource a_remarkMessage, String a_dbHost, String a_dbPort, String a_dbUserName, String a_dbPassWord, String a_dbName) { parameterDataService = a_parameterDataService; auditService = a_auditService; parameterElementDataService = a_parameterElementDataService; auditDataService = a_auditDataService; processResultDataService = a_processResultDataService; webResourceDataService = a_webResourceDataService; webResourceStatisticsDataService = a_webResourceStatisticsDataService; processRemarkDataService = a_processRemarkDataService; contentDataService = a_contentDataService; messagesProducer = a_messagesProducer; referentialAw22Theme = a_referentialAw22Theme; referentialAw22Criterion = a_referentialAw22Criterion; referentialAw22Rule = a_referentialAw22Rule; referentialRgaa2Theme = a_referentialRgaa2Theme; referentialRgaa2Criterion = a_referentialRgaa2Criterion; referentialRgaa2Rule = a_referentialRgaa2Rule; referentialRgaa3Theme = a_referentialRgaa3Theme; referentialRgaa3Criterion = a_referentialRgaa3Criterion; referentialRgaa3Rule = a_referentialRgaa3Rule; referentialRgaa32016Theme = a_referentialRgaa32016Theme; referentialRgaa32016Criterion = a_referentialRgaa32016Criterion; referentialRgaa32016Rule = a_referentialRgaa32016Rule; remarkMessage = a_remarkMessage; dbHost = a_dbHost; dbPort = a_dbPort; dbUserName = a_dbUserName; dbPassWord = a_dbPassWord; dbName = a_dbName; auditService.add(this); } public Map<String, String> getMessages(ExposedResourceMessageBundleSource messageSource, Locale locale) { Properties properties = messageSource.getMessages(locale); Map<String, String> messagesMap = new HashMap<String, String>(); for (Map.Entry<Object, Object> entry : properties.entrySet()) { if (entry.getKey() != null && entry.getValue() != null) { messagesMap.put(entry.getKey().toString(), entry.getValue().toString()); } } return messagesMap; } public JSONObject getDescriptionFromRef(String Ref, String language, String entity, Boolean htmlTags) throws JSONException { JSONObject result = new JSONObject(); Map<String, String> allMessages = null; switch (Ref) { case "Rgaa32016": switch (entity) { case "Theme": if (language.equals("fr")) { allMessages = getMessages(referentialRgaa32016Theme, Locale.FRENCH); } else if (language.equals("en")) { allMessages = getMessages(referentialRgaa32016Theme, Locale.ENGLISH); } else if (language.equals("es_fr") || language.equals("es_en")) { allMessages = getMessages(referentialRgaa32016Theme, new Locale("es")); } break; case "Criterion": if (language.equals("fr") || language.equals("es_fr")) { allMessages = getMessages(referentialRgaa32016Criterion, Locale.FRENCH); } else if (language.equals("en") || language.equals("es_en")) { allMessages = getMessages(referentialRgaa32016Criterion, Locale.ENGLISH); } break; case "Rule": if (language.equals("fr") || language.equals("es_fr")) { allMessages = getMessages(referentialRgaa32016Rule, Locale.FRENCH); } else if (language.equals("en") || language.equals("es_en")) { allMessages = getMessages(referentialRgaa32016Rule, Locale.ENGLISH); } break; } break; case "Rgaa30": switch (entity) { case "Theme": if (language.equals("fr")) { allMessages = getMessages(referentialRgaa3Theme, Locale.FRENCH); } else if (language.equals("en")) { allMessages = getMessages(referentialRgaa3Theme, Locale.ENGLISH); } else if (language.equals("es_fr") || language.equals("es_en")) { allMessages = getMessages(referentialRgaa3Theme, new Locale("es")); } break; case "Criterion": if (language.equals("fr") || language.equals("es_fr")) { allMessages = getMessages(referentialRgaa3Criterion, Locale.FRENCH); } else if (language.equals("en") || language.equals("es_en")) { allMessages = getMessages(referentialRgaa3Criterion, Locale.ENGLISH); } break; case "Rule": if (language.equals("fr") || language.equals("es_fr")) { allMessages = getMessages(referentialRgaa3Rule, Locale.FRENCH); } else if (language.equals("en") || language.equals("es_en")) { allMessages = getMessages(referentialRgaa3Rule, Locale.ENGLISH); } break; } break; case "Rgaa2": switch (entity) { case "Theme": if (language.equals("fr")) { allMessages = getMessages(referentialRgaa2Theme, Locale.FRENCH); } else if (language.equals("en")) { allMessages = getMessages(referentialRgaa2Theme, Locale.ENGLISH); } else if (language.equals("es_fr") || language.equals("es_en")) { allMessages = getMessages(referentialRgaa2Theme, new Locale("es")); } break; case "Criterion": if (language.equals("fr") || language.equals("es_fr")) { allMessages = getMessages(referentialRgaa2Criterion, Locale.FRENCH); } else if (language.equals("en") || language.equals("es_en")) { allMessages = getMessages(referentialRgaa2Criterion, Locale.ENGLISH); } break; case "Rule": if (language.equals("fr") || language.equals("es_fr")) { allMessages = getMessages(referentialRgaa2Rule, Locale.FRENCH); } else if (language.equals("en") || language.equals("es_en")) { allMessages = getMessages(referentialRgaa2Rule, Locale.ENGLISH); } break; } break; case "Aw22": switch (entity) { case "Theme": if (language.equals("fr")) { allMessages = getMessages(referentialAw22Theme, Locale.FRENCH); } else if (language.equals("en")) { allMessages = getMessages(referentialAw22Theme, Locale.ENGLISH); } else if (language.equals("es_fr") || language.equals("es_en")) { allMessages = getMessages(referentialAw22Theme, new Locale("es")); } break; case "Criterion": if (language.equals("fr") || language.equals("es_fr")) { allMessages = getMessages(referentialAw22Criterion, Locale.FRENCH); } else if (language.equals("en") || language.equals("es_en")) { allMessages = getMessages(referentialAw22Criterion, Locale.ENGLISH); } break; case "Rule": if (language.equals("fr") || language.equals("es_fr")) { allMessages = getMessages(referentialAw22Rule, Locale.FRENCH); } else if (language.equals("en") || language.equals("es_en")) { allMessages = getMessages(referentialAw22Rule, Locale.ENGLISH); } break; } break; } for (Map.Entry<String, String> entrySet : allMessages.entrySet()) { String key = entrySet.getKey(); String value; if (htmlTags) { value = StringEscapeUtils.unescapeHtml4(entrySet.getValue()); } else { value = Jsoup.parse(entrySet.getValue()).text(); } result.put(key, value); } return result; } public JSONObject createAuditJson(Audit audit) throws JSONException, ParseException, URISyntaxException { JSONObject auditJson = new JSONObject(); String language = auditLanguage.get(audit.getId()); Boolean descriptionRef = auditDescriptionRef.get(audit.getId()); String ref = auditRef.get(audit.getId()); Boolean htmlTags = auditHtmlTags.get(audit.getId()); auditJson.put("url", auditUrl.get(audit.getId())); auditJson.put("status", audit.getStatus()); auditJson.put("ref", ref); auditJson.put("level", auditLevel.get(audit.getId())); auditJson.put("language", auditLanguage.get(audit.getId())); auditJson.put("screen_width", auditScreenWidth.get(audit.getId())); auditJson.put("screen_height", auditScreenHeight.get(audit.getId())); if (audit.getStatus() == AuditStatus.COMPLETED) { List<ProcessResult> processResultList = (List<ProcessResult>) processResultDataService.getNetResultFromAudit(audit); WebResourceStatistics webResourceStatistics = webResourceStatisticsDataService.getWebResourceStatisticsByWebResource(audit.getSubject()); auditJson.put("score", webResourceStatistics.getRawMark()); auditJson.put("nb_passed", webResourceStatistics.getNbOfPassed()); auditJson.put("nb_failed", webResourceStatistics.getNbOfFailed()); auditJson.put("nb_nmi", webResourceStatistics.getNbOfNmi()); auditJson.put("nb_na", webResourceStatistics.getNbOfNa()); auditJson.put("nb_failed_occurences", webResourceStatistics.getNbOfFailedOccurences()); auditJson.put("nb_detected", webResourceStatistics.getNbOfDetected()); auditJson.put("http_status_code", webResourceStatistics.getHttpStatusCode()); auditJson.put("nb_suspected", webResourceStatistics.getNbOfSuspected()); auditJson.put("nb_not_tested", webResourceStatistics.getNbOfNotTested()); JSONArray remarkArray = new JSONArray(); JSONArray testPassedArray = new JSONArray(); JSONArray testNAArray = new JSONArray(); JSONArray testNTArray = new JSONArray(); JSONObject themesFr = new JSONObject(); JSONObject themesEn = new JSONObject(); JSONObject themesEs = new JSONObject(); JSONObject criterionsFr = new JSONObject(); JSONObject criterionsEn = new JSONObject(); JSONObject testsFr = new JSONObject(); JSONObject testsEn = new JSONObject(); if (descriptionRef) { if (language.equals("fr") || language.equals("all")) { themesFr = getDescriptionFromRef(ref, "fr", "Theme", htmlTags); } if (language.equals("en") || language.equals("all")) { themesEn = getDescriptionFromRef(ref, "en", "Theme", htmlTags); } if (language.equals("es_fr") || language.equals("es_en") || language.equals("all")) { themesEs = getDescriptionFromRef(ref, "es_en", "Theme", htmlTags); } if (language.equals("fr") || language.equals("es_fr") || language.equals("all")) { testsFr = getDescriptionFromRef(ref, "fr", "Rule", htmlTags); criterionsFr = getDescriptionFromRef(ref, "fr", "Criterion", htmlTags); } if (language.equals("en") || language.equals("es_en") || language.equals("all")) { testsEn = getDescriptionFromRef(ref, "en", "Rule", htmlTags); criterionsEn = getDescriptionFromRef(ref, "en", "Criterion", htmlTags); } } for (ProcessResult result : processResultList) { if (result.getTest().getLabel().equals("8.2.1")) { auditJson.put("nb_w3c_invalidated", result.getElementCounter()); } // create testPassed object from ProcessResult JSONObject testPassedObject = new JSONObject(); if (result.getValue().toString().equals("PASSED")) { putTests(result, testPassedObject); testPassedArray.put(testPassedObject); } JSONObject testNTObject = new JSONObject(); if (result.getValue().toString().equals("NOT_TESTED")) { putTests(result, testNTObject); testNTArray.put(testNTObject); } // create testNA object from ProcessResult JSONObject testNAObject = new JSONObject(); if (result.getValue().toString().equals("NOT_APPLICABLE")) { putTests(result, testNAObject); testNAArray.put(testNAObject); } // get remark from processResult & create array of remark int nbrRemarkW3c = 0; Set<ProcessRemark> processRemarkList = (Set<ProcessRemark>) processRemarkDataService.findProcessRemarksFromProcessResult(result, -1); for (ProcessRemark processRemark : processRemarkList) { if (result.getTest().getLabel().equals("8.2.1")) { if (nbrRemarkW3c < 10) { nbrRemarkW3c++; } else { break; } } JSONObject remarkObject = new JSONObject(); String remark_fr, remark_en, remark_es; if (htmlTags) { remark_fr = StringEscapeUtils.unescapeHtml4(remarkMessage.getMessage(processRemark.getMessageCode(), processRemark instanceof SourceCodeRemark ? new Object[]{((SourceCodeRemark) processRemark).getTarget()} : null, Locale.FRENCH)); remark_en = StringEscapeUtils.unescapeHtml4(remarkMessage.getMessage(processRemark.getMessageCode(), processRemark instanceof SourceCodeRemark ? new Object[]{((SourceCodeRemark) processRemark).getTarget()} : null, Locale.ENGLISH)); remark_es = StringEscapeUtils.unescapeHtml4(remarkMessage.getMessage(processRemark.getMessageCode(), processRemark instanceof SourceCodeRemark ? new Object[]{((SourceCodeRemark) processRemark).getTarget()} : null, new Locale("es"))); } else { remark_fr = Jsoup.parse(remarkMessage.getMessage(processRemark.getMessageCode(), processRemark instanceof SourceCodeRemark ? new Object[]{((SourceCodeRemark) processRemark).getTarget()} : null, Locale.FRENCH)).text(); remark_en = Jsoup.parse(remarkMessage.getMessage(processRemark.getMessageCode(), processRemark instanceof SourceCodeRemark ? new Object[]{((SourceCodeRemark) processRemark).getTarget()} : null, Locale.ENGLISH)).text(); remark_es = Jsoup.parse(remarkMessage.getMessage(processRemark.getMessageCode(), processRemark instanceof SourceCodeRemark ? new Object[]{((SourceCodeRemark) processRemark).getTarget()} : null, new Locale("es"))).text(); } if (processRemark instanceof SourceCodeRemark) { remarkObject.put("issue", processRemark.getIssue()); if (language.equals("fr") || language.equals("all")) { remarkObject.put("message_fr", remark_fr); } if (language.equals("en") || language.equals("all")) { remarkObject.put("message_en", remark_en); } if (language.equals("es_fr") || language.equals("es_en") || language.equals("all")) { remarkObject.put("message_es", remark_es); } //remarkObject.put("target", ((SourceCodeRemark) processRemark).getTarget()); remarkObject.put("line_number", ((SourceCodeRemark) processRemark).getLineNumber()); StringBuilder snippet = new StringBuilder(""); if (((SourceCodeRemark) processRemark).getSnippet() != null) { String snippetDirty = ((SourceCodeRemark) processRemark).getSnippet(); if (htmlTags) { snippet.append(StringEscapeUtils.unescapeHtml4(StringEscapeUtils.unescapeHtml4(snippetDirty.replace("\t", "")))); } else { snippet.append(snippetDirty.replace("\t", "")); } } remarkObject.put("snippet", snippet); } else { remarkObject.put("issue", processRemark.getIssue()); if (language.equals("fr") || language.equals("all")) { remarkObject.put("message_fr", remark_fr); } if (language.equals("en") || language.equals("all")) { remarkObject.put("message_en", remark_en); } if (language.equals("es_fr") || language.equals("es_en") || language.equals("all")) { remarkObject.put("message_es", remark_es); } } putTests(result, remarkObject); remarkArray.put(remarkObject); } } auditJson.put("remarks", remarkArray); auditJson.put("test_passed", testPassedArray); auditJson.put("test_na", testNAArray); auditJson.put("test_nt", testNTArray); if (themesFr.length() != 0) { auditJson.put("themes_description_fr", themesFr); } if (themesEn.length() != 0) { auditJson.put("themes_description_en", themesEn); } if (themesEs.length() != 0) { auditJson.put("themes_description_es", themesEs); } if (criterionsFr.length() != 0) { auditJson.put("criterions_description_fr", criterionsFr); } if (criterionsEn.length() != 0) { auditJson.put("criterions_description_en", criterionsEn); } if (testsFr.length() != 0) { auditJson.put("tests_description_fr", testsFr); } if (testsEn.length() != 0) { auditJson.put("tests_description_en", testsEn); } } return auditJson; } public void putTests(ProcessResult result, JSONObject remarkObject) throws JSONException { String codeTest = result.getTest().getCode(); String codeCriterion = result.getTest().getCriterion().getCode(); String codeTheme = result.getTest().getCriterion().getTheme().getCode(); remarkObject.put("theme", codeTheme); remarkObject.put("test", codeTest); remarkObject.put("criterion", codeCriterion); } @Override public void auditCompleted(Audit audit ) { try { if (auditType.get(audit.getId()) != null) { String messageToSend = ""; audit = auditDataService.read(audit.getId()); logger.debug("Audit terminated with success at " + audit.getDateOfCreation()); if (auditType.get(audit.getId()).equals("Rest")) { JSONObject auditJson = createAuditJson(audit); messageToSend = auditHash.get(audit.getId()) + Separator + auditJson; auditUrl.remove(audit.getId()); auditType.remove(audit.getId()); auditRef.remove(audit.getId()); auditLevel.remove(audit.getId()); auditLanguage.remove(audit.getId()); auditDescriptionRef.remove(audit.getId()); auditScreenWidth.remove(audit.getId()); auditScreenHeight.remove(audit.getId()); auditHtmlTags.remove(audit.getId()); auditHash.remove(audit.getId()); messageConsumerLimit.messageRestAudited(); } else if (auditType.get(audit.getId()).equals("Event")) { messageConsumerLimit.messageEventAudited(); int nbrW3cValidated = 0; if (audit.getStatus() == AuditStatus.COMPLETED) { List<ProcessResult> processResultList = (List<ProcessResult>) processResultDataService.getNetResultFromAudit(audit); for (ProcessResult result : processResultList) { if (result.getTest().getLabel().equals("8.2.1")) { nbrW3cValidated = result.getElementCounter(); } } } messageToSend = dbHost + ";" + dbPort + ";" + dbUserName + ";" + dbPassWord + ";" + dbName + ";" + audit.getId() + ";" + tagsByAudit.get(audit.getId()) + ";" + auditName.get(audit.getId()) + ";" + auditUrl.get(audit.getId()) + ";" + auditHash.get(audit.getId()) + ";" + compaignHash + ";" + nbrW3cValidated + ";" + auditRef.get(audit.getId()) + ";" + audit.getStatus(); tagsByAudit.remove(audit.getId()); auditHash.remove(audit.getId()); auditName.remove(audit.getId()); auditUrl.remove(audit.getId()); auditType.remove(audit.getId()); auditRef.remove(audit.getId()); auditLevel.remove(audit.getId()); } messagesProducer.sendMessage(messageToSend); } } catch (Exception ex) { logger.error("Producer Message Kafka ERROR : " + ex); } } @Override public void auditCrashed(Audit audit, Exception exception ) { //To change body of generated methods, choose Tools | Templates. if (auditType.get(audit.getId()) != null) { logger.error("crash (id+message): " + audit.getId() + " " + exception.toString()); if (auditType.get(audit.getId()).equals("Event")) { messageConsumerLimit.messageEventAudited(); } else if (auditType.get(audit.getId()).equals("Rest")) { messageConsumerLimit.messageRestAudited(); } tagsByAudit.remove(audit.getId()); auditHash.remove(audit.getId()); auditName.remove(audit.getId()); auditUrl.remove(audit.getId()); auditType.remove(audit.getId()); auditRef.remove(audit.getId()); auditLevel.remove(audit.getId()); auditLanguage.remove(audit.getId()); auditDescriptionRef.remove(audit.getId()); auditScreenWidth.remove(audit.getId()); auditScreenHeight.remove(audit.getId()); auditHtmlTags.remove(audit.getId()); } } public void auditPageEvent(String message, Set<Parameter> parameters, String ref, String level) { compaignHash = MessageEvent.getIdCampagne(message); Audit audit = auditService.auditPage(MessageEvent.getUrl(message), parameters); auditType.put(audit.getId(), "Event"); tagsByAudit.put(audit.getId(), MessageEvent.getTags(message)); auditHash.put(audit.getId(), MessageEvent.getHashAudit(message)); auditName.put(audit.getId(), MessageEvent.getName(message)); auditUrl.put(audit.getId(), MessageEvent.getUrl(message)); auditRef.put(audit.getId(), ref); auditLevel.put(audit.getId(), level); } public void auditPageRest(String message, Set<Parameter> parameters, String ref, String level) { Audit audit = auditService.auditPage(MessageRest.getUrl(message), parameters); auditType.put(audit.getId(), "Rest"); auditUrl.put(audit.getId(), MessageRest.getUrl(message)); auditRef.put(audit.getId(), ref); auditLevel.put(audit.getId(), level); auditHash.put(audit.getId(), MessageRest.getHashAudit(message)); auditLanguage.put(audit.getId(), MessageRest.getLanguage(message)); auditDescriptionRef.put(audit.getId(), MessageRest.getDescriptionRef(message)); auditScreenWidth.put(audit.getId(), MessageRest.getScreenWidth(message)); auditScreenHeight.put(audit.getId(), MessageRest.getScreenHeight(message)); auditHtmlTags.put(audit.getId(), MessageRest.getHtmlTags(message)); } }
engine/tanaguru-kafka/src/main/java/org/tanaguru/kafka/util/AuditPageConsumed.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.tanaguru.kafka.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.logging.Level; import javax.xml.parsers.ParserConfigurationException; import kafka.consumer.KafkaStream; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.log4j.Logger; import org.hibernate.Hibernate; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.safety.Whitelist; import org.springframework.context.support.ReloadableResourceBundleMessageSource; import org.tanaguru.entity.audit.Audit; import org.tanaguru.entity.audit.AuditStatus; import org.tanaguru.entity.audit.EvidenceElement; import org.tanaguru.entity.audit.ProcessRemark; import org.tanaguru.entity.audit.ProcessResult; import org.tanaguru.entity.audit.SourceCodeRemark; import org.tanaguru.entity.parameterization.Parameter; import org.tanaguru.entity.service.audit.AuditDataService; import org.tanaguru.entity.service.audit.ProcessResultDataService; import org.tanaguru.entity.service.parameterization.ParameterDataService; import org.tanaguru.entity.service.parameterization.ParameterElementDataService; import org.tanaguru.entity.service.audit.ProcessRemarkDataService; import org.tanaguru.entity.service.statistics.WebResourceStatisticsDataService; import org.tanaguru.entity.service.subject.WebResourceDataService; import org.tanaguru.entity.statistics.WebResourceStatistics; import org.tanaguru.kafka.messaging.Consumer; import org.tanaguru.kafka.messaging.MessagesProducer; import org.tanaguru.service.AuditService; import org.tanaguru.service.AuditServiceListener; import org.xml.sax.SAXException; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.tanaguru.entity.audit.Content; import org.tanaguru.entity.audit.RelatedContent; import org.tanaguru.entity.audit.SSP; import org.tanaguru.entity.dao.audit.ContentDAO; import org.tanaguru.entity.service.audit.ContentDataService; import org.tanaguru.entity.service.statistics.TestStatisticsDataService; /** * * @author omokeddem at oceaneconsulting * */ public class AuditPageConsumed implements AuditServiceListener { private ParameterDataService parameterDataService; private AuditService auditService; private ParameterElementDataService parameterElementDataService; private AuditDataService auditDataService; private ProcessResultDataService processResultDataService; private ProcessRemarkDataService processRemarkDataService; private WebResourceStatisticsDataService webResourceStatisticsDataService; private WebResourceDataService webResourceDataService; private ContentDataService contentDataService; private TestStatisticsDataService testStatisticsDataService; private MessagesProducer messagesProducer; private ExposedResourceMessageBundleSource referentialAw22Theme; private ExposedResourceMessageBundleSource referentialAw22Criterion; private ExposedResourceMessageBundleSource referentialAw22Rule; private ExposedResourceMessageBundleSource referentialRgaa2Theme; private ExposedResourceMessageBundleSource referentialRgaa2Criterion; private ExposedResourceMessageBundleSource referentialRgaa2Rule; private ExposedResourceMessageBundleSource referentialRgaa3Theme; private ExposedResourceMessageBundleSource referentialRgaa3Criterion; private ExposedResourceMessageBundleSource referentialRgaa3Rule; private ExposedResourceMessageBundleSource referentialRgaa32016Theme; private ExposedResourceMessageBundleSource referentialRgaa32016Criterion; private ExposedResourceMessageBundleSource referentialRgaa32016Rule; private ExposedResourceMessageBundleSource remarkMessage; private String dbHost; private String dbPort; private String dbUserName; private String dbPassWord; private String dbName; private HashMap<Long, String> auditType = new HashMap<Long, String>(); private HashMap<Long, String> tagsByAudit = new HashMap<Long, String>(); private HashMap<Long, String> auditHash = new HashMap<Long, String>(); private HashMap<Long, String> auditName = new HashMap<Long, String>(); private HashMap<Long, String> auditUrl = new HashMap<Long, String>(); private HashMap<Long, String> auditRef = new HashMap<Long, String>(); private HashMap<Long, String> auditLevel = new HashMap<Long, String>(); private HashMap<Long, String> auditLanguage = new HashMap<Long, String>(); private HashMap<Long, Boolean> auditDescriptionRef = new HashMap<Long, Boolean>(); private HashMap<Long, Integer> auditScreenWidth = new HashMap<Long, Integer>(); private HashMap<Long, Integer> auditScreenHeight = new HashMap<Long, Integer>(); private HashMap<Long, Boolean> auditHtmlTags = new HashMap<Long, Boolean>(); private String compaignHash; private MessageConsumerLimit messageConsumerLimit; private final char Separator = ((char) 007); private static final Logger logger = Logger.getLogger(AuditPageConsumed.class); public void setMessageConsumerLimit(MessageConsumerLimit _messageConsumerLimit) { this.messageConsumerLimit = _messageConsumerLimit; this.messageConsumerLimit.setCurrentNumberMessagesEvent(0); this.messageConsumerLimit.setCurrentNumberMessagesRest(0); } public AuditPageConsumed(ParameterDataService a_parameterDataService, AuditService a_auditService, ParameterElementDataService a_parameterElementDataService, AuditDataService a_auditDataService, ProcessResultDataService a_processResultDataService, WebResourceDataService a_webResourceDataService, WebResourceStatisticsDataService a_webResourceStatisticsDataService, ProcessRemarkDataService a_processRemarkDataService, ContentDataService a_contentDataService, MessagesProducer a_messagesProducer, ExposedResourceMessageBundleSource a_referentialAw22Theme, ExposedResourceMessageBundleSource a_referentialAw22Criterion, ExposedResourceMessageBundleSource a_referentialAw22Rule, ExposedResourceMessageBundleSource a_referentialRgaa2Theme, ExposedResourceMessageBundleSource a_referentialRgaa2Criterion, ExposedResourceMessageBundleSource a_referentialRgaa2Rule, ExposedResourceMessageBundleSource a_referentialRgaa3Theme, ExposedResourceMessageBundleSource a_referentialRgaa3Criterion, ExposedResourceMessageBundleSource a_referentialRgaa3Rule, ExposedResourceMessageBundleSource a_referentialRgaa32016Theme, ExposedResourceMessageBundleSource a_referentialRgaa32016Criterion, ExposedResourceMessageBundleSource a_referentialRgaa32016Rule, ExposedResourceMessageBundleSource a_remarkMessage, String a_dbHost, String a_dbPort, String a_dbUserName, String a_dbPassWord, String a_dbName) { parameterDataService = a_parameterDataService; auditService = a_auditService; parameterElementDataService = a_parameterElementDataService; auditDataService = a_auditDataService; processResultDataService = a_processResultDataService; webResourceDataService = a_webResourceDataService; webResourceStatisticsDataService = a_webResourceStatisticsDataService; processRemarkDataService = a_processRemarkDataService; contentDataService = a_contentDataService; messagesProducer = a_messagesProducer; referentialAw22Theme = a_referentialAw22Theme; referentialAw22Criterion = a_referentialAw22Criterion; referentialAw22Rule = a_referentialAw22Rule; referentialRgaa2Theme = a_referentialRgaa2Theme; referentialRgaa2Criterion = a_referentialRgaa2Criterion; referentialRgaa2Rule = a_referentialRgaa2Rule; referentialRgaa3Theme = a_referentialRgaa3Theme; referentialRgaa3Criterion = a_referentialRgaa3Criterion; referentialRgaa3Rule = a_referentialRgaa3Rule; referentialRgaa32016Theme = a_referentialRgaa32016Theme; referentialRgaa32016Criterion = a_referentialRgaa32016Criterion; referentialRgaa32016Rule = a_referentialRgaa32016Rule; remarkMessage = a_remarkMessage; dbHost = a_dbHost; dbPort = a_dbPort; dbUserName = a_dbUserName; dbPassWord = a_dbPassWord; dbName = a_dbName; auditService.add(this); } public Map<String, String> getMessages(ExposedResourceMessageBundleSource messageSource, Locale locale) { Properties properties = messageSource.getMessages(locale); Map<String, String> messagesMap = new HashMap<String, String>(); for (Map.Entry<Object, Object> entry : properties.entrySet()) { if (entry.getKey() != null && entry.getValue() != null) { messagesMap.put(entry.getKey().toString(), entry.getValue().toString()); } } return messagesMap; } public JSONObject getDescriptionFromRef(String Ref, String language, String entity, Boolean htmlTags) throws JSONException { JSONObject result = new JSONObject(); Map<String, String> allMessages = null; switch (Ref) { case "Rgaa32016": switch (entity) { case "Theme": if (language.equals("fr")) { allMessages = getMessages(referentialRgaa32016Theme, Locale.FRENCH); } else if (language.equals("en")) { allMessages = getMessages(referentialRgaa32016Theme, Locale.ENGLISH); } else if (language.equals("es_fr") || language.equals("es_en")) { allMessages = getMessages(referentialRgaa32016Theme, new Locale("es")); } break; case "Criterion": if (language.equals("fr") || language.equals("es_fr")) { allMessages = getMessages(referentialRgaa32016Criterion, Locale.FRENCH); } else if (language.equals("en") || language.equals("es_en")) { allMessages = getMessages(referentialRgaa32016Criterion, Locale.ENGLISH); } break; case "Rule": if (language.equals("fr") || language.equals("es_fr")) { allMessages = getMessages(referentialRgaa32016Rule, Locale.FRENCH); } else if (language.equals("en") || language.equals("es_en")) { allMessages = getMessages(referentialRgaa32016Rule, Locale.ENGLISH); } break; } break; case "Rgaa30": switch (entity) { case "Theme": if (language.equals("fr")) { allMessages = getMessages(referentialRgaa3Theme, Locale.FRENCH); } else if (language.equals("en")) { allMessages = getMessages(referentialRgaa3Theme, Locale.ENGLISH); } else if (language.equals("es_fr") || language.equals("es_en")) { allMessages = getMessages(referentialRgaa3Theme, new Locale("es")); } break; case "Criterion": if (language.equals("fr") || language.equals("es_fr")) { allMessages = getMessages(referentialRgaa3Criterion, Locale.FRENCH); } else if (language.equals("en") || language.equals("es_en")) { allMessages = getMessages(referentialRgaa3Criterion, Locale.ENGLISH); } break; case "Rule": if (language.equals("fr") || language.equals("es_fr")) { allMessages = getMessages(referentialRgaa3Rule, Locale.FRENCH); } else if (language.equals("en") || language.equals("es_en")) { allMessages = getMessages(referentialRgaa3Rule, Locale.ENGLISH); } break; } break; case "Rgaa2": switch (entity) { case "Theme": if (language.equals("fr")) { allMessages = getMessages(referentialRgaa2Theme, Locale.FRENCH); } else if (language.equals("en")) { allMessages = getMessages(referentialRgaa2Theme, Locale.ENGLISH); } else if (language.equals("es_fr") || language.equals("es_en")) { allMessages = getMessages(referentialRgaa2Theme, new Locale("es")); } break; case "Criterion": if (language.equals("fr") || language.equals("es_fr")) { allMessages = getMessages(referentialRgaa2Criterion, Locale.FRENCH); } else if (language.equals("en") || language.equals("es_en")) { allMessages = getMessages(referentialRgaa2Criterion, Locale.ENGLISH); } break; case "Rule": if (language.equals("fr") || language.equals("es_fr")) { allMessages = getMessages(referentialRgaa2Rule, Locale.FRENCH); } else if (language.equals("en") || language.equals("es_en")) { allMessages = getMessages(referentialRgaa2Rule, Locale.ENGLISH); } break; } break; case "Aw22": switch (entity) { case "Theme": if (language.equals("fr")) { allMessages = getMessages(referentialAw22Theme, Locale.FRENCH); } else if (language.equals("en")) { allMessages = getMessages(referentialAw22Theme, Locale.ENGLISH); } else if (language.equals("es_fr") || language.equals("es_en")) { allMessages = getMessages(referentialAw22Theme, new Locale("es")); } break; case "Criterion": if (language.equals("fr") || language.equals("es_fr")) { allMessages = getMessages(referentialAw22Criterion, Locale.FRENCH); } else if (language.equals("en") || language.equals("es_en")) { allMessages = getMessages(referentialAw22Criterion, Locale.ENGLISH); } break; case "Rule": if (language.equals("fr") || language.equals("es_fr")) { allMessages = getMessages(referentialAw22Rule, Locale.FRENCH); } else if (language.equals("en") || language.equals("es_en")) { allMessages = getMessages(referentialAw22Rule, Locale.ENGLISH); } break; } break; } for (Map.Entry<String, String> entrySet : allMessages.entrySet()) { String key = entrySet.getKey(); String value; if (htmlTags) { value = StringEscapeUtils.unescapeHtml4(entrySet.getValue()); } else { value = Jsoup.parse(entrySet.getValue()).text(); } result.put(key, value); } return result; } public JSONObject createAuditJson(Audit audit) throws JSONException, ParseException, URISyntaxException { JSONObject auditJson = new JSONObject(); String language = auditLanguage.get(audit.getId()); Boolean descriptionRef = auditDescriptionRef.get(audit.getId()); String ref = auditRef.get(audit.getId()); Boolean htmlTags = auditHtmlTags.get(audit.getId()); auditJson.put("url", auditUrl.get(audit.getId())); auditJson.put("status", audit.getStatus()); auditJson.put("ref", ref); auditJson.put("level", auditLevel.get(audit.getId())); auditJson.put("language", auditLanguage.get(audit.getId())); auditJson.put("screen_width", auditScreenWidth.get(audit.getId())); auditJson.put("screen_height", auditScreenHeight.get(audit.getId())); if (audit.getStatus() == AuditStatus.COMPLETED) { List<ProcessResult> processResultList = (List<ProcessResult>) processResultDataService.getNetResultFromAudit(audit); WebResourceStatistics webResourceStatistics = webResourceStatisticsDataService.getWebResourceStatisticsByWebResource(audit.getSubject()); auditJson.put("score", webResourceStatistics.getRawMark()); auditJson.put("nb_passed", webResourceStatistics.getNbOfPassed()); auditJson.put("nb_failed", webResourceStatistics.getNbOfFailed()); auditJson.put("nb_nmi", webResourceStatistics.getNbOfNmi()); auditJson.put("nb_na", webResourceStatistics.getNbOfNa()); auditJson.put("nb_failed_occurences", webResourceStatistics.getNbOfFailedOccurences()); auditJson.put("nb_detected", webResourceStatistics.getNbOfDetected()); auditJson.put("http_status_code", webResourceStatistics.getHttpStatusCode()); auditJson.put("nb_suspected", webResourceStatistics.getNbOfSuspected()); auditJson.put("nb_not_tested", webResourceStatistics.getNbOfNotTested()); JSONArray remarkArray = new JSONArray(); JSONArray testPassedArray = new JSONArray(); JSONArray testNAArray = new JSONArray(); JSONArray testNTArray = new JSONArray(); JSONObject themesFr = new JSONObject(); JSONObject themesEn = new JSONObject(); JSONObject themesEs = new JSONObject(); JSONObject criterionsFr = new JSONObject(); JSONObject criterionsEn = new JSONObject(); JSONObject testsFr = new JSONObject(); JSONObject testsEn = new JSONObject(); if (descriptionRef) { if (language.equals("fr") || language.equals("all")) { themesFr = getDescriptionFromRef(ref, "fr", "Theme", htmlTags); } if (language.equals("en") || language.equals("all")) { themesEn = getDescriptionFromRef(ref, "en", "Theme", htmlTags); } if (language.equals("es_fr") || language.equals("es_en") || language.equals("all")) { themesEs = getDescriptionFromRef(ref, "es_en", "Theme", htmlTags); } if (language.equals("fr") || language.equals("es_fr") || language.equals("all")) { testsFr = getDescriptionFromRef(ref, "fr", "Rule", htmlTags); criterionsFr = getDescriptionFromRef(ref, "fr", "Criterion", htmlTags); } if (language.equals("en") || language.equals("es_en") || language.equals("all")) { testsEn = getDescriptionFromRef(ref, "en", "Rule", htmlTags); criterionsEn = getDescriptionFromRef(ref, "en", "Criterion", htmlTags); } } for (ProcessResult result : processResultList) { if (result.getTest().getLabel().equals("8.2.1")) { auditJson.put("nb_w3c_invalidated", result.getElementCounter()); } // create testPassed object from ProcessResult JSONObject testPassedObject = new JSONObject(); if (result.getValue().toString().equals("PASSED")) { putTests(result, testPassedObject); testPassedArray.put(testPassedObject); } JSONObject testNTObject = new JSONObject(); if (result.getValue().toString().equals("NOT_TESTED")) { putTests(result, testNTObject); testNTArray.put(testNTObject); } // create testNA object from ProcessResult JSONObject testNAObject = new JSONObject(); if (result.getValue().toString().equals("NOT_APPLICABLE")) { putTests(result, testNAObject); testNAArray.put(testNAObject); } // get remark from processResult & create array of remark int nbrRemarkW3c = 0; Set<ProcessRemark> processRemarkList = (Set<ProcessRemark>) processRemarkDataService.findProcessRemarksFromProcessResult(result, -1); for (ProcessRemark processRemark : processRemarkList) { if (result.getTest().getLabel().equals("8.2.1")) { if (nbrRemarkW3c < 10) { nbrRemarkW3c++; } else { break; } } JSONObject remarkObject = new JSONObject(); String remark_fr, remark_en, remark_es; if (htmlTags) { remark_fr = StringEscapeUtils.unescapeHtml4(remarkMessage.getMessage(processRemark.getMessageCode(), processRemark instanceof SourceCodeRemark ? new Object[]{((SourceCodeRemark) processRemark).getTarget()} : null, Locale.FRENCH)); remark_en = StringEscapeUtils.unescapeHtml4(remarkMessage.getMessage(processRemark.getMessageCode(), processRemark instanceof SourceCodeRemark ? new Object[]{((SourceCodeRemark) processRemark).getTarget()} : null, Locale.ENGLISH)); remark_es = StringEscapeUtils.unescapeHtml4(remarkMessage.getMessage(processRemark.getMessageCode(), processRemark instanceof SourceCodeRemark ? new Object[]{((SourceCodeRemark) processRemark).getTarget()} : null, new Locale("es"))); } else { remark_fr = Jsoup.parse(remarkMessage.getMessage(processRemark.getMessageCode(), processRemark instanceof SourceCodeRemark ? new Object[]{((SourceCodeRemark) processRemark).getTarget()} : null, Locale.FRENCH)).text(); remark_en = Jsoup.parse(remarkMessage.getMessage(processRemark.getMessageCode(), processRemark instanceof SourceCodeRemark ? new Object[]{((SourceCodeRemark) processRemark).getTarget()} : null, Locale.ENGLISH)).text(); remark_es = Jsoup.parse(remarkMessage.getMessage(processRemark.getMessageCode(), processRemark instanceof SourceCodeRemark ? new Object[]{((SourceCodeRemark) processRemark).getTarget()} : null, new Locale("es"))).text(); } if (processRemark instanceof SourceCodeRemark) { remarkObject.put("issue", processRemark.getIssue()); if (language.equals("fr") || language.equals("all")) { remarkObject.put("message_fr", remark_fr); } if (language.equals("en") || language.equals("all")) { remarkObject.put("message_en", remark_en); } if (language.equals("es_fr") || language.equals("es_en") || language.equals("all")) { remarkObject.put("message_es", remark_es); } //remarkObject.put("target", ((SourceCodeRemark) processRemark).getTarget()); remarkObject.put("line_number", ((SourceCodeRemark) processRemark).getLineNumber()); StringBuilder snippet = new StringBuilder(""); if (((SourceCodeRemark) processRemark).getSnippet() != null) { String snippetDirty = ((SourceCodeRemark) processRemark).getSnippet(); snippet.append(StringEscapeUtils.unescapeHtml4(snippetDirty.replace("\t", ""))); } remarkObject.put("snippet", snippet); } else { remarkObject.put("issue", processRemark.getIssue()); if (language.equals("fr") || language.equals("all")) { remarkObject.put("message_fr", remark_fr); } if (language.equals("en") || language.equals("all")) { remarkObject.put("message_en", remark_en); } if (language.equals("es_fr") || language.equals("es_en") || language.equals("all")) { remarkObject.put("message_es", remark_es); } } putTests(result, remarkObject); remarkArray.put(remarkObject); } } auditJson.put("remarks", remarkArray); auditJson.put("test_passed", testPassedArray); auditJson.put("test_na", testNAArray); auditJson.put("test_nt", testNTArray); if (themesFr.length() != 0) { auditJson.put("themes_description_fr", themesFr); } if (themesEn.length() != 0) { auditJson.put("themes_description_en", themesEn); } if (themesEs.length() != 0) { auditJson.put("themes_description_es", themesEs); } if (criterionsFr.length() != 0) { auditJson.put("criterions_description_fr", criterionsFr); } if (criterionsEn.length() != 0) { auditJson.put("criterions_description_en", criterionsEn); } if (testsFr.length() != 0) { auditJson.put("tests_description_fr", testsFr); } if (testsEn.length() != 0) { auditJson.put("tests_description_en", testsEn); } } return auditJson; } public void putTests(ProcessResult result, JSONObject remarkObject) throws JSONException { String codeTest = result.getTest().getCode(); String codeCriterion = result.getTest().getCriterion().getCode(); String codeTheme = result.getTest().getCriterion().getTheme().getCode(); remarkObject.put("theme", codeTheme); remarkObject.put("test", codeTest); remarkObject.put("criterion", codeCriterion); } @Override public void auditCompleted(Audit audit ) { try { if (auditType.get(audit.getId()) != null) { String messageToSend = ""; audit = auditDataService.read(audit.getId()); logger.debug("Audit terminated with success at " + audit.getDateOfCreation()); if (auditType.get(audit.getId()).equals("Rest")) { JSONObject auditJson = createAuditJson(audit); messageToSend = auditHash.get(audit.getId()) + Separator + auditJson; auditUrl.remove(audit.getId()); auditType.remove(audit.getId()); auditRef.remove(audit.getId()); auditLevel.remove(audit.getId()); auditLanguage.remove(audit.getId()); auditDescriptionRef.remove(audit.getId()); auditScreenWidth.remove(audit.getId()); auditScreenHeight.remove(audit.getId()); auditHtmlTags.remove(audit.getId()); auditHash.remove(audit.getId()); messageConsumerLimit.messageRestAudited(); } else if (auditType.get(audit.getId()).equals("Event")) { messageConsumerLimit.messageEventAudited(); int nbrW3cValidated = 0; if (audit.getStatus() == AuditStatus.COMPLETED) { List<ProcessResult> processResultList = (List<ProcessResult>) processResultDataService.getNetResultFromAudit(audit); for (ProcessResult result : processResultList) { if (result.getTest().getLabel().equals("8.2.1")) { nbrW3cValidated = result.getElementCounter(); } } } messageToSend = dbHost + ";" + dbPort + ";" + dbUserName + ";" + dbPassWord + ";" + dbName + ";" + audit.getId() + ";" + tagsByAudit.get(audit.getId()) + ";" + auditName.get(audit.getId()) + ";" + auditUrl.get(audit.getId()) + ";" + auditHash.get(audit.getId()) + ";" + compaignHash + ";" + nbrW3cValidated + ";" + auditRef.get(audit.getId()) + ";" + audit.getStatus(); tagsByAudit.remove(audit.getId()); auditHash.remove(audit.getId()); auditName.remove(audit.getId()); auditUrl.remove(audit.getId()); auditType.remove(audit.getId()); auditRef.remove(audit.getId()); auditLevel.remove(audit.getId()); } messagesProducer.sendMessage(messageToSend); } } catch (Exception ex) { logger.error("Producer Message Kafka ERROR : " + ex); } } @Override public void auditCrashed(Audit audit, Exception exception ) { //To change body of generated methods, choose Tools | Templates. if (auditType.get(audit.getId()) != null) { logger.error("crash (id+message): " + audit.getId() + " " + exception.toString()); if (auditType.get(audit.getId()).equals("Event")) { messageConsumerLimit.messageEventAudited(); } else if (auditType.get(audit.getId()).equals("Rest")) { messageConsumerLimit.messageRestAudited(); } tagsByAudit.remove(audit.getId()); auditHash.remove(audit.getId()); auditName.remove(audit.getId()); auditUrl.remove(audit.getId()); auditType.remove(audit.getId()); auditRef.remove(audit.getId()); auditLevel.remove(audit.getId()); auditLanguage.remove(audit.getId()); auditDescriptionRef.remove(audit.getId()); auditScreenWidth.remove(audit.getId()); auditScreenHeight.remove(audit.getId()); auditHtmlTags.remove(audit.getId()); } } public void auditPageEvent(String message, Set<Parameter> parameters, String ref, String level) { compaignHash = MessageEvent.getIdCampagne(message); Audit audit = auditService.auditPage(MessageEvent.getUrl(message), parameters); auditType.put(audit.getId(), "Event"); tagsByAudit.put(audit.getId(), MessageEvent.getTags(message)); auditHash.put(audit.getId(), MessageEvent.getHashAudit(message)); auditName.put(audit.getId(), MessageEvent.getName(message)); auditUrl.put(audit.getId(), MessageEvent.getUrl(message)); auditRef.put(audit.getId(), ref); auditLevel.put(audit.getId(), level); } public void auditPageRest(String message, Set<Parameter> parameters, String ref, String level) { Audit audit = auditService.auditPage(MessageRest.getUrl(message), parameters); auditType.put(audit.getId(), "Rest"); auditUrl.put(audit.getId(), MessageRest.getUrl(message)); auditRef.put(audit.getId(), ref); auditLevel.put(audit.getId(), level); auditHash.put(audit.getId(), MessageRest.getHashAudit(message)); auditLanguage.put(audit.getId(), MessageRest.getLanguage(message)); auditDescriptionRef.put(audit.getId(), MessageRest.getDescriptionRef(message)); auditScreenWidth.put(audit.getId(), MessageRest.getScreenWidth(message)); auditScreenHeight.put(audit.getId(), MessageRest.getScreenHeight(message)); auditHtmlTags.put(audit.getId(), MessageRest.getHtmlTags(message)); } }
Fix Html unescape Json response
engine/tanaguru-kafka/src/main/java/org/tanaguru/kafka/util/AuditPageConsumed.java
Fix Html unescape Json response
<ide><path>ngine/tanaguru-kafka/src/main/java/org/tanaguru/kafka/util/AuditPageConsumed.java <ide> StringBuilder snippet = new StringBuilder(""); <ide> if (((SourceCodeRemark) processRemark).getSnippet() != null) { <ide> String snippetDirty = ((SourceCodeRemark) processRemark).getSnippet(); <del> snippet.append(StringEscapeUtils.unescapeHtml4(snippetDirty.replace("\t", ""))); <add> if (htmlTags) { <add> snippet.append(StringEscapeUtils.unescapeHtml4(StringEscapeUtils.unescapeHtml4(snippetDirty.replace("\t", "")))); <add> } else { <add> snippet.append(snippetDirty.replace("\t", "")); <add> } <ide> } <ide> remarkObject.put("snippet", snippet); <ide> } else {
Java
apache-2.0
e7497b8d492098cab0e21332763315e1aca4abd9
0
zwsong/wicket,zwsong/wicket,martin-g/wicket-osgi,freiheit-com/wicket,astrapi69/wicket,klopfdreh/wicket,topicusonderwijs/wicket,aldaris/wicket,freiheit-com/wicket,mosoft521/wicket,dashorst/wicket,dashorst/wicket,topicusonderwijs/wicket,zwsong/wicket,aldaris/wicket,astrapi69/wicket,martin-g/wicket-osgi,AlienQueen/wicket,bitstorm/wicket,selckin/wicket,mosoft521/wicket,AlienQueen/wicket,mosoft521/wicket,zwsong/wicket,martin-g/wicket-osgi,bitstorm/wicket,aldaris/wicket,mosoft521/wicket,klopfdreh/wicket,aldaris/wicket,apache/wicket,astrapi69/wicket,selckin/wicket,klopfdreh/wicket,bitstorm/wicket,klopfdreh/wicket,bitstorm/wicket,freiheit-com/wicket,apache/wicket,aldaris/wicket,klopfdreh/wicket,freiheit-com/wicket,AlienQueen/wicket,bitstorm/wicket,apache/wicket,freiheit-com/wicket,apache/wicket,selckin/wicket,topicusonderwijs/wicket,mosoft521/wicket,selckin/wicket,dashorst/wicket,apache/wicket,AlienQueen/wicket,astrapi69/wicket,selckin/wicket,mafulafunk/wicket,mafulafunk/wicket,topicusonderwijs/wicket,AlienQueen/wicket,mafulafunk/wicket,topicusonderwijs/wicket,dashorst/wicket,dashorst/wicket
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.wicket; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamException; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.apache.wicket.authorization.IAuthorizationStrategy; import org.apache.wicket.authorization.UnauthorizedActionException; import org.apache.wicket.authorization.strategies.page.SimplePageAuthorizationStrategy; import org.apache.wicket.markup.IMarkupFragment; import org.apache.wicket.markup.MarkupException; import org.apache.wicket.markup.MarkupStream; import org.apache.wicket.markup.MarkupType; import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.markup.resolver.IComponentResolver; import org.apache.wicket.model.IModel; import org.apache.wicket.page.IManageablePage; import org.apache.wicket.page.IPageManager; import org.apache.wicket.pageStore.IPageStore; import org.apache.wicket.request.component.IRequestablePage; import org.apache.wicket.request.cycle.RequestCycle; import org.apache.wicket.request.http.WebResponse; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.session.ISessionStore; import org.apache.wicket.settings.IDebugSettings; import org.apache.wicket.settings.IRequestCycleSettings.RenderStrategy; import org.apache.wicket.util.lang.Classes; import org.apache.wicket.util.lang.WicketObjects; import org.apache.wicket.util.string.StringValue; import org.apache.wicket.util.visit.IVisit; import org.apache.wicket.util.visit.IVisitor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Abstract base class for pages. As a MarkupContainer subclass, a Page can contain a component * hierarchy and markup in some markup language such as HTML. Users of the framework should not * attempt to subclass Page directly. Instead they should subclass a subclass of Page that is * appropriate to the markup type they are using, such as WebPage (for HTML markup). * <ul> * <li><b>Construction </b>- When a page is constructed, it is automatically added to the current * PageMap in the Session. When a Page is added to the Session's PageMap, the PageMap assigns the * Page an id. A PageMap is roughly equivalent to a browser window and encapsulates a set of pages * accessible through that window. When a popup window is created, a new PageMap is created for the * popup. * * <li><b>Identity </b>- The Session that a Page is contained in can be retrieved by calling * Page.getSession(). Page identifiers start at 0 for each PageMap in the Session and increment as * new pages are added to the map. The PageMap-(and Session)-unique identifier assigned to a given * Page can be retrieved by calling getId(). So, the first Page added to a new user Session will * always be named "0". * * <li><b>LifeCycle </b>- Subclasses of Page which are interested in lifecycle events can override * onBeginRequest, onEndRequest() and onModelChanged(). The onBeginRequest() method is inherited * from Component. A call to onBeginRequest() is made for every Component on a Page before page * rendering begins. At the end of a request (when rendering has completed) to a Page, the * onEndRequest() method is called for every Component on the Page. * * <li><b>Nested Component Hierarchy </b>- The Page class is a subclass of MarkupContainer. All * MarkupContainers can have "associated markup", which resides alongside the Java code by default. * All MarkupContainers are also Component containers. Through nesting, of containers, a Page can * contain any arbitrary tree of Components. For more details on MarkupContainers, see * {@link org.apache.wicket.MarkupContainer}. * * <li><b>Bookmarkable Pages </b>- Pages can be constructed with any constructor when they are being * used in a Wicket session, but if you wish to link to a Page using a URL that is "bookmarkable" * (which implies that the URL will not have any session information encoded in it, and that you can * call this page directly without having a session first directly from your browser), you need to * implement your Page with a no-arg constructor or with a constructor that accepts a PageParameters * argument (which wraps any query string parameters for a request). In case the page has both * constructors, the constructor with PageParameters will be used. * * <li><b>Models </b>- Pages, like other Components, can have models (see {@link IModel}). A Page * can be assigned a model by passing one to the Page's constructor, by overriding initModel() or * with an explicit invocation of setModel(). If the model is a * {@link org.apache.wicket.model.CompoundPropertyModel}, Components on the Page can use the Page's * model implicitly via container inheritance. If a Component is not assigned a model, the * initModel() override in Component will cause that Component to use the nearest CompoundModel in * the parent chain, in this case, the Page's model. For basic CompoundModels, the name of the * Component determines which property of the implicit page model the component is bound to. If more * control is desired over the binding of Components to the page model (for example, if you want to * specify some property expression other than the component's name for retrieving the model * object), BoundCompoundPropertyModel can be used. * * <li><b>Back Button </b>- Pages can support the back button by enabling versioning with a call to * setVersioned(boolean). If a Page is versioned and changes occur to it which need to be tracked, a * version manager will be installed using the {@link ISessionStore}'s factory method * newVersionManager(). * * <li><b>Security </b>- See {@link IAuthorizationStrategy}, {@link SimplePageAuthorizationStrategy} * * @see org.apache.wicket.markup.html.WebPage * @see org.apache.wicket.MarkupContainer * @see org.apache.wicket.model.CompoundPropertyModel * @see org.apache.wicket.model.BoundCompoundPropertyModel * @see org.apache.wicket.Component * @see org.apache.wicket.version.IPageVersionManager * @see org.apache.wicket.version.undo.UndoPageVersionManager * * @author Jonathan Locke * @author Chris Turner * @author Eelco Hillenius * @author Johan Compagner * */ public abstract class Page extends MarkupContainer implements IRedirectListener, IManageablePage, IRequestablePage { /** * You can set implementation of the interface in the {@link Page#serializer} then that * implementation will handle the serialization of this page. The serializePage method is called * from the writeObject method then the implementation override the default serialization. * * @author jcompagner */ public static interface IPageSerializer { /** * Called when page is being deserialized * * @param id * TODO * @param name * TODO * @param page * @param stream * @throws IOException * @throws ClassNotFoundException * */ public void deserializePage(int id, String name, Page page, ObjectInputStream stream) throws IOException, ClassNotFoundException; /** * Called from the {@link Page#writeObject(java.io.ObjectOutputStream)} method. * * @param page * The page that must be serialized. * @param stream * ObjectOutputStream * @throws IOException */ public void serializePage(Page page, ObjectOutputStream stream) throws IOException; /** * Returns object to be serialized instead of given page (called from writeReplace). * * @param serializedPage * @return object to be serialized instead of page (or the page instance itself) */ public Object getPageReplacementObject(Page serializedPage); } /** * This is a thread local that is used for serializing page references in this page.It stores a * {@link IPageSerializer} which can be set by the outside world to do the serialization of this * page. */ public static final ThreadLocal<IPageSerializer> serializer = new ThreadLocal<IPageSerializer>(); /** True if the page hierarchy has been modified in the current request. */ private static final int FLAG_IS_DIRTY = FLAG_RESERVED3; /** Set to prevent marking page as dirty under certain circumstances. */ private static final int FLAG_PREVENT_DIRTY = FLAG_RESERVED4; /** True if the page should try to be stateless */ private static final int FLAG_STATELESS_HINT = FLAG_RESERVED5; /** Log. */ private static final Logger log = LoggerFactory.getLogger(Page.class); /** * {@link #isBookmarkable()} is expensive, we cache the result here */ private static final ConcurrentHashMap<String, Boolean> pageClassToBookmarkableCache = new ConcurrentHashMap<String, Boolean>(); private static final long serialVersionUID = 1L; /** Used to create page-unique numbers */ private short autoIndex; /** Numeric version of this page's id */ private int numericId; /** Set of components that rendered if component use checking is enabled */ private transient Set<Component> renderedComponents; /** * Boolean if the page is stateless, so it doesn't have to be in the page map, will be set in * urlFor */ private transient Boolean stateless = null; /** Page parameters used to construct this page */ private final PageParameters pageParameters; /** * The purpose of render count is to detect stale listener interface links. For example: there * is a page A rendered in tab 1. Then page A is opened also in tab 2. During render page state * changes (i.e. some repeater gets rebuilt). This makes all links on tab 2 stale - because they * no longer match the actual page state. This is done by incrementing render count. When link * is clicked Wicket checks if it's render count matches the render count value of page */ private int renderCount = 0; /** TODO WICKET-NG JAVADOC */ // TODO WICKET-NG convert into a flag private boolean wasCreatedBookmarkable; /** * Constructor. */ protected Page() { this(null, null); } /** * Constructor. * * @param model * See Component * @see Component#Component(String, IModel) */ protected Page(final IModel<?> model) { this(null, model); } /** * The {@link PageParameters} parameter will be stored in this page and then those parameters * will be used to create stateless links to this bookmarkable page. * * @param parameters * externally passed parameters * @see PageParameters */ protected Page(final PageParameters parameters) { super(null); if (parameters == null) { pageParameters = new PageParameters(); } else { pageParameters = parameters; } init(); } private Page(final PageParameters parameters, IModel<?> model) { super(null, model); if (parameters == null) { // TODO WICKET-NG is this necessary or can we keep the field as null to save space? pageParameters = new PageParameters(); } else { pageParameters = parameters; } init(); } /** * The {@link PageParameters} object that was used to construct this page. This will be used in * creating stateless/bookmarkable links to this page * * @return {@link PageParameters} The construction page parameter */ public PageParameters getPageParameters() { return pageParameters; } /** * Called right after a component's listener method (the provided method argument) was called. * This method may be used to clean up dependencies, do logging, etc. NOTE: this method will * also be called when {@link WebPage#beforeCallComponent(Component, RequestListenerInterface)} * or the method invocation itself failed. * * @param component * the component that is to be called * @param listener * the listener of that component that is to be called */ // TODO Post-1.3: We should create a listener on Application like // IComponentInstantiationListener // that forwards to IAuthorizationStrategy for RequestListenerInterface // invocations. public void afterCallComponent(final Component component, final RequestListenerInterface listener) { } /** * Called just before a component's listener method (the provided method argument) is called. * This method may be used to set up dependencies, enforce authorization, etc. NOTE: if this * method fails, the method will not be executed. Method * {@link WebPage#afterCallComponent(Component, RequestListenerInterface)} will always be * called. * * @param component * the component that is to be called * @param listener * the listener of that component that is to be called */ // TODO Post-1.3: We should create a listener on Application like // IComponentInstantiationListener // that forwards to IAuthorizationStrategy for RequestListenerInterface // invocations. public void beforeCallComponent(final Component component, final RequestListenerInterface listener) { } /** * Adds a component to the set of rendered components. * * @param component * The component that was rendered */ public final void componentRendered(final Component component) { // Inform the page that this component rendered if (Application.get().getDebugSettings().getComponentUseCheck()) { if (renderedComponents == null) { renderedComponents = new HashSet<Component>(); } if (renderedComponents.add(component) == false) { throw new MarkupException( "The component " + component + " was rendered already. You can render it only once during a render phase. Class relative path: " + component.getClassRelativePath()); } if (log.isDebugEnabled()) { log.debug("Rendered " + component); } } } /** * Detaches any attached models referenced by this page. */ @Override public void detachModels() { super.detachModels(); } @Override public void prepareForRender(boolean setRenderingFlag) { if (!getFlag(FLAG_INITIALIZED)) { // initialize the page if not yet initialized initialize(); } super.prepareForRender(setRenderingFlag); } /** * @see #dirty(boolean) */ public final void dirty() { dirty(false); } /** * INTERNAL. Prevent marking page as dirty. Used to prevent incrementing page id during * REDIRECT_TO_RENDER rendering. * * @param prevent */ private void preventDirty(boolean prevent) { setFlag(FLAG_PREVENT_DIRTY, prevent); } /** * Mark this page as modified in the session. If versioning is supported then a new version of * the page will be stored in {@link IPageStore page store} * * @param isInitialization * a flag whether this is a page instantiation */ public final void dirty(final boolean isInitialization) { checkHierarchyChange(this); if (getFlag(FLAG_PREVENT_DIRTY)) { return; } final IPageManager pageManager = getSession().getPageManager(); if (!getFlag(FLAG_IS_DIRTY) && isVersioned() && pageManager.supportsVersioning()) { setFlag(FLAG_IS_DIRTY, true); setNextAvailableId(); pageManager.touchPage(this); } else if (isInitialization) { // we need to get pageId for new page instances even when the page doesn't need // versioning, otherwise pages override each other in the page store and back button // support is broken setNextAvailableId(); } } /** * THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT CALL. * * This method is called when a component was rendered standalone. If it is a <code> * MarkupContainer</code> * then the rendering for that container is checked. * * @param component * */ public final void endComponentRender(Component component) { if (component instanceof MarkupContainer) { checkRendering((MarkupContainer)component); } else { renderedComponents = null; } } /** * THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT CALL IT. * * Get a page unique number, which will be increased with each call. * * @return A page unique number */ public final short getAutoIndex() { return autoIndex++; } /** * @see org.apache.wicket.Component#getId() */ @Override public final String getId() { return Integer.toString(numericId); } /** * @see org.apache.wicket.session.pagemap.IPageMapEntry#getNumericId() * @deprecated */ @Deprecated public int getNumericId() { return getPageId(); } /** * @see org.apache.wicket.session.pagemap.IPageMapEntry#getPageClass() */ public final Class<? extends Page> getPageClass() { return getClass(); } /** * @return Size of this page in bytes */ @Override public final long getSizeInBytes() { return WicketObjects.sizeof(this); } /** * Returns whether the page should try to be stateless. To be stateless, getStatelessHint() of * every component on page (and it's behavior) must return true and the page must be * bookmarkable. * * @see org.apache.wicket.Component#getStatelessHint() */ @Override public final boolean getStatelessHint() { return getFlag(FLAG_STATELESS_HINT); } /** * @return This page's component hierarchy as a string */ public final String hierarchyAsString() { final StringBuffer buffer = new StringBuffer(); buffer.append("Page " + getId()); visitChildren(new IVisitor<Component, Void>() { public void component(final Component component, final IVisit<Void> visit) { int levels = 0; for (Component current = component; current != null; current = current.getParent()) { levels++; } buffer.append(StringValue.repeat(levels, " ") + component.getPageRelativePath() + ":" + Classes.simpleName(component.getClass())); } }); return buffer.toString(); } /** * Bookmarkable page can be instantiated using a bookmarkable URL. * * @return Returns true if the page is bookmarkable. */ public boolean isBookmarkable() { Boolean bookmarkable = pageClassToBookmarkableCache.get(getClass().getName()); if (bookmarkable == null) { try { if (getClass().getConstructor(new Class[] { }) != null) { bookmarkable = Boolean.TRUE; } } catch (Exception ignore) { try { if (getClass().getConstructor(new Class[] { PageParameters.class }) != null) { bookmarkable = Boolean.TRUE; } } catch (Exception ignore2) { } } if (bookmarkable == null) { bookmarkable = Boolean.FALSE; } pageClassToBookmarkableCache.put(getClass().getName(), bookmarkable); } return bookmarkable.booleanValue(); } /** * Override this method and return true if your page is used to display Wicket errors. This can * help the framework prevent infinite failure loops. * * @return True if this page is intended to display an error to the end user. */ public boolean isErrorPage() { return false; } /** * Determine the "statelessness" of the page while not changing the cached value. * * @return boolean value */ private boolean peekPageStateless() { Boolean old = stateless; Boolean res = isPageStateless(); stateless = old; return res; } /** * Gets whether the page is stateless. Components on stateless page must not render any * statefull urls, and components on statefull page must not render any stateless urls. * Statefull urls are urls, which refer to a certain (current) page instance. * * @return Whether this page is stateless */ public final boolean isPageStateless() { if (isBookmarkable() == false) { stateless = Boolean.FALSE; if (getStatelessHint()) { log.warn("Page '" + this + "' is not stateless because it is not bookmarkable, " + "but the stateless hint is set to true!"); } } if (getStatelessHint() == false) { return false; } if (stateless == null) { if (isStateless() == false) { stateless = Boolean.FALSE; } } if (stateless == null) { final Object[] returnArray = new Object[1]; Boolean returnValue = visitChildren(Component.class, new IVisitor<Component, Boolean>() { public void component(final Component component, final IVisit<Boolean> visit) { if (!component.isStateless()) { returnArray[0] = component; visit.stop(Boolean.FALSE); } } }); if (returnValue == null) { stateless = Boolean.TRUE; } else if (returnValue instanceof Boolean) { stateless = returnValue; } // TODO (matej_k): The stateless hint semantics has been changed, this warning doesn't // work anymore. but we don't really have // alternative to this /* * if (!stateless.booleanValue() && getStatelessHint()) { log.warn("Page '" + this + "' * is not stateless because of '" + returnArray[0] + "' but the stateless hint is set to * true!"); } */ } return stateless.booleanValue(); } /** * Redirect to this page. * * @see org.apache.wicket.IRedirectListener#onRedirect() */ public final void onRedirect() { } /** * THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT CALL. * * Set the id for this Page. This method is called by PageMap when a Page is added because the * id, which is assigned by PageMap, is not known until this time. * * @param id * The id */ public final void setNumericId(final int id) { numericId = id; } /** * Sets whether the page should try to be stateless. To be stateless, getStatelessHint() of * every component on page (and it's behavior) must return true and the page must be * bookmarkable. * * @param value * whether the page should try to be stateless */ public final void setStatelessHint(boolean value) { if (value && !isBookmarkable()) { throw new WicketRuntimeException( "Can't set stateless hint to true on a page when the page is not bookmarkable, page: " + this); } setFlag(FLAG_STATELESS_HINT, value); } /** * THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT CALL. * * This method is called when a component will be rendered standalone. * * @param component * */ public final void startComponentRender(Component component) { renderedComponents = null; } /** * Get the string representation of this container. * * @return String representation of this container */ @Override public String toString() { return "[Page class = " + getClass().getName() + ", id = " + getId() + ", render count = " + getRenderCount() + "]"; } /** * Throw an exception if not all components rendered. * * @param renderedContainer * The page itself if it was a full page render or the container that was rendered * standalone */ private final void checkRendering(final MarkupContainer renderedContainer) { // If the application wants component uses checked and // the response is not a redirect final IDebugSettings debugSettings = Application.get().getDebugSettings(); if (debugSettings.getComponentUseCheck()) { final List<Component> unrenderedComponents = new ArrayList<Component>(); final StringBuffer buffer = new StringBuffer(); renderedContainer.visitChildren(new IVisitor<Component, Void>() { public void component(final Component component, final IVisit<Void> visit) { // If component never rendered if (renderedComponents == null || !renderedComponents.contains(component)) { // If not an auto component ... if (!component.isAuto() && component.isVisibleInHierarchy()) { // Increase number of unrendered components unrenderedComponents.add(component); // Add to explanatory string to buffer buffer.append(Integer.toString(unrenderedComponents.size()) + ". " + component + "\n"); String metadata = component.getMetaData(Component.CONSTRUCTED_AT_KEY); if (metadata != null) { buffer.append(metadata); } metadata = component.getMetaData(Component.ADDED_AT_KEY); if (metadata != null) { buffer.append(metadata); } } else { // if the component is not visible in hierarchy we // should not visit its children since they are also // not visible visit.dontGoDeeper(); } } } }); // Throw exception if any errors were found if (unrenderedComponents.size() > 0) { // Get rid of set renderedComponents = null; List<Component> transparentContainerChildren = new ArrayList<Component>(); Iterator<Component> iterator = unrenderedComponents.iterator(); outerWhile : while (iterator.hasNext()) { Component component = iterator.next(); // If any of the transparentContainerChildren is a parent to component, than // ignore it. for (Component transparentContainerChild : transparentContainerChildren) { MarkupContainer parent = component.getParent(); while (parent != null) { if (parent == transparentContainerChild) { iterator.remove(); continue outerWhile; } parent = parent.getParent(); } } // Now first test if the component has a sibling that is a transparent resolver. Iterator<? extends Component> iterator2 = component.getParent().iterator(); while (iterator2.hasNext()) { Component sibling = iterator2.next(); if (!sibling.isVisible()) { if (sibling instanceof IComponentResolver) { // we found a transparent container that isn't visible // then ignore this component and only do a debug statement here. if (log.isDebugEnabled()) { log.debug( "Component {} wasn't rendered but most likely it has a transparent parent: {}", component, sibling); } transparentContainerChildren.add(component); iterator.remove(); continue outerWhile; } } } } // if still > 0 if (unrenderedComponents.size() > 0) { // Throw exception throw new WicketRuntimeException( "The component(s) below failed to render. A common problem is that you have added a component in code but forgot to reference it in the markup (thus the component will never be rendered).\n\n" + buffer.toString()); } } } // Get rid of set renderedComponents = null; } /** * Initializes Page by adding it to the Session and initializing it. * * @param pageMap * The page map to put this page in. */ private final void init() { if (isBookmarkable()) { setStatelessHint(true); } // Set versioning of page based on default setVersioned(Application.get().getPageSettings().getVersionPagesByDefault()); // All Pages are born dirty so they get clustered right away dirty(true); // this is a bit of a dirty hack, but calling dirty(true) results in isStateless called // which is bound to set the stateless cache to true as there are no components yet stateless = null; } /** * */ private void setNextAvailableId() { setNumericId(getSession().nextPageId()); } /** * This method will be called for all components that are changed on the page So also auto * components or components that are not versioned. * * If the parent is given that it was a remove or add from that parent of the given component. * else it was just a internal property change of that component. * * @param component * @param parent */ protected void componentChanged(Component component, MarkupContainer parent) { if (!component.isAuto()) { dirty(); } } /** * * @param s * @throws IOException * @throws ClassNotFoundException */ void readPageObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException { int id = s.readShort(); String name = (String)s.readObject(); IPageSerializer ps = serializer.get(); if (ps != null) { ps.deserializePage(id, name, this, s); } else { s.defaultReadObject(); } } /** * * @return serialized version of page * @throws ObjectStreamException */ protected Object writeReplace() throws ObjectStreamException { IPageSerializer ps = serializer.get(); if (ps != null) { return ps.getPageReplacementObject(this); } else { return this; } } /** * Set-up response with appropriate content type, locale and encoding. The locale is set equal * to the session's locale. The content type header contains information about the markup type * (@see #getMarkupType()) and the encoding. The response (and request) encoding is determined * by an application setting (@see ApplicationSettings#getResponseRequestEncoding()). In * addition, if the page's markup contains a xml declaration like &lt?xml ... ?&gt; an xml * declaration with proper encoding information is written to the output as well, provided it is * not disabled by an application setting (@see * ApplicationSettings#getStripXmlDeclarationFromOutput()). * <p> * Note: Prior to Wicket 1.1 the output encoding was determined by the page's markup encoding. * Because this caused uncertainties about the /request/ encoding, it has been changed in favor * of the new, much safer, approach. Please see the Wiki for more details. */ protected void configureResponse() { // Get the response and application final RequestCycle cycle = getRequestCycle(); final Application application = Application.get(); final WebResponse response = (WebResponse)cycle.getResponse(); // Determine encoding final String encoding = application.getRequestCycleSettings().getResponseRequestEncoding(); // Set content type based on markup type for page response.setContentType(getMarkupType().getMimeType() + "; charset=" + encoding); // Write out an xml declaration if the markup stream and settings allow final IMarkupFragment markup = getMarkup(); if ((markup != null) && (markup.getMarkupResourceStream().getXmlDeclaration() != null) && (application.getMarkupSettings().getStripXmlDeclarationFromOutput() == false)) { // Gwyn - Wed, 21 May 2008 12:23:41 // If the xml declaration in the markup used double-quotes, use them in the output too // Whether it should be or not, sometimes it's significant... final String quoteChar = (markup.getMarkupResourceStream() .getXmlDeclaration() .indexOf('\"') == -1) ? "'" : "\""; response.write("<?xml version="); response.write(quoteChar); response.write("1.0"); response.write(quoteChar); response.write(" encoding="); response.write(quoteChar); response.write(encoding); response.write(quoteChar); response.write("?>"); } // Set response locale from session locale // TODO: NG Is this really necessary // response.setLocale(getSession().getLocale()); } /** * THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT CALL OR OVERRIDE. * * @see org.apache.wicket.Component#internalOnModelChanged() */ @Override protected final void internalOnModelChanged() { visitChildren(new IVisitor<Component, Void>() { public void component(final Component component, final IVisit<Void> visit) { // If form component is using form model if (component.sameInnermostModel(Page.this)) { component.modelChanged(); } } }); } /** * * @see org.apache.wicket.Component#onBeforeRender() */ @Override protected void onBeforeRender() { // first try to check if the page can be rendered: if (!isActionAuthorized(RENDER)) { if (log.isDebugEnabled()) { log.debug("Page not allowed to render: " + this); } throw new UnauthorizedActionException(this, Component.RENDER); } // Make sure it is really empty renderedComponents = null; // if the page is stateless, reset the flag so that it is tested again if (Boolean.TRUE.equals(stateless)) { stateless = null; } super.onBeforeRender(); // If any of the components on page is not stateless, we need to bind the session // before we start rendering components, as then jsessionid won't be appended // for links rendered before first stateful component if (getSession().isTemporary() && !peekPageStateless()) { getSession().bind(); } } /** * @see org.apache.wicket.Component#onAfterRender() */ @Override protected void onAfterRender() { super.onAfterRender(); // Check rendering if it happened fully checkRendering(this); // clean up debug meta data if component check is on if (Application.get().getDebugSettings().getComponentUseCheck()) { visitChildren(new IVisitor<Component, Void>() { public void component(final Component component, final IVisit<Void> visit) { component.setMetaData(Component.CONSTRUCTED_AT_KEY, null); component.setMetaData(Component.ADDED_AT_KEY, null); } }); } if (!isPageStateless()) { // trigger creation of the actual session in case it was deferred Session.get().getSessionStore().getSessionId(RequestCycle.get().getRequest(), true); // Add/touch the response page in the session. getSession().getPageManager().touchPage(this); } if (getApplication().getDebugSettings().isOutputMarkupContainerClassName()) { Class<?> klass = getClass(); while (klass.isAnonymousClass()) { klass = klass.getSuperclass(); } getResponse().write("<!-- Page Class "); getResponse().write(klass.getName()); getResponse().write(" -->\n"); } } /** * @see org.apache.wicket.Component#onDetach() */ @Override protected void onDetach() { if (log.isDebugEnabled()) { log.debug("ending request for page " + this + ", request " + getRequest()); } setFlag(FLAG_IS_DIRTY, false); super.onDetach(); } /** * @see org.apache.wicket.MarkupContainer#onRender() */ @Override protected void onRender() { // Configure response object with locale and content type configureResponse(); // Loop through the markup in this container MarkupStream markupStream = new MarkupStream(getMarkup()); renderAll(markupStream, null); } /** * A component was added. * * @param component * The component that was added */ final void componentAdded(final Component component) { if (!getFlag(FLAG_INITIALIZED)) { // initialize the page if not yet initialized initialize(); } if (!component.isAuto()) { dirty(); } } /** * A component's model changed. * * @param component * The component whose model is about to change */ final void componentModelChanging(final Component component) { dirty(); } /** * A component was removed. * * @param component * The component that was removed */ final void componentRemoved(final Component component) { if (!component.isAuto()) { dirty(); } } /** * * @param component * @param change */ final void componentStateChanging(final Component component) { if (!component.isAuto()) { dirty(); } } /** * Set page stateless * * @param stateless */ void setPageStateless(Boolean stateless) { this.stateless = stateless; } /** * Called when the page is retrieved from Session. */ public void onPageAttached() { } /** * @see org.apache.wicket.MarkupContainer#getMarkupType() */ @Override public MarkupType getMarkupType() { throw new UnsupportedOperationException( "Page does not support markup. This error can happen if you have extended Page directly, instead extend WebPage"); } /** * Gets page instance's unique identifier * * @return instance unique identifier */ public PageReference getPageReference() { setStatelessHint(false); return new PageReference(numericId); } /** * @see org.apache.wicket.Component#getMarkup() */ @Override public IMarkupFragment getMarkup() { return getAssociatedMarkup(); } /** * @see org.apache.wicket.page.IManageablePage#getPageId() */ public int getPageId() { return numericId; } /** * @see org.apache.wicket.request.component.IRequestablePage#getRenderCount() */ public int getRenderCount() { return renderCount; } /** TODO WICKET-NG javadoc */ public final void setWasCreatedBookmarkable(boolean wasCreatedBookmarkable) { this.wasCreatedBookmarkable = wasCreatedBookmarkable; } /** TODO WICKET-NG javadoc */ public final boolean wasCreatedBookmarkable() { return wasCreatedBookmarkable; } /** * @see org.apache.wicket.request.component.IRequestablePage#renderPage() */ public void renderPage() { if (getApplication().getRequestCycleSettings().getRenderStrategy() != RenderStrategy.REDIRECT_TO_BUFFER) { // don't increment page id for redirect to render and one pass render during rendering preventDirty(true); } try { ++renderCount; render(); } finally { preventDirty(false); } } /** TODO WICKET-NG is this really needed? can we remove? */ public static Page getPage(int id) { Session session = Session.get(); if (session == null) { return null; } return (Page)session.getPageManager().getPage(id); } }
wicket/src/main/java/org/apache/wicket/Page.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.wicket; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamException; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.apache.wicket.authorization.IAuthorizationStrategy; import org.apache.wicket.authorization.UnauthorizedActionException; import org.apache.wicket.authorization.strategies.page.SimplePageAuthorizationStrategy; import org.apache.wicket.markup.IMarkupFragment; import org.apache.wicket.markup.MarkupException; import org.apache.wicket.markup.MarkupStream; import org.apache.wicket.markup.MarkupType; import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.markup.resolver.IComponentResolver; import org.apache.wicket.model.IModel; import org.apache.wicket.page.IManageablePage; import org.apache.wicket.page.IPageManager; import org.apache.wicket.pageStore.IPageStore; import org.apache.wicket.request.component.IRequestablePage; import org.apache.wicket.request.cycle.RequestCycle; import org.apache.wicket.request.http.WebResponse; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.session.ISessionStore; import org.apache.wicket.settings.IDebugSettings; import org.apache.wicket.util.lang.Classes; import org.apache.wicket.util.lang.WicketObjects; import org.apache.wicket.util.string.StringValue; import org.apache.wicket.util.visit.IVisit; import org.apache.wicket.util.visit.IVisitor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Abstract base class for pages. As a MarkupContainer subclass, a Page can contain a component * hierarchy and markup in some markup language such as HTML. Users of the framework should not * attempt to subclass Page directly. Instead they should subclass a subclass of Page that is * appropriate to the markup type they are using, such as WebPage (for HTML markup). * <ul> * <li><b>Construction </b>- When a page is constructed, it is automatically added to the current * PageMap in the Session. When a Page is added to the Session's PageMap, the PageMap assigns the * Page an id. A PageMap is roughly equivalent to a browser window and encapsulates a set of pages * accessible through that window. When a popup window is created, a new PageMap is created for the * popup. * * <li><b>Identity </b>- The Session that a Page is contained in can be retrieved by calling * Page.getSession(). Page identifiers start at 0 for each PageMap in the Session and increment as * new pages are added to the map. The PageMap-(and Session)-unique identifier assigned to a given * Page can be retrieved by calling getId(). So, the first Page added to a new user Session will * always be named "0". * * <li><b>LifeCycle </b>- Subclasses of Page which are interested in lifecycle events can override * onBeginRequest, onEndRequest() and onModelChanged(). The onBeginRequest() method is inherited * from Component. A call to onBeginRequest() is made for every Component on a Page before page * rendering begins. At the end of a request (when rendering has completed) to a Page, the * onEndRequest() method is called for every Component on the Page. * * <li><b>Nested Component Hierarchy </b>- The Page class is a subclass of MarkupContainer. All * MarkupContainers can have "associated markup", which resides alongside the Java code by default. * All MarkupContainers are also Component containers. Through nesting, of containers, a Page can * contain any arbitrary tree of Components. For more details on MarkupContainers, see * {@link org.apache.wicket.MarkupContainer}. * * <li><b>Bookmarkable Pages </b>- Pages can be constructed with any constructor when they are being * used in a Wicket session, but if you wish to link to a Page using a URL that is "bookmarkable" * (which implies that the URL will not have any session information encoded in it, and that you can * call this page directly without having a session first directly from your browser), you need to * implement your Page with a no-arg constructor or with a constructor that accepts a PageParameters * argument (which wraps any query string parameters for a request). In case the page has both * constructors, the constructor with PageParameters will be used. * * <li><b>Models </b>- Pages, like other Components, can have models (see {@link IModel}). A Page * can be assigned a model by passing one to the Page's constructor, by overriding initModel() or * with an explicit invocation of setModel(). If the model is a * {@link org.apache.wicket.model.CompoundPropertyModel}, Components on the Page can use the Page's * model implicitly via container inheritance. If a Component is not assigned a model, the * initModel() override in Component will cause that Component to use the nearest CompoundModel in * the parent chain, in this case, the Page's model. For basic CompoundModels, the name of the * Component determines which property of the implicit page model the component is bound to. If more * control is desired over the binding of Components to the page model (for example, if you want to * specify some property expression other than the component's name for retrieving the model * object), BoundCompoundPropertyModel can be used. * * <li><b>Back Button </b>- Pages can support the back button by enabling versioning with a call to * setVersioned(boolean). If a Page is versioned and changes occur to it which need to be tracked, a * version manager will be installed using the {@link ISessionStore}'s factory method * newVersionManager(). * * <li><b>Security </b>- See {@link IAuthorizationStrategy}, {@link SimplePageAuthorizationStrategy} * * @see org.apache.wicket.markup.html.WebPage * @see org.apache.wicket.MarkupContainer * @see org.apache.wicket.model.CompoundPropertyModel * @see org.apache.wicket.model.BoundCompoundPropertyModel * @see org.apache.wicket.Component * @see org.apache.wicket.version.IPageVersionManager * @see org.apache.wicket.version.undo.UndoPageVersionManager * * @author Jonathan Locke * @author Chris Turner * @author Eelco Hillenius * @author Johan Compagner * */ public abstract class Page extends MarkupContainer implements IRedirectListener, IManageablePage, IRequestablePage { /** * You can set implementation of the interface in the {@link Page#serializer} then that * implementation will handle the serialization of this page. The serializePage method is called * from the writeObject method then the implementation override the default serialization. * * @author jcompagner */ public static interface IPageSerializer { /** * Called when page is being deserialized * * @param id * TODO * @param name * TODO * @param page * @param stream * @throws IOException * @throws ClassNotFoundException * */ public void deserializePage(int id, String name, Page page, ObjectInputStream stream) throws IOException, ClassNotFoundException; /** * Called from the {@link Page#writeObject(java.io.ObjectOutputStream)} method. * * @param page * The page that must be serialized. * @param stream * ObjectOutputStream * @throws IOException */ public void serializePage(Page page, ObjectOutputStream stream) throws IOException; /** * Returns object to be serialized instead of given page (called from writeReplace). * * @param serializedPage * @return object to be serialized instead of page (or the page instance itself) */ public Object getPageReplacementObject(Page serializedPage); } /** * This is a thread local that is used for serializing page references in this page.It stores a * {@link IPageSerializer} which can be set by the outside world to do the serialization of this * page. */ public static final ThreadLocal<IPageSerializer> serializer = new ThreadLocal<IPageSerializer>(); /** True if the page hierarchy has been modified in the current request. */ private static final int FLAG_IS_DIRTY = FLAG_RESERVED3; /** True if the page should try to be stateless */ private static final int FLAG_STATELESS_HINT = FLAG_RESERVED5; /** Log. */ private static final Logger log = LoggerFactory.getLogger(Page.class); /** * {@link #isBookmarkable()} is expensive, we cache the result here */ private static final ConcurrentHashMap<String, Boolean> pageClassToBookmarkableCache = new ConcurrentHashMap<String, Boolean>(); private static final long serialVersionUID = 1L; /** Used to create page-unique numbers */ private short autoIndex; /** Numeric version of this page's id */ private int numericId; /** Set of components that rendered if component use checking is enabled */ private transient Set<Component> renderedComponents; /** * Boolean if the page is stateless, so it doesn't have to be in the page map, will be set in * urlFor */ private transient Boolean stateless = null; /** Page parameters used to construct this page */ private final PageParameters pageParameters; /** * The purpose of render count is to detect stale listener interface links. For example: there * is a page A rendered in tab 1. Then page A is opened also in tab 2. During render page state * changes (i.e. some repeater gets rebuilt). This makes all links on tab 2 stale - because they * no longer match the actual page state. This is done by incrementing render count. When link * is clicked Wicket checks if it's render count matches the render count value of page */ private int renderCount = 0; /** TODO WICKET-NG JAVADOC */ // TODO WICKET-NG convert into a flag private boolean wasCreatedBookmarkable; /** * Constructor. */ protected Page() { this(null, null); } /** * Constructor. * * @param model * See Component * @see Component#Component(String, IModel) */ protected Page(final IModel<?> model) { this(null, model); } /** * The {@link PageParameters} parameter will be stored in this page and then those parameters * will be used to create stateless links to this bookmarkable page. * * @param parameters * externally passed parameters * @see PageParameters */ protected Page(final PageParameters parameters) { super(null); if (parameters == null) { pageParameters = new PageParameters(); } else { pageParameters = parameters; } init(); } private Page(final PageParameters parameters, IModel<?> model) { super(null, model); if (parameters == null) { // TODO WICKET-NG is this necessary or can we keep the field as null to save space? pageParameters = new PageParameters(); } else { pageParameters = parameters; } init(); } /** * The {@link PageParameters} object that was used to construct this page. This will be used in * creating stateless/bookmarkable links to this page * * @return {@link PageParameters} The construction page parameter */ public PageParameters getPageParameters() { return pageParameters; } /** * Called right after a component's listener method (the provided method argument) was called. * This method may be used to clean up dependencies, do logging, etc. NOTE: this method will * also be called when {@link WebPage#beforeCallComponent(Component, RequestListenerInterface)} * or the method invocation itself failed. * * @param component * the component that is to be called * @param listener * the listener of that component that is to be called */ // TODO Post-1.3: We should create a listener on Application like // IComponentInstantiationListener // that forwards to IAuthorizationStrategy for RequestListenerInterface // invocations. public void afterCallComponent(final Component component, final RequestListenerInterface listener) { } /** * Called just before a component's listener method (the provided method argument) is called. * This method may be used to set up dependencies, enforce authorization, etc. NOTE: if this * method fails, the method will not be executed. Method * {@link WebPage#afterCallComponent(Component, RequestListenerInterface)} will always be * called. * * @param component * the component that is to be called * @param listener * the listener of that component that is to be called */ // TODO Post-1.3: We should create a listener on Application like // IComponentInstantiationListener // that forwards to IAuthorizationStrategy for RequestListenerInterface // invocations. public void beforeCallComponent(final Component component, final RequestListenerInterface listener) { } /** * Adds a component to the set of rendered components. * * @param component * The component that was rendered */ public final void componentRendered(final Component component) { // Inform the page that this component rendered if (Application.get().getDebugSettings().getComponentUseCheck()) { if (renderedComponents == null) { renderedComponents = new HashSet<Component>(); } if (renderedComponents.add(component) == false) { throw new MarkupException( "The component " + component + " was rendered already. You can render it only once during a render phase. Class relative path: " + component.getClassRelativePath()); } if (log.isDebugEnabled()) { log.debug("Rendered " + component); } } } /** * Detaches any attached models referenced by this page. */ @Override public void detachModels() { super.detachModels(); } @Override public void prepareForRender(boolean setRenderingFlag) { if (!getFlag(FLAG_INITIALIZED)) { // initialize the page if not yet initialized initialize(); } super.prepareForRender(setRenderingFlag); } /** * @see #dirty(boolean) */ public final void dirty() { dirty(false); } /** * Mark this page as modified in the session. If versioning is supported then a new version of * the page will be stored in {@link IPageStore page store} * * @param isInitialization * a flag whether this is a page instantiation */ public final void dirty(final boolean isInitialization) { checkHierarchyChange(this); final IPageManager pageManager = getSession().getPageManager(); if (!getFlag(FLAG_IS_DIRTY) && isVersioned() && pageManager.supportsVersioning()) { setFlag(FLAG_IS_DIRTY, true); setNextAvailableId(); pageManager.touchPage(this); } else if (isInitialization) { // we need to get pageId for new page instances even when the page doesn't need // versioning, otherwise pages override each other in the page store and back button // support is broken setNextAvailableId(); } } /** * THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT CALL. * * This method is called when a component was rendered standalone. If it is a <code> * MarkupContainer</code> then the rendering for that container is checked. * * @param component * */ public final void endComponentRender(Component component) { if (component instanceof MarkupContainer) { checkRendering((MarkupContainer)component); } else { renderedComponents = null; } } /** * THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT CALL IT. * * Get a page unique number, which will be increased with each call. * * @return A page unique number */ public final short getAutoIndex() { return autoIndex++; } /** * @see org.apache.wicket.Component#getId() */ @Override public final String getId() { return Integer.toString(numericId); } /** * @see org.apache.wicket.session.pagemap.IPageMapEntry#getNumericId() * @deprecated */ @Deprecated public int getNumericId() { return getPageId(); } /** * @see org.apache.wicket.session.pagemap.IPageMapEntry#getPageClass() */ public final Class<? extends Page> getPageClass() { return getClass(); } /** * @return Size of this page in bytes */ @Override public final long getSizeInBytes() { return WicketObjects.sizeof(this); } /** * Returns whether the page should try to be stateless. To be stateless, getStatelessHint() of * every component on page (and it's behavior) must return true and the page must be * bookmarkable. * * @see org.apache.wicket.Component#getStatelessHint() */ @Override public final boolean getStatelessHint() { return getFlag(FLAG_STATELESS_HINT); } /** * @return This page's component hierarchy as a string */ public final String hierarchyAsString() { final StringBuffer buffer = new StringBuffer(); buffer.append("Page " + getId()); visitChildren(new IVisitor<Component, Void>() { public void component(final Component component, final IVisit<Void> visit) { int levels = 0; for (Component current = component; current != null; current = current.getParent()) { levels++; } buffer.append(StringValue.repeat(levels, " ") + component.getPageRelativePath() + ":" + Classes.simpleName(component.getClass())); } }); return buffer.toString(); } /** * Bookmarkable page can be instantiated using a bookmarkable URL. * * @return Returns true if the page is bookmarkable. */ public boolean isBookmarkable() { Boolean bookmarkable = pageClassToBookmarkableCache.get(getClass().getName()); if (bookmarkable == null) { try { if (getClass().getConstructor(new Class[] { }) != null) { bookmarkable = Boolean.TRUE; } } catch (Exception ignore) { try { if (getClass().getConstructor(new Class[] { PageParameters.class }) != null) { bookmarkable = Boolean.TRUE; } } catch (Exception ignore2) { } } if (bookmarkable == null) { bookmarkable = Boolean.FALSE; } pageClassToBookmarkableCache.put(getClass().getName(), bookmarkable); } return bookmarkable.booleanValue(); } /** * Override this method and return true if your page is used to display Wicket errors. This can * help the framework prevent infinite failure loops. * * @return True if this page is intended to display an error to the end user. */ public boolean isErrorPage() { return false; } /** * Determine the "statelessness" of the page while not changing the cached value. * * @return boolean value */ private boolean peekPageStateless() { Boolean old = stateless; Boolean res = isPageStateless(); stateless = old; return res; } /** * Gets whether the page is stateless. Components on stateless page must not render any * statefull urls, and components on statefull page must not render any stateless urls. * Statefull urls are urls, which refer to a certain (current) page instance. * * @return Whether this page is stateless */ public final boolean isPageStateless() { if (isBookmarkable() == false) { stateless = Boolean.FALSE; if (getStatelessHint()) { log.warn("Page '" + this + "' is not stateless because it is not bookmarkable, " + "but the stateless hint is set to true!"); } } if (getStatelessHint() == false) { return false; } if (stateless == null) { if (isStateless() == false) { stateless = Boolean.FALSE; } } if (stateless == null) { final Object[] returnArray = new Object[1]; Boolean returnValue = visitChildren(Component.class, new IVisitor<Component, Boolean>() { public void component(final Component component, final IVisit<Boolean> visit) { if (!component.isStateless()) { returnArray[0] = component; visit.stop(Boolean.FALSE); } } }); if (returnValue == null) { stateless = Boolean.TRUE; } else if (returnValue instanceof Boolean) { stateless = returnValue; } // TODO (matej_k): The stateless hint semantics has been changed, this warning doesn't // work anymore. but we don't really have // alternative to this /* * if (!stateless.booleanValue() && getStatelessHint()) { log.warn("Page '" + this + "' * is not stateless because of '" + returnArray[0] + "' but the stateless hint is set to * true!"); } */ } return stateless.booleanValue(); } /** * Redirect to this page. * * @see org.apache.wicket.IRedirectListener#onRedirect() */ public final void onRedirect() { } /** * THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT CALL. * * Set the id for this Page. This method is called by PageMap when a Page is added because the * id, which is assigned by PageMap, is not known until this time. * * @param id * The id */ public final void setNumericId(final int id) { numericId = id; } /** * Sets whether the page should try to be stateless. To be stateless, getStatelessHint() of * every component on page (and it's behavior) must return true and the page must be * bookmarkable. * * @param value * whether the page should try to be stateless */ public final void setStatelessHint(boolean value) { if (value && !isBookmarkable()) { throw new WicketRuntimeException( "Can't set stateless hint to true on a page when the page is not bookmarkable, page: " + this); } setFlag(FLAG_STATELESS_HINT, value); } /** * THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT CALL. * * This method is called when a component will be rendered standalone. * * @param component * */ public final void startComponentRender(Component component) { renderedComponents = null; } /** * Get the string representation of this container. * * @return String representation of this container */ @Override public String toString() { return "[Page class = " + getClass().getName() + ", id = " + getId() + ", render count = " + getRenderCount() + "]"; } /** * Throw an exception if not all components rendered. * * @param renderedContainer * The page itself if it was a full page render or the container that was rendered * standalone */ private final void checkRendering(final MarkupContainer renderedContainer) { // If the application wants component uses checked and // the response is not a redirect final IDebugSettings debugSettings = Application.get().getDebugSettings(); if (debugSettings.getComponentUseCheck()) { final List<Component> unrenderedComponents = new ArrayList<Component>(); final StringBuffer buffer = new StringBuffer(); renderedContainer.visitChildren(new IVisitor<Component, Void>() { public void component(final Component component, final IVisit<Void> visit) { // If component never rendered if (renderedComponents == null || !renderedComponents.contains(component)) { // If not an auto component ... if (!component.isAuto() && component.isVisibleInHierarchy()) { // Increase number of unrendered components unrenderedComponents.add(component); // Add to explanatory string to buffer buffer.append(Integer.toString(unrenderedComponents.size()) + ". " + component + "\n"); String metadata = component.getMetaData(Component.CONSTRUCTED_AT_KEY); if (metadata != null) { buffer.append(metadata); } metadata = component.getMetaData(Component.ADDED_AT_KEY); if (metadata != null) { buffer.append(metadata); } } else { // if the component is not visible in hierarchy we // should not visit its children since they are also // not visible visit.dontGoDeeper(); } } } }); // Throw exception if any errors were found if (unrenderedComponents.size() > 0) { // Get rid of set renderedComponents = null; List<Component> transparentContainerChildren = new ArrayList<Component>(); Iterator<Component> iterator = unrenderedComponents.iterator(); outerWhile : while (iterator.hasNext()) { Component component = iterator.next(); // If any of the transparentContainerChildren is a parent to component, than // ignore it. for (Component transparentContainerChild : transparentContainerChildren) { MarkupContainer parent = component.getParent(); while (parent != null) { if (parent == transparentContainerChild) { iterator.remove(); continue outerWhile; } parent = parent.getParent(); } } // Now first test if the component has a sibling that is a transparent resolver. Iterator<? extends Component> iterator2 = component.getParent().iterator(); while (iterator2.hasNext()) { Component sibling = iterator2.next(); if (!sibling.isVisible()) { if (sibling instanceof IComponentResolver) { // we found a transparent container that isn't visible // then ignore this component and only do a debug statement here. if (log.isDebugEnabled()) { log.debug( "Component {} wasn't rendered but most likely it has a transparent parent: {}", component, sibling); } transparentContainerChildren.add(component); iterator.remove(); continue outerWhile; } } } } // if still > 0 if (unrenderedComponents.size() > 0) { // Throw exception throw new WicketRuntimeException( "The component(s) below failed to render. A common problem is that you have added a component in code but forgot to reference it in the markup (thus the component will never be rendered).\n\n" + buffer.toString()); } } } // Get rid of set renderedComponents = null; } /** * Initializes Page by adding it to the Session and initializing it. * * @param pageMap * The page map to put this page in. */ private final void init() { if (isBookmarkable()) { setStatelessHint(true); } // Set versioning of page based on default setVersioned(Application.get().getPageSettings().getVersionPagesByDefault()); // All Pages are born dirty so they get clustered right away dirty(true); // this is a bit of a dirty hack, but calling dirty(true) results in isStateless called // which is bound to set the stateless cache to true as there are no components yet stateless = null; } /** * */ private void setNextAvailableId() { setNumericId(getSession().nextPageId()); } /** * This method will be called for all components that are changed on the page So also auto * components or components that are not versioned. * * If the parent is given that it was a remove or add from that parent of the given component. * else it was just a internal property change of that component. * * @param component * @param parent */ protected void componentChanged(Component component, MarkupContainer parent) { if (!component.isAuto()) { dirty(); } } /** * * @param s * @throws IOException * @throws ClassNotFoundException */ void readPageObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException { int id = s.readShort(); String name = (String)s.readObject(); IPageSerializer ps = serializer.get(); if (ps != null) { ps.deserializePage(id, name, this, s); } else { s.defaultReadObject(); } } /** * * @return serialized version of page * @throws ObjectStreamException */ protected Object writeReplace() throws ObjectStreamException { IPageSerializer ps = serializer.get(); if (ps != null) { return ps.getPageReplacementObject(this); } else { return this; } } /** * Set-up response with appropriate content type, locale and encoding. The locale is set equal * to the session's locale. The content type header contains information about the markup type * (@see #getMarkupType()) and the encoding. The response (and request) encoding is determined * by an application setting (@see ApplicationSettings#getResponseRequestEncoding()). In * addition, if the page's markup contains a xml declaration like &lt?xml ... ?&gt; an xml * declaration with proper encoding information is written to the output as well, provided it is * not disabled by an application setting (@see * ApplicationSettings#getStripXmlDeclarationFromOutput()). * <p> * Note: Prior to Wicket 1.1 the output encoding was determined by the page's markup encoding. * Because this caused uncertainties about the /request/ encoding, it has been changed in favor * of the new, much safer, approach. Please see the Wiki for more details. */ protected void configureResponse() { // Get the response and application final RequestCycle cycle = getRequestCycle(); final Application application = Application.get(); final WebResponse response = (WebResponse)cycle.getResponse(); // Determine encoding final String encoding = application.getRequestCycleSettings().getResponseRequestEncoding(); // Set content type based on markup type for page response.setContentType(getMarkupType().getMimeType() + "; charset=" + encoding); // Write out an xml declaration if the markup stream and settings allow final IMarkupFragment markup = getMarkup(); if ((markup != null) && (markup.getMarkupResourceStream().getXmlDeclaration() != null) && (application.getMarkupSettings().getStripXmlDeclarationFromOutput() == false)) { // Gwyn - Wed, 21 May 2008 12:23:41 // If the xml declaration in the markup used double-quotes, use them in the output too // Whether it should be or not, sometimes it's significant... final String quoteChar = (markup.getMarkupResourceStream() .getXmlDeclaration() .indexOf('\"') == -1) ? "'" : "\""; response.write("<?xml version="); response.write(quoteChar); response.write("1.0"); response.write(quoteChar); response.write(" encoding="); response.write(quoteChar); response.write(encoding); response.write(quoteChar); response.write("?>"); } // Set response locale from session locale // TODO: NG Is this really necessary // response.setLocale(getSession().getLocale()); } /** * THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT CALL OR OVERRIDE. * * @see org.apache.wicket.Component#internalOnModelChanged() */ @Override protected final void internalOnModelChanged() { visitChildren(new IVisitor<Component, Void>() { public void component(final Component component, final IVisit<Void> visit) { // If form component is using form model if (component.sameInnermostModel(Page.this)) { component.modelChanged(); } } }); } /** * * @see org.apache.wicket.Component#onBeforeRender() */ @Override protected void onBeforeRender() { // first try to check if the page can be rendered: if (!isActionAuthorized(RENDER)) { if (log.isDebugEnabled()) { log.debug("Page not allowed to render: " + this); } throw new UnauthorizedActionException(this, Component.RENDER); } // Make sure it is really empty renderedComponents = null; // if the page is stateless, reset the flag so that it is tested again if (Boolean.TRUE.equals(stateless)) { stateless = null; } super.onBeforeRender(); // If any of the components on page is not stateless, we need to bind the session // before we start rendering components, as then jsessionid won't be appended // for links rendered before first stateful component if (getSession().isTemporary() && !peekPageStateless()) { getSession().bind(); } } /** * @see org.apache.wicket.Component#onAfterRender() */ @Override protected void onAfterRender() { super.onAfterRender(); // Check rendering if it happened fully checkRendering(this); // clean up debug meta data if component check is on if (Application.get().getDebugSettings().getComponentUseCheck()) { visitChildren(new IVisitor<Component, Void>() { public void component(final Component component, final IVisit<Void> visit) { component.setMetaData(Component.CONSTRUCTED_AT_KEY, null); component.setMetaData(Component.ADDED_AT_KEY, null); } }); } if (!isPageStateless()) { // trigger creation of the actual session in case it was deferred Session.get().getSessionStore().getSessionId(RequestCycle.get().getRequest(), true); // Add/touch the response page in the session. getSession().getPageManager().touchPage(this); } if (getApplication().getDebugSettings().isOutputMarkupContainerClassName()) { Class<?> klass = getClass(); while (klass.isAnonymousClass()) { klass = klass.getSuperclass(); } getResponse().write("<!-- Page Class "); getResponse().write(klass.getName()); getResponse().write(" -->\n"); } } /** * @see org.apache.wicket.Component#onDetach() */ @Override protected void onDetach() { if (log.isDebugEnabled()) { log.debug("ending request for page " + this + ", request " + getRequest()); } setFlag(FLAG_IS_DIRTY, false); super.onDetach(); } /** * @see org.apache.wicket.MarkupContainer#onRender() */ @Override protected void onRender() { // Configure response object with locale and content type configureResponse(); // Loop through the markup in this container MarkupStream markupStream = new MarkupStream(getMarkup()); renderAll(markupStream, null); } /** * A component was added. * * @param component * The component that was added */ final void componentAdded(final Component component) { if (!getFlag(FLAG_INITIALIZED)) { // initialize the page if not yet initialized initialize(); } if (!component.isAuto()) { dirty(); } } /** * A component's model changed. * * @param component * The component whose model is about to change */ final void componentModelChanging(final Component component) { dirty(); } /** * A component was removed. * * @param component * The component that was removed */ final void componentRemoved(final Component component) { if (!component.isAuto()) { dirty(); } } /** * * @param component * @param change */ final void componentStateChanging(final Component component) { if (!component.isAuto()) { dirty(); } } /** * Set page stateless * * @param stateless */ void setPageStateless(Boolean stateless) { this.stateless = stateless; } /** * Called when the page is retrieved from Session. */ public void onPageAttached() { } /** * @see org.apache.wicket.MarkupContainer#getMarkupType() */ @Override public MarkupType getMarkupType() { throw new UnsupportedOperationException( "Page does not support markup. This error can happen if you have extended Page directly, instead extend WebPage"); } /** * Gets page instance's unique identifier * * @return instance unique identifier */ public PageReference getPageReference() { setStatelessHint(false); return new PageReference(numericId); } /** * @see org.apache.wicket.Component#getMarkup() */ @Override public IMarkupFragment getMarkup() { return getAssociatedMarkup(); } /** * @see org.apache.wicket.page.IManageablePage#getPageId() */ public int getPageId() { return numericId; } /** * @see org.apache.wicket.request.component.IRequestablePage#getRenderCount() */ public int getRenderCount() { return renderCount; } /** TODO WICKET-NG javadoc */ public final void setWasCreatedBookmarkable(boolean wasCreatedBookmarkable) { this.wasCreatedBookmarkable = wasCreatedBookmarkable; } /** TODO WICKET-NG javadoc */ public final boolean wasCreatedBookmarkable() { return wasCreatedBookmarkable; } /** * @see org.apache.wicket.request.component.IRequestablePage#renderPage() */ public void renderPage() { ++renderCount; render(); } /** TODO WICKET-NG is this really needed? can we remove? */ public static Page getPage(int id) { Session session = Session.get(); if (session == null) { return null; } return (Page)session.getPageManager().getPage(id); } }
Fix unecessary page id incrementing with redirect_to_render git-svn-id: 5a74b5304d8e7e474561603514f78b697e5d94c4@981337 13f79535-47bb-0310-9956-ffa450edef68
wicket/src/main/java/org/apache/wicket/Page.java
Fix unecessary page id incrementing with redirect_to_render
<ide><path>icket/src/main/java/org/apache/wicket/Page.java <ide> import org.apache.wicket.request.mapper.parameter.PageParameters; <ide> import org.apache.wicket.session.ISessionStore; <ide> import org.apache.wicket.settings.IDebugSettings; <add>import org.apache.wicket.settings.IRequestCycleSettings.RenderStrategy; <ide> import org.apache.wicket.util.lang.Classes; <ide> import org.apache.wicket.util.lang.WicketObjects; <ide> import org.apache.wicket.util.string.StringValue; <ide> /** True if the page hierarchy has been modified in the current request. */ <ide> private static final int FLAG_IS_DIRTY = FLAG_RESERVED3; <ide> <add> /** Set to prevent marking page as dirty under certain circumstances. */ <add> private static final int FLAG_PREVENT_DIRTY = FLAG_RESERVED4; <add> <ide> /** True if the page should try to be stateless */ <ide> private static final int FLAG_STATELESS_HINT = FLAG_RESERVED5; <ide> <ide> } <ide> <ide> /** <add> * INTERNAL. Prevent marking page as dirty. Used to prevent incrementing page id during <add> * REDIRECT_TO_RENDER rendering. <add> * <add> * @param prevent <add> */ <add> private void preventDirty(boolean prevent) <add> { <add> setFlag(FLAG_PREVENT_DIRTY, prevent); <add> } <add> <add> /** <ide> * Mark this page as modified in the session. If versioning is supported then a new version of <ide> * the page will be stored in {@link IPageStore page store} <ide> * <ide> public final void dirty(final boolean isInitialization) <ide> { <ide> checkHierarchyChange(this); <add> <add> if (getFlag(FLAG_PREVENT_DIRTY)) <add> { <add> return; <add> } <ide> <ide> final IPageManager pageManager = getSession().getPageManager(); <ide> if (!getFlag(FLAG_IS_DIRTY) && isVersioned() && pageManager.supportsVersioning()) <ide> * THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT CALL. <ide> * <ide> * This method is called when a component was rendered standalone. If it is a <code> <del> * MarkupContainer</code> then the rendering for that container is checked. <add> * MarkupContainer</code> <add> * then the rendering for that container is checked. <ide> * <ide> * @param component <ide> * <ide> */ <ide> public void renderPage() <ide> { <del> ++renderCount; <del> render(); <add> if (getApplication().getRequestCycleSettings().getRenderStrategy() != RenderStrategy.REDIRECT_TO_BUFFER) <add> { <add> // don't increment page id for redirect to render and one pass render during rendering <add> preventDirty(true); <add> } <add> try <add> { <add> ++renderCount; <add> render(); <add> } <add> finally <add> { <add> preventDirty(false); <add> } <ide> } <ide> <ide> /** TODO WICKET-NG is this really needed? can we remove? */
Java
apache-2.0
2144479a27cbcc0220ec792f92f7bc21702dea61
0
davidmoten/logan,davidmoten/logan,davidmoten/logan,davidmoten/logan
package com.github.davidmoten.logan; import java.io.File; import java.util.Date; import java.util.Map.Entry; import java.util.NavigableSet; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Logger; import org.davidmoten.kool.Stream; import com.github.davidmoten.bplustree.BPlusTree; public final class DataPersistedBPlusTree implements Data { private static final int LOG_COUNT_EVERY = 10000; private static final Logger log = Logger.getLogger(DataPersistedBPlusTree.class.getName()); private final BPlusTree<IntWithTimestamp, PropertyWithTimestamp> properties; private final ReentrantLock lock = new ReentrantLock(); private long numEntries; private final NavigableSet<String> keys = new ConcurrentSkipListSet<>(); private final NavigableSet<String> sources = new ConcurrentSkipListSet<>(); public DataPersistedBPlusTree(String directory) { new File(directory).mkdirs(); this.properties = BPlusTree // .file() // .directory(directory) // .clearDirectory() // .keySerializer(IntWithTimestamp.SERIALIZER) // .valueSerializer(PropertyWithTimestamp.SERIALIZER) // .naturalOrder(); log.info("constructed"); } @Override public Buckets execute(BucketQuery query) { long t = System.currentTimeMillis(); lock.lock(); try { log.info(query.toString()); Buckets buckets = new Buckets(query); if (query.getField().isPresent()) { IntWithTimestamp start = new IntWithTimestamp(query.getField().get().hashCode(), query.getStartTime()); IntWithTimestamp finish = new IntWithTimestamp(query.getField().get().hashCode(), query.getFinishTime()); log.info("querying properties for range " + start + " to " + finish); properties.find(start, finish, true) // .forEach(x -> { if (x.key.equals(query.getField().get())) { // TODO check source, scan, etc buckets.add(x.time, x.value); } }); } long elapsed = System.currentTimeMillis() - t; long count = buckets.getBucketForAll().count(); log.info("scannedRecords=" + count + ", queryElapsedTimeMs="+ elapsed + ", recordsPerSecond=" + (count*1000/elapsed)); return buckets; } finally { lock.unlock(); } } @Override public Stream<String> getLogs(long startTime, long finishTime) { log.info("querying logs for range " + new Date(startTime) + " to " + new Date(finishTime)); int hashCode = Field.MSG.hashCode(); IntWithTimestamp start = new IntWithTimestamp(hashCode, startTime); IntWithTimestamp finish = new IntWithTimestamp(hashCode, finishTime); return Stream.defer(() -> Stream // .from(properties.find(start, finish, true)) // .filter(x -> Field.MSG.equals(x.key)) // .map(x -> x.stringValue)) // .doOnStart(() -> lock.lock()) // .doBeforeDispose(() -> lock.unlock()); } @Override public Stream<LogEntry> find(long startTime, long finishTime) { throw new UnsupportedOperationException(); } @Override public Data add(LogEntry entry) { lock.lock(); try { numEntries++; for (Entry<String, String> pair : entry.getProperties().entrySet()) { if (Field.MSG.equals(pair.getKey())) { // insert a string value IntWithTimestamp k = new IntWithTimestamp(pair.getKey().hashCode(), entry.getTime()); PropertyWithTimestamp v = new PropertyWithTimestamp(pair.getKey(), 0, pair.getValue(), entry.getTime()); properties.insert(k, v); } else { Double value = Util.parseDouble(pair.getValue()); if (value != null) { // insert a numeric value keys.add(pair.getKey()); IntWithTimestamp k = new IntWithTimestamp(pair.getKey().hashCode(), entry.getTime()); PropertyWithTimestamp v = new PropertyWithTimestamp(pair.getKey(), value, null, entry.getTime()); // System.out.println("inserting\n " + k + "\n->" + v); properties.insert(k, v); } } } String source = entry.getSource(); if (source != null) { sources.add(source); } if (numEntries % LOG_COUNT_EVERY == 0) { log.info("numEntries=" + numEntries); } return this; } finally { lock.unlock(); } } @Override public long getNumEntries() { return numEntries; } @Override public long getNumEntriesAdded() { return numEntries; } @Override public NavigableSet<String> getKeys() { return keys; } @Override public NavigableSet<String> getSources() { return sources; } @Override public void close() throws Exception { properties.close(); } public void print() { properties.findAll((k, v) -> k + " -> " + v).forEach(System.out::println); } }
src/main/java/com/github/davidmoten/logan/DataPersistedBPlusTree.java
package com.github.davidmoten.logan; import java.io.File; import java.util.Date; import java.util.Map.Entry; import java.util.NavigableSet; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Logger; import org.davidmoten.kool.Stream; import com.github.davidmoten.bplustree.BPlusTree; public final class DataPersistedBPlusTree implements Data { private static final int LOG_COUNT_EVERY = 10000; private static final Logger log = Logger.getLogger(DataPersistedBPlusTree.class.getName()); private final BPlusTree<IntWithTimestamp, PropertyWithTimestamp> properties; private final ReentrantLock lock = new ReentrantLock(); private long numEntries; private final NavigableSet<String> keys = new ConcurrentSkipListSet<>(); private final NavigableSet<String> sources = new ConcurrentSkipListSet<>(); public DataPersistedBPlusTree(String directory) { new File(directory).mkdirs(); this.properties = BPlusTree // .file() // .directory(directory) // .clearDirectory() // .keySerializer(IntWithTimestamp.SERIALIZER) // .valueSerializer(PropertyWithTimestamp.SERIALIZER) // .naturalOrder(); log.info("constructed"); } @Override public Buckets execute(BucketQuery query) { lock.lock(); try { log.info(query.toString()); Buckets buckets = new Buckets(query); if (query.getField().isPresent()) { IntWithTimestamp start = new IntWithTimestamp(query.getField().get().hashCode(), query.getStartTime()); IntWithTimestamp finish = new IntWithTimestamp(query.getField().get().hashCode(), query.getFinishTime()); log.info("querying properties for range " + start + " to " + finish); properties.find(start, finish, true) // .forEach(x -> { if (x.key.equals(query.getField().get())) { // TODO check source, scan, etc buckets.add(x.time, x.value); } }); } log.info("scanned " + buckets.getBucketForAll().count() + " records for query"); return buckets; } finally { lock.unlock(); } } @Override public Stream<String> getLogs(long startTime, long finishTime) { log.info("querying logs for range " + new Date(startTime) + " to " + new Date(finishTime)); int hashCode = Field.MSG.hashCode(); IntWithTimestamp start = new IntWithTimestamp(hashCode, startTime); IntWithTimestamp finish = new IntWithTimestamp(hashCode, finishTime); return Stream.defer(() -> Stream // .from(properties.find(start, finish, true)) // .filter(x -> Field.MSG.equals(x.key)) // .map(x -> x.stringValue)) // .doOnStart(() -> lock.lock()) // .doBeforeDispose(() -> lock.unlock()); } @Override public Stream<LogEntry> find(long startTime, long finishTime) { throw new UnsupportedOperationException(); } @Override public Data add(LogEntry entry) { lock.lock(); try { numEntries++; for (Entry<String, String> pair : entry.getProperties().entrySet()) { if (Field.MSG.equals(pair.getKey())) { // insert a string value IntWithTimestamp k = new IntWithTimestamp(pair.getKey().hashCode(), entry.getTime()); PropertyWithTimestamp v = new PropertyWithTimestamp(pair.getKey(), 0, pair.getValue(), entry.getTime()); properties.insert(k, v); } else { Double value = Util.parseDouble(pair.getValue()); if (value != null) { // insert a numeric value keys.add(pair.getKey()); IntWithTimestamp k = new IntWithTimestamp(pair.getKey().hashCode(), entry.getTime()); PropertyWithTimestamp v = new PropertyWithTimestamp(pair.getKey(), value, null, entry.getTime()); // System.out.println("inserting\n " + k + "\n->" + v); properties.insert(k, v); } } } String source = entry.getSource(); if (source != null) { sources.add(source); } if (numEntries % LOG_COUNT_EVERY == 0) { log.info("numEntries=" + numEntries); } return this; } finally { lock.unlock(); } } @Override public long getNumEntries() { return numEntries; } @Override public long getNumEntriesAdded() { return numEntries; } @Override public NavigableSet<String> getKeys() { return keys; } @Override public NavigableSet<String> getSources() { return sources; } @Override public void close() throws Exception { properties.close(); } public void print() { properties.findAll((k, v) -> k + " -> " + v).forEach(System.out::println); } }
add logging to query
src/main/java/com/github/davidmoten/logan/DataPersistedBPlusTree.java
add logging to query
<ide><path>rc/main/java/com/github/davidmoten/logan/DataPersistedBPlusTree.java <ide> <ide> @Override <ide> public Buckets execute(BucketQuery query) { <add> long t = System.currentTimeMillis(); <ide> lock.lock(); <ide> try { <ide> log.info(query.toString()); <ide> } <ide> }); <ide> } <del> log.info("scanned " + buckets.getBucketForAll().count() + " records for query"); <add> long elapsed = System.currentTimeMillis() - t; <add> long count = buckets.getBucketForAll().count(); <add> log.info("scannedRecords=" + count + ", queryElapsedTimeMs="+ elapsed + ", recordsPerSecond=" + (count*1000/elapsed)); <ide> return buckets; <ide> } finally { <ide> lock.unlock();
Java
apache-2.0
5e1ed2acbbfcd5413555ed7d6fb72c4c282a4bf0
0
ChristianNavolskyi/YCSB,cricket007/YCSB,leschekhomann/YCSB,leschekhomann/YCSB,madhurihn/YCSB_ToyDB,brianfrankcooper/YCSB,zyguan/ycsb,cricket007/YCSB,zyguan/ycsb,madhurihn/YCSB_ToyDB,madhurihn/YCSB_ToyDB,madhurihn/YCSB_ToyDB,jaemyoun/YCSB,leschekhomann/YCSB,cricket007/YCSB,manolama/YCSB,brianfrankcooper/YCSB,leschekhomann/YCSB,jaemyoun/YCSB,ChristianNavolskyi/YCSB,cricket007/YCSB,manolama/YCSB,jaemyoun/YCSB,zyguan/ycsb,manolama/YCSB,brianfrankcooper/YCSB,brianfrankcooper/YCSB,ChristianNavolskyi/YCSB,manolama/YCSB,jaemyoun/YCSB,zyguan/ycsb,ChristianNavolskyi/YCSB
package com.yahoo.ycsb.generator; import java.util.concurrent.locks.ReentrantLock; /** * A CounterGenerator that reports generated integers via lastInt() * only after they have been acknowledged. */ public class AcknowledgedCounterGenerator extends CounterGenerator { private static final int WINDOW_SIZE = 10000; private ReentrantLock lock; private boolean[] window; private int limit; /** * Create a counter that starts at countstart. */ public AcknowledgedCounterGenerator(int countstart) { super(countstart); lock = new ReentrantLock(); window = new boolean[WINDOW_SIZE]; limit = countstart - 1; } /** * In this generator, the highest acknowledged counter value * (as opposed to the highest generated counter value). */ @Override public int lastInt() { return limit; } /** * Make a generated counter value available via lastInt(). */ public void acknowledge(int value) { if (value > limit + WINDOW_SIZE) { throw new RuntimeException("This should be a different exception."); } window[value % WINDOW_SIZE] = true; if (lock.tryLock()) { // move a contiguous sequence from the window // over to the "limit" variable try { int index; for (index = limit + 1; index <= value; ++index) { int slot = index % WINDOW_SIZE; if (!window[slot]) { break; } window[slot] = false; } limit = index - 1; } finally { lock.unlock(); } } } }
core/src/main/java/com/yahoo/ycsb/generator/AcknowledgedCounterGenerator.java
package com.yahoo.ycsb.generator; import java.util.PriorityQueue; /** * A CounterGenerator that reports generated integers via lastInt() * only after they have been acknowledged. */ public class AcknowledgedCounterGenerator extends CounterGenerator { private PriorityQueue<Integer> ack; private int limit; /** * Create a counter that starts at countstart. */ public AcknowledgedCounterGenerator(int countstart) { super(countstart); ack = new PriorityQueue<Integer>(); limit = countstart - 1; } /** * In this generator, the highest acknowledged counter value * (as opposed to the highest generated counter value). */ @Override public int lastInt() { return limit; } /** * Make a generated counter value available via lastInt(). */ public synchronized void acknowledge(int value) { ack.add(value); // move a contiguous sequence from the priority queue // over to the "limit" variable Integer min; while ((min = ack.peek()) != null && min == limit + 1) { limit = ack.poll(); } } }
Use a sliding window to track acknowledged values.
core/src/main/java/com/yahoo/ycsb/generator/AcknowledgedCounterGenerator.java
Use a sliding window to track acknowledged values.
<ide><path>ore/src/main/java/com/yahoo/ycsb/generator/AcknowledgedCounterGenerator.java <ide> package com.yahoo.ycsb.generator; <ide> <del>import java.util.PriorityQueue; <add>import java.util.concurrent.locks.ReentrantLock; <ide> <ide> /** <ide> * A CounterGenerator that reports generated integers via lastInt() <ide> */ <ide> public class AcknowledgedCounterGenerator extends CounterGenerator <ide> { <del> private PriorityQueue<Integer> ack; <add> private static final int WINDOW_SIZE = 10000; <add> <add> private ReentrantLock lock; <add> private boolean[] window; <ide> private int limit; <ide> <ide> /** <ide> public AcknowledgedCounterGenerator(int countstart) <ide> { <ide> super(countstart); <del> ack = new PriorityQueue<Integer>(); <add> lock = new ReentrantLock(); <add> window = new boolean[WINDOW_SIZE]; <ide> limit = countstart - 1; <ide> } <ide> <ide> /** <ide> * Make a generated counter value available via lastInt(). <ide> */ <del> public synchronized void acknowledge(int value) <add> public void acknowledge(int value) <ide> { <del> ack.add(value); <add> if (value > limit + WINDOW_SIZE) { <add> throw new RuntimeException("This should be a different exception."); <add> } <ide> <del> // move a contiguous sequence from the priority queue <del> // over to the "limit" variable <add> window[value % WINDOW_SIZE] = true; <ide> <del> Integer min; <add> if (lock.tryLock()) { <add> // move a contiguous sequence from the window <add> // over to the "limit" variable <ide> <del> while ((min = ack.peek()) != null && min == limit + 1) { <del> limit = ack.poll(); <add> try { <add> int index; <add> <add> for (index = limit + 1; index <= value; ++index) { <add> int slot = index % WINDOW_SIZE; <add> <add> if (!window[slot]) { <add> break; <add> } <add> <add> window[slot] = false; <add> } <add> <add> limit = index - 1; <add> } finally { <add> lock.unlock(); <add> } <ide> } <ide> } <ide> }
Java
apache-2.0
0181961ac9d045b7b6473d76f7e75234962199e9
0
electrum/presto,shixuan-fan/presto,prestodb/presto,miniway/presto,nezihyigitbasi/presto,haozhun/presto,wyukawa/presto,youngwookim/presto,Yaliang/presto,electrum/presto,treasure-data/presto,elonazoulay/presto,Teradata/presto,twitter-forks/presto,hgschmie/presto,prestodb/presto,losipiuk/presto,mvp/presto,martint/presto,haozhun/presto,facebook/presto,elonazoulay/presto,arhimondr/presto,losipiuk/presto,youngwookim/presto,facebook/presto,dain/presto,youngwookim/presto,prestodb/presto,miniway/presto,11xor6/presto,prateek1306/presto,gh351135612/presto,losipiuk/presto,shixuan-fan/presto,prestodb/presto,facebook/presto,ebyhr/presto,ebyhr/presto,dain/presto,facebook/presto,Teradata/presto,hgschmie/presto,Yaliang/presto,erichwang/presto,Praveen2112/presto,shixuan-fan/presto,treasure-data/presto,treasure-data/presto,zzhao0/presto,Praveen2112/presto,Yaliang/presto,stewartpark/presto,ebyhr/presto,mvp/presto,elonazoulay/presto,electrum/presto,gh351135612/presto,erichwang/presto,wyukawa/presto,zzhao0/presto,stewartpark/presto,11xor6/presto,wyukawa/presto,prateek1306/presto,yuananf/presto,miniway/presto,EvilMcJerkface/presto,youngwookim/presto,zzhao0/presto,hgschmie/presto,electrum/presto,Teradata/presto,11xor6/presto,smartnews/presto,arhimondr/presto,mvp/presto,yuananf/presto,yuananf/presto,EvilMcJerkface/presto,prestodb/presto,hgschmie/presto,raghavsethi/presto,hgschmie/presto,twitter-forks/presto,Teradata/presto,ebyhr/presto,wyukawa/presto,ebyhr/presto,yuananf/presto,mvp/presto,11xor6/presto,martint/presto,erichwang/presto,EvilMcJerkface/presto,prestodb/presto,losipiuk/presto,EvilMcJerkface/presto,elonazoulay/presto,raghavsethi/presto,Praveen2112/presto,twitter-forks/presto,smartnews/presto,twitter-forks/presto,mvp/presto,stewartpark/presto,Praveen2112/presto,Yaliang/presto,prateek1306/presto,EvilMcJerkface/presto,haozhun/presto,treasure-data/presto,gh351135612/presto,ptkool/presto,treasure-data/presto,martint/presto,treasure-data/presto,sopel39/presto,11xor6/presto,shixuan-fan/presto,arhimondr/presto,electrum/presto,wyukawa/presto,youngwookim/presto,arhimondr/presto,dain/presto,smartnews/presto,yuananf/presto,dain/presto,zzhao0/presto,zzhao0/presto,nezihyigitbasi/presto,smartnews/presto,stewartpark/presto,ptkool/presto,twitter-forks/presto,smartnews/presto,sopel39/presto,sopel39/presto,dain/presto,raghavsethi/presto,ptkool/presto,nezihyigitbasi/presto,nezihyigitbasi/presto,martint/presto,erichwang/presto,raghavsethi/presto,Yaliang/presto,prateek1306/presto,arhimondr/presto,erichwang/presto,sopel39/presto,haozhun/presto,facebook/presto,haozhun/presto,ptkool/presto,ptkool/presto,stewartpark/presto,Teradata/presto,gh351135612/presto,losipiuk/presto,miniway/presto,shixuan-fan/presto,miniway/presto,prateek1306/presto,elonazoulay/presto,nezihyigitbasi/presto,raghavsethi/presto,gh351135612/presto,martint/presto,Praveen2112/presto,sopel39/presto
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.geospatial; import com.esri.core.geometry.Envelope; import com.esri.core.geometry.Geometry; import com.esri.core.geometry.MultiVertexGeometry; import com.esri.core.geometry.Point; import com.esri.core.geometry.Polygon; import com.esri.core.geometry.Polyline; import com.esri.core.geometry.ogc.OGCGeometry; import com.esri.core.geometry.ogc.OGCPoint; import com.esri.core.geometry.ogc.OGCPolygon; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.block.Block; import com.facebook.presto.spi.block.BlockBuilder; import com.facebook.presto.spi.block.BlockBuilderStatus; import com.facebook.presto.spi.function.Description; import com.facebook.presto.spi.function.ScalarFunction; import com.facebook.presto.spi.function.SqlType; import com.facebook.presto.spi.type.StandardTypes; import com.google.common.base.Verify; import io.airlift.slice.Slice; import java.util.HashSet; import java.util.Set; import static com.facebook.presto.geospatial.BingTile.MAX_ZOOM_LEVEL; import static com.facebook.presto.geospatial.GeometryType.GEOMETRY_TYPE_NAME; import static com.facebook.presto.geospatial.GeometryUtils.deserialize; import static com.facebook.presto.geospatial.GeometryUtils.serialize; import static com.facebook.presto.spi.StandardErrorCode.INVALID_FUNCTION_ARGUMENT; import static com.facebook.presto.spi.type.BigintType.BIGINT; import static com.facebook.presto.spi.type.IntegerType.INTEGER; import static com.google.common.base.Preconditions.checkArgument; import static io.airlift.slice.Slices.utf8Slice; import static java.lang.Math.toIntExact; import static java.lang.String.format; /** * A set of functions to convert between geometries and Bing tiles. * * @see <a href="https://msdn.microsoft.com/en-us/library/bb259689.aspx">https://msdn.microsoft.com/en-us/library/bb259689.aspx</a> * for the description of the Bing tiles. */ public class BingTileFunctions { private static final int TILE_PIXELS = 256; private static final double MAX_LATITUDE = 85.05112878; private static final double MIN_LATITUDE = -85.05112878; private static final double MIN_LONGITUDE = -180; private static final double MAX_LONGITUDE = 180; private static final int OPTIMIZED_TILING_MIN_ZOOM_LEVEL = 10; private static final String LATITUDE_OUT_OF_RANGE = "Latitude must be between " + MIN_LATITUDE + " and " + MAX_LATITUDE; private static final String LATITUDE_SPAN_OUT_OF_RANGE = String.format("Latitude span for the geometry must be in [%.2f, %.2f] range", MIN_LATITUDE, MAX_LATITUDE); private static final String LONGITUDE_OUT_OF_RANGE = "Longitude must be between " + MIN_LONGITUDE + " and " + MAX_LONGITUDE; private static final String LONGITUDE_SPAN_OUT_OF_RANGE = String.format("Longitude span for the geometry must be in [%.2f, %.2f] range", MIN_LONGITUDE, MAX_LONGITUDE); private static final String QUAD_KEY_EMPTY = "QuadKey must not be empty string"; private static final String QUAD_KEY_TOO_LONG = "QuadKey must be " + MAX_ZOOM_LEVEL + " characters or less"; private static final String ZOOM_LEVEL_TOO_SMALL = "Zoom level must be > 0"; private static final String ZOOM_LEVEL_TOO_LARGE = "Zoom level must be <= " + MAX_ZOOM_LEVEL; private BingTileFunctions() {} @Description("Creates a Bing tile from XY coordinates and zoom level") @ScalarFunction("bing_tile") @SqlType(BingTileType.NAME) public static long toBingTile(@SqlType(StandardTypes.INTEGER) long tileX, @SqlType(StandardTypes.INTEGER) long tileY, @SqlType(StandardTypes.INTEGER) long zoomLevel) { checkZoomLevel(zoomLevel); checkCoordinate(tileX, zoomLevel); checkCoordinate(tileY, zoomLevel); return BingTile.fromCoordinates(toIntExact(tileX), toIntExact(tileY), toIntExact(zoomLevel)).encode(); } @Description("Given a Bing tile, returns its QuadKey") @ScalarFunction("bing_tile_quadkey") @SqlType(StandardTypes.VARCHAR) public static Slice toQuadKey(@SqlType(BingTileType.NAME) long input) { return utf8Slice(BingTile.decode(input).toQuadKey()); } @Description("Given a Bing tile, returns XY coordinates of the tile") @ScalarFunction("bing_tile_coordinates") @SqlType("row(x integer,y integer)") public static Block bingTileCoordinates(@SqlType(BingTileType.NAME) long input) { BingTile tile = BingTile.decode(input); BlockBuilder tileBlockBuilder = INTEGER.createBlockBuilder(new BlockBuilderStatus(), 2); INTEGER.writeLong(tileBlockBuilder, tile.getX()); INTEGER.writeLong(tileBlockBuilder, tile.getY()); return tileBlockBuilder.build(); } @Description("Given a Bing tile, returns zoom level of the tile") @ScalarFunction("bing_tile_zoom_level") @SqlType(StandardTypes.TINYINT) public static long bingTileZoomLevel(@SqlType(BingTileType.NAME) long input) { return BingTile.decode(input).getZoomLevel(); } @Description("Creates a Bing tile from a QuadKey") @ScalarFunction("bing_tile") @SqlType(BingTileType.NAME) public static long toBingTile(@SqlType(StandardTypes.VARCHAR) Slice quadKey) { checkQuadKey(quadKey); return BingTile.fromQuadKey(quadKey.toStringUtf8()).encode(); } @Description("Given a (longitude, latitude) point, returns the containing Bing tile at the specified zoom level") @ScalarFunction("bing_tile_at") @SqlType(BingTileType.NAME) public static long bingTileAt( @SqlType(StandardTypes.DOUBLE) double latitude, @SqlType(StandardTypes.DOUBLE) double longitude, @SqlType(StandardTypes.INTEGER) long zoomLevel) { checkLatitude(latitude, LATITUDE_OUT_OF_RANGE); checkLongitude(longitude, LONGITUDE_OUT_OF_RANGE); checkZoomLevel(zoomLevel); return latitudeLongitudeToTile(latitude, longitude, toIntExact(zoomLevel)).encode(); } @Description("Given a Bing tile, returns the polygon representation of the tile") @ScalarFunction("bing_tile_polygon") @SqlType(GEOMETRY_TYPE_NAME) public static Slice bingTilePolygon(@SqlType(BingTileType.NAME) long input) { BingTile tile = BingTile.decode(input); return serialize(tileToPolygon(tile)); } @Description("Given a geometry and a zoom level, returns the minimum set of Bing tiles that fully covers that geometry") @ScalarFunction("geometry_to_bing_tiles") @SqlType("array(" + BingTileType.NAME + ")") public static Block geometryToBingTiles(@SqlType(GEOMETRY_TYPE_NAME) Slice input, @SqlType(StandardTypes.INTEGER) long zoomLevelInput) { checkZoomLevel(zoomLevelInput); int zoomLevel = toIntExact(zoomLevelInput); OGCGeometry geometry = deserialize(input); checkCondition(!geometry.isEmpty(), "Input geometry must not be empty"); Envelope envelope = new Envelope(); geometry.getEsriGeometry().queryEnvelope(envelope); checkLatitude(envelope.getYMin(), LATITUDE_SPAN_OUT_OF_RANGE); checkLatitude(envelope.getYMax(), LATITUDE_SPAN_OUT_OF_RANGE); checkLongitude(envelope.getXMin(), LONGITUDE_SPAN_OUT_OF_RANGE); checkLongitude(envelope.getXMax(), LONGITUDE_SPAN_OUT_OF_RANGE); boolean pointOrRectangle = isPointOrRectangle(geometry, envelope); BingTile leftUpperTile = latitudeLongitudeToTile(envelope.getYMax(), envelope.getXMin(), zoomLevel); BingTile rightLowerTile = latitudeLongitudeToTile(envelope.getYMin(), envelope.getXMax(), zoomLevel); // XY coordinates start at (0,0) in the left upper corner and increase left to right and top to bottom int tileCount = toIntExact((rightLowerTile.getX() - leftUpperTile.getX() + 1) * (rightLowerTile.getY() - leftUpperTile.getY() + 1)); checkGeometryToBingTilesLimits(geometry, pointOrRectangle, tileCount); BlockBuilder blockBuilder = BIGINT.createBlockBuilder(null, tileCount); if (pointOrRectangle || zoomLevel <= OPTIMIZED_TILING_MIN_ZOOM_LEVEL) { // Collect tiles covering the bounding box and check each tile for intersection with the geometry. // Skip intersection check if geometry is a point or rectangle. In these cases, by definition, // all tiles covering the bounding box intersect the geometry. for (int x = leftUpperTile.getX(); x <= rightLowerTile.getX(); x++) { for (int y = leftUpperTile.getY(); y <= rightLowerTile.getY(); y++) { BingTile tile = BingTile.fromCoordinates(x, y, zoomLevel); if (pointOrRectangle || !tileToPolygon(tile).disjoint(geometry)) { BIGINT.writeLong(blockBuilder, tile.encode()); } } } } else { // Intersection checks above are expensive. The logic below attempts to reduce the number // of these checks. The idea is to identify large tiles which are fully covered by the // geometry. For each such tile, we can cheaply compute all the containing tiles at // the right zoom level and append them to results in bulk. This way we perform a single // containment check instead of 2 to the power of level delta intersection checks, where // level delta is the difference between the desired zoom level and level of the large // tile covered by the geometry. BingTile[] tiles = getTilesInBetween(leftUpperTile, rightLowerTile, OPTIMIZED_TILING_MIN_ZOOM_LEVEL); for (BingTile tile : tiles) { writeTilesToBlockBuilder(geometry, zoomLevel, tile, blockBuilder); } } return blockBuilder.build(); } private static void checkGeometryToBingTilesLimits(OGCGeometry geometry, boolean pointOrRectangle, int tileCount) { if (pointOrRectangle) { checkCondition(tileCount <= 1_000_000, "The number of input tiles is too large (more than 1M) to compute a set of covering bing tiles."); } else { long complexity = ((long) tileCount) * getPointCount(geometry.getEsriGeometry()); checkCondition(complexity <= 25_000_000, "The zoom level is too high or the geometry is too complex to compute a set of covering bing tiles. " + "Please use a lower zoom level or convert the geometry to its bounding box using the ST_Envelope function."); } } private static BingTile[] getTilesInBetween(BingTile leftUpperTile, BingTile rightLowerTile, int zoomLevel) { checkArgument(leftUpperTile.getZoomLevel() == rightLowerTile.getZoomLevel()); checkArgument(leftUpperTile.getZoomLevel() > zoomLevel); int divisor = 1 << (leftUpperTile.getZoomLevel() - zoomLevel); int minX = (int) Math.floor(leftUpperTile.getX() / divisor); int maxX = (int) Math.floor(rightLowerTile.getX() / divisor); int minY = (int) Math.floor(leftUpperTile.getY() / divisor); int maxY = (int) Math.floor(rightLowerTile.getY() / divisor); BingTile[] tiles = new BingTile[(maxX - minX + 1) * (maxY - minY + 1)]; int index = 0; for (int x = minX; x <= maxX; x++) { for (int y = minY; y <= maxY; y++) { tiles[index] = BingTile.fromCoordinates(x, y, OPTIMIZED_TILING_MIN_ZOOM_LEVEL); index++; } } return tiles; } /** * Identifies a minimum set of tiles at specified zoom level that cover intersection of the * specified geometry and a specified tile of the same or lower level. Adds tiles to provided * BlockBuilder. */ private static void writeTilesToBlockBuilder( OGCGeometry geometry, int zoomLevel, BingTile tile, BlockBuilder blockBuilder) { int tileZoomLevel = tile.getZoomLevel(); checkArgument(tile.getZoomLevel() <= zoomLevel); OGCGeometry polygon = tileToPolygon(tile); if (tileZoomLevel == zoomLevel) { if (!geometry.disjoint(polygon)) { BIGINT.writeLong(blockBuilder, tile.encode()); } return; } if (geometry.contains(polygon)) { int subTileCount = 1 << (zoomLevel - tileZoomLevel); int minX = subTileCount * tile.getX(); int minY = subTileCount * tile.getY(); for (int x = minX; x < minX + subTileCount; x++) { for (int y = minY; y < minY + subTileCount; y++) { BIGINT.writeLong(blockBuilder, BingTile.fromCoordinates(x, y, zoomLevel).encode()); } } return; } if (geometry.disjoint(polygon)) { return; } int minX = 2 * tile.getX(); int minY = 2 * tile.getY(); int nextZoomLevel = tileZoomLevel + 1; Verify.verify(nextZoomLevel <= MAX_ZOOM_LEVEL); for (int x = minX; x < minX + 2; x++) { for (int y = minY; y < minY + 2; y++) { writeTilesToBlockBuilder( geometry, zoomLevel, BingTile.fromCoordinates(x, y, nextZoomLevel), blockBuilder); } } } private static int getPointCount(Geometry geometry) { if (geometry instanceof Point) { return 1; } return ((MultiVertexGeometry) geometry).getPointCount(); } private static Point tileXYToLatitudeLongitude(int tileX, int tileY, int zoomLevel) { int mapSize = mapSize(zoomLevel); double x = (clip(tileX * TILE_PIXELS, 0, mapSize) / mapSize) - 0.5; double y = 0.5 - (clip(tileY * TILE_PIXELS, 0, mapSize) / mapSize); double latitude = 90 - 360 * Math.atan(Math.exp(-y * 2 * Math.PI)) / Math.PI; double longitude = 360 * x; return new Point(longitude, latitude); } private static BingTile latitudeLongitudeToTile(double latitude, double longitude, int zoomLevel) { double x = (longitude + 180) / 360; double sinLatitude = Math.sin(latitude * Math.PI / 180); double y = 0.5 - Math.log((1 + sinLatitude) / (1 - sinLatitude)) / (4 * Math.PI); int mapSize = mapSize(zoomLevel); int tileX = (int) clip(x * mapSize, 0, mapSize - 1); int tileY = (int) clip(y * mapSize, 0, mapSize - 1); return BingTile.fromCoordinates(tileX / TILE_PIXELS, tileY / TILE_PIXELS, zoomLevel); } private static OGCGeometry tileToPolygon(BingTile tile) { Point upperLeftCorner = tileXYToLatitudeLongitude(tile.getX(), tile.getY(), tile.getZoomLevel()); Point lowerRightCorner = tileXYToLatitudeLongitude(tile.getX() + 1, tile.getY() + 1, tile.getZoomLevel()); Polyline boundary = new Polyline(); boundary.startPath(upperLeftCorner); boundary.lineTo(lowerRightCorner.getX(), upperLeftCorner.getY()); boundary.lineTo(lowerRightCorner); boundary.lineTo(upperLeftCorner.getX(), lowerRightCorner.getY()); Polygon polygon = new Polygon(); polygon.add(boundary, false); return OGCGeometry.createFromEsriGeometry(polygon, null); } /** * @return true if the geometry is a point or a rectangle */ private static boolean isPointOrRectangle(OGCGeometry geometry, Envelope envelope) { if (geometry instanceof OGCPoint) { return true; } if (!(geometry instanceof OGCPolygon)) { return false; } OGCPolygon polygon = (OGCPolygon) geometry; if (polygon.numInteriorRing() > 0) { return false; } MultiVertexGeometry multiVertexGeometry = (MultiVertexGeometry) polygon.getEsriGeometry(); if (multiVertexGeometry.getPointCount() != 4) { return false; } Set<Point> corners = new HashSet<>(); corners.add(new Point(envelope.getXMin(), envelope.getYMin())); corners.add(new Point(envelope.getXMin(), envelope.getYMax())); corners.add(new Point(envelope.getXMax(), envelope.getYMin())); corners.add(new Point(envelope.getXMax(), envelope.getYMax())); for (int i = 0; i < 4; i++) { Point point = multiVertexGeometry.getPoint(i); if (!corners.contains(point)) { return false; } } return true; } private static void checkZoomLevel(long zoomLevel) { checkCondition(zoomLevel > 0, ZOOM_LEVEL_TOO_SMALL); checkCondition(zoomLevel <= MAX_ZOOM_LEVEL, ZOOM_LEVEL_TOO_LARGE); } private static void checkCoordinate(long coordinate, long zoomLevel) { checkCondition(coordinate >= 0 && coordinate < (1 << zoomLevel), "XY coordinates for a Bing tile at zoom level %s must be within [0, %s) range", zoomLevel, 1 << zoomLevel); } private static void checkQuadKey(@SqlType(StandardTypes.VARCHAR) Slice quadkey) { checkCondition(quadkey.length() > 0, QUAD_KEY_EMPTY); checkCondition(quadkey.length() <= MAX_ZOOM_LEVEL, QUAD_KEY_TOO_LONG); } private static void checkLatitude(double latitude, String errorMessage) { checkCondition(latitude >= MIN_LATITUDE && latitude <= MAX_LATITUDE, errorMessage); } private static void checkLongitude(double longitude, String errorMessage) { checkCondition(longitude >= MIN_LONGITUDE && longitude <= MAX_LONGITUDE, errorMessage); } private static void checkCondition(boolean condition, String formatString, Object... args) { if (!condition) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format(formatString, args)); } } private static double clip(double n, double minValue, double maxValue) { return Math.min(Math.max(n, minValue), maxValue); } private static int mapSize(int zoomLevel) { return 256 << zoomLevel; } }
presto-geospatial/src/main/java/com/facebook/presto/geospatial/BingTileFunctions.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.geospatial; import com.esri.core.geometry.Envelope; import com.esri.core.geometry.Geometry; import com.esri.core.geometry.MultiVertexGeometry; import com.esri.core.geometry.Point; import com.esri.core.geometry.Polygon; import com.esri.core.geometry.Polyline; import com.esri.core.geometry.ogc.OGCGeometry; import com.esri.core.geometry.ogc.OGCPoint; import com.esri.core.geometry.ogc.OGCPolygon; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.block.Block; import com.facebook.presto.spi.block.BlockBuilder; import com.facebook.presto.spi.block.BlockBuilderStatus; import com.facebook.presto.spi.function.Description; import com.facebook.presto.spi.function.ScalarFunction; import com.facebook.presto.spi.function.SqlType; import com.facebook.presto.spi.type.StandardTypes; import com.google.common.base.Verify; import io.airlift.slice.Slice; import java.util.HashSet; import java.util.Set; import static com.facebook.presto.geospatial.BingTile.MAX_ZOOM_LEVEL; import static com.facebook.presto.geospatial.GeometryType.GEOMETRY_TYPE_NAME; import static com.facebook.presto.geospatial.GeometryUtils.deserialize; import static com.facebook.presto.geospatial.GeometryUtils.serialize; import static com.facebook.presto.spi.StandardErrorCode.INVALID_FUNCTION_ARGUMENT; import static com.facebook.presto.spi.type.BigintType.BIGINT; import static com.facebook.presto.spi.type.IntegerType.INTEGER; import static com.google.common.base.Preconditions.checkArgument; import static io.airlift.slice.Slices.utf8Slice; import static java.lang.Math.toIntExact; import static java.lang.String.format; /** * A set of functions to convert between geometries and Bing tiles. * * @see <a href="https://msdn.microsoft.com/en-us/library/bb259689.aspx">https://msdn.microsoft.com/en-us/library/bb259689.aspx</a> * for the description of the Bing tiles. */ public class BingTileFunctions { private static final int TILE_PIXELS = 256; private static final double MAX_LATITUDE = 85.05112878; private static final double MIN_LATITUDE = -85.05112878; private static final double MIN_LONGITUDE = -180; private static final double MAX_LONGITUDE = 180; private static final int OPTIMIZED_TILING_MIN_ZOOM_LEVEL = 10; private static final String LATITUDE_OUT_OF_RANGE = "Latitude must be between " + MIN_LATITUDE + " and " + MAX_LATITUDE; private static final String LATITUDE_SPAN_OUT_OF_RANGE = String.format("Latitude span for the geometry must be in [%.2f, %.2f] range", MIN_LATITUDE, MAX_LATITUDE); private static final String LONGITUDE_OUT_OF_RANGE = "Longitude must be between " + MIN_LONGITUDE + " and " + MAX_LONGITUDE; private static final String LONGITUDE_SPAN_OUT_OF_RANGE = String.format("Longitude span for the geometry must be in [%.2f, %.2f] range", MIN_LONGITUDE, MAX_LONGITUDE); private static final String QUAD_KEY_EMPTY = "QuadKey must not be empty string"; private static final String QUAD_KEY_TOO_LONG = "QuadKey must be " + MAX_ZOOM_LEVEL + " characters or less"; private static final String ZOOM_LEVEL_TOO_SMALL = "Zoom level must be > 0"; private static final String ZOOM_LEVEL_TOO_LARGE = "Zoom level must be <= " + MAX_ZOOM_LEVEL; private BingTileFunctions() {} @Description("Creates a Bing tile from XY coordinates and zoom level") @ScalarFunction("bing_tile") @SqlType(BingTileType.NAME) public static long toBingTile(@SqlType(StandardTypes.INTEGER) long tileX, @SqlType(StandardTypes.INTEGER) long tileY, @SqlType(StandardTypes.INTEGER) long zoomLevel) { checkZoomLevel(zoomLevel); checkCoordinate(tileX, zoomLevel); checkCoordinate(tileY, zoomLevel); return BingTile.fromCoordinates(toIntExact(tileX), toIntExact(tileY), toIntExact(zoomLevel)).encode(); } @Description("Given a Bing tile, returns its QuadKey") @ScalarFunction("bing_tile_quadkey") @SqlType(StandardTypes.VARCHAR) public static Slice toQuadKey(@SqlType(BingTileType.NAME) long input) { return utf8Slice(BingTile.decode(input).toQuadKey()); } @Description("Given a Bing tile, returns XY coordinates of the tile") @ScalarFunction("bing_tile_coordinates") @SqlType("row(x integer,y integer)") public static Block bingTileCoordinates(@SqlType(BingTileType.NAME) long input) { BingTile tile = BingTile.decode(input); BlockBuilder tileBlockBuilder = INTEGER.createBlockBuilder(new BlockBuilderStatus(), 2); INTEGER.writeLong(tileBlockBuilder, tile.getX()); INTEGER.writeLong(tileBlockBuilder, tile.getY()); return tileBlockBuilder.build(); } @Description("Given a Bing tile, returns zoom level of the tile") @ScalarFunction("bing_tile_zoom_level") @SqlType(StandardTypes.TINYINT) public static long bingTileZoomLevel(@SqlType(BingTileType.NAME) long input) { return BingTile.decode(input).getZoomLevel(); } @Description("Creates a Bing tile from a QuadKey") @ScalarFunction("bing_tile") @SqlType(BingTileType.NAME) public static long toBingTile(@SqlType(StandardTypes.VARCHAR) Slice quadKey) { checkQuadKey(quadKey); return BingTile.fromQuadKey(quadKey.toStringUtf8()).encode(); } @Description("Given a (longitude, latitude) point, returns the containing Bing tile at the specified zoom level") @ScalarFunction("bing_tile_at") @SqlType(BingTileType.NAME) public static long bingTileAt( @SqlType(StandardTypes.DOUBLE) double latitude, @SqlType(StandardTypes.DOUBLE) double longitude, @SqlType(StandardTypes.INTEGER) long zoomLevel) { checkLatitude(latitude, LATITUDE_OUT_OF_RANGE); checkLongitude(longitude, LONGITUDE_OUT_OF_RANGE); checkZoomLevel(zoomLevel); return latitudeLongitudeToTile(latitude, longitude, toIntExact(zoomLevel)).encode(); } @Description("Given a Bing tile, returns the polygon representation of the tile") @ScalarFunction("bing_tile_polygon") @SqlType(GEOMETRY_TYPE_NAME) public static Slice bingTilePolygon(@SqlType(BingTileType.NAME) long input) { BingTile tile = BingTile.decode(input); return serialize(tileToPolygon(tile)); } @Description("Given a geometry and a zoom level, returns the minimum set of Bing tiles that fully covers that geometry") @ScalarFunction("geometry_to_bing_tiles") @SqlType("array(" + BingTileType.NAME + ")") public static Block geometryToBingTiles(@SqlType(GEOMETRY_TYPE_NAME) Slice input, @SqlType(StandardTypes.INTEGER) long zoomLevelInput) { checkZoomLevel(zoomLevelInput); int zoomLevel = toIntExact(zoomLevelInput); OGCGeometry geometry = deserialize(input); checkCondition(!geometry.isEmpty(), "Input geometry must not be empty"); Envelope envelope = new Envelope(); geometry.getEsriGeometry().queryEnvelope(envelope); checkLatitude(envelope.getYMin(), LATITUDE_SPAN_OUT_OF_RANGE); checkLatitude(envelope.getYMax(), LATITUDE_SPAN_OUT_OF_RANGE); checkLongitude(envelope.getXMin(), LONGITUDE_SPAN_OUT_OF_RANGE); checkLongitude(envelope.getXMax(), LONGITUDE_SPAN_OUT_OF_RANGE); boolean pointOrRectangle = isPointOrRectangle(geometry, envelope); BingTile leftUpperTile = latitudeLongitudeToTile(envelope.getYMax(), envelope.getXMin(), zoomLevel); BingTile rightLowerTile = latitudeLongitudeToTile(envelope.getYMin(), envelope.getXMax(), zoomLevel); // XY coordinates start at (0,0) in the left upper corner and increase left to right and top to bottom int tileCount = toIntExact((rightLowerTile.getX() - leftUpperTile.getX() + 1) * (rightLowerTile.getY() - leftUpperTile.getY() + 1)); checkGeometryToBingTilesLimits(geometry, pointOrRectangle, tileCount); BlockBuilder blockBuilder = BIGINT.createBlockBuilder(null, tileCount); if (pointOrRectangle || zoomLevel <= OPTIMIZED_TILING_MIN_ZOOM_LEVEL) { // Collect tiles covering the bounding box and check each tile for intersection with the geometry. // Skip intersection check if geometry is a point or rectangle. In these cases, by definition, // all tiles covering the bounding box intersect the geometry. for (int x = leftUpperTile.getX(); x <= rightLowerTile.getX(); x++) { for (int y = leftUpperTile.getY(); y <= rightLowerTile.getY(); y++) { BingTile tile = BingTile.fromCoordinates(x, y, zoomLevel); if (pointOrRectangle || !tileToPolygon(tile).disjoint(geometry)) { BIGINT.writeLong(blockBuilder, tile.encode()); } } } } else { // Intersection checks above are expensive. The logic below attempts to reduce the number // of these checks. The idea is to identify large tiles which are fully covered by the // geometry. For each such tile, we can cheaply compute all the containing tiles at // the right zoom level and append them to results in bulk. This way we perform a single // containment check instead of 2 to the power of level delta intersection checks, where // level delta is the difference between the desired zoom level and level of the large // tile covered by the geometry. BingTile[] tiles = getTilesInBetween(leftUpperTile, rightLowerTile, OPTIMIZED_TILING_MIN_ZOOM_LEVEL); for (BingTile tile : tiles) { writeTilesToBlockBuilder(geometry, zoomLevel, tile, blockBuilder); } } return blockBuilder.build(); } private static void checkGeometryToBingTilesLimits(OGCGeometry geometry, boolean pointOrRectangle, int tileCount) { if (pointOrRectangle) { checkCondition(tileCount <= 1_000_000, "The number of input tiles is too large (more than 1M) to compute a set of covering bing tiles."); } else { long complexity = tileCount * getPointCount(geometry.getEsriGeometry()); checkCondition(complexity <= 25_000_000, "The zoom level is too high or the geometry is too complex to compute a set of covering bing tiles. " + "Please use a lower zoom level or convert the geometry to its bounding box using the ST_Envelope function."); } } private static BingTile[] getTilesInBetween(BingTile leftUpperTile, BingTile rightLowerTile, int zoomLevel) { checkArgument(leftUpperTile.getZoomLevel() == rightLowerTile.getZoomLevel()); checkArgument(leftUpperTile.getZoomLevel() > zoomLevel); int divisor = 1 << (leftUpperTile.getZoomLevel() - zoomLevel); int minX = (int) Math.floor(leftUpperTile.getX() / divisor); int maxX = (int) Math.floor(rightLowerTile.getX() / divisor); int minY = (int) Math.floor(leftUpperTile.getY() / divisor); int maxY = (int) Math.floor(rightLowerTile.getY() / divisor); BingTile[] tiles = new BingTile[(maxX - minX + 1) * (maxY - minY + 1)]; int index = 0; for (int x = minX; x <= maxX; x++) { for (int y = minY; y <= maxY; y++) { tiles[index] = BingTile.fromCoordinates(x, y, OPTIMIZED_TILING_MIN_ZOOM_LEVEL); index++; } } return tiles; } /** * Identifies a minimum set of tiles at specified zoom level that cover intersection of the * specified geometry and a specified tile of the same or lower level. Adds tiles to provided * BlockBuilder. */ private static void writeTilesToBlockBuilder( OGCGeometry geometry, int zoomLevel, BingTile tile, BlockBuilder blockBuilder) { int tileZoomLevel = tile.getZoomLevel(); checkArgument(tile.getZoomLevel() <= zoomLevel); OGCGeometry polygon = tileToPolygon(tile); if (tileZoomLevel == zoomLevel) { if (!geometry.disjoint(polygon)) { BIGINT.writeLong(blockBuilder, tile.encode()); } return; } if (geometry.contains(polygon)) { int subTileCount = 1 << (zoomLevel - tileZoomLevel); int minX = subTileCount * tile.getX(); int minY = subTileCount * tile.getY(); for (int x = minX; x < minX + subTileCount; x++) { for (int y = minY; y < minY + subTileCount; y++) { BIGINT.writeLong(blockBuilder, BingTile.fromCoordinates(x, y, zoomLevel).encode()); } } return; } if (geometry.disjoint(polygon)) { return; } int minX = 2 * tile.getX(); int minY = 2 * tile.getY(); int nextZoomLevel = tileZoomLevel + 1; Verify.verify(nextZoomLevel <= MAX_ZOOM_LEVEL); for (int x = minX; x < minX + 2; x++) { for (int y = minY; y < minY + 2; y++) { writeTilesToBlockBuilder( geometry, zoomLevel, BingTile.fromCoordinates(x, y, nextZoomLevel), blockBuilder); } } } private static int getPointCount(Geometry geometry) { if (geometry instanceof Point) { return 1; } return ((MultiVertexGeometry) geometry).getPointCount(); } private static Point tileXYToLatitudeLongitude(int tileX, int tileY, int zoomLevel) { int mapSize = mapSize(zoomLevel); double x = (clip(tileX * TILE_PIXELS, 0, mapSize) / mapSize) - 0.5; double y = 0.5 - (clip(tileY * TILE_PIXELS, 0, mapSize) / mapSize); double latitude = 90 - 360 * Math.atan(Math.exp(-y * 2 * Math.PI)) / Math.PI; double longitude = 360 * x; return new Point(longitude, latitude); } private static BingTile latitudeLongitudeToTile(double latitude, double longitude, int zoomLevel) { double x = (longitude + 180) / 360; double sinLatitude = Math.sin(latitude * Math.PI / 180); double y = 0.5 - Math.log((1 + sinLatitude) / (1 - sinLatitude)) / (4 * Math.PI); int mapSize = mapSize(zoomLevel); int tileX = (int) clip(x * mapSize, 0, mapSize - 1); int tileY = (int) clip(y * mapSize, 0, mapSize - 1); return BingTile.fromCoordinates(tileX / TILE_PIXELS, tileY / TILE_PIXELS, zoomLevel); } private static OGCGeometry tileToPolygon(BingTile tile) { Point upperLeftCorner = tileXYToLatitudeLongitude(tile.getX(), tile.getY(), tile.getZoomLevel()); Point lowerRightCorner = tileXYToLatitudeLongitude(tile.getX() + 1, tile.getY() + 1, tile.getZoomLevel()); Polyline boundary = new Polyline(); boundary.startPath(upperLeftCorner); boundary.lineTo(lowerRightCorner.getX(), upperLeftCorner.getY()); boundary.lineTo(lowerRightCorner); boundary.lineTo(upperLeftCorner.getX(), lowerRightCorner.getY()); Polygon polygon = new Polygon(); polygon.add(boundary, false); return OGCGeometry.createFromEsriGeometry(polygon, null); } /** * @return true if the geometry is a point or a rectangle */ private static boolean isPointOrRectangle(OGCGeometry geometry, Envelope envelope) { if (geometry instanceof OGCPoint) { return true; } if (!(geometry instanceof OGCPolygon)) { return false; } OGCPolygon polygon = (OGCPolygon) geometry; if (polygon.numInteriorRing() > 0) { return false; } MultiVertexGeometry multiVertexGeometry = (MultiVertexGeometry) polygon.getEsriGeometry(); if (multiVertexGeometry.getPointCount() != 4) { return false; } Set<Point> corners = new HashSet<>(); corners.add(new Point(envelope.getXMin(), envelope.getYMin())); corners.add(new Point(envelope.getXMin(), envelope.getYMax())); corners.add(new Point(envelope.getXMax(), envelope.getYMin())); corners.add(new Point(envelope.getXMax(), envelope.getYMax())); for (int i = 0; i < 4; i++) { Point point = multiVertexGeometry.getPoint(i); if (!corners.contains(point)) { return false; } } return true; } private static void checkZoomLevel(long zoomLevel) { checkCondition(zoomLevel > 0, ZOOM_LEVEL_TOO_SMALL); checkCondition(zoomLevel <= MAX_ZOOM_LEVEL, ZOOM_LEVEL_TOO_LARGE); } private static void checkCoordinate(long coordinate, long zoomLevel) { checkCondition(coordinate >= 0 && coordinate < (1 << zoomLevel), "XY coordinates for a Bing tile at zoom level %s must be within [0, %s) range", zoomLevel, 1 << zoomLevel); } private static void checkQuadKey(@SqlType(StandardTypes.VARCHAR) Slice quadkey) { checkCondition(quadkey.length() > 0, QUAD_KEY_EMPTY); checkCondition(quadkey.length() <= MAX_ZOOM_LEVEL, QUAD_KEY_TOO_LONG); } private static void checkLatitude(double latitude, String errorMessage) { checkCondition(latitude >= MIN_LATITUDE && latitude <= MAX_LATITUDE, errorMessage); } private static void checkLongitude(double longitude, String errorMessage) { checkCondition(longitude >= MIN_LONGITUDE && longitude <= MAX_LONGITUDE, errorMessage); } private static void checkCondition(boolean condition, String formatString, Object... args) { if (!condition) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format(formatString, args)); } } private static double clip(double n, double minValue, double maxValue) { return Math.min(Math.max(n, minValue), maxValue); } private static int mapSize(int zoomLevel) { return 256 << zoomLevel; } }
Fix potential overflow in Bing tile functions Both tileCount and the return value of getPointCount() are integers and the multiplication can overflow before it is widened to a long.
presto-geospatial/src/main/java/com/facebook/presto/geospatial/BingTileFunctions.java
Fix potential overflow in Bing tile functions
<ide><path>resto-geospatial/src/main/java/com/facebook/presto/geospatial/BingTileFunctions.java <ide> checkCondition(tileCount <= 1_000_000, "The number of input tiles is too large (more than 1M) to compute a set of covering bing tiles."); <ide> } <ide> else { <del> long complexity = tileCount * getPointCount(geometry.getEsriGeometry()); <add> long complexity = ((long) tileCount) * getPointCount(geometry.getEsriGeometry()); <ide> checkCondition(complexity <= 25_000_000, "The zoom level is too high or the geometry is too complex to compute a set of covering bing tiles. " + <ide> "Please use a lower zoom level or convert the geometry to its bounding box using the ST_Envelope function."); <ide> }
Java
apache-2.0
error: pathspec 'src/main/java/es/usc/citius/lab/hipster/function/impl/ScalarOperation.java' did not match any file(s) known to git
2af12c9a506e5d74043128b0ecb8a67a2a700531
1
pablormier/hipster,kigsmtua/hipster,Navaneethsen/hipster,Navaneethsen/hipster,artfullyContrived/hipster,Navaneethsen/hipster,artfullyContrived/hipster,citiususc/hipster,caidongyun/hipster,caidongyun/hipster,pablormier/hipster,caidongyun/hipster,pablormier/hipster,kigsmtua/hipster,gabizekany/hipster,nkhuyu/hipster,gabizekany/hipster,citiususc/hipster,gabizekany/hipster,artfullyContrived/hipster,citiususc/hipster,kigsmtua/hipster,nkhuyu/hipster,nkhuyu/hipster
package es.usc.citius.lab.hipster.function.impl; import es.usc.citius.lab.hipster.function.ScalarFunction; /** * A scalar operation is an implementation of {@link ScalarFunction} that * also defines: * <ul> * <li>identity element (A*i = A)</li> * </ul> * * @author Adrián González <[email protected]> * * @param <E> operator class */ public class ScalarOperation<E extends Comparable<E>> implements ScalarFunction<E> { private double identityElem; private ScalarFunction<E> op; /** * Unique constructor for {@link ScalarOperation}, that takes the {@link ScalarFunction} * applied and the identity element. * * @param operation * @param identityElem */ public ScalarOperation(ScalarFunction<E> operation, double identityElem) { this.identityElem = identityElem; this.op = operation; } @Override public E scale(E a, double b) { return this.op.scale(a, b); } public double getIdentityElem() { return identityElem; } /** * Builds the scaling operation for Doubles, that is the multiplying * operation for the factor. * * @return {@link ScalarOperation} for Double */ public static ScalarOperation<Double> doubleMultiplicationOp() { return new ScalarOperation<Double>(new ScalarFunction<Double>() { @Override public Double scale(Double a, double b) { return a * b; } }, 1d); } }
src/main/java/es/usc/citius/lab/hipster/function/impl/ScalarOperation.java
Added ScalarOperation
src/main/java/es/usc/citius/lab/hipster/function/impl/ScalarOperation.java
Added ScalarOperation
<ide><path>rc/main/java/es/usc/citius/lab/hipster/function/impl/ScalarOperation.java <add>package es.usc.citius.lab.hipster.function.impl; <add> <add>import es.usc.citius.lab.hipster.function.ScalarFunction; <add> <add>/** <add> * A scalar operation is an implementation of {@link ScalarFunction} that <add> * also defines: <add> * <ul> <add> * <li>identity element (A*i = A)</li> <add> * </ul> <add> * <add> * @author Adrián González <[email protected]> <add> * <add> * @param <E> operator class <add> */ <add>public class ScalarOperation<E extends Comparable<E>> implements ScalarFunction<E> { <add> <add> private double identityElem; <add> private ScalarFunction<E> op; <add> <add> /** <add> * Unique constructor for {@link ScalarOperation}, that takes the {@link ScalarFunction} <add> * applied and the identity element. <add> * <add> * @param operation <add> * @param identityElem <add> */ <add> public ScalarOperation(ScalarFunction<E> operation, double identityElem) { <add> this.identityElem = identityElem; <add> this.op = operation; <add> } <add> <add> @Override <add> public E scale(E a, double b) { <add> return this.op.scale(a, b); <add> } <add> <add> public double getIdentityElem() { <add> return identityElem; <add> } <add> <add> /** <add> * Builds the scaling operation for Doubles, that is the multiplying <add> * operation for the factor. <add> * <add> * @return {@link ScalarOperation} for Double <add> */ <add> public static ScalarOperation<Double> doubleMultiplicationOp() { <add> return new ScalarOperation<Double>(new ScalarFunction<Double>() { <add> <add> @Override <add> public Double scale(Double a, double b) { <add> return a * b; <add> } <add> <add> }, 1d); <add> } <add> <add>}
JavaScript
agpl-3.0
680c0fda09c8d6a9d091b4a9c5f74f15166d64df
0
schuel/hmmm,schuel/hmmm,schuel/hmmm,Openki/Openki,digideskio/hmmm,Openki/Openki,digideskio/hmmm,Openki/Openki,digideskio/hmmm
////////////// loading-indicator Meteor.startup(function () { Session.setDefault('coursesLoaded', false); var region = localStorage.getItem("region") if (!region) region = 'all'; Session.set("region", region); }); ////////////// db-subscriptions: Meteor.subscribe('categories'); Meteor.subscribe('comments'); Meteor.subscribe('discussions'); Meteor.subscribe('locations'); Meteor.subscribe('messages'); Meteor.subscribe('regions'); Meteor.subscribe('roles'); Meteor.subscribe('votings'); Meteor.subscribe('currentUser'); // close any verification dialogs still open Router.onBeforeAction(function() { Session.set('verify', false); this.next(); }); // Use browser language for date formatting Deps.autorun(function() { var desiredLocale = Session.get('locale'); var setLocale = moment.locale(desiredLocale); Session.set('timeLocale', setLocale); if (desiredLocale !== setLocale) console.log("Date formatting set to "+setLocale+" because "+desiredLocale+" not available"); }); // Set up a reactive date sources that can be used for updates based on time function setTimes() { var now = moment(); Session.set('coarseTime', ''+moment().startOf('hour').toDate()); Session.set('fineTime', ''+moment().startOf('minute').toDate()); } setTimes(); // Update interval of five seconds is okay Meteor.setInterval(setTimes, 1000*5);
client/main.js
////////////// loading-indicator Meteor.startup(function () { Session.setDefault('coursesLoaded', false); var region = localStorage.getItem("region") if (!region) region = 'all'; Session.set("region", region); }); ////////////// db-subscriptions: Meteor.subscribe('categories'); Meteor.subscribe('comments'); Meteor.subscribe('discussions'); Meteor.subscribe('locations'); Meteor.subscribe('messages'); Meteor.subscribe('regions'); Meteor.subscribe('roles'); Meteor.subscribe('votings'); Meteor.subscribe('currentUser'); // close any verification dialogs still open Router.onBeforeAction(function() { Session.set('verify', false); this.next(); }); // Use browser language for date formatting Deps.autorun(function() { var desiredLocale = Session.get('locale'); var setLocale = moment.locale(desiredLocale); Session.set('timeLocale', setLocale); if (desiredLocale !== setLocale) console.log("Date formatting set to "+setLocale+" because "+desiredLocale+" not available"); }); // Set up a reactive date sources that can be used for updates based on time function setTimes() { var now = moment(); Session.set('coarseTime', ''+moment().startOf('hour').toDate()); Session.set('fineTime', ''+moment().startOf('minute').toDate()); } setTimes(); // Update interval of five seconds is okay Meteor.setInterval(setTimes, 1000*5);
whitespace
client/main.js
whitespace
<ide><path>lient/main.js <ide> <ide> ////////////// loading-indicator <ide> Meteor.startup(function () { <del> Session.setDefault('coursesLoaded', false); <del> var region = localStorage.getItem("region") <del> if (!region) region = 'all'; <del> Session.set("region", region); <add> Session.setDefault('coursesLoaded', false); <add> var region = localStorage.getItem("region") <add> if (!region) region = 'all'; <add> Session.set("region", region); <ide> }); <ide> <ide>
Java
apache-2.0
81e2cadc4f677e0b312bf87258378c530e4942d1
0
google/j2cl,google/j2cl,google/j2cl,google/j2cl,google/j2cl
/* * Copyright 2015 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.j2cl.transpiler.frontend.jdt; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.ImmutableList.toImmutableList; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.j2cl.common.InternalCompilerError; import com.google.j2cl.common.SourcePosition; import com.google.j2cl.transpiler.ast.ArrayLength; import com.google.j2cl.transpiler.ast.ArrayTypeDescriptor; import com.google.j2cl.transpiler.ast.BinaryOperator; import com.google.j2cl.transpiler.ast.DeclaredTypeDescriptor; import com.google.j2cl.transpiler.ast.Expression; import com.google.j2cl.transpiler.ast.FieldAccess; import com.google.j2cl.transpiler.ast.FieldDescriptor; import com.google.j2cl.transpiler.ast.IntersectionTypeDescriptor; import com.google.j2cl.transpiler.ast.JsEnumInfo; import com.google.j2cl.transpiler.ast.JsInfo; import com.google.j2cl.transpiler.ast.JsMemberType; import com.google.j2cl.transpiler.ast.Kind; import com.google.j2cl.transpiler.ast.MethodDescriptor; import com.google.j2cl.transpiler.ast.MethodDescriptor.ParameterDescriptor; import com.google.j2cl.transpiler.ast.PostfixOperator; import com.google.j2cl.transpiler.ast.PrefixOperator; import com.google.j2cl.transpiler.ast.PrimitiveTypeDescriptor; import com.google.j2cl.transpiler.ast.PrimitiveTypes; import com.google.j2cl.transpiler.ast.TypeDeclaration; import com.google.j2cl.transpiler.ast.TypeDescriptor; import com.google.j2cl.transpiler.ast.TypeDescriptors; import com.google.j2cl.transpiler.ast.TypeVariable; import com.google.j2cl.transpiler.ast.Variable; import com.google.j2cl.transpiler.ast.Visibility; import com.google.j2cl.transpiler.frontend.common.PackageInfoCache; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Queue; import java.util.Set; import java.util.function.Supplier; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.Assignment; import org.eclipse.jdt.core.dom.BodyDeclaration; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.IAnnotationBinding; import org.eclipse.jdt.core.dom.IBinding; import org.eclipse.jdt.core.dom.IMethodBinding; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.IVariableBinding; import org.eclipse.jdt.core.dom.InfixExpression; import org.eclipse.jdt.core.dom.Modifier; import org.eclipse.jdt.core.dom.PostfixExpression; import org.eclipse.jdt.core.dom.PrefixExpression; /** Utility functions to manipulate JDT internal representations. */ class JdtUtils { // JdtUtil members are all package private. Code outside frontend should not be aware of the // dependency on JDT. public static String getCompilationUnitPackageName(CompilationUnit compilationUnit) { return compilationUnit.getPackage() == null ? "" : compilationUnit.getPackage().getName().getFullyQualifiedName(); } public static FieldDescriptor createFieldDescriptor(IVariableBinding variableBinding) { checkArgument(!isArrayLengthBinding(variableBinding)); boolean isStatic = isStatic(variableBinding); Visibility visibility = getVisibility(variableBinding); DeclaredTypeDescriptor enclosingTypeDescriptor = createDeclaredTypeDescriptor(variableBinding.getDeclaringClass()); String fieldName = variableBinding.getName(); TypeDescriptor thisTypeDescriptor = createTypeDescriptorWithNullability( variableBinding.getType(), variableBinding.getAnnotations()); if (variableBinding.isEnumConstant()) { // Enum fields are always non-nullable. thisTypeDescriptor = thisTypeDescriptor.toNonNullable(); } FieldDescriptor declarationFieldDescriptor = null; if (variableBinding.getVariableDeclaration() != variableBinding) { declarationFieldDescriptor = createFieldDescriptor(variableBinding.getVariableDeclaration()); } JsInfo jsInfo = JsInteropUtils.getJsInfo(variableBinding); boolean isCompileTimeConstant = variableBinding.getConstantValue() != null; boolean isFinal = JdtUtils.isFinal(variableBinding); return FieldDescriptor.newBuilder() .setEnclosingTypeDescriptor(enclosingTypeDescriptor) .setName(fieldName) .setTypeDescriptor(thisTypeDescriptor) .setStatic(isStatic) .setVisibility(visibility) .setJsInfo(jsInfo) .setFinal(isFinal) .setCompileTimeConstant(isCompileTimeConstant) .setDeclarationDescriptor(declarationFieldDescriptor) .setEnumConstant(variableBinding.isEnumConstant()) .setUnusableByJsSuppressed( JsInteropAnnotationUtils.isUnusableByJsSuppressed(variableBinding)) .setDeprecated(isDeprecated(variableBinding)) .build(); } public static Variable createVariable( SourcePosition sourcePosition, IVariableBinding variableBinding) { String name = variableBinding.getName(); TypeDescriptor typeDescriptor = variableBinding.isParameter() ? createTypeDescriptorWithNullability( variableBinding.getType(), variableBinding.getAnnotations()) : createTypeDescriptor(variableBinding.getType()); boolean isFinal = variableBinding.isEffectivelyFinal(); boolean isParameter = variableBinding.isParameter(); boolean isUnusableByJsSuppressed = JsInteropAnnotationUtils.isUnusableByJsSuppressed(variableBinding); return Variable.newBuilder() .setName(name) .setTypeDescriptor(typeDescriptor) .setFinal(isFinal) .setParameter(isParameter) .setUnusableByJsSuppressed(isUnusableByJsSuppressed) .setSourcePosition(sourcePosition) .build(); } public static BinaryOperator getBinaryOperator(InfixExpression.Operator operator) { switch (operator.toString()) { case "*": return BinaryOperator.TIMES; case "/": return BinaryOperator.DIVIDE; case "%": return BinaryOperator.REMAINDER; case "+": return BinaryOperator.PLUS; case "-": return BinaryOperator.MINUS; case "<<": return BinaryOperator.LEFT_SHIFT; case ">>": return BinaryOperator.RIGHT_SHIFT_SIGNED; case ">>>": return BinaryOperator.RIGHT_SHIFT_UNSIGNED; case "<": return BinaryOperator.LESS; case ">": return BinaryOperator.GREATER; case "<=": return BinaryOperator.LESS_EQUALS; case ">=": return BinaryOperator.GREATER_EQUALS; case "==": return BinaryOperator.EQUALS; case "!=": return BinaryOperator.NOT_EQUALS; case "^": return BinaryOperator.BIT_XOR; case "&": return BinaryOperator.BIT_AND; case "|": return BinaryOperator.BIT_OR; case "&&": return BinaryOperator.CONDITIONAL_AND; case "||": return BinaryOperator.CONDITIONAL_OR; default: return null; } } public static BinaryOperator getBinaryOperator(Assignment.Operator operator) { switch (operator.toString()) { case "=": return BinaryOperator.ASSIGN; case "+=": return BinaryOperator.PLUS_ASSIGN; case "-=": return BinaryOperator.MINUS_ASSIGN; case "*=": return BinaryOperator.TIMES_ASSIGN; case "/=": return BinaryOperator.DIVIDE_ASSIGN; case "&=": return BinaryOperator.BIT_AND_ASSIGN; case "|=": return BinaryOperator.BIT_OR_ASSIGN; case "^=": return BinaryOperator.BIT_XOR_ASSIGN; case "%=": return BinaryOperator.REMAINDER_ASSIGN; case "<<=": return BinaryOperator.LEFT_SHIFT_ASSIGN; case ">>=": return BinaryOperator.RIGHT_SHIFT_SIGNED_ASSIGN; case ">>>=": return BinaryOperator.RIGHT_SHIFT_UNSIGNED_ASSIGN; default: return null; } } public static IMethodBinding getMethodBinding( ITypeBinding typeBinding, String methodName, ITypeBinding... parameterTypes) { Queue<ITypeBinding> deque = new ArrayDeque<>(); deque.add(typeBinding); while (!deque.isEmpty()) { typeBinding = deque.poll(); for (IMethodBinding methodBinding : typeBinding.getDeclaredMethods()) { if (methodBinding.getName().equals(methodName) && Arrays.equals(methodBinding.getParameterTypes(), parameterTypes)) { return methodBinding; } } ITypeBinding superclass = typeBinding.getSuperclass(); if (superclass != null) { deque.add(superclass); } ITypeBinding[] superInterfaces = typeBinding.getInterfaces(); if (superInterfaces != null) { for (ITypeBinding superInterface : superInterfaces) { deque.add(superInterface); } } } return null; } public static PrefixOperator getPrefixOperator(PrefixExpression.Operator operator) { switch (operator.toString()) { case "++": return PrefixOperator.INCREMENT; case "--": return PrefixOperator.DECREMENT; case "+": return PrefixOperator.PLUS; case "-": return PrefixOperator.MINUS; case "~": return PrefixOperator.COMPLEMENT; case "!": return PrefixOperator.NOT; default: return null; } } public static PostfixOperator getPostfixOperator(PostfixExpression.Operator operator) { switch (operator.toString()) { case "++": return PostfixOperator.INCREMENT; case "--": return PostfixOperator.DECREMENT; default: return null; } } public static Expression createFieldAccess(Expression qualifier, IVariableBinding fieldBinding) { if (isArrayLengthBinding(fieldBinding)) { return ArrayLength.newBuilder().setArrayExpression(qualifier).build(); } return FieldAccess.Builder.from(JdtUtils.createFieldDescriptor(fieldBinding)) .setQualifier(qualifier) .build(); } private static boolean isArrayLengthBinding(IVariableBinding variableBinding) { return variableBinding.getName().equals("length") && variableBinding.isField() && variableBinding.getDeclaringClass() == null; } /** Returns true if the binding is annotated with @UncheckedCast. */ public static boolean hasUncheckedCastAnnotation(IBinding binding) { return JdtAnnotationUtils.hasAnnotation(binding, "javaemul.internal.annotations.UncheckedCast"); } /** Helper method to work around JDT habit of returning raw collections. */ @SuppressWarnings("rawtypes") public static <T> List<T> asTypedList(List jdtRawCollection) { @SuppressWarnings("unchecked") List<T> typedList = jdtRawCollection; return typedList; } /** Creates a DeclaredTypeDescriptor from a JDT TypeBinding. */ public static DeclaredTypeDescriptor createDeclaredTypeDescriptor(ITypeBinding typeBinding) { return createTypeDescriptor(typeBinding, DeclaredTypeDescriptor.class); } /** Creates a DeclaredTypeDescriptor from a JDT TypeBinding. */ private static <T extends TypeDescriptor> T createTypeDescriptor( ITypeBinding typeBinding, Class<T> clazz) { return clazz.cast(createTypeDescriptor(typeBinding)); } /** Creates a TypeDescriptor from a JDT TypeBinding. */ public static TypeDescriptor createTypeDescriptor(ITypeBinding typeBinding) { return createTypeDescriptorWithNullability(typeBinding, new IAnnotationBinding[0]); } /** Creates a type descriptor for the given type binding, taking into account nullability. */ private static TypeDescriptor createTypeDescriptorWithNullability( ITypeBinding typeBinding, IAnnotationBinding[] elementAnnotations) { if (typeBinding == null) { return null; } if (typeBinding.isPrimitive()) { return PrimitiveTypes.get(typeBinding.getName()); } if (isIntersectionType(typeBinding)) { return createIntersectionType(typeBinding); } if (typeBinding.isNullType()) { return TypeDescriptors.get().javaLangObject; } if (typeBinding.isTypeVariable() || typeBinding.isCapture() || typeBinding.isWildcardType()) { return createTypeVariable(typeBinding); } boolean isNullable = isNullable(typeBinding, elementAnnotations); if (typeBinding.isArray()) { TypeDescriptor componentTypeDescriptor = createTypeDescriptor(typeBinding.getComponentType()); return ArrayTypeDescriptor.newBuilder() .setComponentTypeDescriptor(componentTypeDescriptor) .setNullable(isNullable) .build(); } return withNullability(createDeclaredType(typeBinding), isNullable); } private static TypeDescriptor createTypeVariable(ITypeBinding typeBinding) { Supplier<TypeDescriptor> boundTypeDescriptorFactory = () -> getTypeBound(typeBinding); return TypeVariable.newBuilder() .setBoundTypeDescriptorSupplier(boundTypeDescriptorFactory) .setWildcardOrCapture(typeBinding.isWildcardType() || typeBinding.isCapture()) .setUniqueKey(typeBinding.getKey()) .setName(typeBinding.getName()) .build(); } private static TypeDescriptor getTypeBound(ITypeBinding typeBinding) { ITypeBinding[] bounds = typeBinding.getTypeBounds(); if (bounds == null || bounds.length == 0) { return TypeDescriptors.get().javaLangObject; } if (bounds.length == 1) { return createTypeDescriptor(bounds[0]); } return createIntersectionType(typeBinding); } private static DeclaredTypeDescriptor withNullability( DeclaredTypeDescriptor typeDescriptor, boolean nullable) { return nullable ? typeDescriptor.toNullable() : typeDescriptor.toNonNullable(); } /** * Returns whether the given type binding should be nullable, according to the annotations on it * and if nullability is enabled for the package containing the binding. */ private static boolean isNullable( ITypeBinding typeBinding, IAnnotationBinding[] elementAnnotations) { checkArgument(!typeBinding.isPrimitive()); if (typeBinding.getQualifiedName().equals("java.lang.Void")) { // Void is always nullable. return true; } if (JsInteropAnnotationUtils.hasJsNonNullAnnotation(typeBinding)) { return false; } // TODO(b/70164536): Deprecate non J2CL-specific nullability annotations. Iterable<IAnnotationBinding> allAnnotations = Iterables.concat( Arrays.asList(elementAnnotations), Arrays.asList(typeBinding.getTypeAnnotations()), Arrays.asList(typeBinding.getAnnotations())); for (IAnnotationBinding annotation : allAnnotations) { String annotationName = annotation.getName(); if (annotationName.equalsIgnoreCase("Nonnull")) { return false; } } return true; } /** * In case the given type binding is nested, return the outermost possible enclosing type binding. */ private static ITypeBinding toTopLevelTypeBinding(ITypeBinding typeBinding) { ITypeBinding topLevelClass = typeBinding; while (topLevelClass.getDeclaringClass() != null) { topLevelClass = topLevelClass.getDeclaringClass(); } return topLevelClass; } private static boolean isIntersectionType(ITypeBinding binding) { return binding.isIntersectionType() // JDT returns true for isIntersectionType() for type variables, wildcards and captures // with intersection type bounds. && !binding.isCapture() && !binding.isTypeVariable() && !binding.isWildcardType(); } private static List<String> getClassComponents(ITypeBinding typeBinding) { List<String> classComponents = new ArrayList<>(); ITypeBinding currentType = typeBinding; while (currentType != null) { checkArgument(currentType.getTypeDeclaration() != null); if (currentType.isLocal()) { // JDT binary name for local class is like package.components.EnclosingClass$1SimpleName // Extract the generated name by taking the part after the binary name of the declaring // class. String binaryName = getBinaryNameFromTypeBinding(currentType); String declaringClassPrefix = getBinaryNameFromTypeBinding(currentType.getDeclaringClass()) + "$"; checkState(binaryName.startsWith(declaringClassPrefix)); classComponents.add(0, binaryName.substring(declaringClassPrefix.length())); } else { classComponents.add(0, currentType.getName()); } currentType = currentType.getDeclaringClass(); } return classComponents; } /** * Returns the binary name for a type binding. * * <p>NOTE: This accounts for the cases that JDT does not assign binary names, which are those of * unreachable local or anonymous classes. */ private static String getBinaryNameFromTypeBinding(ITypeBinding typeBinding) { String binaryName = typeBinding.getBinaryName(); if (binaryName == null && (typeBinding.isLocal() || typeBinding.isAnonymous())) { // Local and anonymous classes in unreachable code have null binary name. // The code here is a HACK that relies on the way that JDT synthesizes keys. Keys for // unreachable classes have the closest enclosing reachable class key as a prefix (minus the // ending semicolon) ITypeBinding closestReachableExclosingClass = typeBinding.getDeclaringClass(); while (closestReachableExclosingClass.getBinaryName() == null) { closestReachableExclosingClass = closestReachableExclosingClass.getDeclaringClass(); } String parentKey = closestReachableExclosingClass.getKey(); String key = typeBinding.getKey(); return getBinaryNameFromTypeBinding(typeBinding.getDeclaringClass()) + "$$Unreachable" // remove the parent prefix and the ending semicolon + key.substring(parentKey.length() - 1, key.length() - 1); } return binaryName; } private static List<TypeDescriptor> getTypeArgumentTypeDescriptors(ITypeBinding typeBinding) { return getTypeArgumentTypeDescriptors(typeBinding, TypeDescriptor.class); } private static <T extends TypeDescriptor> List<T> getTypeArgumentTypeDescriptors( ITypeBinding typeBinding, Class<T> clazz) { ImmutableList.Builder<T> typeArgumentDescriptorsBuilder = ImmutableList.builder(); if (typeBinding.isParameterizedType()) { typeArgumentDescriptorsBuilder.addAll( createTypeDescriptors(typeBinding.getTypeArguments(), clazz)); } else { typeArgumentDescriptorsBuilder.addAll( createTypeDescriptors(typeBinding.getTypeParameters(), clazz)); } // DO NOT USE getDeclaringMethod(). getDeclaringMethod() returns a synthetic static method // in the declaring class, instead of the proper lambda method with the declaring method // enclosing it when the declaration is inside a lambda. If the declaring method declares a // type variable, it would get lost. IBinding declarationBinding = getDeclaringMethodOrFieldBinding(typeBinding); if (declarationBinding instanceof IMethodBinding) { typeArgumentDescriptorsBuilder.addAll( createTypeDescriptors(((IMethodBinding) declarationBinding).getTypeParameters(), clazz)); } if (capturesEnclosingInstance(typeBinding.getTypeDeclaration())) { // Find type parameters in the enclosing scope and copy them over as well. createDeclaredTypeDescriptor(typeBinding.getDeclaringClass()) .getTypeArgumentDescriptors() .stream() .map(clazz::cast) .forEach(typeArgumentDescriptorsBuilder::add); } return typeArgumentDescriptorsBuilder.build(); } public static Visibility getVisibility(IBinding binding) { return getVisibility(binding.getModifiers()); } private static Visibility getVisibility(int modifiers) { if (Modifier.isPublic(modifiers)) { return Visibility.PUBLIC; } else if (Modifier.isProtected(modifiers)) { return Visibility.PROTECTED; } else if (Modifier.isPrivate(modifiers)) { return Visibility.PRIVATE; } else { return Visibility.PACKAGE_PRIVATE; } } private static boolean isDeprecated(IBinding binding) { return JdtAnnotationUtils.hasAnnotation(binding, Deprecated.class.getName()); } private static boolean isDefaultMethod(IMethodBinding binding) { return Modifier.isDefault(binding.getModifiers()); } private static boolean isAbstract(IBinding binding) { return Modifier.isAbstract(binding.getModifiers()); } private static boolean isFinal(IBinding binding) { return Modifier.isFinal(binding.getModifiers()); } public static boolean isStatic(IBinding binding) { if (binding instanceof IVariableBinding) { IVariableBinding variableBinding = (IVariableBinding) binding; if (!variableBinding.isField() || variableBinding.getDeclaringClass().isInterface()) { // Interface fields and variables are implicitly static. return true; } } return Modifier.isStatic(binding.getModifiers()); } public static boolean isStatic(BodyDeclaration bodyDeclaration) { return Modifier.isStatic(bodyDeclaration.getModifiers()); } private static boolean isEnumSyntheticMethod(IMethodBinding methodBinding) { // Enum synthetic methods are not marked as such because per JLS 13.1 these methods are // implicitly declared but are not marked as synthetic. return methodBinding.getDeclaringClass().isEnum() && (isEnumValuesMethod(methodBinding) || isEnumValueOfMethod(methodBinding)); } private static boolean isEnumValuesMethod(IMethodBinding methodBinding) { return methodBinding.getName().equals("values") && methodBinding.getParameterTypes().length == 0; } private static boolean isEnumValueOfMethod(IMethodBinding methodBinding) { return methodBinding.getName().equals("valueOf") && methodBinding.getParameterTypes().length == 1 && methodBinding.getParameterTypes()[0].getQualifiedName().equals("java.lang.String"); } /** * Returns true if instances of this type capture its outer instances; i.e. if it is an non static * member class, or an anonymous or local class defined in an instance context. */ public static boolean capturesEnclosingInstance(ITypeBinding typeBinding) { if (!typeBinding.isClass() || !typeBinding.isNested()) { // Only non-top level classes (excludes Enums, Interfaces etc.) can capture outer instances. return false; } if (typeBinding.isLocal()) { // Local types (which include anonymous classes in JDT) are static only if they are declared // in a static context; i.e. if the member where they are declared is static. return !isStatic(getDeclaringMethodOrFieldBinding(typeBinding)); } else { checkArgument(typeBinding.isMember()); // Member classes must be marked explicitly static. return !isStatic(typeBinding); } } /** * Returns the declaring member binding if any, skipping lambdas which are returned by JDT as * declaring members but are not. */ private static IBinding getDeclaringMethodOrFieldBinding(ITypeBinding typeBinding) { IBinding declarationBinding = getDeclaringMember(typeBinding); // Skip all lambda method bindings. while (isLambdaBinding(declarationBinding)) { declarationBinding = ((IMethodBinding) declarationBinding).getDeclaringMember(); } return declarationBinding; } private static IBinding getDeclaringMember(ITypeBinding typeBinding) { ITypeBinding typeDeclaration = typeBinding.getTypeDeclaration(); IBinding declaringMember = typeDeclaration.getDeclaringMember(); if (declaringMember == null) { // Work around for b/147690014, in which getDeclaringMember returns null, but there is // a declaring member and is returned by getDeclaringMethod. declaringMember = typeDeclaration.getDeclaringMethod(); } return declaringMember; } private static boolean isLambdaBinding(IBinding binding) { return binding instanceof IMethodBinding && ((IMethodBinding) binding).getDeclaringMember() != null; } /** Create a MethodDescriptor directly based on the given JDT method binding. */ public static MethodDescriptor createMethodDescriptor(IMethodBinding methodBinding) { if (methodBinding == null) { return null; } DeclaredTypeDescriptor enclosingTypeDescriptor = createDeclaredTypeDescriptor(methodBinding.getDeclaringClass()); boolean isStatic = isStatic(methodBinding); Visibility visibility = getVisibility(methodBinding); boolean isDefault = isDefaultMethod(methodBinding); JsInfo jsInfo = computeJsInfo(methodBinding); boolean isNative = Modifier.isNative(methodBinding.getModifiers()) || (!jsInfo.isJsOverlay() && enclosingTypeDescriptor.isNative() && isAbstract(methodBinding)); boolean isConstructor = methodBinding.isConstructor(); String methodName = methodBinding.getName(); TypeDescriptor returnTypeDescriptor = createTypeDescriptorWithNullability( methodBinding.getReturnType(), methodBinding.getAnnotations()); MethodDescriptor declarationMethodDescriptor = null; if (methodBinding.getMethodDeclaration() != methodBinding) { // The declaration for methods in a lambda binding is two hops away. Since the declaration // binding of a declaration is itself, we get the declaration of the declaration here. IMethodBinding declarationBinding = methodBinding.getMethodDeclaration().getMethodDeclaration(); declarationMethodDescriptor = createMethodDescriptor(declarationBinding); } // generate type parameters declared in the method. Iterable<TypeVariable> typeParameterTypeDescriptors = FluentIterable.from(methodBinding.getTypeParameters()) .transform(JdtUtils::createTypeDescriptor) .transform(typeDescriptor -> (TypeVariable) typeDescriptor); ImmutableList.Builder<ParameterDescriptor> parameterDescriptorBuilder = ImmutableList.builder(); for (int i = 0; i < methodBinding.getParameterTypes().length; i++) { parameterDescriptorBuilder.add( ParameterDescriptor.newBuilder() .setTypeDescriptor( createTypeDescriptorWithNullability( methodBinding.getParameterTypes()[i], methodBinding.getParameterAnnotations(i))) .setJsOptional(JsInteropUtils.isJsOptional(methodBinding, i)) .setVarargs( i == methodBinding.getParameterTypes().length - 1 && methodBinding.isVarargs()) .setDoNotAutobox(JsInteropUtils.isDoNotAutobox(methodBinding, i)) .build()); } if (enclosingTypeDescriptor.getTypeDeclaration().isAnonymous() && isConstructor && enclosingTypeDescriptor.getSuperTypeDescriptor().hasJsConstructor()) { jsInfo = JsInfo.Builder.from(jsInfo).setJsMemberType(JsMemberType.CONSTRUCTOR).build(); } boolean hasUncheckedCast = hasUncheckedCastAnnotation(methodBinding); return MethodDescriptor.newBuilder() .setEnclosingTypeDescriptor(enclosingTypeDescriptor) .setName(isConstructor ? null : methodName) .setParameterDescriptors(parameterDescriptorBuilder.build()) .setDeclarationDescriptor(declarationMethodDescriptor) .setReturnTypeDescriptor(returnTypeDescriptor) .setTypeParameterTypeDescriptors(typeParameterTypeDescriptors) .setJsInfo(jsInfo) .setWasmInfo(getWasmInfo(methodBinding)) .setJsFunction(isOrOverridesJsFunctionMethod(methodBinding)) .setVisibility(visibility) .setStatic(isStatic) .setConstructor(isConstructor) .setNative(isNative) .setFinal(JdtUtils.isFinal(methodBinding)) .setDefaultMethod(isDefault) .setAbstract(Modifier.isAbstract(methodBinding.getModifiers())) .setSynthetic(methodBinding.isSynthetic()) .setEnumSyntheticMethod(isEnumSyntheticMethod(methodBinding)) .setUnusableByJsSuppressed(JsInteropAnnotationUtils.isUnusableByJsSuppressed(methodBinding)) .setDeprecated(isDeprecated(methodBinding)) .setUncheckedCast(hasUncheckedCast) .build(); } private static String getWasmInfo(IMethodBinding binding) { return JdtAnnotationUtils.getStringAttribute( JdtAnnotationUtils.findAnnotationBindingByName( binding.getAnnotations(), "javaemul.internal.annotations.Wasm"), "value"); } private static boolean isOrOverridesJsFunctionMethod(IMethodBinding methodBinding) { ITypeBinding declaringType = methodBinding.getDeclaringClass(); if (JsInteropUtils.isJsFunction(declaringType) && declaringType.getFunctionalInterfaceMethod() != null && methodBinding.getMethodDeclaration() == declaringType.getFunctionalInterfaceMethod().getMethodDeclaration()) { return true; } for (IMethodBinding overriddenMethodBinding : getOverriddenMethods(methodBinding)) { if (isOrOverridesJsFunctionMethod(overriddenMethodBinding)) { return true; } } return false; } /** Checks overriding chain to compute JsInfo. */ private static JsInfo computeJsInfo(IMethodBinding methodBinding) { JsInfo originalJsInfo = JsInteropUtils.getJsInfo(methodBinding); if (originalJsInfo.isJsOverlay() || originalJsInfo.getJsName() != null || originalJsInfo.getJsNamespace() != null) { // Do not examine overridden methods if the method is marked as JsOverlay or it has a JsMember // annotation that customizes the name. return originalJsInfo; } boolean hasExplicitJsMemberAnnotation = hasJsMemberAnnotation(methodBinding); JsInfo defaultJsInfo = originalJsInfo; for (IMethodBinding overriddenMethod : getOverriddenMethods(methodBinding)) { JsInfo inheritedJsInfo = JsInteropUtils.getJsInfo(overriddenMethod); if (inheritedJsInfo.getJsMemberType() == JsMemberType.NONE) { continue; } if (hasExplicitJsMemberAnnotation && originalJsInfo.getJsMemberType() != inheritedJsInfo.getJsMemberType()) { // Only inherit from the overridden method if the JsMember types are consistent. continue; } if (inheritedJsInfo.getJsName() != null) { // Found an overridden method of the same JsMember type one that customizes the name, done. // If there are any conflicts with other overrides they will be reported by // JsInteropRestrictionsChecker. return JsInfo.Builder.from(inheritedJsInfo).setJsAsync(originalJsInfo.isJsAsync()).build(); } if (defaultJsInfo == originalJsInfo && !hasExplicitJsMemberAnnotation) { // The original method does not have a JsMember annotation and traversing the list of // overridden methods we found the first that has an explicit JsMember annotation. // Keep it as the one to be used if none is found that customizes the name. // This allows to "inherit" the JsMember type from the override. defaultJsInfo = inheritedJsInfo; } } // Don't inherit @JsAsync annotation from overridden methods. return JsInfo.Builder.from(defaultJsInfo).setJsAsync(originalJsInfo.isJsAsync()).build(); } private static boolean hasJsMemberAnnotation(IMethodBinding methodBinding) { return JsInteropAnnotationUtils.getJsMethodAnnotation(methodBinding) != null || JsInteropAnnotationUtils.getJsPropertyAnnotation(methodBinding) != null || JsInteropAnnotationUtils.getJsConstructorAnnotation(methodBinding) != null; } public static Set<IMethodBinding> getOverriddenMethods(IMethodBinding methodBinding) { return getOverriddenMethodsInType(methodBinding, methodBinding.getDeclaringClass()); } private static Set<IMethodBinding> getOverriddenMethodsInType( IMethodBinding methodBinding, ITypeBinding typeBinding) { Set<IMethodBinding> overriddenMethods = new HashSet<>(); for (IMethodBinding declaredMethod : typeBinding.getDeclaredMethods()) { if (methodBinding.overrides(declaredMethod) && !methodBinding.isConstructor()) { checkArgument(!Modifier.isStatic(methodBinding.getModifiers())); overriddenMethods.add(declaredMethod); } } // Recurse into immediate super class and interfaces for overridden method. if (typeBinding.getSuperclass() != null) { overriddenMethods.addAll( getOverriddenMethodsInType(methodBinding, typeBinding.getSuperclass())); } for (ITypeBinding interfaceBinding : typeBinding.getInterfaces()) { overriddenMethods.addAll(getOverriddenMethodsInType(methodBinding, interfaceBinding)); } ITypeBinding javaLangObjectTypeBinding = JdtUtils.javaLangObjectTypeBinding.get(); if (typeBinding != javaLangObjectTypeBinding) { for (IMethodBinding objectMethodBinding : javaLangObjectTypeBinding.getDeclaredMethods()) { if (!isPolymorphic(objectMethodBinding)) { continue; } checkState(!getVisibility(objectMethodBinding).isPackagePrivate()); if (methodBinding.isSubsignature(objectMethodBinding)) { overriddenMethods.add(objectMethodBinding); } } } return overriddenMethods; } private static boolean isPolymorphic(IMethodBinding methodBinding) { return !methodBinding.isConstructor() && !isStatic(methodBinding) && !Modifier.isPrivate(methodBinding.getModifiers()); } private static boolean isLocal(ITypeBinding typeBinding) { return typeBinding.isLocal(); } /** Returns the MethodDescriptor for the JsFunction method. */ private static MethodDescriptor getJsFunctionMethodDescriptor(ITypeBinding typeBinding) { if (JsInteropUtils.isJsFunction(typeBinding) && typeBinding.getFunctionalInterfaceMethod() != null) { // typeBinding.getFunctionalInterfaceMethod returns in some cases the method declaration // instead of the method with the corresponding parameterization. Note: this is observed in // the case when a type is parameterized with a wildcard, e.g. JsFunction<?>. IMethodBinding jsFunctionMethodBinding = Arrays.stream(typeBinding.getDeclaredMethods()) .filter( methodBinding -> methodBinding.getMethodDeclaration() == typeBinding.getFunctionalInterfaceMethod().getMethodDeclaration()) .findFirst() .get(); return createMethodDescriptor(jsFunctionMethodBinding).withoutTypeParameters(); } // Find implementation method that corresponds to JsFunction. Optional<ITypeBinding> jsFunctionInterface = Arrays.stream(typeBinding.getInterfaces()).filter(JsInteropUtils::isJsFunction).findFirst(); return jsFunctionInterface .map(ITypeBinding::getFunctionalInterfaceMethod) .flatMap(jsFunctionMethod -> getOverrideInType(typeBinding, jsFunctionMethod)) .map(MethodDescriptor::withoutTypeParameters) .orElse(null); } private static Optional<MethodDescriptor> getOverrideInType( ITypeBinding typeBinding, IMethodBinding methodBinding) { return Arrays.stream(typeBinding.getDeclaredMethods()) .filter(m -> m.overrides(methodBinding)) .findFirst() .map(JdtUtils::createMethodDescriptor); } private static <T extends TypeDescriptor> ImmutableList<T> createTypeDescriptors( List<ITypeBinding> typeBindings, Class<T> clazz) { return typeBindings.stream() .map(typeBinding -> createTypeDescriptor(typeBinding, clazz)) .collect(toImmutableList()); } private static <T extends TypeDescriptor> ImmutableList<T> createTypeDescriptors( ITypeBinding[] typeBindings, Class<T> clazz) { return createTypeDescriptors(Arrays.asList(typeBindings), clazz); } private static ThreadLocal<ITypeBinding> javaLangObjectTypeBinding = new ThreadLocal<>(); public static void initWellKnownTypes(AST ast, Iterable<ITypeBinding> typeBindings) { javaLangObjectTypeBinding.set(ast.resolveWellKnownType("java.lang.Object")); if (TypeDescriptors.isInitialized()) { return; } TypeDescriptors.SingletonBuilder builder = new TypeDescriptors.SingletonBuilder(); for (PrimitiveTypeDescriptor typeDescriptor : PrimitiveTypes.TYPES) { addPrimitive(ast, builder, typeDescriptor); } // Add well-known, non-primitive types. for (ITypeBinding typeBinding : typeBindings) { builder.addReferenceType(createDeclaredTypeDescriptor(typeBinding)); } builder.buildSingleton(); } private static void addPrimitive( AST ast, TypeDescriptors.SingletonBuilder builder, PrimitiveTypeDescriptor typeDescriptor) { DeclaredTypeDescriptor boxedType = createDeclaredTypeDescriptor(ast.resolveWellKnownType(typeDescriptor.getBoxedClassName())); builder.addPrimitiveBoxedTypeDescriptorPair(typeDescriptor, boxedType); } private static final TypeDescriptor createIntersectionType(ITypeBinding typeBinding) { List<DeclaredTypeDescriptor> intersectedTypeDescriptors = createTypeDescriptors(typeBinding.getTypeBounds(), DeclaredTypeDescriptor.class); return IntersectionTypeDescriptor.newBuilder() .setIntersectionTypeDescriptors(intersectedTypeDescriptors) .build(); } /** * This cache is a Hashtable so is already synchronized and safe to use from multiple threads. We * don't need a separate cache for each thread (like interners have) since JDT's ITypeBinding * instances (which we are using as keys) are unique per JDT parse. */ @SuppressWarnings("JdkObsolete") private static Map<ITypeBinding, DeclaredTypeDescriptor> cachedDeclaredTypeDescriptorByTypeBinding = new Hashtable<>(); private static DeclaredTypeDescriptor createDeclaredType(final ITypeBinding typeBinding) { if (cachedDeclaredTypeDescriptorByTypeBinding.containsKey(typeBinding)) { return cachedDeclaredTypeDescriptorByTypeBinding.get(typeBinding); } checkArgument(typeBinding.isClass() || typeBinding.isEnum() || typeBinding.isInterface()); Supplier<ImmutableList<MethodDescriptor>> declaredMethods = () -> Arrays.stream(typeBinding.getDeclaredMethods()) .map(JdtUtils::createMethodDescriptor) .collect(toImmutableList()); ; Supplier<ImmutableList<FieldDescriptor>> declaredFields = () -> Arrays.stream(typeBinding.getDeclaredFields()) .map(JdtUtils::createFieldDescriptor) .collect(toImmutableList()); TypeDeclaration typeDeclaration = JdtUtils.createDeclarationForType(typeBinding.getTypeDeclaration()); // Compute these even later DeclaredTypeDescriptor typeDescriptor = DeclaredTypeDescriptor.newBuilder() .setTypeDeclaration(typeDeclaration) .setEnclosingTypeDescriptor( createDeclaredTypeDescriptor(typeBinding.getDeclaringClass())) .setInterfaceTypeDescriptorsFactory( () -> createTypeDescriptors( typeBinding.getInterfaces(), DeclaredTypeDescriptor.class)) .setSingleAbstractMethodDescriptorFactory( () -> createMethodDescriptor(typeBinding.getFunctionalInterfaceMethod())) .setJsFunctionMethodDescriptorFactory(() -> getJsFunctionMethodDescriptor(typeBinding)) .setSuperTypeDescriptorFactory( () -> createDeclaredTypeDescriptor(typeBinding.getSuperclass())) .setTypeArgumentDescriptors(getTypeArgumentTypeDescriptors(typeBinding)) .setDeclaredFieldDescriptorsFactory(declaredFields) .setDeclaredMethodDescriptorsFactory(declaredMethods) .build(); cachedDeclaredTypeDescriptorByTypeBinding.put(typeBinding, typeDescriptor); return typeDescriptor; } private static Kind getKindFromTypeBinding(ITypeBinding typeBinding) { if (typeBinding.isEnum() && !typeBinding.isAnonymous()) { // Do not consider the anonymous classes that constitute enum values as Enums, only the // enum "class" itself is considered Kind.ENUM. return Kind.ENUM; } else if (typeBinding.isClass() || (typeBinding.isEnum() && typeBinding.isAnonymous())) { return Kind.CLASS; } else if (typeBinding.isInterface()) { return Kind.INTERFACE; } throw new InternalCompilerError("Type binding %s not handled", typeBinding); } private static String getJsName(final ITypeBinding typeBinding) { checkArgument(!typeBinding.isPrimitive()); return JsInteropAnnotationUtils.getJsName(typeBinding); } private static String getJsNamespace( ITypeBinding typeBinding, PackageInfoCache packageInfoCache) { checkArgument(!typeBinding.isPrimitive()); String jsNamespace = JsInteropAnnotationUtils.getJsNamespace(typeBinding); if (jsNamespace != null) { return jsNamespace; } // Maybe namespace is set via package-info file? boolean isTopLevelType = typeBinding.getDeclaringClass() == null; if (isTopLevelType) { return packageInfoCache.getJsNamespace( getBinaryNameFromTypeBinding(toTopLevelTypeBinding(typeBinding))); } return null; } public static TypeDeclaration createDeclarationForType(final ITypeBinding typeBinding) { if (typeBinding == null) { return null; } checkArgument(typeBinding.getTypeDeclaration() == typeBinding); checkArgument(!typeBinding.isArray()); checkArgument(!typeBinding.isParameterizedType()); checkArgument(!typeBinding.isTypeVariable()); checkArgument(!typeBinding.isWildcardType()); checkArgument(!typeBinding.isCapture()); PackageInfoCache packageInfoCache = PackageInfoCache.get(); ITypeBinding topLevelTypeBinding = toTopLevelTypeBinding(typeBinding); if (topLevelTypeBinding.isFromSource()) { // Let the PackageInfoCache know that this class is Source, otherwise it would have to rummage // around in the class path to figure it out and it might even come up with the wrong answer // for example if this class has also been globbed into some other library that is a // dependency of this one. PackageInfoCache.get().markAsSource(getBinaryNameFromTypeBinding(topLevelTypeBinding)); } // Compute these first since they're reused in other calculations. String packageName = typeBinding.getPackage() == null ? null : typeBinding.getPackage().getName(); boolean isAbstract = isAbstract(typeBinding); boolean isFinal = isFinal(typeBinding); Supplier<ImmutableList<MethodDescriptor>> declaredMethods = () -> Arrays.stream(typeBinding.getDeclaredMethods()) .map(JdtUtils::createMethodDescriptor) .collect(toImmutableList()); ; Supplier<ImmutableList<FieldDescriptor>> declaredFields = () -> Arrays.stream(typeBinding.getDeclaredFields()) .map(JdtUtils::createFieldDescriptor) .collect(toImmutableList()); JsEnumInfo jsEnumInfo = JsInteropUtils.getJsEnumInfo(typeBinding); return TypeDeclaration.newBuilder() .setClassComponents(getClassComponents(typeBinding)) .setEnclosingTypeDeclaration(createDeclarationForType(typeBinding.getDeclaringClass())) .setInterfaceTypeDescriptorsFactory( () -> createTypeDescriptors(typeBinding.getInterfaces(), DeclaredTypeDescriptor.class)) .setUnparameterizedTypeDescriptorFactory(() -> createDeclaredTypeDescriptor(typeBinding)) .setHasAbstractModifier(isAbstract) .setKind(getKindFromTypeBinding(typeBinding)) .setCapturingEnclosingInstance(capturesEnclosingInstance(typeBinding)) .setFinal(isFinal) .setFunctionalInterface( !typeBinding.isAnnotation() && typeBinding.getFunctionalInterfaceMethod() != null) .setJsFunctionInterface(JsInteropUtils.isJsFunction(typeBinding)) .setAnnotatedWithFunctionalInterface(isAnnotatedWithFunctionalInterface(typeBinding)) .setAnnotatedWithAutoValue(isAnnotatedWithAutoValue(typeBinding)) .setJsType(JsInteropUtils.isJsType(typeBinding)) .setJsEnumInfo(jsEnumInfo) .setNative(JsInteropUtils.isJsNativeType(typeBinding)) .setAnonymous(typeBinding.isAnonymous()) .setLocal(isLocal(typeBinding)) .setSimpleJsName(getJsName(typeBinding)) .setCustomizedJsNamespace(getJsNamespace(typeBinding, packageInfoCache)) .setPackageName(packageName) .setSuperTypeDescriptorFactory( () -> createDeclaredTypeDescriptor(typeBinding.getSuperclass())) .setTypeParameterDescriptors( getTypeArgumentTypeDescriptors(typeBinding, TypeVariable.class)) .setVisibility(getVisibility(typeBinding)) .setDeclaredMethodDescriptorsFactory(declaredMethods) .setDeclaredFieldDescriptorsFactory(declaredFields) .setUnusableByJsSuppressed(JsInteropAnnotationUtils.isUnusableByJsSuppressed(typeBinding)) .setDeprecated(isDeprecated(typeBinding)) .build(); } private static boolean isAnnotatedWithFunctionalInterface(ITypeBinding typeBinding) { return JdtAnnotationUtils.hasAnnotation(typeBinding, FunctionalInterface.class.getName()); } private static boolean isAnnotatedWithAutoValue(ITypeBinding typeBinding) { return JdtAnnotationUtils.hasAnnotation(typeBinding, "com.google.auto.value.AutoValue"); } private JdtUtils() {} }
transpiler/java/com/google/j2cl/transpiler/frontend/jdt/JdtUtils.java
/* * Copyright 2015 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.j2cl.transpiler.frontend.jdt; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.ImmutableList.toImmutableList; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.j2cl.common.InternalCompilerError; import com.google.j2cl.common.SourcePosition; import com.google.j2cl.transpiler.ast.ArrayLength; import com.google.j2cl.transpiler.ast.ArrayTypeDescriptor; import com.google.j2cl.transpiler.ast.BinaryOperator; import com.google.j2cl.transpiler.ast.DeclaredTypeDescriptor; import com.google.j2cl.transpiler.ast.Expression; import com.google.j2cl.transpiler.ast.FieldAccess; import com.google.j2cl.transpiler.ast.FieldDescriptor; import com.google.j2cl.transpiler.ast.IntersectionTypeDescriptor; import com.google.j2cl.transpiler.ast.JsEnumInfo; import com.google.j2cl.transpiler.ast.JsInfo; import com.google.j2cl.transpiler.ast.JsMemberType; import com.google.j2cl.transpiler.ast.Kind; import com.google.j2cl.transpiler.ast.MethodDescriptor; import com.google.j2cl.transpiler.ast.MethodDescriptor.ParameterDescriptor; import com.google.j2cl.transpiler.ast.PostfixOperator; import com.google.j2cl.transpiler.ast.PrefixOperator; import com.google.j2cl.transpiler.ast.PrimitiveTypeDescriptor; import com.google.j2cl.transpiler.ast.PrimitiveTypes; import com.google.j2cl.transpiler.ast.TypeDeclaration; import com.google.j2cl.transpiler.ast.TypeDescriptor; import com.google.j2cl.transpiler.ast.TypeDescriptors; import com.google.j2cl.transpiler.ast.TypeVariable; import com.google.j2cl.transpiler.ast.Variable; import com.google.j2cl.transpiler.ast.Visibility; import com.google.j2cl.transpiler.frontend.common.PackageInfoCache; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Queue; import java.util.Set; import java.util.function.Supplier; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.Assignment; import org.eclipse.jdt.core.dom.BodyDeclaration; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.IAnnotationBinding; import org.eclipse.jdt.core.dom.IBinding; import org.eclipse.jdt.core.dom.IMethodBinding; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.IVariableBinding; import org.eclipse.jdt.core.dom.InfixExpression; import org.eclipse.jdt.core.dom.Modifier; import org.eclipse.jdt.core.dom.PostfixExpression; import org.eclipse.jdt.core.dom.PrefixExpression; /** Utility functions to manipulate JDT internal representations. */ class JdtUtils { // JdtUtil members are all package private. Code outside frontend should not be aware of the // dependency on JDT. public static String getCompilationUnitPackageName(CompilationUnit compilationUnit) { return compilationUnit.getPackage() == null ? "" : compilationUnit.getPackage().getName().getFullyQualifiedName(); } public static FieldDescriptor createFieldDescriptor(IVariableBinding variableBinding) { checkArgument(!isArrayLengthBinding(variableBinding)); boolean isStatic = isStatic(variableBinding); Visibility visibility = getVisibility(variableBinding); DeclaredTypeDescriptor enclosingTypeDescriptor = createDeclaredTypeDescriptor(variableBinding.getDeclaringClass()); String fieldName = variableBinding.getName(); TypeDescriptor thisTypeDescriptor = createTypeDescriptorWithNullability( variableBinding.getType(), variableBinding.getAnnotations()); if (variableBinding.isEnumConstant()) { // Enum fields are always non-nullable. thisTypeDescriptor = thisTypeDescriptor.toNonNullable(); } FieldDescriptor declarationFieldDescriptor = null; if (variableBinding.getVariableDeclaration() != variableBinding) { declarationFieldDescriptor = createFieldDescriptor(variableBinding.getVariableDeclaration()); } JsInfo jsInfo = JsInteropUtils.getJsInfo(variableBinding); boolean isCompileTimeConstant = variableBinding.getConstantValue() != null; boolean isFinal = JdtUtils.isFinal(variableBinding); return FieldDescriptor.newBuilder() .setEnclosingTypeDescriptor(enclosingTypeDescriptor) .setName(fieldName) .setTypeDescriptor(thisTypeDescriptor) .setStatic(isStatic) .setVisibility(visibility) .setJsInfo(jsInfo) .setFinal(isFinal) .setCompileTimeConstant(isCompileTimeConstant) .setDeclarationDescriptor(declarationFieldDescriptor) .setEnumConstant(variableBinding.isEnumConstant()) .setUnusableByJsSuppressed( JsInteropAnnotationUtils.isUnusableByJsSuppressed(variableBinding)) .setDeprecated(isDeprecated(variableBinding)) .build(); } public static Variable createVariable( SourcePosition sourcePosition, IVariableBinding variableBinding) { String name = variableBinding.getName(); TypeDescriptor typeDescriptor = variableBinding.isParameter() ? createTypeDescriptorWithNullability( variableBinding.getType(), variableBinding.getAnnotations()) : createTypeDescriptor(variableBinding.getType()); boolean isFinal = variableBinding.isEffectivelyFinal(); boolean isParameter = variableBinding.isParameter(); boolean isUnusableByJsSuppressed = JsInteropAnnotationUtils.isUnusableByJsSuppressed(variableBinding); return Variable.newBuilder() .setName(name) .setTypeDescriptor(typeDescriptor) .setFinal(isFinal) .setParameter(isParameter) .setUnusableByJsSuppressed(isUnusableByJsSuppressed) .setSourcePosition(sourcePosition) .build(); } public static BinaryOperator getBinaryOperator(InfixExpression.Operator operator) { switch (operator.toString()) { case "*": return BinaryOperator.TIMES; case "/": return BinaryOperator.DIVIDE; case "%": return BinaryOperator.REMAINDER; case "+": return BinaryOperator.PLUS; case "-": return BinaryOperator.MINUS; case "<<": return BinaryOperator.LEFT_SHIFT; case ">>": return BinaryOperator.RIGHT_SHIFT_SIGNED; case ">>>": return BinaryOperator.RIGHT_SHIFT_UNSIGNED; case "<": return BinaryOperator.LESS; case ">": return BinaryOperator.GREATER; case "<=": return BinaryOperator.LESS_EQUALS; case ">=": return BinaryOperator.GREATER_EQUALS; case "==": return BinaryOperator.EQUALS; case "!=": return BinaryOperator.NOT_EQUALS; case "^": return BinaryOperator.BIT_XOR; case "&": return BinaryOperator.BIT_AND; case "|": return BinaryOperator.BIT_OR; case "&&": return BinaryOperator.CONDITIONAL_AND; case "||": return BinaryOperator.CONDITIONAL_OR; default: return null; } } public static BinaryOperator getBinaryOperator(Assignment.Operator operator) { switch (operator.toString()) { case "=": return BinaryOperator.ASSIGN; case "+=": return BinaryOperator.PLUS_ASSIGN; case "-=": return BinaryOperator.MINUS_ASSIGN; case "*=": return BinaryOperator.TIMES_ASSIGN; case "/=": return BinaryOperator.DIVIDE_ASSIGN; case "&=": return BinaryOperator.BIT_AND_ASSIGN; case "|=": return BinaryOperator.BIT_OR_ASSIGN; case "^=": return BinaryOperator.BIT_XOR_ASSIGN; case "%=": return BinaryOperator.REMAINDER_ASSIGN; case "<<=": return BinaryOperator.LEFT_SHIFT_ASSIGN; case ">>=": return BinaryOperator.RIGHT_SHIFT_SIGNED_ASSIGN; case ">>>=": return BinaryOperator.RIGHT_SHIFT_UNSIGNED_ASSIGN; default: return null; } } public static IMethodBinding getMethodBinding( ITypeBinding typeBinding, String methodName, ITypeBinding... parameterTypes) { Queue<ITypeBinding> deque = new ArrayDeque<>(); deque.add(typeBinding); while (!deque.isEmpty()) { typeBinding = deque.poll(); for (IMethodBinding methodBinding : typeBinding.getDeclaredMethods()) { if (methodBinding.getName().equals(methodName) && Arrays.equals(methodBinding.getParameterTypes(), parameterTypes)) { return methodBinding; } } ITypeBinding superclass = typeBinding.getSuperclass(); if (superclass != null) { deque.add(superclass); } ITypeBinding[] superInterfaces = typeBinding.getInterfaces(); if (superInterfaces != null) { for (ITypeBinding superInterface : superInterfaces) { deque.add(superInterface); } } } return null; } public static PrefixOperator getPrefixOperator(PrefixExpression.Operator operator) { switch (operator.toString()) { case "++": return PrefixOperator.INCREMENT; case "--": return PrefixOperator.DECREMENT; case "+": return PrefixOperator.PLUS; case "-": return PrefixOperator.MINUS; case "~": return PrefixOperator.COMPLEMENT; case "!": return PrefixOperator.NOT; default: return null; } } public static PostfixOperator getPostfixOperator(PostfixExpression.Operator operator) { switch (operator.toString()) { case "++": return PostfixOperator.INCREMENT; case "--": return PostfixOperator.DECREMENT; default: return null; } } public static Expression createFieldAccess(Expression qualifier, IVariableBinding fieldBinding) { if (isArrayLengthBinding(fieldBinding)) { return ArrayLength.newBuilder().setArrayExpression(qualifier).build(); } return FieldAccess.Builder.from(JdtUtils.createFieldDescriptor(fieldBinding)) .setQualifier(qualifier) .build(); } private static boolean isArrayLengthBinding(IVariableBinding variableBinding) { return variableBinding.getName().equals("length") && variableBinding.isField() && variableBinding.getDeclaringClass() == null; } /** Returns true if the binding is annotated with @UncheckedCast. */ public static boolean hasUncheckedCastAnnotation(IBinding binding) { return JdtAnnotationUtils.hasAnnotation(binding, "javaemul.internal.annotations.UncheckedCast"); } /** Helper method to work around JDT habit of returning raw collections. */ @SuppressWarnings("rawtypes") public static <T> List<T> asTypedList(List jdtRawCollection) { @SuppressWarnings("unchecked") List<T> typedList = jdtRawCollection; return typedList; } /** Creates a DeclaredTypeDescriptor from a JDT TypeBinding. */ public static DeclaredTypeDescriptor createDeclaredTypeDescriptor(ITypeBinding typeBinding) { return createTypeDescriptor(typeBinding, DeclaredTypeDescriptor.class); } /** Creates a DeclaredTypeDescriptor from a JDT TypeBinding. */ private static <T extends TypeDescriptor> T createTypeDescriptor( ITypeBinding typeBinding, Class<T> clazz) { return clazz.cast(createTypeDescriptor(typeBinding)); } /** Creates a TypeDescriptor from a JDT TypeBinding. */ public static TypeDescriptor createTypeDescriptor(ITypeBinding typeBinding) { return createTypeDescriptorWithNullability(typeBinding, new IAnnotationBinding[0]); } /** * Creates a type descriptor for the given type binding, taking into account nullability. * * @param typeBinding the type binding, used to create the type descriptor. * @param elementAnnotations the annotations on the element */ private static TypeDescriptor createTypeDescriptorWithNullability( ITypeBinding typeBinding, IAnnotationBinding[] elementAnnotations) { if (typeBinding == null) { return null; } if (typeBinding.isPrimitive()) { return PrimitiveTypes.get(typeBinding.getName()); } if (isIntersectionType(typeBinding)) { return createIntersectionType(typeBinding); } if (typeBinding.isNullType()) { return TypeDescriptors.get().javaLangObject; } if (typeBinding.isTypeVariable() || typeBinding.isCapture() || typeBinding.isWildcardType()) { return createTypeVariable(typeBinding); } boolean isNullable = isNullable(typeBinding, elementAnnotations); if (typeBinding.isArray()) { TypeDescriptor componentTypeDescriptor = createTypeDescriptor(typeBinding.getComponentType()); return ArrayTypeDescriptor.newBuilder() .setComponentTypeDescriptor(componentTypeDescriptor) .setNullable(isNullable) .build(); } return withNullability(createDeclaredType(typeBinding), isNullable); } private static TypeDescriptor createTypeVariable(ITypeBinding typeBinding) { Supplier<TypeDescriptor> boundTypeDescriptorFactory = () -> getTypeBound(typeBinding); return TypeVariable.newBuilder() .setBoundTypeDescriptorSupplier(boundTypeDescriptorFactory) .setWildcardOrCapture(typeBinding.isWildcardType() || typeBinding.isCapture()) .setUniqueKey(typeBinding.getKey()) .setName(typeBinding.getName()) .build(); } private static TypeDescriptor getTypeBound(ITypeBinding typeBinding) { ITypeBinding[] bounds = typeBinding.getTypeBounds(); if (bounds == null || bounds.length == 0) { return TypeDescriptors.get().javaLangObject; } if (bounds.length == 1) { return createTypeDescriptor(bounds[0]); } return IntersectionTypeDescriptor.newBuilder() .setIntersectionTypeDescriptors(createTypeDescriptors(bounds, DeclaredTypeDescriptor.class)) .build(); } private static DeclaredTypeDescriptor withNullability( DeclaredTypeDescriptor typeDescriptor, boolean nullable) { return nullable ? typeDescriptor.toNullable() : typeDescriptor.toNonNullable(); } /** * Returns whether the given type binding should be nullable, according to the annotations on it * and if nullability is enabled for the package containing the binding. */ private static boolean isNullable( ITypeBinding typeBinding, IAnnotationBinding[] elementAnnotations) { checkArgument(!typeBinding.isPrimitive()); if (typeBinding.getQualifiedName().equals("java.lang.Void")) { // Void is always nullable. return true; } if (JsInteropAnnotationUtils.hasJsNonNullAnnotation(typeBinding)) { return false; } // TODO(b/70164536): Deprecate non J2CL-specific nullability annotations. Iterable<IAnnotationBinding> allAnnotations = Iterables.concat( Arrays.asList(elementAnnotations), Arrays.asList(typeBinding.getTypeAnnotations()), Arrays.asList(typeBinding.getAnnotations())); for (IAnnotationBinding annotation : allAnnotations) { String annotationName = annotation.getName(); if (annotationName.equalsIgnoreCase("Nonnull")) { return false; } } return true; } /** * In case the given type binding is nested, return the outermost possible enclosing type binding. */ private static ITypeBinding toTopLevelTypeBinding(ITypeBinding typeBinding) { ITypeBinding topLevelClass = typeBinding; while (topLevelClass.getDeclaringClass() != null) { topLevelClass = topLevelClass.getDeclaringClass(); } return topLevelClass; } private static boolean isIntersectionType(ITypeBinding binding) { return binding.isIntersectionType() // JDT returns true for isIntersectionType() for type variables, wildcards and captures // with intersection type bounds. && !binding.isCapture() && !binding.isTypeVariable() && !binding.isWildcardType(); } private static List<String> getClassComponents(ITypeBinding typeBinding) { List<String> classComponents = new ArrayList<>(); ITypeBinding currentType = typeBinding; while (currentType != null) { checkArgument(currentType.getTypeDeclaration() != null); if (currentType.isLocal()) { // JDT binary name for local class is like package.components.EnclosingClass$1SimpleName // Extract the generated name by taking the part after the binary name of the declaring // class. String binaryName = getBinaryNameFromTypeBinding(currentType); String declaringClassPrefix = getBinaryNameFromTypeBinding(currentType.getDeclaringClass()) + "$"; checkState(binaryName.startsWith(declaringClassPrefix)); classComponents.add(0, binaryName.substring(declaringClassPrefix.length())); } else { classComponents.add(0, currentType.getName()); } currentType = currentType.getDeclaringClass(); } return classComponents; } /** * Returns the binary name for a type binding. * * <p>NOTE: This accounts for the cases that JDT does not assign binary names, which are those of * unreachable local or anonymous classes. */ private static String getBinaryNameFromTypeBinding(ITypeBinding typeBinding) { String binaryName = typeBinding.getBinaryName(); if (binaryName == null && (typeBinding.isLocal() || typeBinding.isAnonymous())) { // Local and anonymous classes in unreachable code have null binary name. // The code here is a HACK that relies on the way that JDT synthesizes keys. Keys for // unreachable classes have the closest enclosing reachable class key as a prefix (minus the // ending semicolon) ITypeBinding closestReachableExclosingClass = typeBinding.getDeclaringClass(); while (closestReachableExclosingClass.getBinaryName() == null) { closestReachableExclosingClass = closestReachableExclosingClass.getDeclaringClass(); } String parentKey = closestReachableExclosingClass.getKey(); String key = typeBinding.getKey(); return getBinaryNameFromTypeBinding(typeBinding.getDeclaringClass()) + "$$Unreachable" // remove the parent prefix and the ending semicolon + key.substring(parentKey.length() - 1, key.length() - 1); } return binaryName; } private static List<TypeDescriptor> getTypeArgumentTypeDescriptors(ITypeBinding typeBinding) { return getTypeArgumentTypeDescriptors(typeBinding, TypeDescriptor.class); } private static <T extends TypeDescriptor> List<T> getTypeArgumentTypeDescriptors( ITypeBinding typeBinding, Class<T> clazz) { ImmutableList.Builder<T> typeArgumentDescriptorsBuilder = ImmutableList.builder(); if (typeBinding.isParameterizedType()) { typeArgumentDescriptorsBuilder.addAll( createTypeDescriptors(typeBinding.getTypeArguments(), clazz)); } else { typeArgumentDescriptorsBuilder.addAll( createTypeDescriptors(typeBinding.getTypeParameters(), clazz)); } // DO NOT USE getDeclaringMethod(). getDeclaringMethod() returns a synthetic static method // in the declaring class, instead of the proper lambda method with the declaring method // enclosing it when the declaration is inside a lambda. If the declaring method declares a // type variable, it would get lost. IBinding declarationBinding = getDeclaringMethodOrFieldBinding(typeBinding); if (declarationBinding instanceof IMethodBinding) { typeArgumentDescriptorsBuilder.addAll( createTypeDescriptors(((IMethodBinding) declarationBinding).getTypeParameters(), clazz)); } if (capturesEnclosingInstance(typeBinding.getTypeDeclaration())) { // Find type parameters in the enclosing scope and copy them over as well. createDeclaredTypeDescriptor(typeBinding.getDeclaringClass()) .getTypeArgumentDescriptors() .stream() .map(clazz::cast) .forEach(typeArgumentDescriptorsBuilder::add); } return typeArgumentDescriptorsBuilder.build(); } public static Visibility getVisibility(IBinding binding) { return getVisibility(binding.getModifiers()); } private static Visibility getVisibility(int modifiers) { if (Modifier.isPublic(modifiers)) { return Visibility.PUBLIC; } else if (Modifier.isProtected(modifiers)) { return Visibility.PROTECTED; } else if (Modifier.isPrivate(modifiers)) { return Visibility.PRIVATE; } else { return Visibility.PACKAGE_PRIVATE; } } private static boolean isDeprecated(IBinding binding) { return JdtAnnotationUtils.hasAnnotation(binding, Deprecated.class.getName()); } private static boolean isDefaultMethod(IMethodBinding binding) { return Modifier.isDefault(binding.getModifiers()); } private static boolean isAbstract(IBinding binding) { return Modifier.isAbstract(binding.getModifiers()); } private static boolean isFinal(IBinding binding) { return Modifier.isFinal(binding.getModifiers()); } public static boolean isStatic(IBinding binding) { if (binding instanceof IVariableBinding) { IVariableBinding variableBinding = (IVariableBinding) binding; if (!variableBinding.isField() || variableBinding.getDeclaringClass().isInterface()) { // Interface fields and variables are implicitly static. return true; } } return Modifier.isStatic(binding.getModifiers()); } public static boolean isStatic(BodyDeclaration bodyDeclaration) { return Modifier.isStatic(bodyDeclaration.getModifiers()); } private static boolean isEnumSyntheticMethod(IMethodBinding methodBinding) { // Enum synthetic methods are not marked as such because per JLS 13.1 these methods are // implicitly declared but are not marked as synthetic. return methodBinding.getDeclaringClass().isEnum() && (isEnumValuesMethod(methodBinding) || isEnumValueOfMethod(methodBinding)); } private static boolean isEnumValuesMethod(IMethodBinding methodBinding) { return methodBinding.getName().equals("values") && methodBinding.getParameterTypes().length == 0; } private static boolean isEnumValueOfMethod(IMethodBinding methodBinding) { return methodBinding.getName().equals("valueOf") && methodBinding.getParameterTypes().length == 1 && methodBinding.getParameterTypes()[0].getQualifiedName().equals("java.lang.String"); } /** * Returns true if instances of this type capture its outer instances; i.e. if it is an non static * member class, or an anonymous or local class defined in an instance context. */ public static boolean capturesEnclosingInstance(ITypeBinding typeBinding) { if (!typeBinding.isClass() || !typeBinding.isNested()) { // Only non-top level classes (excludes Enums, Interfaces etc.) can capture outer instances. return false; } if (typeBinding.isLocal()) { // Local types (which include anonymous classes in JDT) are static only if they are declared // in a static context; i.e. if the member where they are declared is static. return !isStatic(getDeclaringMethodOrFieldBinding(typeBinding)); } else { checkArgument(typeBinding.isMember()); // Member classes must be marked explicitly static. return !isStatic(typeBinding); } } /** * Returns the declaring member binding if any, skipping lambdas which are returned by JDT as * declaring members but are not. */ private static IBinding getDeclaringMethodOrFieldBinding(ITypeBinding typeBinding) { IBinding declarationBinding = getDeclaringMember(typeBinding); // Skip all lambda method bindings. while (isLambdaBinding(declarationBinding)) { declarationBinding = ((IMethodBinding) declarationBinding).getDeclaringMember(); } return declarationBinding; } private static IBinding getDeclaringMember(ITypeBinding typeBinding) { ITypeBinding typeDeclaration = typeBinding.getTypeDeclaration(); IBinding declaringMember = typeDeclaration.getDeclaringMember(); if (declaringMember == null) { // Work around for b/147690014, in which getDeclaringMember returns null, but there is // a declaring member and is returned by getDeclaringMethod. declaringMember = typeDeclaration.getDeclaringMethod(); } return declaringMember; } private static boolean isLambdaBinding(IBinding binding) { return binding instanceof IMethodBinding && ((IMethodBinding) binding).getDeclaringMember() != null; } /** Create a MethodDescriptor directly based on the given JDT method binding. */ public static MethodDescriptor createMethodDescriptor(IMethodBinding methodBinding) { if (methodBinding == null) { return null; } DeclaredTypeDescriptor enclosingTypeDescriptor = createDeclaredTypeDescriptor(methodBinding.getDeclaringClass()); boolean isStatic = isStatic(methodBinding); Visibility visibility = getVisibility(methodBinding); boolean isDefault = isDefaultMethod(methodBinding); JsInfo jsInfo = computeJsInfo(methodBinding); boolean isNative = Modifier.isNative(methodBinding.getModifiers()) || (!jsInfo.isJsOverlay() && enclosingTypeDescriptor.isNative() && isAbstract(methodBinding)); boolean isConstructor = methodBinding.isConstructor(); String methodName = methodBinding.getName(); TypeDescriptor returnTypeDescriptor = createTypeDescriptorWithNullability( methodBinding.getReturnType(), methodBinding.getAnnotations()); MethodDescriptor declarationMethodDescriptor = null; if (methodBinding.getMethodDeclaration() != methodBinding) { // The declaration for methods in a lambda binding is two hops away. Since the declaration // binding of a declaration is itself, we get the declaration of the declaration here. IMethodBinding declarationBinding = methodBinding.getMethodDeclaration().getMethodDeclaration(); declarationMethodDescriptor = createMethodDescriptor(declarationBinding); } // generate type parameters declared in the method. Iterable<TypeVariable> typeParameterTypeDescriptors = FluentIterable.from(methodBinding.getTypeParameters()) .transform(JdtUtils::createTypeDescriptor) .transform(typeDescriptor -> (TypeVariable) typeDescriptor); ImmutableList.Builder<ParameterDescriptor> parameterDescriptorBuilder = ImmutableList.builder(); for (int i = 0; i < methodBinding.getParameterTypes().length; i++) { parameterDescriptorBuilder.add( ParameterDescriptor.newBuilder() .setTypeDescriptor( createTypeDescriptorWithNullability( methodBinding.getParameterTypes()[i], methodBinding.getParameterAnnotations(i))) .setJsOptional(JsInteropUtils.isJsOptional(methodBinding, i)) .setVarargs( i == methodBinding.getParameterTypes().length - 1 && methodBinding.isVarargs()) .setDoNotAutobox(JsInteropUtils.isDoNotAutobox(methodBinding, i)) .build()); } if (enclosingTypeDescriptor.getTypeDeclaration().isAnonymous() && isConstructor && enclosingTypeDescriptor.getSuperTypeDescriptor().hasJsConstructor()) { jsInfo = JsInfo.Builder.from(jsInfo).setJsMemberType(JsMemberType.CONSTRUCTOR).build(); } boolean hasUncheckedCast = hasUncheckedCastAnnotation(methodBinding); return MethodDescriptor.newBuilder() .setEnclosingTypeDescriptor(enclosingTypeDescriptor) .setName(isConstructor ? null : methodName) .setParameterDescriptors(parameterDescriptorBuilder.build()) .setDeclarationDescriptor(declarationMethodDescriptor) .setReturnTypeDescriptor(returnTypeDescriptor) .setTypeParameterTypeDescriptors(typeParameterTypeDescriptors) .setJsInfo(jsInfo) .setWasmInfo(getWasmInfo(methodBinding)) .setJsFunction(isOrOverridesJsFunctionMethod(methodBinding)) .setVisibility(visibility) .setStatic(isStatic) .setConstructor(isConstructor) .setNative(isNative) .setFinal(JdtUtils.isFinal(methodBinding)) .setDefaultMethod(isDefault) .setAbstract(Modifier.isAbstract(methodBinding.getModifiers())) .setSynthetic(methodBinding.isSynthetic()) .setEnumSyntheticMethod(isEnumSyntheticMethod(methodBinding)) .setUnusableByJsSuppressed(JsInteropAnnotationUtils.isUnusableByJsSuppressed(methodBinding)) .setDeprecated(isDeprecated(methodBinding)) .setUncheckedCast(hasUncheckedCast) .build(); } private static String getWasmInfo(IMethodBinding binding) { return JdtAnnotationUtils.getStringAttribute( JdtAnnotationUtils.findAnnotationBindingByName( binding.getAnnotations(), "javaemul.internal.annotations.Wasm"), "value"); } private static boolean isOrOverridesJsFunctionMethod(IMethodBinding methodBinding) { ITypeBinding declaringType = methodBinding.getDeclaringClass(); if (JsInteropUtils.isJsFunction(declaringType) && declaringType.getFunctionalInterfaceMethod() != null && methodBinding.getMethodDeclaration() == declaringType.getFunctionalInterfaceMethod().getMethodDeclaration()) { return true; } for (IMethodBinding overriddenMethodBinding : getOverriddenMethods(methodBinding)) { if (isOrOverridesJsFunctionMethod(overriddenMethodBinding)) { return true; } } return false; } /** Checks overriding chain to compute JsInfo. */ private static JsInfo computeJsInfo(IMethodBinding methodBinding) { JsInfo originalJsInfo = JsInteropUtils.getJsInfo(methodBinding); if (originalJsInfo.isJsOverlay() || originalJsInfo.getJsName() != null || originalJsInfo.getJsNamespace() != null) { // Do not examine overridden methods if the method is marked as JsOverlay or it has a JsMember // annotation that customizes the name. return originalJsInfo; } boolean hasExplicitJsMemberAnnotation = hasJsMemberAnnotation(methodBinding); JsInfo defaultJsInfo = originalJsInfo; for (IMethodBinding overriddenMethod : getOverriddenMethods(methodBinding)) { JsInfo inheritedJsInfo = JsInteropUtils.getJsInfo(overriddenMethod); if (inheritedJsInfo.getJsMemberType() == JsMemberType.NONE) { continue; } if (hasExplicitJsMemberAnnotation && originalJsInfo.getJsMemberType() != inheritedJsInfo.getJsMemberType()) { // Only inherit from the overridden method if the JsMember types are consistent. continue; } if (inheritedJsInfo.getJsName() != null) { // Found an overridden method of the same JsMember type one that customizes the name, done. // If there are any conflicts with other overrides they will be reported by // JsInteropRestrictionsChecker. return JsInfo.Builder.from(inheritedJsInfo).setJsAsync(originalJsInfo.isJsAsync()).build(); } if (defaultJsInfo == originalJsInfo && !hasExplicitJsMemberAnnotation) { // The original method does not have a JsMember annotation and traversing the list of // overridden methods we found the first that has an explicit JsMember annotation. // Keep it as the one to be used if none is found that customizes the name. // This allows to "inherit" the JsMember type from the override. defaultJsInfo = inheritedJsInfo; } } // Don't inherit @JsAsync annotation from overridden methods. return JsInfo.Builder.from(defaultJsInfo).setJsAsync(originalJsInfo.isJsAsync()).build(); } private static boolean hasJsMemberAnnotation(IMethodBinding methodBinding) { return JsInteropAnnotationUtils.getJsMethodAnnotation(methodBinding) != null || JsInteropAnnotationUtils.getJsPropertyAnnotation(methodBinding) != null || JsInteropAnnotationUtils.getJsConstructorAnnotation(methodBinding) != null; } public static Set<IMethodBinding> getOverriddenMethods(IMethodBinding methodBinding) { return getOverriddenMethodsInType(methodBinding, methodBinding.getDeclaringClass()); } private static Set<IMethodBinding> getOverriddenMethodsInType( IMethodBinding methodBinding, ITypeBinding typeBinding) { Set<IMethodBinding> overriddenMethods = new HashSet<>(); for (IMethodBinding declaredMethod : typeBinding.getDeclaredMethods()) { if (methodBinding.overrides(declaredMethod) && !methodBinding.isConstructor()) { checkArgument(!Modifier.isStatic(methodBinding.getModifiers())); overriddenMethods.add(declaredMethod); } } // Recurse into immediate super class and interfaces for overridden method. if (typeBinding.getSuperclass() != null) { overriddenMethods.addAll( getOverriddenMethodsInType(methodBinding, typeBinding.getSuperclass())); } for (ITypeBinding interfaceBinding : typeBinding.getInterfaces()) { overriddenMethods.addAll(getOverriddenMethodsInType(methodBinding, interfaceBinding)); } ITypeBinding javaLangObjectTypeBinding = JdtUtils.javaLangObjectTypeBinding.get(); if (typeBinding != javaLangObjectTypeBinding) { for (IMethodBinding objectMethodBinding : javaLangObjectTypeBinding.getDeclaredMethods()) { if (!isPolymorphic(objectMethodBinding)) { continue; } checkState(!getVisibility(objectMethodBinding).isPackagePrivate()); if (methodBinding.isSubsignature(objectMethodBinding)) { overriddenMethods.add(objectMethodBinding); } } } return overriddenMethods; } private static boolean isPolymorphic(IMethodBinding methodBinding) { return !methodBinding.isConstructor() && !isStatic(methodBinding) && !Modifier.isPrivate(methodBinding.getModifiers()); } private static boolean isLocal(ITypeBinding typeBinding) { return typeBinding.isLocal(); } /** Returns the MethodDescriptor for the JsFunction method. */ private static MethodDescriptor getJsFunctionMethodDescriptor(ITypeBinding typeBinding) { if (JsInteropUtils.isJsFunction(typeBinding) && typeBinding.getFunctionalInterfaceMethod() != null) { // typeBinding.getFunctionalInterfaceMethod returns in some cases the method declaration // instead of the method with the corresponding parameterization. Note: this is observed in // the case when a type is parameterized with a wildcard, e.g. JsFunction<?>. IMethodBinding jsFunctionMethodBinding = Arrays.stream(typeBinding.getDeclaredMethods()) .filter( methodBinding -> methodBinding.getMethodDeclaration() == typeBinding.getFunctionalInterfaceMethod().getMethodDeclaration()) .findFirst() .get(); return createMethodDescriptor(jsFunctionMethodBinding).withoutTypeParameters(); } // Find implementation method that corresponds to JsFunction. Optional<ITypeBinding> jsFunctionInterface = Arrays.stream(typeBinding.getInterfaces()).filter(JsInteropUtils::isJsFunction).findFirst(); return jsFunctionInterface .map(ITypeBinding::getFunctionalInterfaceMethod) .flatMap(jsFunctionMethod -> getOverrideInType(typeBinding, jsFunctionMethod)) .map(MethodDescriptor::withoutTypeParameters) .orElse(null); } private static Optional<MethodDescriptor> getOverrideInType( ITypeBinding typeBinding, IMethodBinding methodBinding) { return Arrays.stream(typeBinding.getDeclaredMethods()) .filter(m -> m.overrides(methodBinding)) .findFirst() .map(JdtUtils::createMethodDescriptor); } private static <T extends TypeDescriptor> ImmutableList<T> createTypeDescriptors( List<ITypeBinding> typeBindings, Class<T> clazz) { return typeBindings.stream() .map(typeBinding -> createTypeDescriptor(typeBinding, clazz)) .collect(toImmutableList()); } private static <T extends TypeDescriptor> ImmutableList<T> createTypeDescriptors( ITypeBinding[] typeBindings, Class<T> clazz) { return createTypeDescriptors(Arrays.asList(typeBindings), clazz); } private static ThreadLocal<ITypeBinding> javaLangObjectTypeBinding = new ThreadLocal<>(); public static void initWellKnownTypes(AST ast, Iterable<ITypeBinding> typeBindings) { javaLangObjectTypeBinding.set(ast.resolveWellKnownType("java.lang.Object")); if (TypeDescriptors.isInitialized()) { return; } TypeDescriptors.SingletonBuilder builder = new TypeDescriptors.SingletonBuilder(); for (PrimitiveTypeDescriptor typeDescriptor : PrimitiveTypes.TYPES) { addPrimitive(ast, builder, typeDescriptor); } // Add well-known, non-primitive types. for (ITypeBinding typeBinding : typeBindings) { builder.addReferenceType(createDeclaredTypeDescriptor(typeBinding)); } builder.buildSingleton(); } private static void addPrimitive( AST ast, TypeDescriptors.SingletonBuilder builder, PrimitiveTypeDescriptor typeDescriptor) { DeclaredTypeDescriptor boxedType = createDeclaredTypeDescriptor(ast.resolveWellKnownType(typeDescriptor.getBoxedClassName())); builder.addPrimitiveBoxedTypeDescriptorPair(typeDescriptor, boxedType); } /** * Since we don't have access to the enclosing class, the proper package and naming cannot be * computed here. Instead we have an early normalization pass that traverses the intersection * types and sets the correct package and binaryName etc. */ private static final TypeDescriptor createIntersectionType(ITypeBinding typeBinding) { checkArgument(isIntersectionType(typeBinding)); List<DeclaredTypeDescriptor> intersectedTypeDescriptors = createTypeDescriptors(typeBinding.getTypeBounds(), DeclaredTypeDescriptor.class); return IntersectionTypeDescriptor.newBuilder() .setIntersectionTypeDescriptors(intersectedTypeDescriptors) .build(); } /** * This cache is a Hashtable so is already synchronized and safe to use from multiple threads. We * don't need a separate cache for each thread (like interners have) since JDT's ITypeBinding * instances (which we are using as keys) are unique per JDT parse. */ @SuppressWarnings("JdkObsolete") private static Map<ITypeBinding, DeclaredTypeDescriptor> cachedDeclaredTypeDescriptorByTypeBinding = new Hashtable<>(); // This is only used by TypeProxyUtils, and cannot be used elsewhere. Because to create a // TypeDescriptor from a TypeBinding, it should go through the path to check array type. private static DeclaredTypeDescriptor createDeclaredType(final ITypeBinding typeBinding) { if (cachedDeclaredTypeDescriptorByTypeBinding.containsKey(typeBinding)) { return cachedDeclaredTypeDescriptorByTypeBinding.get(typeBinding); } checkArgument(!typeBinding.isArray()); checkArgument(!typeBinding.isPrimitive()); Supplier<ImmutableList<MethodDescriptor>> declaredMethods = () -> Arrays.stream(typeBinding.getDeclaredMethods()) .map(JdtUtils::createMethodDescriptor) .collect(toImmutableList()); ; Supplier<ImmutableList<FieldDescriptor>> declaredFields = () -> Arrays.stream(typeBinding.getDeclaredFields()) .map(JdtUtils::createFieldDescriptor) .collect(toImmutableList()); TypeDeclaration typeDeclaration = JdtUtils.createDeclarationForType(typeBinding.getTypeDeclaration()); // Compute these even later DeclaredTypeDescriptor typeDescriptor = DeclaredTypeDescriptor.newBuilder() .setTypeDeclaration(typeDeclaration) .setEnclosingTypeDescriptor( createDeclaredTypeDescriptor(typeBinding.getDeclaringClass())) .setInterfaceTypeDescriptorsFactory( () -> createTypeDescriptors( typeBinding.getInterfaces(), DeclaredTypeDescriptor.class)) .setSingleAbstractMethodDescriptorFactory( () -> createMethodDescriptor(typeBinding.getFunctionalInterfaceMethod())) .setJsFunctionMethodDescriptorFactory(() -> getJsFunctionMethodDescriptor(typeBinding)) .setSuperTypeDescriptorFactory( () -> createDeclaredTypeDescriptor(typeBinding.getSuperclass())) .setTypeArgumentDescriptors(getTypeArgumentTypeDescriptors(typeBinding)) .setDeclaredFieldDescriptorsFactory(declaredFields) .setDeclaredMethodDescriptorsFactory(declaredMethods) .build(); cachedDeclaredTypeDescriptorByTypeBinding.put(typeBinding, typeDescriptor); return typeDescriptor; } private static Kind getKindFromTypeBinding(ITypeBinding typeBinding) { if (typeBinding.isEnum() && !typeBinding.isAnonymous()) { // Do not consider the anonymous classes that constitute enum values as Enums, only the // enum "class" itself is considered Kind.ENUM. return Kind.ENUM; } else if (typeBinding.isClass() || (typeBinding.isEnum() && typeBinding.isAnonymous())) { return Kind.CLASS; } else if (typeBinding.isInterface()) { return Kind.INTERFACE; } throw new InternalCompilerError("Type binding %s not handled", typeBinding); } private static String getJsName(final ITypeBinding typeBinding) { checkArgument(!typeBinding.isPrimitive()); return JsInteropAnnotationUtils.getJsName(typeBinding); } private static String getJsNamespace( ITypeBinding typeBinding, PackageInfoCache packageInfoCache) { checkArgument(!typeBinding.isPrimitive()); String jsNamespace = JsInteropAnnotationUtils.getJsNamespace(typeBinding); if (jsNamespace != null) { return jsNamespace; } // Maybe namespace is set via package-info file? boolean isTopLevelType = typeBinding.getDeclaringClass() == null; if (isTopLevelType) { return packageInfoCache.getJsNamespace( getBinaryNameFromTypeBinding(toTopLevelTypeBinding(typeBinding))); } return null; } public static TypeDeclaration createDeclarationForType(final ITypeBinding typeBinding) { if (typeBinding == null) { return null; } checkArgument(typeBinding.getTypeDeclaration() == typeBinding); checkArgument(!typeBinding.isArray()); checkArgument(!typeBinding.isParameterizedType()); checkArgument(!typeBinding.isTypeVariable()); checkArgument(!typeBinding.isWildcardType()); checkArgument(!typeBinding.isCapture()); PackageInfoCache packageInfoCache = PackageInfoCache.get(); ITypeBinding topLevelTypeBinding = toTopLevelTypeBinding(typeBinding); if (topLevelTypeBinding.isFromSource()) { // Let the PackageInfoCache know that this class is Source, otherwise it would have to rummage // around in the class path to figure it out and it might even come up with the wrong answer // for example if this class has also been globbed into some other library that is a // dependency of this one. PackageInfoCache.get().markAsSource(getBinaryNameFromTypeBinding(topLevelTypeBinding)); } // Compute these first since they're reused in other calculations. String packageName = typeBinding.getPackage() == null ? null : typeBinding.getPackage().getName(); boolean isAbstract = isAbstract(typeBinding); boolean isFinal = isFinal(typeBinding); Supplier<ImmutableList<MethodDescriptor>> declaredMethods = () -> Arrays.stream(typeBinding.getDeclaredMethods()) .map(JdtUtils::createMethodDescriptor) .collect(toImmutableList()); ; Supplier<ImmutableList<FieldDescriptor>> declaredFields = () -> Arrays.stream(typeBinding.getDeclaredFields()) .map(JdtUtils::createFieldDescriptor) .collect(toImmutableList()); JsEnumInfo jsEnumInfo = JsInteropUtils.getJsEnumInfo(typeBinding); return TypeDeclaration.newBuilder() .setClassComponents(getClassComponents(typeBinding)) .setEnclosingTypeDeclaration(createDeclarationForType(typeBinding.getDeclaringClass())) .setInterfaceTypeDescriptorsFactory( () -> createTypeDescriptors(typeBinding.getInterfaces(), DeclaredTypeDescriptor.class)) .setUnparameterizedTypeDescriptorFactory(() -> createDeclaredTypeDescriptor(typeBinding)) .setHasAbstractModifier(isAbstract) .setKind(getKindFromTypeBinding(typeBinding)) .setCapturingEnclosingInstance(capturesEnclosingInstance(typeBinding)) .setFinal(isFinal) .setFunctionalInterface( !typeBinding.isAnnotation() && typeBinding.getFunctionalInterfaceMethod() != null) .setJsFunctionInterface(JsInteropUtils.isJsFunction(typeBinding)) .setAnnotatedWithFunctionalInterface(isAnnotatedWithFunctionalInterface(typeBinding)) .setAnnotatedWithAutoValue(isAnnotatedWithAutoValue(typeBinding)) .setJsType(JsInteropUtils.isJsType(typeBinding)) .setJsEnumInfo(jsEnumInfo) .setNative(JsInteropUtils.isJsNativeType(typeBinding)) .setAnonymous(typeBinding.isAnonymous()) .setLocal(isLocal(typeBinding)) .setSimpleJsName(getJsName(typeBinding)) .setCustomizedJsNamespace(getJsNamespace(typeBinding, packageInfoCache)) .setPackageName(packageName) .setSuperTypeDescriptorFactory( () -> createDeclaredTypeDescriptor(typeBinding.getSuperclass())) .setTypeParameterDescriptors( getTypeArgumentTypeDescriptors(typeBinding, TypeVariable.class)) .setVisibility(getVisibility(typeBinding)) .setDeclaredMethodDescriptorsFactory(declaredMethods) .setDeclaredFieldDescriptorsFactory(declaredFields) .setUnusableByJsSuppressed(JsInteropAnnotationUtils.isUnusableByJsSuppressed(typeBinding)) .setDeprecated(isDeprecated(typeBinding)) .build(); } private static boolean isAnnotatedWithFunctionalInterface(ITypeBinding typeBinding) { return JdtAnnotationUtils.hasAnnotation(typeBinding, FunctionalInterface.class.getName()); } private static boolean isAnnotatedWithAutoValue(ITypeBinding typeBinding) { return JdtAnnotationUtils.hasAnnotation(typeBinding, "com.google.auto.value.AutoValue"); } private JdtUtils() {} }
Remove stale comments and small cleanups in JdtUtils. PiperOrigin-RevId: 378407125
transpiler/java/com/google/j2cl/transpiler/frontend/jdt/JdtUtils.java
Remove stale comments and small cleanups in JdtUtils.
<ide><path>ranspiler/java/com/google/j2cl/transpiler/frontend/jdt/JdtUtils.java <ide> return createTypeDescriptorWithNullability(typeBinding, new IAnnotationBinding[0]); <ide> } <ide> <del> /** <del> * Creates a type descriptor for the given type binding, taking into account nullability. <del> * <del> * @param typeBinding the type binding, used to create the type descriptor. <del> * @param elementAnnotations the annotations on the element <del> */ <add> /** Creates a type descriptor for the given type binding, taking into account nullability. */ <ide> private static TypeDescriptor createTypeDescriptorWithNullability( <ide> ITypeBinding typeBinding, IAnnotationBinding[] elementAnnotations) { <ide> if (typeBinding == null) { <ide> if (bounds.length == 1) { <ide> return createTypeDescriptor(bounds[0]); <ide> } <del> return IntersectionTypeDescriptor.newBuilder() <del> .setIntersectionTypeDescriptors(createTypeDescriptors(bounds, DeclaredTypeDescriptor.class)) <del> .build(); <add> return createIntersectionType(typeBinding); <ide> } <ide> <ide> private static DeclaredTypeDescriptor withNullability( <ide> builder.addPrimitiveBoxedTypeDescriptorPair(typeDescriptor, boxedType); <ide> } <ide> <del> /** <del> * Since we don't have access to the enclosing class, the proper package and naming cannot be <del> * computed here. Instead we have an early normalization pass that traverses the intersection <del> * types and sets the correct package and binaryName etc. <del> */ <ide> private static final TypeDescriptor createIntersectionType(ITypeBinding typeBinding) { <del> checkArgument(isIntersectionType(typeBinding)); <ide> List<DeclaredTypeDescriptor> intersectedTypeDescriptors = <ide> createTypeDescriptors(typeBinding.getTypeBounds(), DeclaredTypeDescriptor.class); <ide> return IntersectionTypeDescriptor.newBuilder() <ide> private static Map<ITypeBinding, DeclaredTypeDescriptor> <ide> cachedDeclaredTypeDescriptorByTypeBinding = new Hashtable<>(); <ide> <del> // This is only used by TypeProxyUtils, and cannot be used elsewhere. Because to create a <del> // TypeDescriptor from a TypeBinding, it should go through the path to check array type. <ide> private static DeclaredTypeDescriptor createDeclaredType(final ITypeBinding typeBinding) { <ide> if (cachedDeclaredTypeDescriptorByTypeBinding.containsKey(typeBinding)) { <ide> return cachedDeclaredTypeDescriptorByTypeBinding.get(typeBinding); <ide> } <ide> <del> checkArgument(!typeBinding.isArray()); <del> checkArgument(!typeBinding.isPrimitive()); <add> checkArgument(typeBinding.isClass() || typeBinding.isEnum() || typeBinding.isInterface()); <ide> <ide> Supplier<ImmutableList<MethodDescriptor>> declaredMethods = <ide> () ->
Java
apache-2.0
d25e35431256bbd575c09fadc652925354eaf6d8
0
JayanthyChengan/dataverse,JayanthyChengan/dataverse,JayanthyChengan/dataverse,JayanthyChengan/dataverse,JayanthyChengan/dataverse,JayanthyChengan/dataverse,JayanthyChengan/dataverse,JayanthyChengan/dataverse
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package edu.harvard.iq.dataverse; import com.sun.mail.smtp.SMTPSendFailedException; import edu.harvard.iq.dataverse.authorization.groups.Group; import edu.harvard.iq.dataverse.authorization.groups.GroupServiceBean; import edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser; import edu.harvard.iq.dataverse.branding.BrandingUtil; import edu.harvard.iq.dataverse.confirmemail.ConfirmEmailServiceBean; import edu.harvard.iq.dataverse.settings.SettingsServiceBean; import edu.harvard.iq.dataverse.settings.SettingsServiceBean.Key; import edu.harvard.iq.dataverse.util.BundleUtil; import edu.harvard.iq.dataverse.util.MailUtil; import edu.harvard.iq.dataverse.util.SystemConfig; import java.io.UnsupportedEncodingException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.Properties; import java.util.Map; import java.util.HashMap; import java.util.List; import java.util.ResourceBundle; import java.util.Set; import java.util.logging.Logger; import javax.annotation.Resource; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.mail.Address; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.apache.commons.lang.StringUtils; /** * * original author: roberttreacy */ @Stateless public class MailServiceBean implements java.io.Serializable { @EJB UserNotificationServiceBean userNotificationService; @EJB DataverseServiceBean dataverseService; @EJB DataFileServiceBean dataFileService; @EJB DatasetServiceBean datasetService; @EJB DatasetVersionServiceBean versionService; @EJB SystemConfig systemConfig; @EJB SettingsServiceBean settingsService; @EJB PermissionServiceBean permissionService; @EJB GroupServiceBean groupService; @EJB ConfirmEmailServiceBean confirmEmailService; private static final Logger logger = Logger.getLogger(MailServiceBean.class.getCanonicalName()); private static final String charset = "UTF-8"; private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; /** * Creates a new instance of MailServiceBean */ public MailServiceBean() { } public void sendMail(String host, String reply, String to, String subject, String messageText) { Properties props = System.getProperties(); props.put("mail.smtp.host", host); Session session = Session.getDefaultInstance(props, null); try { MimeMessage msg = new MimeMessage(session); String[] recipientStrings = to.split(","); InternetAddress[] recipients = new InternetAddress[recipientStrings.length]; try { InternetAddress fromAddress=getSystemAddress(); fromAddress.setPersonal(BundleUtil.getStringFromBundle("contact.delegation", Arrays.asList( fromAddress.getPersonal(), reply)), charset); msg.setFrom(fromAddress); msg.setReplyTo(new Address[] {new InternetAddress(reply, charset)}); for (int i = 0; i < recipients.length; i++) { recipients[i] = new InternetAddress(recipientStrings[i], "", charset); } } catch (UnsupportedEncodingException ex) { logger.severe(ex.getMessage()); } msg.setRecipients(Message.RecipientType.TO, recipients); msg.setSubject(subject, charset); msg.setText(messageText, charset); Transport.send(msg, recipients); } catch (AddressException ae) { ae.printStackTrace(System.out); } catch (MessagingException me) { me.printStackTrace(System.out); } } @Resource(name = "mail/notifyMailSession") private Session session; public boolean sendSystemEmail(String to, String subject, String messageText) { boolean sent = false; String rootDataverseName = dataverseService.findRootDataverse().getName(); InternetAddress systemAddress = getSystemAddress(); String body = messageText + BundleUtil.getStringFromBundle("notification.email.closing", Arrays.asList(BrandingUtil.getSupportTeamEmailAddress(systemAddress), BrandingUtil.getSupportTeamName(systemAddress, rootDataverseName))); logger.fine("Sending email to " + to + ". Subject: <<<" + subject + ">>>. Body: " + body); try { MimeMessage msg = new MimeMessage(session); if (systemAddress != null) { msg.setFrom(systemAddress); msg.setSentDate(new Date()); String[] recipientStrings = to.split(","); InternetAddress[] recipients = new InternetAddress[recipientStrings.length]; for (int i = 0; i < recipients.length; i++) { try { recipients[i] = new InternetAddress(recipientStrings[i], "", charset); } catch (UnsupportedEncodingException ex) { logger.severe(ex.getMessage()); } } msg.setRecipients(Message.RecipientType.TO, recipients); msg.setSubject(subject, charset); msg.setText(body, charset); try { Transport.send(msg, recipients); sent = true; } catch (SMTPSendFailedException ssfe) { logger.warning("Failed to send mail to: " + to); logger.warning("SMTPSendFailedException Message: " + ssfe); } } else { logger.fine("Skipping sending mail to " + to + ", because the \"no-reply\" address not set (" + Key.SystemEmail + " setting)."); } } catch (AddressException ae) { logger.warning("Failed to send mail to " + to); ae.printStackTrace(System.out); } catch (MessagingException me) { logger.warning("Failed to send mail to " + to); me.printStackTrace(System.out); } return sent; } private InternetAddress getSystemAddress() { String systemEmail = settingsService.getValueForKey(Key.SystemEmail); return MailUtil.parseSystemAddress(systemEmail); } //@Resource(name="mail/notifyMailSession") public void sendMail(String from, String to, String subject, String messageText) { sendMail(from, to, subject, messageText, new HashMap<>()); } public void sendMail(String reply, String to, String subject, String messageText, Map<Object, Object> extraHeaders) { try { MimeMessage msg = new MimeMessage(session); //Always send from system address to avoid email being blocked InternetAddress fromAddress=getSystemAddress(); try { fromAddress.setPersonal(BundleUtil.getStringFromBundle("contact.delegation", Arrays.asList( fromAddress.getPersonal(), reply)), charset); } catch (UnsupportedEncodingException ex) { logger.severe(ex.getMessage()); } msg.setFrom(fromAddress); if (reply.matches(EMAIL_PATTERN)) { //But set the reply-to address to direct replies to the requested 'from' party if it is a valid email address msg.setReplyTo(new Address[] {new InternetAddress(reply)}); } else { //Otherwise include the invalid 'from' address in the message messageText = "From: " + reply + "\n\n" + messageText; } msg.setSentDate(new Date()); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); msg.setSubject(subject, charset); msg.setText(messageText, charset); if (extraHeaders != null) { for (Object key : extraHeaders.keySet()) { String headerName = key.toString(); String headerValue = extraHeaders.get(key).toString(); msg.addHeader(headerName, headerValue); } } Transport.send(msg); } catch (AddressException ae) { ae.printStackTrace(System.out); } catch (MessagingException me) { me.printStackTrace(System.out); } } public Boolean sendNotificationEmail(UserNotification notification){ return sendNotificationEmail(notification, ""); } public Boolean sendNotificationEmail(UserNotification notification, String comment){ boolean retval = false; String emailAddress = getUserEmailAddress(notification); if (emailAddress != null){ Object objectOfNotification = getObjectOfNotification(notification); if (objectOfNotification != null){ String messageText = getMessageTextBasedOnNotification(notification, objectOfNotification); String rootDataverseName = dataverseService.findRootDataverse().getName(); String subjectText = MailUtil.getSubjectTextBasedOnNotification(notification, rootDataverseName, objectOfNotification); if (!(messageText.isEmpty() || subjectText.isEmpty())){ retval = sendSystemEmail(emailAddress, subjectText, messageText); } else { logger.warning("Skipping " + notification.getType() + " notification, because couldn't get valid message"); } } else { logger.warning("Skipping " + notification.getType() + " notification, because no valid Object was found"); } } else { logger.warning("Skipping " + notification.getType() + " notification, because email address is null"); } return retval; } private String getDatasetManageFileAccessLink(DataFile datafile){ return systemConfig.getDataverseSiteUrl() + "/permissions-manage-files.xhtml?id=" + datafile.getOwner().getId(); } private String getDatasetLink(Dataset dataset){ return systemConfig.getDataverseSiteUrl() + "/dataset.xhtml?persistentId=" + dataset.getGlobalId(); } private String getDatasetDraftLink(Dataset dataset){ return systemConfig.getDataverseSiteUrl() + "/dataset.xhtml?persistentId=" + dataset.getGlobalId() + "&version=DRAFT" + "&faces-redirect=true"; } private String getDataverseLink(Dataverse dataverse){ return systemConfig.getDataverseSiteUrl() + "/dataverse/" + dataverse.getAlias(); } /** * Returns a '/'-separated string of roles that are effective for {@code au} * over {@code dvObj}. Traverses the containment hierarchy of the {@code d}. * Takes into consideration all groups that {@code au} is part of. * @param au The authenticated user whose role assignments we look for. * @param dvObj The Dataverse object over which the roles are assigned * @return A set of all the role assignments for {@code ra} over {@code d}. */ private String getRoleStringFromUser(AuthenticatedUser au, DvObject dvObj) { // Find user's role(s) for given dataverse/dataset Set<RoleAssignment> roles = permissionService.assignmentsFor(au, dvObj); List<String> roleNames = new ArrayList<>(); // Include roles derived from a user's groups Set<Group> groupsUserBelongsTo = groupService.groupsFor(au, dvObj); for (Group g : groupsUserBelongsTo) { roles.addAll(permissionService.assignmentsFor(g, dvObj)); } for (RoleAssignment ra : roles) { roleNames.add(ra.getRole().getName()); } return StringUtils.join(roleNames, "/"); } /** * Returns the URL to a given {@code DvObject} {@code d}. If {@code d} is a * {@code DataFile}, return a link to its {@code DataSet}. * @param d The Dataverse object to get a link for. * @return A string with a URL to the given Dataverse object. */ private String getDvObjectLink(DvObject d) { if (d instanceof Dataverse) { return getDataverseLink((Dataverse) d); } else if (d instanceof Dataset) { return getDatasetLink((Dataset) d); } else if (d instanceof DataFile) { return getDatasetLink(((DataFile) d).getOwner()); } return ""; } /** * Returns string representation of the type of {@code DvObject} {@code d}. * @param d The Dataverse object to get the string for * @return A string that represents the type of a given Dataverse object. */ private String getDvObjectTypeString(DvObject d) { if (d instanceof Dataverse) { return "dataverse"; } else if (d instanceof Dataset) { return "dataset"; } else if (d instanceof DataFile) { return "data file"; } return ""; } public String getMessageTextBasedOnNotification(UserNotification userNotification, Object targetObject){ return getMessageTextBasedOnNotification(userNotification, targetObject, ""); } public String getMessageTextBasedOnNotification(UserNotification userNotification, Object targetObject, String comment){ String messageText = ResourceBundle.getBundle("Bundle").getString("notification.email.greeting"); DatasetVersion version; Dataset dataset; DvObject dvObj; String dvObjURL; String dvObjTypeStr; String pattern; switch (userNotification.getType()) { case ASSIGNROLE: AuthenticatedUser au = userNotification.getUser(); dvObj = (DvObject) targetObject; String joinedRoleNames = getRoleStringFromUser(au, dvObj); dvObjURL = getDvObjectLink(dvObj); dvObjTypeStr = getDvObjectTypeString(dvObj); pattern = ResourceBundle.getBundle("Bundle").getString("notification.email.assignRole"); String[] paramArrayAssignRole = {joinedRoleNames, dvObjTypeStr, dvObj.getDisplayName(), dvObjURL}; messageText += MessageFormat.format(pattern, paramArrayAssignRole); if (joinedRoleNames.contains("File Downloader")){ if (dvObjTypeStr.equals("dataset")){ pattern = ResourceBundle.getBundle("Bundle").getString("notification.access.granted.fileDownloader.additionalDataset"); String[] paramArrayAssignRoleDS = {" "}; messageText += MessageFormat.format(pattern, paramArrayAssignRoleDS); } if (dvObjTypeStr.equals("dataverse")){ pattern = ResourceBundle.getBundle("Bundle").getString("notification.access.granted.fileDownloader.additionalDataverse"); String[] paramArrayAssignRoleDV = {" "}; messageText += MessageFormat.format(pattern, paramArrayAssignRoleDV); } } return messageText; case REVOKEROLE: dvObj = (DvObject) targetObject; dvObjURL = getDvObjectLink(dvObj); dvObjTypeStr = getDvObjectTypeString(dvObj); pattern = ResourceBundle.getBundle("Bundle").getString("notification.email.revokeRole"); String[] paramArrayRevokeRole = {dvObjTypeStr, dvObj.getDisplayName(), dvObjURL}; messageText += MessageFormat.format(pattern, paramArrayRevokeRole); return messageText; case CREATEDV: Dataverse dataverse = (Dataverse) targetObject; Dataverse parentDataverse = dataverse.getOwner(); // initialize to empty string in the rare case that there is no parent dataverse (i.e. root dataverse just created) String parentDataverseDisplayName = ""; String parentDataverseUrl = ""; if (parentDataverse != null) { parentDataverseDisplayName = parentDataverse.getDisplayName(); parentDataverseUrl = getDataverseLink(parentDataverse); } String dataverseCreatedMessage = BundleUtil.getStringFromBundle("notification.email.createDataverse", Arrays.asList( dataverse.getDisplayName(), getDataverseLink(dataverse), parentDataverseDisplayName, parentDataverseUrl, systemConfig.getGuidesBaseUrl(), systemConfig.getGuidesVersion())); logger.fine(dataverseCreatedMessage); return messageText += dataverseCreatedMessage; case REQUESTFILEACCESS: DataFile datafile = (DataFile) targetObject; pattern = ResourceBundle.getBundle("Bundle").getString("notification.email.requestFileAccess"); String[] paramArrayRequestFileAccess = {datafile.getOwner().getDisplayName(), getDatasetManageFileAccessLink(datafile)}; messageText += MessageFormat.format(pattern, paramArrayRequestFileAccess); return messageText; case GRANTFILEACCESS: dataset = (Dataset) targetObject; pattern = ResourceBundle.getBundle("Bundle").getString("notification.email.grantFileAccess"); String[] paramArrayGrantFileAccess = {dataset.getDisplayName(), getDatasetLink(dataset)}; messageText += MessageFormat.format(pattern, paramArrayGrantFileAccess); return messageText; case REJECTFILEACCESS: dataset = (Dataset) targetObject; pattern = ResourceBundle.getBundle("Bundle").getString("notification.email.rejectFileAccess"); String[] paramArrayRejectFileAccess = {dataset.getDisplayName(), getDatasetLink(dataset)}; messageText += MessageFormat.format(pattern, paramArrayRejectFileAccess); return messageText; case CREATEDS: version = (DatasetVersion) targetObject; String datasetCreatedMessage = BundleUtil.getStringFromBundle("notification.email.createDataset", Arrays.asList( version.getDataset().getDisplayName(), getDatasetLink(version.getDataset()), version.getDataset().getOwner().getDisplayName(), getDataverseLink(version.getDataset().getOwner()), systemConfig.getGuidesBaseUrl(), systemConfig.getGuidesVersion() )); logger.fine(datasetCreatedMessage); return messageText += datasetCreatedMessage; case MAPLAYERUPDATED: version = (DatasetVersion) targetObject; pattern = ResourceBundle.getBundle("Bundle").getString("notification.email.worldMap.added"); String[] paramArrayMapLayer = {version.getDataset().getDisplayName(), getDatasetLink(version.getDataset())}; messageText += MessageFormat.format(pattern, paramArrayMapLayer); return messageText; case MAPLAYERDELETEFAILED: FileMetadata targetFileMetadata = (FileMetadata) targetObject; version = targetFileMetadata.getDatasetVersion(); pattern = ResourceBundle.getBundle("Bundle").getString("notification.email.maplayer.deletefailed.text"); String[] paramArrayMapLayerDelete = {targetFileMetadata.getLabel(), getDatasetLink(version.getDataset())}; messageText += MessageFormat.format(pattern, paramArrayMapLayerDelete); return messageText; case SUBMITTEDDS: version = (DatasetVersion) targetObject; String mightHaveSubmissionComment = ""; /* FIXME Setting up to add single comment when design completed "submissionComment" needs to be added to Bundle mightHaveSubmissionComment = "."; if (comment != null && !comment.isEmpty()) { mightHaveSubmissionComment = ".\n\n" + BundleUtil.getStringFromBundle("submissionComment") + "\n\n" + comment; } */ pattern = ResourceBundle.getBundle("Bundle").getString("notification.email.wasSubmittedForReview"); String[] paramArraySubmittedDataset = {version.getDataset().getDisplayName(), getDatasetDraftLink(version.getDataset()), version.getDataset().getOwner().getDisplayName(), getDataverseLink(version.getDataset().getOwner()), mightHaveSubmissionComment}; messageText += MessageFormat.format(pattern, paramArraySubmittedDataset); return messageText; case PUBLISHEDDS: version = (DatasetVersion) targetObject; pattern = ResourceBundle.getBundle("Bundle").getString("notification.email.wasPublished"); String[] paramArrayPublishedDataset = {version.getDataset().getDisplayName(), getDatasetLink(version.getDataset()), version.getDataset().getOwner().getDisplayName(), getDataverseLink(version.getDataset().getOwner())}; messageText += MessageFormat.format(pattern, paramArrayPublishedDataset); return messageText; case RETURNEDDS: version = (DatasetVersion) targetObject; pattern = ResourceBundle.getBundle("Bundle").getString("notification.email.wasReturnedByReviewer"); String optionalReturnReason = ""; /* FIXME Setting up to add single comment when design completed optionalReturnReason = "."; if (comment != null && !comment.isEmpty()) { optionalReturnReason = ".\n\n" + BundleUtil.getStringFromBundle("wasReturnedReason") + "\n\n" + comment; } */ String[] paramArrayReturnedDataset = {version.getDataset().getDisplayName(), getDatasetDraftLink(version.getDataset()), version.getDataset().getOwner().getDisplayName(), getDataverseLink(version.getDataset().getOwner()), optionalReturnReason}; messageText += MessageFormat.format(pattern, paramArrayReturnedDataset); return messageText; case CREATEACC: String rootDataverseName = dataverseService.findRootDataverse().getName(); InternetAddress systemAddress = getSystemAddress(); String accountCreatedMessage = BundleUtil.getStringFromBundle("notification.email.welcome", Arrays.asList( BrandingUtil.getInstallationBrandName(rootDataverseName), systemConfig.getGuidesBaseUrl(), systemConfig.getGuidesVersion(), BrandingUtil.getSupportTeamName(systemAddress, rootDataverseName), BrandingUtil.getSupportTeamEmailAddress(systemAddress) )); String optionalConfirmEmailAddon = confirmEmailService.optionalConfirmEmailAddonMsg(userNotification.getUser()); accountCreatedMessage += optionalConfirmEmailAddon; logger.fine("accountCreatedMessage: " + accountCreatedMessage); return messageText += accountCreatedMessage; case CHECKSUMFAIL: dataset = (Dataset) targetObject; String checksumFailMsg = BundleUtil.getStringFromBundle("notification.checksumfail", Arrays.asList( dataset.getGlobalId() )); logger.fine("checksumFailMsg: " + checksumFailMsg); return messageText += checksumFailMsg; case FILESYSTEMIMPORT: version = (DatasetVersion) targetObject; String fileImportMsg = BundleUtil.getStringFromBundle("notification.mail.import.filesystem", Arrays.asList( systemConfig.getDataverseSiteUrl(), version.getDataset().getGlobalId(), version.getDataset().getDisplayName() )); logger.fine("fileImportMsg: " + fileImportMsg); return messageText += fileImportMsg; case CHECKSUMIMPORT: version = (DatasetVersion) targetObject; String checksumImportMsg = BundleUtil.getStringFromBundle("notification.import.checksum", Arrays.asList( version.getDataset().getGlobalId(), version.getDataset().getDisplayName() )); logger.fine("checksumImportMsg: " + checksumImportMsg); return messageText += checksumImportMsg; } return ""; } private Object getObjectOfNotification (UserNotification userNotification){ switch (userNotification.getType()) { case ASSIGNROLE: case REVOKEROLE: // Can either be a dataverse or dataset, so search both Dataverse dataverse = dataverseService.find(userNotification.getObjectId()); if (dataverse != null) { return dataverse; } Dataset dataset = datasetService.find(userNotification.getObjectId()); return dataset; case CREATEDV: return dataverseService.find(userNotification.getObjectId()); case REQUESTFILEACCESS: return dataFileService.find(userNotification.getObjectId()); case GRANTFILEACCESS: case REJECTFILEACCESS: return datasetService.find(userNotification.getObjectId()); case MAPLAYERDELETEFAILED: return dataFileService.findFileMetadata(userNotification.getObjectId()); case MAPLAYERUPDATED: case CREATEDS: case SUBMITTEDDS: case PUBLISHEDDS: case RETURNEDDS: return versionService.find(userNotification.getObjectId()); case CREATEACC: return userNotification.getUser(); case CHECKSUMFAIL: return datasetService.find(userNotification.getObjectId()); case FILESYSTEMIMPORT: return versionService.find(userNotification.getObjectId()); case CHECKSUMIMPORT: return versionService.find(userNotification.getObjectId()); } return null; } private String getUserEmailAddress(UserNotification notification) { if (notification != null) { if (notification.getUser() != null) { if (notification.getUser().getDisplayInfo() != null) { if (notification.getUser().getDisplayInfo().getEmailAddress() != null) { logger.fine("Email address: "+notification.getUser().getDisplayInfo().getEmailAddress()); return notification.getUser().getDisplayInfo().getEmailAddress(); } } } } logger.fine("no email address"); return null; } }
src/main/java/edu/harvard/iq/dataverse/MailServiceBean.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package edu.harvard.iq.dataverse; import com.sun.mail.smtp.SMTPSendFailedException; import edu.harvard.iq.dataverse.authorization.groups.Group; import edu.harvard.iq.dataverse.authorization.groups.GroupServiceBean; import edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser; import edu.harvard.iq.dataverse.branding.BrandingUtil; import edu.harvard.iq.dataverse.confirmemail.ConfirmEmailServiceBean; import edu.harvard.iq.dataverse.settings.SettingsServiceBean; import edu.harvard.iq.dataverse.settings.SettingsServiceBean.Key; import edu.harvard.iq.dataverse.util.BundleUtil; import edu.harvard.iq.dataverse.util.MailUtil; import edu.harvard.iq.dataverse.util.SystemConfig; import java.io.UnsupportedEncodingException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.Properties; import java.util.Map; import java.util.HashMap; import java.util.List; import java.util.ResourceBundle; import java.util.Set; import java.util.logging.Logger; import javax.annotation.Resource; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.mail.Address; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.apache.commons.lang.StringUtils; /** * * original author: roberttreacy */ @Stateless public class MailServiceBean implements java.io.Serializable { @EJB UserNotificationServiceBean userNotificationService; @EJB DataverseServiceBean dataverseService; @EJB DataFileServiceBean dataFileService; @EJB DatasetServiceBean datasetService; @EJB DatasetVersionServiceBean versionService; @EJB SystemConfig systemConfig; @EJB SettingsServiceBean settingsService; @EJB PermissionServiceBean permissionService; @EJB GroupServiceBean groupService; @EJB ConfirmEmailServiceBean confirmEmailService; private static final Logger logger = Logger.getLogger(MailServiceBean.class.getCanonicalName()); private static final String charset = "UTF-8"; private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; /** * Creates a new instance of MailServiceBean */ public MailServiceBean() { } public void sendMail(String host, String reply, String to, String subject, String messageText) { Properties props = System.getProperties(); props.put("mail.smtp.host", host); Session session = Session.getDefaultInstance(props, null); try { MimeMessage msg = new MimeMessage(session); String[] recipientStrings = to.split(","); InternetAddress[] recipients = new InternetAddress[recipientStrings.length]; try { InternetAddress fromAddress=getSystemAddress(); fromAddress.setPersonal(fromAddress.getPersonal() + " on behalf of " + reply, charset); msg.setFrom(fromAddress); msg.setReplyTo(new Address[] {new InternetAddress(reply, charset)}); for (int i = 0; i < recipients.length; i++) { recipients[i] = new InternetAddress(recipientStrings[i], "", charset); } } catch (UnsupportedEncodingException ex) { logger.severe(ex.getMessage()); } msg.setRecipients(Message.RecipientType.TO, recipients); msg.setSubject(subject, charset); msg.setText(messageText, charset); Transport.send(msg, recipients); } catch (AddressException ae) { ae.printStackTrace(System.out); } catch (MessagingException me) { me.printStackTrace(System.out); } } @Resource(name = "mail/notifyMailSession") private Session session; public boolean sendSystemEmail(String to, String subject, String messageText) { boolean sent = false; String rootDataverseName = dataverseService.findRootDataverse().getName(); InternetAddress systemAddress = getSystemAddress(); String body = messageText + BundleUtil.getStringFromBundle("notification.email.closing", Arrays.asList(BrandingUtil.getSupportTeamEmailAddress(systemAddress), BrandingUtil.getSupportTeamName(systemAddress, rootDataverseName))); logger.fine("Sending email to " + to + ". Subject: <<<" + subject + ">>>. Body: " + body); try { MimeMessage msg = new MimeMessage(session); if (systemAddress != null) { msg.setFrom(systemAddress); msg.setSentDate(new Date()); String[] recipientStrings = to.split(","); InternetAddress[] recipients = new InternetAddress[recipientStrings.length]; for (int i = 0; i < recipients.length; i++) { try { recipients[i] = new InternetAddress(recipientStrings[i], "", charset); } catch (UnsupportedEncodingException ex) { logger.severe(ex.getMessage()); } } msg.setRecipients(Message.RecipientType.TO, recipients); msg.setSubject(subject, charset); msg.setText(body, charset); try { Transport.send(msg, recipients); sent = true; } catch (SMTPSendFailedException ssfe) { logger.warning("Failed to send mail to: " + to); logger.warning("SMTPSendFailedException Message: " + ssfe); } } else { logger.fine("Skipping sending mail to " + to + ", because the \"no-reply\" address not set (" + Key.SystemEmail + " setting)."); } } catch (AddressException ae) { logger.warning("Failed to send mail to " + to); ae.printStackTrace(System.out); } catch (MessagingException me) { logger.warning("Failed to send mail to " + to); me.printStackTrace(System.out); } return sent; } private InternetAddress getSystemAddress() { String systemEmail = settingsService.getValueForKey(Key.SystemEmail); return MailUtil.parseSystemAddress(systemEmail); } //@Resource(name="mail/notifyMailSession") public void sendMail(String from, String to, String subject, String messageText) { sendMail(from, to, subject, messageText, new HashMap<>()); } public void sendMail(String reply, String to, String subject, String messageText, Map<Object, Object> extraHeaders) { try { MimeMessage msg = new MimeMessage(session); //Always send from system address to avoid email being blocked InternetAddress fromAddress=getSystemAddress(); try { fromAddress.setPersonal(BundleUtil.getStringFromBundle("contact.delegation", Arrays.asList( fromAddress.getPersonal(), reply)), charset); } catch (UnsupportedEncodingException ex) { logger.severe(ex.getMessage()); } msg.setFrom(fromAddress); if (reply.matches(EMAIL_PATTERN)) { //But set the reply-to address to direct replies to the requested 'from' party if it is a valid email address msg.setReplyTo(new Address[] {new InternetAddress(reply)}); } else { //Otherwise include the invalid 'from' address in the message messageText = "From: " + reply + "\n\n" + messageText; } msg.setSentDate(new Date()); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); msg.setSubject(subject, charset); msg.setText(messageText, charset); if (extraHeaders != null) { for (Object key : extraHeaders.keySet()) { String headerName = key.toString(); String headerValue = extraHeaders.get(key).toString(); msg.addHeader(headerName, headerValue); } } Transport.send(msg); } catch (AddressException ae) { ae.printStackTrace(System.out); } catch (MessagingException me) { me.printStackTrace(System.out); } } public Boolean sendNotificationEmail(UserNotification notification){ return sendNotificationEmail(notification, ""); } public Boolean sendNotificationEmail(UserNotification notification, String comment){ boolean retval = false; String emailAddress = getUserEmailAddress(notification); if (emailAddress != null){ Object objectOfNotification = getObjectOfNotification(notification); if (objectOfNotification != null){ String messageText = getMessageTextBasedOnNotification(notification, objectOfNotification); String rootDataverseName = dataverseService.findRootDataverse().getName(); String subjectText = MailUtil.getSubjectTextBasedOnNotification(notification, rootDataverseName, objectOfNotification); if (!(messageText.isEmpty() || subjectText.isEmpty())){ retval = sendSystemEmail(emailAddress, subjectText, messageText); } else { logger.warning("Skipping " + notification.getType() + " notification, because couldn't get valid message"); } } else { logger.warning("Skipping " + notification.getType() + " notification, because no valid Object was found"); } } else { logger.warning("Skipping " + notification.getType() + " notification, because email address is null"); } return retval; } private String getDatasetManageFileAccessLink(DataFile datafile){ return systemConfig.getDataverseSiteUrl() + "/permissions-manage-files.xhtml?id=" + datafile.getOwner().getId(); } private String getDatasetLink(Dataset dataset){ return systemConfig.getDataverseSiteUrl() + "/dataset.xhtml?persistentId=" + dataset.getGlobalId(); } private String getDatasetDraftLink(Dataset dataset){ return systemConfig.getDataverseSiteUrl() + "/dataset.xhtml?persistentId=" + dataset.getGlobalId() + "&version=DRAFT" + "&faces-redirect=true"; } private String getDataverseLink(Dataverse dataverse){ return systemConfig.getDataverseSiteUrl() + "/dataverse/" + dataverse.getAlias(); } /** * Returns a '/'-separated string of roles that are effective for {@code au} * over {@code dvObj}. Traverses the containment hierarchy of the {@code d}. * Takes into consideration all groups that {@code au} is part of. * @param au The authenticated user whose role assignments we look for. * @param dvObj The Dataverse object over which the roles are assigned * @return A set of all the role assignments for {@code ra} over {@code d}. */ private String getRoleStringFromUser(AuthenticatedUser au, DvObject dvObj) { // Find user's role(s) for given dataverse/dataset Set<RoleAssignment> roles = permissionService.assignmentsFor(au, dvObj); List<String> roleNames = new ArrayList<>(); // Include roles derived from a user's groups Set<Group> groupsUserBelongsTo = groupService.groupsFor(au, dvObj); for (Group g : groupsUserBelongsTo) { roles.addAll(permissionService.assignmentsFor(g, dvObj)); } for (RoleAssignment ra : roles) { roleNames.add(ra.getRole().getName()); } return StringUtils.join(roleNames, "/"); } /** * Returns the URL to a given {@code DvObject} {@code d}. If {@code d} is a * {@code DataFile}, return a link to its {@code DataSet}. * @param d The Dataverse object to get a link for. * @return A string with a URL to the given Dataverse object. */ private String getDvObjectLink(DvObject d) { if (d instanceof Dataverse) { return getDataverseLink((Dataverse) d); } else if (d instanceof Dataset) { return getDatasetLink((Dataset) d); } else if (d instanceof DataFile) { return getDatasetLink(((DataFile) d).getOwner()); } return ""; } /** * Returns string representation of the type of {@code DvObject} {@code d}. * @param d The Dataverse object to get the string for * @return A string that represents the type of a given Dataverse object. */ private String getDvObjectTypeString(DvObject d) { if (d instanceof Dataverse) { return "dataverse"; } else if (d instanceof Dataset) { return "dataset"; } else if (d instanceof DataFile) { return "data file"; } return ""; } public String getMessageTextBasedOnNotification(UserNotification userNotification, Object targetObject){ return getMessageTextBasedOnNotification(userNotification, targetObject, ""); } public String getMessageTextBasedOnNotification(UserNotification userNotification, Object targetObject, String comment){ String messageText = ResourceBundle.getBundle("Bundle").getString("notification.email.greeting"); DatasetVersion version; Dataset dataset; DvObject dvObj; String dvObjURL; String dvObjTypeStr; String pattern; switch (userNotification.getType()) { case ASSIGNROLE: AuthenticatedUser au = userNotification.getUser(); dvObj = (DvObject) targetObject; String joinedRoleNames = getRoleStringFromUser(au, dvObj); dvObjURL = getDvObjectLink(dvObj); dvObjTypeStr = getDvObjectTypeString(dvObj); pattern = ResourceBundle.getBundle("Bundle").getString("notification.email.assignRole"); String[] paramArrayAssignRole = {joinedRoleNames, dvObjTypeStr, dvObj.getDisplayName(), dvObjURL}; messageText += MessageFormat.format(pattern, paramArrayAssignRole); if (joinedRoleNames.contains("File Downloader")){ if (dvObjTypeStr.equals("dataset")){ pattern = ResourceBundle.getBundle("Bundle").getString("notification.access.granted.fileDownloader.additionalDataset"); String[] paramArrayAssignRoleDS = {" "}; messageText += MessageFormat.format(pattern, paramArrayAssignRoleDS); } if (dvObjTypeStr.equals("dataverse")){ pattern = ResourceBundle.getBundle("Bundle").getString("notification.access.granted.fileDownloader.additionalDataverse"); String[] paramArrayAssignRoleDV = {" "}; messageText += MessageFormat.format(pattern, paramArrayAssignRoleDV); } } return messageText; case REVOKEROLE: dvObj = (DvObject) targetObject; dvObjURL = getDvObjectLink(dvObj); dvObjTypeStr = getDvObjectTypeString(dvObj); pattern = ResourceBundle.getBundle("Bundle").getString("notification.email.revokeRole"); String[] paramArrayRevokeRole = {dvObjTypeStr, dvObj.getDisplayName(), dvObjURL}; messageText += MessageFormat.format(pattern, paramArrayRevokeRole); return messageText; case CREATEDV: Dataverse dataverse = (Dataverse) targetObject; Dataverse parentDataverse = dataverse.getOwner(); // initialize to empty string in the rare case that there is no parent dataverse (i.e. root dataverse just created) String parentDataverseDisplayName = ""; String parentDataverseUrl = ""; if (parentDataverse != null) { parentDataverseDisplayName = parentDataverse.getDisplayName(); parentDataverseUrl = getDataverseLink(parentDataverse); } String dataverseCreatedMessage = BundleUtil.getStringFromBundle("notification.email.createDataverse", Arrays.asList( dataverse.getDisplayName(), getDataverseLink(dataverse), parentDataverseDisplayName, parentDataverseUrl, systemConfig.getGuidesBaseUrl(), systemConfig.getGuidesVersion())); logger.fine(dataverseCreatedMessage); return messageText += dataverseCreatedMessage; case REQUESTFILEACCESS: DataFile datafile = (DataFile) targetObject; pattern = ResourceBundle.getBundle("Bundle").getString("notification.email.requestFileAccess"); String[] paramArrayRequestFileAccess = {datafile.getOwner().getDisplayName(), getDatasetManageFileAccessLink(datafile)}; messageText += MessageFormat.format(pattern, paramArrayRequestFileAccess); return messageText; case GRANTFILEACCESS: dataset = (Dataset) targetObject; pattern = ResourceBundle.getBundle("Bundle").getString("notification.email.grantFileAccess"); String[] paramArrayGrantFileAccess = {dataset.getDisplayName(), getDatasetLink(dataset)}; messageText += MessageFormat.format(pattern, paramArrayGrantFileAccess); return messageText; case REJECTFILEACCESS: dataset = (Dataset) targetObject; pattern = ResourceBundle.getBundle("Bundle").getString("notification.email.rejectFileAccess"); String[] paramArrayRejectFileAccess = {dataset.getDisplayName(), getDatasetLink(dataset)}; messageText += MessageFormat.format(pattern, paramArrayRejectFileAccess); return messageText; case CREATEDS: version = (DatasetVersion) targetObject; String datasetCreatedMessage = BundleUtil.getStringFromBundle("notification.email.createDataset", Arrays.asList( version.getDataset().getDisplayName(), getDatasetLink(version.getDataset()), version.getDataset().getOwner().getDisplayName(), getDataverseLink(version.getDataset().getOwner()), systemConfig.getGuidesBaseUrl(), systemConfig.getGuidesVersion() )); logger.fine(datasetCreatedMessage); return messageText += datasetCreatedMessage; case MAPLAYERUPDATED: version = (DatasetVersion) targetObject; pattern = ResourceBundle.getBundle("Bundle").getString("notification.email.worldMap.added"); String[] paramArrayMapLayer = {version.getDataset().getDisplayName(), getDatasetLink(version.getDataset())}; messageText += MessageFormat.format(pattern, paramArrayMapLayer); return messageText; case MAPLAYERDELETEFAILED: FileMetadata targetFileMetadata = (FileMetadata) targetObject; version = targetFileMetadata.getDatasetVersion(); pattern = ResourceBundle.getBundle("Bundle").getString("notification.email.maplayer.deletefailed.text"); String[] paramArrayMapLayerDelete = {targetFileMetadata.getLabel(), getDatasetLink(version.getDataset())}; messageText += MessageFormat.format(pattern, paramArrayMapLayerDelete); return messageText; case SUBMITTEDDS: version = (DatasetVersion) targetObject; String mightHaveSubmissionComment = ""; /* FIXME Setting up to add single comment when design completed "submissionComment" needs to be added to Bundle mightHaveSubmissionComment = "."; if (comment != null && !comment.isEmpty()) { mightHaveSubmissionComment = ".\n\n" + BundleUtil.getStringFromBundle("submissionComment") + "\n\n" + comment; } */ pattern = ResourceBundle.getBundle("Bundle").getString("notification.email.wasSubmittedForReview"); String[] paramArraySubmittedDataset = {version.getDataset().getDisplayName(), getDatasetDraftLink(version.getDataset()), version.getDataset().getOwner().getDisplayName(), getDataverseLink(version.getDataset().getOwner()), mightHaveSubmissionComment}; messageText += MessageFormat.format(pattern, paramArraySubmittedDataset); return messageText; case PUBLISHEDDS: version = (DatasetVersion) targetObject; pattern = ResourceBundle.getBundle("Bundle").getString("notification.email.wasPublished"); String[] paramArrayPublishedDataset = {version.getDataset().getDisplayName(), getDatasetLink(version.getDataset()), version.getDataset().getOwner().getDisplayName(), getDataverseLink(version.getDataset().getOwner())}; messageText += MessageFormat.format(pattern, paramArrayPublishedDataset); return messageText; case RETURNEDDS: version = (DatasetVersion) targetObject; pattern = ResourceBundle.getBundle("Bundle").getString("notification.email.wasReturnedByReviewer"); String optionalReturnReason = ""; /* FIXME Setting up to add single comment when design completed optionalReturnReason = "."; if (comment != null && !comment.isEmpty()) { optionalReturnReason = ".\n\n" + BundleUtil.getStringFromBundle("wasReturnedReason") + "\n\n" + comment; } */ String[] paramArrayReturnedDataset = {version.getDataset().getDisplayName(), getDatasetDraftLink(version.getDataset()), version.getDataset().getOwner().getDisplayName(), getDataverseLink(version.getDataset().getOwner()), optionalReturnReason}; messageText += MessageFormat.format(pattern, paramArrayReturnedDataset); return messageText; case CREATEACC: String rootDataverseName = dataverseService.findRootDataverse().getName(); InternetAddress systemAddress = getSystemAddress(); String accountCreatedMessage = BundleUtil.getStringFromBundle("notification.email.welcome", Arrays.asList( BrandingUtil.getInstallationBrandName(rootDataverseName), systemConfig.getGuidesBaseUrl(), systemConfig.getGuidesVersion(), BrandingUtil.getSupportTeamName(systemAddress, rootDataverseName), BrandingUtil.getSupportTeamEmailAddress(systemAddress) )); String optionalConfirmEmailAddon = confirmEmailService.optionalConfirmEmailAddonMsg(userNotification.getUser()); accountCreatedMessage += optionalConfirmEmailAddon; logger.fine("accountCreatedMessage: " + accountCreatedMessage); return messageText += accountCreatedMessage; case CHECKSUMFAIL: dataset = (Dataset) targetObject; String checksumFailMsg = BundleUtil.getStringFromBundle("notification.checksumfail", Arrays.asList( dataset.getGlobalId() )); logger.fine("checksumFailMsg: " + checksumFailMsg); return messageText += checksumFailMsg; case FILESYSTEMIMPORT: version = (DatasetVersion) targetObject; String fileImportMsg = BundleUtil.getStringFromBundle("notification.mail.import.filesystem", Arrays.asList( systemConfig.getDataverseSiteUrl(), version.getDataset().getGlobalId(), version.getDataset().getDisplayName() )); logger.fine("fileImportMsg: " + fileImportMsg); return messageText += fileImportMsg; case CHECKSUMIMPORT: version = (DatasetVersion) targetObject; String checksumImportMsg = BundleUtil.getStringFromBundle("notification.import.checksum", Arrays.asList( version.getDataset().getGlobalId(), version.getDataset().getDisplayName() )); logger.fine("checksumImportMsg: " + checksumImportMsg); return messageText += checksumImportMsg; } return ""; } private Object getObjectOfNotification (UserNotification userNotification){ switch (userNotification.getType()) { case ASSIGNROLE: case REVOKEROLE: // Can either be a dataverse or dataset, so search both Dataverse dataverse = dataverseService.find(userNotification.getObjectId()); if (dataverse != null) { return dataverse; } Dataset dataset = datasetService.find(userNotification.getObjectId()); return dataset; case CREATEDV: return dataverseService.find(userNotification.getObjectId()); case REQUESTFILEACCESS: return dataFileService.find(userNotification.getObjectId()); case GRANTFILEACCESS: case REJECTFILEACCESS: return datasetService.find(userNotification.getObjectId()); case MAPLAYERDELETEFAILED: return dataFileService.findFileMetadata(userNotification.getObjectId()); case MAPLAYERUPDATED: case CREATEDS: case SUBMITTEDDS: case PUBLISHEDDS: case RETURNEDDS: return versionService.find(userNotification.getObjectId()); case CREATEACC: return userNotification.getUser(); case CHECKSUMFAIL: return datasetService.find(userNotification.getObjectId()); case FILESYSTEMIMPORT: return versionService.find(userNotification.getObjectId()); case CHECKSUMIMPORT: return versionService.find(userNotification.getObjectId()); } return null; } private String getUserEmailAddress(UserNotification notification) { if (notification != null) { if (notification.getUser() != null) { if (notification.getUser().getDisplayInfo() != null) { if (notification.getUser().getDisplayInfo().getEmailAddress() != null) { logger.fine("Email address: "+notification.getUser().getDisplayInfo().getEmailAddress()); return notification.getUser().getDisplayInfo().getEmailAddress(); } } } } logger.fine("no email address"); return null; } }
use bundle in 'unused' method as well
src/main/java/edu/harvard/iq/dataverse/MailServiceBean.java
use bundle in 'unused' method as well
<ide><path>rc/main/java/edu/harvard/iq/dataverse/MailServiceBean.java <ide> InternetAddress[] recipients = new InternetAddress[recipientStrings.length]; <ide> try { <ide> InternetAddress fromAddress=getSystemAddress(); <del> fromAddress.setPersonal(fromAddress.getPersonal() + " on behalf of " + reply, charset); <add> fromAddress.setPersonal(BundleUtil.getStringFromBundle("contact.delegation", Arrays.asList( <add> fromAddress.getPersonal(), reply)), charset); <ide> msg.setFrom(fromAddress); <ide> msg.setReplyTo(new Address[] {new InternetAddress(reply, charset)}); <ide> for (int i = 0; i < recipients.length; i++) {
Java
mit
e3a5da4b50cd01ebc6b7f213c52c764503811c4a
0
DiamondSwordDev/moddle
package com.dsdev.assets; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import java.io.*; import java.net.URL; import org.apache.commons.io.FileUtils; import com.dsdev.moddle.*; /** * This class contains all of the tools required to build and maintain a copy of * the Minecraft assets. * * @author Nathan2055 */ public class AssetBuilder { /** * Checks to see if the assets needs updating, and if so, updates them. * * @param directory A String representing the directory where the assets * should be created. * @throws java.io.IOException */ public static void updateAssets(String directory) throws IOException { } /** * This method builds a fresh copy of the Minecraft assets in the provided * directory. If the directory already exists, it is deleted. * * @param directory A String representing the directory where the assets * should be created. * @throws java.io.IOException */ private static void buildAssets(String directory) throws IOException { // Ensure they added a / at the end like they were supposed to and if not try and fix it String finalChar = directory.substring(directory.length() - 1); if (!finalChar.equals("/")) { Logger.warning("Assets", "A slash was not added at the end of the asset output directory. Attempting to fix..."); directory = directory + "/"; } Logger.info("Assets", "Building Minecraft assets at " + directory); // Let's start by setting up the stuff we're gonna need Logger.info("Assets", "Setting up folders..."); File assetFolder = new File(directory); try { FileUtils.deleteDirectory(assetFolder); Logger.info("Assets", "Deleting existing assets..."); } catch (IOException e) { // Folder already exists } assetFolder.mkdir(); File assetFolderLegacy = new File(directory + "/legacy"); assetFolderLegacy.mkdir(); // Now let's download the version definition file from Mojang and store it in a temporary file Logger.info("Assets", "Fetching asset definition file..."); File defFile = File.createTempFile("assets", ".json"); URL defWeb = new URL("https://s3.amazonaws.com/Minecraft.Download/indexes/legacy.json"); FileUtils.copyURLToFile(defWeb, defFile); Logger.info("Assets", "Saving asset definition file..."); File defFileSaved = new File(directory + "assetDef.json"); FileUtils.copyFile(defFile, defFileSaved); // And now we parse... Logger.info("Assets", "String asset download..."); String defString = FileUtils.readFileToString(defFile); StringReader defReader = new StringReader(defString); JsonReader reader = new JsonReader(defReader); try { reader.beginObject(); reader.nextName(); reader.nextBoolean(); reader.nextName(); reader.beginObject(); boolean newFile = true; while (newFile) { String assetName = reader.nextName(); reader.beginObject(); reader.nextName(); String hash = reader.nextString(); String subhash = hash.substring(0, 2); Logger.info("Assets", "Downloading " + assetName + "..."); URL asset = new URL("http://resources.download.minecraft.net/" + subhash + "/" + hash); File assetDest = new File(directory + "modern/" + subhash + "/" + hash); FileUtils.copyURLToFile(asset, assetDest); assetDest = new File(directory + "legacy/" + assetName); FileUtils.copyURLToFile(asset, assetDest); reader.nextName(); reader.nextInt(); reader.endObject(); JsonToken next = reader.peek(); newFile = next == JsonToken.NAME; } reader.endObject(); } finally { reader.close(); Logger.info("Assets", "Asset download completed"); } Logger.info("Assets", "Deleting tempfiles..."); boolean deleted = defFile.delete(); if (!deleted) { Logger.warning("Assets", "Tempfile " + defFile.getAbsolutePath() + " failed to delete. Scheduling deletion upon termination of Moddle..."); defFile.deleteOnExit(); } } /** * Checks the assetDef.json's SHA-512 against a fresh copy from Mojang's * servers to determine if it's up-to-date. * * @param directory A String representing the directory where the assets * should be created. MAKE SURE THAT IT ENDS WITH A / CHARCTER OR THIS CODE * WILL GO BOOM! * @return A boolean representing whether the assets are up-to-date or not. * @throws java.io.IOException */ private static boolean assetsUpdateRequired(String directory) throws IOException { Logger.info("Assets Checker", "Fetching asset definition file..."); File defFileCurrent = File.createTempFile("assets", ".json"); URL defWeb = new URL("https://s3.amazonaws.com/Minecraft.Download/indexes/legacy.json"); FileUtils.copyURLToFile(defWeb, defFileCurrent); File defFileExisting = new File(directory + "assetDef.json"); if (defFileExisting.exists() && defFileExisting.isFile()) { } return false; } }
src/com/dsdev/assets/AssetBuilder.java
package com.dsdev.assets; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import java.io.*; import java.net.URL; import org.apache.commons.io.FileUtils; import com.dsdev.moddle.*; /** * This class contains all of the tools required to build and maintain a copy of * the Minecraft assets. * * @author Nathan2055 */ public class AssetBuilder { /** * This method builds a fresh copy of the Minecraft assets in the provided * directory. If the directory already exists, it is deleted. * * @param directory A String representing the directory where the assets * should be created. MAKE SURE THAT IT ENDS WITH A / CHARCTER OR THIS CODE * WILL GO BOOM! * @throws java.io.IOException */ public static void buildAssets(String directory) throws IOException { Logger.info("Assets", "Building Minecraft assets at " + directory); // Let's start by setting up the stuff we're gonna need Logger.info("Assets", "Setting up folders..."); File assetFolder = new File(directory); try { FileUtils.deleteDirectory(assetFolder); Logger.info("Assets", "Deleting existing folder..."); } catch (IOException e) { Logger.info("Assets", "Folder exists. Skipping deletion..."); } assetFolder.mkdir(); File assetFolderLegacy = new File(directory + "/legacy"); assetFolderLegacy.mkdir(); // Now let's download the version definition file from Mojang and store it in a temporary file Logger.info("Assets", "Fetching asset definition file..."); File defFile = File.createTempFile("assets", ".json"); URL defWeb = new URL("https://s3.amazonaws.com/Minecraft.Download/indexes/legacy.json"); FileUtils.copyURLToFile(defWeb, defFile); Logger.info("Assets", "Saving asset definition file..."); File defFileSaved = new File(directory + "assetDef.json"); FileUtils.copyFile(defFile, defFileSaved); // And now we parse... Logger.info("Assets", "String asset download..."); String defString = FileUtils.readFileToString(defFile); StringReader defReader = new StringReader(defString); JsonReader reader = new JsonReader(defReader); try { reader.beginObject(); reader.nextName(); reader.nextBoolean(); reader.nextName(); reader.beginObject(); boolean newFile = true; while (newFile) { String assetName = reader.nextName(); reader.beginObject(); reader.nextName(); String hash = reader.nextString(); String subhash = hash.substring(0, 2); Logger.info("Assets", "Downloading " + assetName + "..."); URL asset = new URL("http://resources.download.minecraft.net/" + subhash + "/" + hash); File assetDest = new File(directory + "modern/" + subhash + "/" + hash); FileUtils.copyURLToFile(asset, assetDest); assetDest = new File(directory + "legacy/" + assetName); FileUtils.copyURLToFile(asset, assetDest); reader.nextName(); reader.nextInt(); reader.endObject(); JsonToken next = reader.peek(); newFile = next == JsonToken.NAME; } reader.endObject(); } finally { reader.close(); Logger.info("Assets", "Asset download completed."); } } /** * Checks the assetDef.json's SHA-512 against a fresh copy from Mojang's * servers to determine if it's up-to-date. * * @param directory A String representing the directory where the assets * should be created. MAKE SURE THAT IT ENDS WITH A / CHARCTER OR THIS CODE * WILL GO BOOM! * @return A boolean representing whether the assets are up-to-date or not. * @throws java.io.IOException */ public static boolean assetsUpdateRequired(String directory) throws IOException { Logger.info("Assets Checker", "Fetching asset definition file..."); File defFileCurrent = File.createTempFile("assets", ".json"); URL defWeb = new URL("https://s3.amazonaws.com/Minecraft.Download/indexes/legacy.json"); FileUtils.copyURLToFile(defWeb, defFileCurrent); File defFileExisting = new File(directory + "assetDef.json"); if (defFileExisting.exists() && defFileExisting.isFile()) { } return false; } }
Continuing to refactor assets #5, Fixed #16 Signed-off-by:Nathan2055 <[email protected]>
src/com/dsdev/assets/AssetBuilder.java
Continuing to refactor assets
<ide><path>rc/com/dsdev/assets/AssetBuilder.java <ide> public class AssetBuilder { <ide> <ide> /** <add> * Checks to see if the assets needs updating, and if so, updates them. <add> * <add> * @param directory A String representing the directory where the assets <add> * should be created. <add> * @throws java.io.IOException <add> */ <add> public static void updateAssets(String directory) throws IOException { <add> <add> } <add> <add> /** <ide> * This method builds a fresh copy of the Minecraft assets in the provided <ide> * directory. If the directory already exists, it is deleted. <ide> * <ide> * @param directory A String representing the directory where the assets <del> * should be created. MAKE SURE THAT IT ENDS WITH A / CHARCTER OR THIS CODE <del> * WILL GO BOOM! <add> * should be created. <ide> * @throws java.io.IOException <ide> */ <del> public static void buildAssets(String directory) throws IOException { <add> private static void buildAssets(String directory) throws IOException { <add> // Ensure they added a / at the end like they were supposed to and if not try and fix it <add> String finalChar = directory.substring(directory.length() - 1); <add> if (!finalChar.equals("/")) { <add> Logger.warning("Assets", "A slash was not added at the end of the asset output directory. Attempting to fix..."); <add> directory = directory + "/"; <add> } <add> <ide> Logger.info("Assets", "Building Minecraft assets at " + directory); <ide> <ide> // Let's start by setting up the stuff we're gonna need <ide> File assetFolder = new File(directory); <ide> try { <ide> FileUtils.deleteDirectory(assetFolder); <del> Logger.info("Assets", "Deleting existing folder..."); <add> Logger.info("Assets", "Deleting existing assets..."); <ide> } catch (IOException e) { <del> Logger.info("Assets", "Folder exists. Skipping deletion..."); <add> // Folder already exists <ide> } <ide> assetFolder.mkdir(); <ide> File assetFolderLegacy = new File(directory + "/legacy"); <ide> reader.endObject(); <ide> } finally { <ide> reader.close(); <del> Logger.info("Assets", "Asset download completed."); <add> Logger.info("Assets", "Asset download completed"); <ide> } <del> <add> <add> Logger.info("Assets", "Deleting tempfiles..."); <add> boolean deleted = defFile.delete(); <add> if (!deleted) { <add> Logger.warning("Assets", "Tempfile " + defFile.getAbsolutePath() + " failed to delete. Scheduling deletion upon termination of Moddle..."); <add> defFile.deleteOnExit(); <add> } <ide> } <ide> <ide> /** <ide> * @return A boolean representing whether the assets are up-to-date or not. <ide> * @throws java.io.IOException <ide> */ <del> public static boolean assetsUpdateRequired(String directory) throws IOException { <add> private static boolean assetsUpdateRequired(String directory) throws IOException { <ide> Logger.info("Assets Checker", "Fetching asset definition file..."); <ide> File defFileCurrent = File.createTempFile("assets", ".json"); <ide> URL defWeb = new URL("https://s3.amazonaws.com/Minecraft.Download/indexes/legacy.json");
Java
bsd-3-clause
af14bea53b3b628e66715a66f55b871fff4812c6
0
CBIIT/caaers,CBIIT/caaers,NCIP/caaers,CBIIT/caaers,CBIIT/caaers,CBIIT/caaers,NCIP/caaers,NCIP/caaers,NCIP/caaers
package gov.nih.nci.cabig.caaers.security; import gov.nih.nci.cagrid.common.Utils; import java.io.StringReader; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; import org.acegisecurity.AuthenticationException; import org.acegisecurity.providers.cas.CasAuthoritiesPopulator; import org.acegisecurity.userdetails.UserDetails; import org.acegisecurity.userdetails.UserDetailsService; import org.apache.log4j.Logger; import org.cagrid.gaards.cds.client.CredentialDelegationServiceClient; import org.cagrid.gaards.cds.client.DelegatedCredentialUserClient; import org.cagrid.gaards.cds.delegated.stubs.types.DelegatedCredentialReference; import org.globus.gsi.GlobusCredential; import org.springframework.beans.factory.annotation.Required; /** * Will create a WebSSOUser object from CAS assertion <p/> Created by IntelliJ IDEA. User: kherm * Date: Dec 11, 2007 Time: 6:59:57 PM To change this template use File | Settings | File Templates. */ public class WebSSOAuthoritiesPopulator implements CasAuthoritiesPopulator { private UserDetailsService userDetailsService; public static final String ATTRIBUTE_DELIMITER = "$"; public static final String KEY_VALUE_PAIR_DELIMITER = "^"; // public static final String CCTS_USER_ID_KEY = "CAGRID_SSO_EMAIL_ID"; public static final String CAGRID_SSO_FIRST_NAME = "CAGRID_SSO_FIRST_NAME"; public static final String CAGRID_SSO_LAST_NAME = "CAGRID_SSO_LAST_NAME"; public static final String CAGRID_SSO_GRID_IDENTITY = "CAGRID_SSO_GRID_IDENTITY"; public static final String CAGRID_SSO_DELEGATION_SERVICE_EPR = "CAGRID_SSO_DELEGATION_SERVICE_EPR"; Logger log = Logger.getLogger(WebSSOAuthoritiesPopulator.class); private String hostCertificate; private String hostKey; /** * Obtains the granted authorities for the specified user. * <P> * May throw any <code>AuthenticationException</code> or return <code>null</code> if the * authorities are unavailable. * </p> * * @param casUserId * as obtained from the webSSO CAS validation service * @return the details of the indicated user (at minimum the granted authorities and the * username) * @throws org.acegisecurity.AuthenticationException * DOCUMENT ME! */ public UserDetails getUserDetails(String casUserId) throws AuthenticationException { Map<String, String> attrMap = new HashMap<String, String>(); StringTokenizer stringTokenizer = new StringTokenizer(casUserId, ATTRIBUTE_DELIMITER); while (stringTokenizer.hasMoreTokens()) { String attributeKeyValuePair = stringTokenizer.nextToken(); attrMap.put(attributeKeyValuePair.substring(0, attributeKeyValuePair .indexOf(KEY_VALUE_PAIR_DELIMITER)), attributeKeyValuePair.substring( attributeKeyValuePair.indexOf(KEY_VALUE_PAIR_DELIMITER) + 1, attributeKeyValuePair.length())); } String gridIdentity = attrMap.get(CAGRID_SSO_GRID_IDENTITY); String userName = ""; if (gridIdentity != null) { userName = gridIdentity.substring(gridIdentity.indexOf("/CN=")+4, gridIdentity.length()); } else { log.error(CAGRID_SSO_GRID_IDENTITY + " is null"); } //WebSSOUser user = new WebSSOUser(userDetailsService.loadUserByUsername(attrMap.get(CCTS_USER_ID_KEY))); WebSSOUser user = new WebSSOUser(userDetailsService.loadUserByUsername(userName)); // user.setGridId(attrMap.get(CCTS_USER_ID_KEY)); user.setGridId(userName); user.setDelegatedEPR(attrMap.get(CAGRID_SSO_DELEGATION_SERVICE_EPR)); user.setFirstName(attrMap.get(CAGRID_SSO_FIRST_NAME)); user.setLastName(attrMap.get(CAGRID_SSO_LAST_NAME)); // Get the delegated credential and store it in the UserDetails object // This will be available later in the Authenticaiton object try { GlobusCredential hostCredential = new GlobusCredential(hostCertificate, hostKey); DelegatedCredentialReference delegatedCredentialReference = (DelegatedCredentialReference) Utils .deserializeObject( new StringReader(attrMap .get(CAGRID_SSO_DELEGATION_SERVICE_EPR)), DelegatedCredentialReference.class, CredentialDelegationServiceClient.class .getResourceAsStream("client-config.wsdd")); DelegatedCredentialUserClient delegatedCredentialUserClient = new DelegatedCredentialUserClient( delegatedCredentialReference, hostCredential); GlobusCredential userCredential = delegatedCredentialUserClient .getDelegatedCredential(); user.setGridCredential(userCredential); } catch (Exception e) { // just log it and move on for now log.error("Could not retreive user credential from CDS service", e); } return user; } public UserDetailsService getUserDetailsService() { return userDetailsService; } @Required public void setUserDetailsService(UserDetailsService userDetailsService) { this.userDetailsService = userDetailsService; } public String getHostCertificate() { return hostCertificate; } public void setHostCertificate(String hostCertificate) { this.hostCertificate = hostCertificate; } public String getHostKey() { return hostKey; } public void setHostKey(String hostKey) { this.hostKey = hostKey; } }
projects/core/src/main/java/gov/nih/nci/cabig/caaers/security/WebSSOAuthoritiesPopulator.java
package gov.nih.nci.cabig.caaers.security; import java.util.Map; import java.util.HashMap; import java.util.StringTokenizer; import java.io.StringReader; import gov.nih.nci.cagrid.common.Utils; import org.acegisecurity.AuthenticationException; import org.acegisecurity.providers.cas.CasAuthoritiesPopulator; import org.acegisecurity.userdetails.UserDetails; import org.acegisecurity.userdetails.UserDetailsService; import org.apache.log4j.Logger; import org.cagrid.gaards.cds.client.CredentialDelegationServiceClient; import org.cagrid.gaards.cds.client.DelegatedCredentialUserClient; import org.cagrid.gaards.cds.delegated.stubs.types.DelegatedCredentialReference; import org.globus.gsi.GlobusCredential; import org.springframework.beans.factory.annotation.Required; import java.io.StringReader; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; /** * Will create a WebSSOUser object from CAS assertion <p/> Created by IntelliJ IDEA. User: kherm * Date: Dec 11, 2007 Time: 6:59:57 PM To change this template use File | Settings | File Templates. */ public class WebSSOAuthoritiesPopulator implements CasAuthoritiesPopulator { private UserDetailsService userDetailsService; public static final String ATTRIBUTE_DELIMITER = "$"; public static final String KEY_VALUE_PAIR_DELIMITER = "^"; public static final String CCTS_USER_ID_KEY = "CAGRID_SSO_EMAIL_ID"; public static final String CAGRID_SSO_FIRST_NAME = "CAGRID_SSO_FIRST_NAME"; public static final String CAGRID_SSO_LAST_NAME = "CAGRID_SSO_LAST_NAME"; public static final String CAGRID_SSO_GRID_IDENTITY = "CAGRID_SSO_GRID_IDENTITY"; public static final String CAGRID_SSO_DELEGATION_SERVICE_EPR = "CAGRID_SSO_DELEGATION_SERVICE_EPR"; Logger log = Logger.getLogger(WebSSOAuthoritiesPopulator.class); private String hostCertificate; private String hostKey; /** * Obtains the granted authorities for the specified user. * <P> * May throw any <code>AuthenticationException</code> or return <code>null</code> if the * authorities are unavailable. * </p> * * @param casUserId * as obtained from the webSSO CAS validation service * @return the details of the indicated user (at minimum the granted authorities and the * username) * @throws org.acegisecurity.AuthenticationException * DOCUMENT ME! */ public UserDetails getUserDetails(String casUserId) throws AuthenticationException { Map<String, String> attrMap = new HashMap<String, String>(); StringTokenizer stringTokenizer = new StringTokenizer(casUserId, ATTRIBUTE_DELIMITER); while (stringTokenizer.hasMoreTokens()) { String attributeKeyValuePair = stringTokenizer.nextToken(); attrMap.put(attributeKeyValuePair.substring(0, attributeKeyValuePair .indexOf(KEY_VALUE_PAIR_DELIMITER)), attributeKeyValuePair.substring( attributeKeyValuePair.indexOf(KEY_VALUE_PAIR_DELIMITER) + 1, attributeKeyValuePair.length())); } WebSSOUser user = new WebSSOUser(userDetailsService.loadUserByUsername(attrMap .get(CCTS_USER_ID_KEY))); user.setGridId(attrMap.get(CCTS_USER_ID_KEY)); user.setDelegatedEPR(attrMap.get(CAGRID_SSO_DELEGATION_SERVICE_EPR)); user.setFirstName(attrMap.get(CAGRID_SSO_FIRST_NAME)); user.setLastName(attrMap.get(CAGRID_SSO_LAST_NAME)); // Get the delegated credential and store it in the UserDetails object // This will be available later in the Authenticaiton object try { GlobusCredential hostCredential = new GlobusCredential(hostCertificate, hostKey); DelegatedCredentialReference delegatedCredentialReference = (DelegatedCredentialReference) Utils .deserializeObject( new StringReader(attrMap .get(CAGRID_SSO_DELEGATION_SERVICE_EPR)), DelegatedCredentialReference.class, CredentialDelegationServiceClient.class .getResourceAsStream("client-config.wsdd")); DelegatedCredentialUserClient delegatedCredentialUserClient = new DelegatedCredentialUserClient( delegatedCredentialReference, hostCredential); GlobusCredential userCredential = delegatedCredentialUserClient .getDelegatedCredential(); user.setGridCredential(userCredential); } catch (Exception e) { // just log it and move on for now log.error("Could not retreive user credential from CDS service", e); } return user; } public UserDetailsService getUserDetailsService() { return userDetailsService; } @Required public void setUserDetailsService(UserDetailsService userDetailsService) { this.userDetailsService = userDetailsService; } public String getHostCertificate() { return hostCertificate; } public void setHostCertificate(String hostCertificate) { this.hostCertificate = hostCertificate; } public String getHostKey() { return hostKey; } public void setHostKey(String hostKey) { this.hostKey = hostKey; } }
extracting user id from CAGRID_SSO_GRID_IDENTITY SVN-Revision: 6463
projects/core/src/main/java/gov/nih/nci/cabig/caaers/security/WebSSOAuthoritiesPopulator.java
extracting user id from CAGRID_SSO_GRID_IDENTITY
<ide><path>rojects/core/src/main/java/gov/nih/nci/cabig/caaers/security/WebSSOAuthoritiesPopulator.java <ide> package gov.nih.nci.cabig.caaers.security; <ide> <add>import gov.nih.nci.cagrid.common.Utils; <add> <add>import java.io.StringReader; <add>import java.util.HashMap; <ide> import java.util.Map; <del>import java.util.HashMap; <ide> import java.util.StringTokenizer; <del>import java.io.StringReader; <ide> <del>import gov.nih.nci.cagrid.common.Utils; <ide> import org.acegisecurity.AuthenticationException; <ide> import org.acegisecurity.providers.cas.CasAuthoritiesPopulator; <ide> import org.acegisecurity.userdetails.UserDetails; <ide> import org.cagrid.gaards.cds.delegated.stubs.types.DelegatedCredentialReference; <ide> import org.globus.gsi.GlobusCredential; <ide> import org.springframework.beans.factory.annotation.Required; <del> <del>import java.io.StringReader; <del>import java.util.HashMap; <del>import java.util.Map; <del>import java.util.StringTokenizer; <ide> <ide> /** <ide> * Will create a WebSSOUser object from CAS assertion <p/> Created by IntelliJ IDEA. User: kherm <ide> <ide> public static final String KEY_VALUE_PAIR_DELIMITER = "^"; <ide> <del> public static final String CCTS_USER_ID_KEY = "CAGRID_SSO_EMAIL_ID"; <add> // public static final String CCTS_USER_ID_KEY = "CAGRID_SSO_EMAIL_ID"; <ide> <ide> public static final String CAGRID_SSO_FIRST_NAME = "CAGRID_SSO_FIRST_NAME"; <ide> <ide> attributeKeyValuePair.indexOf(KEY_VALUE_PAIR_DELIMITER) + 1, <ide> attributeKeyValuePair.length())); <ide> } <add> <add> String gridIdentity = attrMap.get(CAGRID_SSO_GRID_IDENTITY); <add> String userName = ""; <add> if (gridIdentity != null) { <add> userName = gridIdentity.substring(gridIdentity.indexOf("/CN=")+4, gridIdentity.length()); <add> } else { <add> log.error(CAGRID_SSO_GRID_IDENTITY + " is null"); <add> } <ide> <del> WebSSOUser user = new WebSSOUser(userDetailsService.loadUserByUsername(attrMap <del> .get(CCTS_USER_ID_KEY))); <del> user.setGridId(attrMap.get(CCTS_USER_ID_KEY)); <add> //WebSSOUser user = new WebSSOUser(userDetailsService.loadUserByUsername(attrMap.get(CCTS_USER_ID_KEY))); <add> WebSSOUser user = new WebSSOUser(userDetailsService.loadUserByUsername(userName)); <add> <add> // user.setGridId(attrMap.get(CCTS_USER_ID_KEY)); <add> user.setGridId(userName); <ide> user.setDelegatedEPR(attrMap.get(CAGRID_SSO_DELEGATION_SERVICE_EPR)); <ide> user.setFirstName(attrMap.get(CAGRID_SSO_FIRST_NAME)); <ide> user.setLastName(attrMap.get(CAGRID_SSO_LAST_NAME));
Java
unlicense
fd4bdf1ccb3d420db4c28a0edea5db6dc6ff62fe
0
errorPort3R/CodeSnipper,errorPort3R/CodeSnipper
package sample.View; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.layout.ColumnConstraints; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.text.Text; import javafx.stage.Stage; import sample.Controller.Controller; import sample.Model.CodeSection; import java.util.ArrayList; import java.util.Optional; import static javafx.scene.input.KeyCode.H; /** * Created by jeffryporter on 8/30/16. */ public class DisplayResults implements EventHandler<ActionEvent> { private Stage theStage; private TableView<CodeSection> snippetList = new TableView<>(); ObservableList<CodeSection> olCodeSearchList; private CodeSection snippet; private Button viewBtn; private Button updateBtn; private Button deleteBtn; private Button cancelBtn; public class updateButtonHandler implements EventHandler<ActionEvent> { public void handle(ActionEvent event) { snippet= new CodeSection(); snippet = snippetList.selectionModelProperty().getValue().getSelectedItem(); if(snippet == null) { //TODO alertbox } else { Controller.editSnippets(snippet); UpdateSnippet updatepage = new UpdateSnippet(); updatepage.show(); } } } public class viewButtonHandler implements EventHandler<ActionEvent> { public void handle(ActionEvent event) { theStage.hide(); ViewSnippet updatepage = new ViewSnippet(); updatepage.show(); } } public class deleteButtonHandler implements EventHandler<ActionEvent> { public void handle(ActionEvent event) { Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Delete"); alert.setHeaderText("You are about to delete this code."); alert.setContentText("Are you sure?"); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == ButtonType.OK) { Controller.deleteSnippet(snippet); } else { alert.close(); } } } public DisplayResults(ArrayList<CodeSection> codeSearchList) { theStage = new Stage(); GridPane pane = new GridPane(); GridPane topPane = new GridPane(); GridPane bottomPane = new GridPane(); pane.add(topPane, 0, 0); pane.add(bottomPane, 0, 1); ScrollPane scrollPane = new ScrollPane(); HBox Hbox1 = new HBox(); GridPane insetPane = new GridPane(); GridPane insetInnerPane = new GridPane(); GridPane outsetPane = new GridPane(); Hbox1.getChildren().add(0, insetPane); Scene scene = new Scene(pane); theStage.setScene(scene); theStage.setTitle("Search Results"); pane.setHgap(5); pane.setVgap(5); pane.setPadding(new Insets(10,10,10,10)); bottomPane.setHgap(5); bottomPane.setVgap(5); olCodeSearchList = FXCollections.observableArrayList(codeSearchList); ArrayList<Node> scrollListNodes = new ArrayList<>(); int i = 0; for(CodeSection c: olCodeSearchList) { Text id = new Text(); id.setText("ID: " + c.getId()); Text language = new Text(); language.setText("Lang: " + c.getLanguage()); Text tags = new Text(); tags.setText("Tags: " + c.getTags()); Text writer = new Text(); writer.setText("Writer: " + c.getWriter()); Text code = new Text(); code.setText(c.getSnippet()); insetInnerPane.add(id, 0, 0); insetInnerPane.add(language, 0, 1); insetInnerPane.add(tags, 0, 2); insetInnerPane.add(writer, 0, 3); ColumnConstraints column1 = new ColumnConstraints(); column1.setPercentWidth(30); ColumnConstraints column2 = new ColumnConstraints(); column2.setPercentWidth(70); insetPane.getColumnConstraints().addAll(column1, column2); insetPane.add(insetInnerPane, 0, 0); insetPane.add(code, 1, 0); insetPane.setGridLinesVisible(true); outsetPane.setPrefSize(800, 400); outsetPane.add(insetPane, 0,i); i++; int j = i%2; insetPane.setStyle("-fx-background-color: white;"); if(j == 1) { insetPane.setStyle("-fx-background-color: lightgrey;"); } insetPane = new GridPane(); insetInnerPane = new GridPane(); } scrollPane.setContent(outsetPane); topPane.add(scrollPane, 0 ,0); viewBtn = new Button("View"); updateBtn = new Button("Edit"); deleteBtn = new Button("Delete"); cancelBtn = new Button("Go Back"); bottomPane.add(viewBtn, 0, 0); bottomPane.add(updateBtn, 1, 0); bottomPane.add(deleteBtn, 2, 0); bottomPane.add(cancelBtn, 3, 0); viewBtn.setOnAction(new viewButtonHandler()); updateBtn.setOnAction(new updateButtonHandler()); deleteBtn.setOnAction(new deleteButtonHandler()); cancelBtn.setOnAction(this); } public void show() { theStage.show(); } public void handle(ActionEvent event) { theStage.hide(); } }
src/sample/View/DisplayResults.java
package sample.View; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.text.Text; import javafx.stage.Stage; import sample.Controller.Controller; import sample.Model.CodeSection; import java.util.ArrayList; import java.util.Optional; import static javafx.scene.input.KeyCode.H; /** * Created by jeffryporter on 8/30/16. */ public class DisplayResults implements EventHandler<ActionEvent> { private Stage theStage; private TableView<CodeSection> snippetList = new TableView<>(); ObservableList<CodeSection> olCodeSearchList; private CodeSection snippet; private Button viewBtn; private Button updateBtn; private Button deleteBtn; private Button cancelBtn; public class updateButtonHandler implements EventHandler<ActionEvent> { public void handle(ActionEvent event) { snippet= new CodeSection(); snippet = snippetList.selectionModelProperty().getValue().getSelectedItem(); if(snippet == null) { //TODO alertbox } else { Controller.editSnippets(snippet); UpdateSnippet updatepage = new UpdateSnippet(); updatepage.show(); } } } public class viewButtonHandler implements EventHandler<ActionEvent> { public void handle(ActionEvent event) { theStage.hide(); ViewSnippet updatepage = new ViewSnippet(); updatepage.show(); } } public class deleteButtonHandler implements EventHandler<ActionEvent> { public void handle(ActionEvent event) { Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Delete"); alert.setHeaderText("You are about to delete this code."); alert.setContentText("Are you sure?"); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == ButtonType.OK) { Controller.deleteSnippet(snippet); } else { alert.close(); } } } public DisplayResults(ArrayList<CodeSection> codeSearchList) { theStage = new Stage(); GridPane pane = new GridPane(); GridPane topPane = new GridPane(); GridPane bottomPane = new GridPane(); pane.add(topPane, 0, 0); pane.add(bottomPane, 0, 1); ScrollPane scrollPane = new ScrollPane(); HBox Hbox1 = new HBox(); GridPane insetPane = new GridPane(); GridPane insetInnerPane = new GridPane(); GridPane outsetPane = new GridPane(); Hbox1.getChildren().add(0, insetPane); Scene scene = new Scene(pane); theStage.setScene(scene); theStage.setTitle("Search Results"); pane.setHgap(5); pane.setVgap(5); pane.setPadding(new Insets(10,10,10,10)); bottomPane.setHgap(5); bottomPane.setVgap(5); olCodeSearchList = FXCollections.observableArrayList(codeSearchList); ArrayList<Node> scrollListNodes = new ArrayList<>(); int i = 0; for(CodeSection c: olCodeSearchList) { Text id = new Text(); id.setText("ID: " + c.getId()); Text language = new Text(); language.setText("Lang: " + c.getLanguage()); Text tags = new Text(); tags.setText("Tags: " + c.getTags()); Text writer = new Text(); writer.setText("Writer: " + c.getWriter()); Text code = new Text(); code.setText(c.getSnippet()); insetInnerPane.add(id, 0, 0); insetInnerPane.add(language, 0, 1); insetInnerPane.add(tags, 0, 2); insetInnerPane.add(writer, 0, 3); insetPane.add(insetInnerPane, 0, 0); insetPane.add(code, 1, 0); insetPane.setGridLinesVisible(true); outsetPane.add(insetPane, 0,i); i++; int j = i%2; insetPane.setStyle("-fx-background-color: white;"); if(j == 1) { insetPane.setStyle("-fx-background-color: lightgrey;"); } insetPane = new GridPane(); insetInnerPane = new GridPane(); } scrollPane.setContent(outsetPane); topPane.add(scrollPane, 0 ,0); viewBtn = new Button("View"); updateBtn = new Button("Edit"); deleteBtn = new Button("Delete"); cancelBtn = new Button("Go Back"); bottomPane.add(viewBtn, 0, 0); bottomPane.add(updateBtn, 1, 0); bottomPane.add(deleteBtn, 2, 0); bottomPane.add(cancelBtn, 3, 0); viewBtn.setOnAction(new viewButtonHandler()); updateBtn.setOnAction(new updateButtonHandler()); deleteBtn.setOnAction(new deleteButtonHandler()); cancelBtn.setOnAction(this); } public void show() { theStage.show(); } public void handle(ActionEvent event) { theStage.hide(); } }
Set widths on DisplayResults
src/sample/View/DisplayResults.java
Set widths on DisplayResults
<ide><path>rc/sample/View/DisplayResults.java <ide> import javafx.scene.Node; <ide> import javafx.scene.Scene; <ide> import javafx.scene.control.*; <add>import javafx.scene.layout.ColumnConstraints; <ide> import javafx.scene.layout.GridPane; <ide> import javafx.scene.layout.HBox; <ide> import javafx.scene.text.Text; <ide> insetInnerPane.add(language, 0, 1); <ide> insetInnerPane.add(tags, 0, 2); <ide> insetInnerPane.add(writer, 0, 3); <add> ColumnConstraints column1 = new ColumnConstraints(); <add> column1.setPercentWidth(30); <add> ColumnConstraints column2 = new ColumnConstraints(); <add> column2.setPercentWidth(70); <add> insetPane.getColumnConstraints().addAll(column1, column2); <ide> insetPane.add(insetInnerPane, 0, 0); <ide> insetPane.add(code, 1, 0); <ide> insetPane.setGridLinesVisible(true); <add> outsetPane.setPrefSize(800, 400); <ide> outsetPane.add(insetPane, 0,i); <ide> <ide> i++;
Java
mit
10b4180aa6b8beb79a0bab6f4c044007a433741a
0
hhu-stups/bmoth
package de.bmoth.modelchecker.esmc; import com.microsoft.z3.BoolExpr; import com.microsoft.z3.Context; import com.microsoft.z3.Expr; import com.microsoft.z3.Sort; import java.util.ArrayList; import java.util.List; import java.util.Map; public class State { private State predecessor; private Map<String, Expr> values; public State(State predecessor, Map<String, Expr> values) { this.predecessor = predecessor; this.values = values; } public String toString() { return this.values.toString(); } @Override public int hashCode() { return values.hashCode(); } @Override public boolean equals(Object obj) { if (!(obj instanceof State)) { return false; } if (this == obj) { return true; } State that = (State) obj; return this.values.equals(that.values); } public BoolExpr getStateConstraint(Context context) { BoolExpr[] result = values.entrySet().stream().map(entry -> { Expr singleExpression = entry.getValue(); Sort sort = singleExpression.getSort(); Expr identifierExpr = context.mkConst(entry.getKey(), sort); return context.mkEq(identifierExpr, singleExpression); }).toArray(BoolExpr[]::new); switch (result.length) { case 0: return null; case 1: return result[0]; default: return context.mkAnd(result); } } public List<String> getPath() { List<String> path = new ArrayList<>(); for (State current = this.predecessor; current != null; current = current.predecessor) { path.add(current.toString()); } return path; } }
src/main/java/de/bmoth/modelchecker/esmc/State.java
package de.bmoth.modelchecker.esmc; import com.microsoft.z3.BoolExpr; import com.microsoft.z3.Context; import com.microsoft.z3.Expr; import com.microsoft.z3.Sort; import java.util.ArrayList; import java.util.List; import java.util.Map; public class State { State predecessor; Map<String, Expr> values; public State(State predecessor, Map<String, Expr> values) { this.predecessor = predecessor; this.values = values; } public String toString() { return this.values.toString(); } @Override public int hashCode() { return values.hashCode(); } @Override public boolean equals(Object obj) { if (!(obj instanceof State)) { return false; } if (this == obj) { return true; } State that = (State) obj; return this.values.equals(that.values); } public BoolExpr getStateConstraint(Context context) { BoolExpr[] result = values.entrySet().stream().map(entry -> { Expr singleExpression = entry.getValue(); Sort sort = singleExpression.getSort(); Expr identifierExpr = context.mkConst(entry.getKey(), sort); return context.mkEq(identifierExpr, singleExpression); }).toArray(BoolExpr[]::new); switch (result.length) { case 0: return null; case 1: return result[0]; default: return context.mkAnd(result); } } public List<String> getPath() { List<String> path = new ArrayList<>(); for (State current = this.predecessor; current != null; current = current.predecessor) { path.add(current.toString()); } return path; } }
minor visibility changes
src/main/java/de/bmoth/modelchecker/esmc/State.java
minor visibility changes
<ide><path>rc/main/java/de/bmoth/modelchecker/esmc/State.java <ide> import java.util.Map; <ide> <ide> public class State { <del> State predecessor; <del> Map<String, Expr> values; <add> private State predecessor; <add> private Map<String, Expr> values; <ide> <ide> public State(State predecessor, Map<String, Expr> values) { <ide> this.predecessor = predecessor;
Java
lgpl-2.1
503bbe3f45781bb0c49a23a135cc2e0287b720ee
0
gallardo/opencms-core,gallardo/opencms-core,alkacon/opencms-core,gallardo/opencms-core,gallardo/opencms-core,alkacon/opencms-core,alkacon/opencms-core,alkacon/opencms-core
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (C) Alkacon Software (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.ui.components; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_CACHE; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_COPYRIGHT; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_DATE_CREATED; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_DATE_EXPIRED; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_DATE_MODIFIED; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_DATE_RELEASED; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_INSIDE_PROJECT; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_IN_NAVIGATION; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_IS_FOLDER; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_NAVIGATION_POSITION; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_NAVIGATION_TEXT; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_PERMISSIONS; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_PROJECT; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_RELEASED_NOT_EXPIRED; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_RESOURCE_NAME; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_RESOURCE_TYPE; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_SIZE; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_STATE; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_STATE_NAME; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_TITLE; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_TYPE_ICON; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_USER_CREATED; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_USER_LOCKED; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_USER_MODIFIED; import org.opencms.db.CmsResourceState; import org.opencms.file.CmsObject; import org.opencms.file.CmsResource; import org.opencms.file.CmsResourceFilter; import org.opencms.file.CmsVfsResourceNotFoundException; import org.opencms.main.CmsException; import org.opencms.main.CmsLog; import org.opencms.main.OpenCms; import org.opencms.ui.A_CmsUI; import org.opencms.ui.CmsVaadinUtils; import org.opencms.ui.I_CmsDialogContext; import org.opencms.ui.I_CmsEditPropertyContext; import org.opencms.ui.actions.I_CmsDefaultAction; import org.opencms.ui.apps.CmsFileExplorerSettings; import org.opencms.ui.apps.I_CmsContextProvider; import org.opencms.ui.contextmenu.CmsContextMenu; import org.opencms.ui.contextmenu.CmsResourceContextMenuBuilder; import org.opencms.ui.contextmenu.I_CmsContextMenuBuilder; import org.opencms.ui.util.I_CmsItemSorter; import org.opencms.util.CmsStringUtil; import org.opencms.util.CmsUUID; import java.text.Collator; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.commons.logging.Log; import com.google.common.collect.Lists; import com.vaadin.event.FieldEvents.BlurEvent; import com.vaadin.event.FieldEvents.BlurListener; import com.vaadin.event.ShortcutAction.KeyCode; import com.vaadin.event.ShortcutListener; import com.vaadin.shared.MouseEventDetails.MouseButton; import com.vaadin.ui.Component; import com.vaadin.ui.themes.ValoTheme; import com.vaadin.v7.data.Container; import com.vaadin.v7.data.Container.Filter; import com.vaadin.v7.data.Item; import com.vaadin.v7.data.Property.ValueChangeEvent; import com.vaadin.v7.data.Property.ValueChangeListener; import com.vaadin.v7.data.util.DefaultItemSorter; import com.vaadin.v7.data.util.IndexedContainer; import com.vaadin.v7.data.util.filter.Or; import com.vaadin.v7.data.util.filter.SimpleStringFilter; import com.vaadin.v7.event.ItemClickEvent; import com.vaadin.v7.event.ItemClickEvent.ItemClickListener; import com.vaadin.v7.ui.AbstractTextField.TextChangeEventMode; import com.vaadin.v7.ui.DefaultFieldFactory; import com.vaadin.v7.ui.Field; import com.vaadin.v7.ui.Table; import com.vaadin.v7.ui.Table.TableDragMode; import com.vaadin.v7.ui.TextField; /** * Table for displaying resources.<p> */ public class CmsFileTable extends CmsResourceTable { /** * File edit handler.<p> */ public class FileEditHandler implements BlurListener { /** The serial version id. */ private static final long serialVersionUID = -2286815522247807054L; /** * @see com.vaadin.event.FieldEvents.BlurListener#blur(com.vaadin.event.FieldEvents.BlurEvent) */ public void blur(BlurEvent event) { stopEdit(); } } /** * Field factory to enable inline editing of individual file properties.<p> */ public class FileFieldFactory extends DefaultFieldFactory { /** The serial version id. */ private static final long serialVersionUID = 3079590603587933576L; /** * @see com.vaadin.ui.DefaultFieldFactory#createField(com.vaadin.v7.data.Container, java.lang.Object, java.lang.Object, com.vaadin.ui.Component) */ @Override public Field<?> createField(Container container, Object itemId, Object propertyId, Component uiContext) { Field<?> result = null; if (itemId.equals(getEditItemId().toString()) && isEditProperty((CmsResourceTableProperty)propertyId)) { result = super.createField(container, itemId, propertyId, uiContext); result.addStyleName(OpenCmsTheme.INLINE_TEXTFIELD); result.addValidator(m_editHandler); if (result instanceof TextField) { ((TextField)result).setComponentError(null); ((TextField)result).addShortcutListener(new ShortcutListener("Cancel edit", KeyCode.ESCAPE, null) { private static final long serialVersionUID = 1L; @Override public void handleAction(Object sender, Object target) { cancelEdit(); } }); ((TextField)result).addShortcutListener(new ShortcutListener("Save", KeyCode.ENTER, null) { private static final long serialVersionUID = 1L; @Override public void handleAction(Object sender, Object target) { stopEdit(); } }); ((TextField)result).addBlurListener(m_fileEditHandler); ((TextField)result).setTextChangeEventMode(TextChangeEventMode.LAZY); ((TextField)result).addTextChangeListener(m_editHandler); } result.focus(); } return result; } } /** * Extends the default sorting to differentiate between files and folder when sorting by name.<p> * Also allows sorting by navPos property for the Resource icon column.<p> */ public static class FileSorter extends DefaultItemSorter implements I_CmsItemSorter { /** The serial version id. */ private static final long serialVersionUID = 1L; /** * @see org.opencms.ui.util.I_CmsItemSorter#getSortableContainerPropertyIds(com.vaadin.v7.data.Container) */ public Collection<?> getSortableContainerPropertyIds(Container container) { Set<Object> result = new HashSet<Object>(); for (Object propId : container.getContainerPropertyIds()) { Class<?> propertyType = container.getType(propId); if (Comparable.class.isAssignableFrom(propertyType) || propertyType.isPrimitive() || (propId.equals(CmsResourceTableProperty.PROPERTY_TYPE_ICON) && container.getContainerPropertyIds().contains( CmsResourceTableProperty.PROPERTY_NAVIGATION_POSITION))) { result.add(propId); } } return result; } /** * @see com.vaadin.v7.data.util.DefaultItemSorter#compareProperty(java.lang.Object, boolean, com.vaadin.v7.data.Item, com.vaadin.v7.data.Item) */ @Override protected int compareProperty(Object propertyId, boolean sortDirection, Item item1, Item item2) { if (CmsResourceTableProperty.PROPERTY_RESOURCE_NAME.equals(propertyId)) { Boolean isFolder1 = (Boolean)item1.getItemProperty( CmsResourceTableProperty.PROPERTY_IS_FOLDER).getValue(); Boolean isFolder2 = (Boolean)item2.getItemProperty( CmsResourceTableProperty.PROPERTY_IS_FOLDER).getValue(); if (!isFolder1.equals(isFolder2)) { int result = isFolder1.booleanValue() ? -1 : 1; if (!sortDirection) { result = result * (-1); } return result; } } else if ((CmsResourceTableProperty.PROPERTY_TYPE_ICON.equals(propertyId) || CmsResourceTableProperty.PROPERTY_NAVIGATION_TEXT.equals(propertyId)) && (item1.getItemProperty(CmsResourceTableProperty.PROPERTY_NAVIGATION_POSITION) != null)) { int result; Float pos1 = (Float)item1.getItemProperty( CmsResourceTableProperty.PROPERTY_NAVIGATION_POSITION).getValue(); Float pos2 = (Float)item2.getItemProperty( CmsResourceTableProperty.PROPERTY_NAVIGATION_POSITION).getValue(); if (pos1 == null) { result = pos2 == null ? compareProperty(CmsResourceTableProperty.PROPERTY_RESOURCE_NAME, true, item1, item2) : 1; } else { result = pos2 == null ? -1 : Float.compare(pos1.floatValue(), pos2.floatValue()); } if (!sortDirection) { result = result * (-1); } return result; } else if (((CmsResourceTableProperty)propertyId).getColumnType().equals(String.class)) { String value1 = (String)item1.getItemProperty(propertyId).getValue(); String value2 = (String)item2.getItemProperty(propertyId).getValue(); Collator collator = Collator.getInstance( OpenCms.getWorkplaceManager().getWorkplaceLocale(A_CmsUI.getCmsObject())); return collator.compare(value1, value2); } return super.compareProperty(propertyId, sortDirection, item1, item2); } } /** * Handles folder selects in the file table.<p> */ public interface I_FolderSelectHandler { /** * Called when the folder name is left clicked.<p> * * @param folderId the selected folder id */ void onFolderSelect(CmsUUID folderId); } /** The default file table columns. */ public static final Map<CmsResourceTableProperty, Integer> DEFAULT_TABLE_PROPERTIES; /** The logger instance for this class. */ static final Log LOG = CmsLog.getLog(CmsFileTable.class); /** The serial version id. */ private static final long serialVersionUID = 5460048685141699277L; static { Map<CmsResourceTableProperty, Integer> defaultProps = new LinkedHashMap<CmsResourceTableProperty, Integer>(); defaultProps.put(PROPERTY_TYPE_ICON, Integer.valueOf(0)); defaultProps.put(PROPERTY_PROJECT, Integer.valueOf(COLLAPSED)); defaultProps.put(PROPERTY_RESOURCE_NAME, Integer.valueOf(0)); defaultProps.put(PROPERTY_TITLE, Integer.valueOf(0)); defaultProps.put(PROPERTY_NAVIGATION_TEXT, Integer.valueOf(COLLAPSED)); defaultProps.put(PROPERTY_NAVIGATION_POSITION, Integer.valueOf(INVISIBLE)); defaultProps.put(PROPERTY_IN_NAVIGATION, Integer.valueOf(INVISIBLE)); defaultProps.put(PROPERTY_COPYRIGHT, Integer.valueOf(COLLAPSED)); defaultProps.put(PROPERTY_CACHE, Integer.valueOf(COLLAPSED)); defaultProps.put(PROPERTY_RESOURCE_TYPE, Integer.valueOf(0)); defaultProps.put(PROPERTY_SIZE, Integer.valueOf(0)); defaultProps.put(PROPERTY_PERMISSIONS, Integer.valueOf(COLLAPSED)); defaultProps.put(PROPERTY_DATE_MODIFIED, Integer.valueOf(0)); defaultProps.put(PROPERTY_USER_MODIFIED, Integer.valueOf(COLLAPSED)); defaultProps.put(PROPERTY_DATE_CREATED, Integer.valueOf(COLLAPSED)); defaultProps.put(PROPERTY_USER_CREATED, Integer.valueOf(COLLAPSED)); defaultProps.put(PROPERTY_DATE_RELEASED, Integer.valueOf(0)); defaultProps.put(PROPERTY_DATE_EXPIRED, Integer.valueOf(0)); defaultProps.put(PROPERTY_STATE_NAME, Integer.valueOf(0)); defaultProps.put(PROPERTY_USER_LOCKED, Integer.valueOf(0)); defaultProps.put(PROPERTY_IS_FOLDER, Integer.valueOf(INVISIBLE)); defaultProps.put(PROPERTY_STATE, Integer.valueOf(INVISIBLE)); defaultProps.put(PROPERTY_INSIDE_PROJECT, Integer.valueOf(INVISIBLE)); defaultProps.put(PROPERTY_RELEASED_NOT_EXPIRED, Integer.valueOf(INVISIBLE)); DEFAULT_TABLE_PROPERTIES = Collections.unmodifiableMap(defaultProps); } /** The selected resources. */ protected List<CmsResource> m_currentResources = new ArrayList<CmsResource>(); /** The default action column property. */ CmsResourceTableProperty m_actionColumnProperty; /** The additional cell style generators. */ List<Table.CellStyleGenerator> m_additionalStyleGenerators; /** The current file property edit handler. */ I_CmsFilePropertyEditHandler m_editHandler; /** File edit event handler. */ FileEditHandler m_fileEditHandler = new FileEditHandler(); /** The context menu. */ CmsContextMenu m_menu; /** The context menu builder. */ I_CmsContextMenuBuilder m_menuBuilder; /** The table drag mode, stored during item editing. */ private TableDragMode m_beforEditDragMode; /** The dialog context provider. */ private I_CmsContextProvider m_contextProvider; /** The edited item id. */ private CmsUUID m_editItemId; /** The edited property id. */ private CmsResourceTableProperty m_editProperty; /** Saved container filters. */ private Collection<Filter> m_filters = Collections.emptyList(); /** The folder select handler. */ private I_FolderSelectHandler m_folderSelectHandler; /** The original edit value. */ private String m_originalEditValue; /** * Default constructor.<p> * * @param contextProvider the dialog context provider */ public CmsFileTable(I_CmsContextProvider contextProvider) { this(contextProvider, DEFAULT_TABLE_PROPERTIES); } /** * Default constructor.<p> * * @param contextProvider the dialog context provider * @param tableColumns the table columns to show */ public CmsFileTable(I_CmsContextProvider contextProvider, Map<CmsResourceTableProperty, Integer> tableColumns) { super(); m_additionalStyleGenerators = new ArrayList<Table.CellStyleGenerator>(); m_actionColumnProperty = PROPERTY_RESOURCE_NAME; m_contextProvider = contextProvider; m_container.setItemSorter(new FileSorter()); m_fileTable.addStyleName(ValoTheme.TABLE_BORDERLESS); m_fileTable.addStyleName(OpenCmsTheme.SIMPLE_DRAG); m_fileTable.setSizeFull(); m_fileTable.setColumnCollapsingAllowed(true); m_fileTable.setSelectable(true); m_fileTable.setMultiSelect(true); m_fileTable.setTableFieldFactory(new FileFieldFactory()); ColumnBuilder builder = new ColumnBuilder(); for (Entry<CmsResourceTableProperty, Integer> entry : tableColumns.entrySet()) { builder.column(entry.getKey(), entry.getValue().intValue()); } builder.buildColumns(); m_fileTable.setSortContainerPropertyId(CmsResourceTableProperty.PROPERTY_RESOURCE_NAME); m_menu = new CmsContextMenu(); m_fileTable.addValueChangeListener(new ValueChangeListener() { private static final long serialVersionUID = 1L; public void valueChange(ValueChangeEvent event) { @SuppressWarnings("unchecked") Set<String> selectedIds = (Set<String>)event.getProperty().getValue(); List<CmsResource> selectedResources = new ArrayList<CmsResource>(); for (String id : selectedIds) { try { CmsResource resource = A_CmsUI.getCmsObject().readResource( getUUIDFromItemID(id), CmsResourceFilter.ALL); selectedResources.add(resource); } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); } } m_currentResources = selectedResources; rebuildMenu(); } }); m_fileTable.addItemClickListener(new ItemClickListener() { private static final long serialVersionUID = 1L; public void itemClick(ItemClickEvent event) { handleFileItemClick(event); } }); m_fileTable.setCellStyleGenerator(new Table.CellStyleGenerator() { private static final long serialVersionUID = 1L; public String getStyle(Table source, Object itemId, Object propertyId) { Item item = m_container.getItem(itemId); String style = getStateStyle(item); if (m_actionColumnProperty == propertyId) { style += " " + OpenCmsTheme.HOVER_COLUMN; } else if ((CmsResourceTableProperty.PROPERTY_NAVIGATION_TEXT == propertyId) || (CmsResourceTableProperty.PROPERTY_TITLE == propertyId)) { if ((item.getItemProperty(CmsResourceTableProperty.PROPERTY_IN_NAVIGATION) != null) && ((Boolean)item.getItemProperty( CmsResourceTableProperty.PROPERTY_IN_NAVIGATION).getValue()).booleanValue()) { style += " " + OpenCmsTheme.IN_NAVIGATION; } } for (Table.CellStyleGenerator generator : m_additionalStyleGenerators) { String additional = generator.getStyle(source, itemId, propertyId); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(additional)) { style += " " + additional; } } return style; } }); m_menu.setAsTableContextMenu(m_fileTable); } /** * Returns the resource state specific style name.<p> * * @param resourceItem the resource item * * @return the style name */ public static String getStateStyle(Item resourceItem) { String result = ""; if (resourceItem != null) { if ((resourceItem.getItemProperty(PROPERTY_INSIDE_PROJECT) == null) || ((Boolean)resourceItem.getItemProperty(PROPERTY_INSIDE_PROJECT).getValue()).booleanValue()) { CmsResourceState state = (CmsResourceState)resourceItem.getItemProperty( CmsResourceTableProperty.PROPERTY_STATE).getValue(); result = getStateStyle(state); } else { result = OpenCmsTheme.PROJECT_OTHER; } if ((resourceItem.getItemProperty(PROPERTY_RELEASED_NOT_EXPIRED) != null) && !((Boolean)resourceItem.getItemProperty(PROPERTY_RELEASED_NOT_EXPIRED).getValue()).booleanValue()) { result += " " + OpenCmsTheme.EXPIRED; } if ((resourceItem.getItemProperty(CmsResourceTableProperty.PROPERTY_DISABLED) != null) && ((Boolean)resourceItem.getItemProperty( CmsResourceTableProperty.PROPERTY_DISABLED).getValue()).booleanValue()) { result += " " + OpenCmsTheme.DISABLED; } } return result; } /** * Adds an additional cell style generator.<p> * * @param styleGenerator the cell style generator */ public void addAdditionalStyleGenerator(Table.CellStyleGenerator styleGenerator) { m_additionalStyleGenerators.add(styleGenerator); } /** * Applies settings generally used within workplace app file lists.<p> */ public void applyWorkplaceAppSettings() { // add site path property to container m_container.addContainerProperty( CmsResourceTableProperty.PROPERTY_SITE_PATH, CmsResourceTableProperty.PROPERTY_SITE_PATH.getColumnType(), CmsResourceTableProperty.PROPERTY_SITE_PATH.getDefaultValue()); // replace the resource name column with the path column Object[] visibleCols = m_fileTable.getVisibleColumns(); for (int i = 0; i < visibleCols.length; i++) { if (CmsResourceTableProperty.PROPERTY_RESOURCE_NAME.equals(visibleCols[i])) { visibleCols[i] = CmsResourceTableProperty.PROPERTY_SITE_PATH; } } m_fileTable.setVisibleColumns(visibleCols); m_fileTable.setColumnCollapsible(CmsResourceTableProperty.PROPERTY_SITE_PATH, false); m_fileTable.setColumnHeader( CmsResourceTableProperty.PROPERTY_SITE_PATH, CmsVaadinUtils.getMessageText(CmsResourceTableProperty.PROPERTY_SITE_PATH.getHeaderKey())); // update column visibility according to the latest file explorer settings CmsFileExplorerSettings settings; try { settings = OpenCms.getWorkplaceAppManager().getAppSettings( A_CmsUI.getCmsObject(), CmsFileExplorerSettings.class); setTableState(settings); } catch (Exception e) { LOG.error("Error while reading file explorer settings from user.", e); } m_fileTable.setSortContainerPropertyId(CmsResourceTableProperty.PROPERTY_SITE_PATH); setActionColumnProperty(CmsResourceTableProperty.PROPERTY_SITE_PATH); setMenuBuilder(new CmsResourceContextMenuBuilder()); } /** * Clears all container filters. */ public void clearFilters() { IndexedContainer container = (IndexedContainer)m_fileTable.getContainerDataSource(); container.removeAllContainerFilters(); } /** * Filters the displayed resources.<p> * Only resources where either the resource name, the title or the nav-text contains the given substring are shown.<p> * * @param search the search term */ public void filterTable(String search) { m_container.removeAllContainerFilters(); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(search)) { m_container.addContainerFilter( new Or( new SimpleStringFilter(CmsResourceTableProperty.PROPERTY_RESOURCE_NAME, search, true, false), new SimpleStringFilter(CmsResourceTableProperty.PROPERTY_NAVIGATION_TEXT, search, true, false), new SimpleStringFilter(CmsResourceTableProperty.PROPERTY_TITLE, search, true, false))); } if ((m_fileTable.getValue() != null) & !((Set<?>)m_fileTable.getValue()).isEmpty()) { m_fileTable.setCurrentPageFirstItemId(((Set<?>)m_fileTable.getValue()).iterator().next()); } } /** * Returns the index of the first visible item.<p> * * @return the first visible item */ public int getFirstVisibleItemIndex() { return m_fileTable.getCurrentPageFirstItemIndex(); } /** * Gets the selected structure ids.<p> * * @return the set of selected structure ids */ @SuppressWarnings("unchecked") public Collection<CmsUUID> getSelectedIds() { return itemIdsToUUIDs((Collection<String>)m_fileTable.getValue()); } /** * Gets the list of selected resources.<p> * * @return the list of selected resources */ public List<CmsResource> getSelectedResources() { return m_currentResources; } /** * Returns the current table state.<p> * * @return the table state */ public CmsFileExplorerSettings getTableSettings() { CmsFileExplorerSettings fileTableState = new CmsFileExplorerSettings(); fileTableState.setSortAscending(m_fileTable.isSortAscending()); fileTableState.setSortColumnId((CmsResourceTableProperty)m_fileTable.getSortContainerPropertyId()); List<CmsResourceTableProperty> collapsedCollumns = new ArrayList<CmsResourceTableProperty>(); Object[] visibleCols = m_fileTable.getVisibleColumns(); for (int i = 0; i < visibleCols.length; i++) { if (m_fileTable.isColumnCollapsed(visibleCols[i])) { collapsedCollumns.add((CmsResourceTableProperty)visibleCols[i]); } } fileTableState.setCollapsedColumns(collapsedCollumns); return fileTableState; } /** * Handles the item selection.<p> * * @param itemId the selected item id */ public void handleSelection(String itemId) { Collection<?> selection = (Collection<?>)m_fileTable.getValue(); if (selection == null) { m_fileTable.select(itemId); } else if (!selection.contains(itemId)) { m_fileTable.setValue(null); m_fileTable.select(itemId); } } /** * Returns if a file property is being edited.<p> * @return <code>true</code> if a file property is being edited */ public boolean isEditing() { return m_editItemId != null; } /** * Returns if the given property is being edited.<p> * * @param propertyId the property id * * @return <code>true</code> if the given property is being edited */ public boolean isEditProperty(CmsResourceTableProperty propertyId) { return (m_editProperty != null) && m_editProperty.equals(propertyId); } /** * Opens the context menu.<p> * * @param event the click event */ public void openContextMenu(ItemClickEvent event) { m_menu.openForTable(event, m_fileTable); } /** * Removes the given cell style generator.<p> * * @param styleGenerator the cell style generator to remove */ public void removeAdditionalStyleGenerator(Table.CellStyleGenerator styleGenerator) { m_additionalStyleGenerators.remove(styleGenerator); } /** * Restores container filters to the ones previously saved via saveFilters(). */ public void restoreFilters() { IndexedContainer container = (IndexedContainer)m_fileTable.getContainerDataSource(); container.removeAllContainerFilters(); for (Filter filter : m_filters) { container.addContainerFilter(filter); } } /** * Saves currently active filters.<p> */ public void saveFilters() { IndexedContainer container = (IndexedContainer)m_fileTable.getContainerDataSource(); m_filters = container.getContainerFilters(); } /** * Sets the default action column property.<p> * * @param actionColumnProperty the default action column property */ public void setActionColumnProperty(CmsResourceTableProperty actionColumnProperty) { m_actionColumnProperty = actionColumnProperty; } /** * Sets the dialog context provider.<p> * * @param provider the dialog context provider */ public void setContextProvider(I_CmsContextProvider provider) { m_contextProvider = provider; } /** * Sets the first visible item index.<p> * * @param i the item index */ public void setFirstVisibleItemIndex(int i) { m_fileTable.setCurrentPageFirstItemIndex(i); } /** * Sets the folder select handler.<p> * * @param folderSelectHandler the folder select handler */ public void setFolderSelectHandler(I_FolderSelectHandler folderSelectHandler) { m_folderSelectHandler = folderSelectHandler; } /** * Sets the menu builder.<p> * * @param builder the menu builder */ public void setMenuBuilder(I_CmsContextMenuBuilder builder) { m_menuBuilder = builder; } /** * Sets the table state.<p> * * @param state the table state */ public void setTableState(CmsFileExplorerSettings state) { if (state != null) { m_fileTable.setSortContainerPropertyId(state.getSortColumnId()); m_fileTable.setSortAscending(state.isSortAscending()); Object[] visibleCols = m_fileTable.getVisibleColumns(); for (int i = 0; i < visibleCols.length; i++) { m_fileTable.setColumnCollapsed(visibleCols[i], state.getCollapsedColumns().contains(visibleCols[i])); } } } /** * Starts inline editing of the given file property.<p> * * @param itemId the item resource structure id * @param propertyId the property to edit * @param editHandler the edit handler */ public void startEdit( CmsUUID itemId, CmsResourceTableProperty propertyId, I_CmsFilePropertyEditHandler editHandler) { m_editItemId = itemId; m_editProperty = propertyId; m_originalEditValue = (String)m_container.getItem(m_editItemId.toString()).getItemProperty( m_editProperty).getValue(); m_editHandler = editHandler; // storing current drag mode and setting it to none to avoid text selection issues in IE11 m_beforEditDragMode = m_fileTable.getDragMode(); m_fileTable.setDragMode(TableDragMode.NONE); m_fileTable.setEditable(true); } /** * Stops the current edit process to save the changed property value.<p> */ public void stopEdit() { if (m_editHandler != null) { String value = (String)m_container.getItem(m_editItemId.toString()).getItemProperty( m_editProperty).getValue(); if (!value.equals(m_originalEditValue)) { m_editHandler.validate(value); m_editHandler.save(value); } else { // call cancel to ensure unlock m_editHandler.cancel(); } } clearEdit(); // restoring drag mode m_fileTable.setDragMode(m_beforEditDragMode); m_beforEditDragMode = null; } /** * Updates all items with ids from the given list.<p> * * @param ids the resource structure ids to update * @param remove true if the item should be removed only */ public void update(Collection<CmsUUID> ids, boolean remove) { for (CmsUUID id : ids) { updateItem(id, remove); } rebuildMenu(); } /** * Updates the column widths.<p> * * The reason this is needed is that the Vaadin table does not support minimum widths for columns, * so expanding columns get squished when most of the horizontal space is used by other columns. * So we try to determine whether the expanded columns would have enough space, and if not, give them a * fixed width. * * @param estimatedSpace the estimated horizontal space available for the table. */ public void updateColumnWidths(int estimatedSpace) { Object[] cols = m_fileTable.getVisibleColumns(); List<CmsResourceTableProperty> expandCols = Lists.newArrayList(); int nonExpandWidth = 0; int totalExpandMinWidth = 0; for (Object colObj : cols) { if (m_fileTable.isColumnCollapsed(colObj)) { continue; } CmsResourceTableProperty prop = (CmsResourceTableProperty)colObj; if (0 < m_fileTable.getColumnExpandRatio(prop)) { expandCols.add(prop); totalExpandMinWidth += getAlternativeWidthForExpandingColumns(prop); } else { nonExpandWidth += prop.getColumnWidth(); } } if (estimatedSpace < (totalExpandMinWidth + nonExpandWidth)) { for (CmsResourceTableProperty expandCol : expandCols) { m_fileTable.setColumnWidth(expandCol, getAlternativeWidthForExpandingColumns(expandCol)); } } } /** * Updates the file table sorting.<p> */ public void updateSorting() { m_fileTable.sort(); } /** * Cancels the current edit process.<p> */ void cancelEdit() { if (m_editHandler != null) { m_editHandler.cancel(); } clearEdit(); } /** * Returns the dialog context provider.<p> * * @return the dialog context provider */ I_CmsContextProvider getContextProvider() { return m_contextProvider; } /** * Returns the edit item id.<p> * * @return the edit item id */ CmsUUID getEditItemId() { return m_editItemId; } /** * Returns the edit property id.<p> * * @return the edit property id */ CmsResourceTableProperty getEditProperty() { return m_editProperty; } /** * Handles the file table item click.<p> * * @param event the click event */ void handleFileItemClick(ItemClickEvent event) { if (isEditing()) { stopEdit(); } else if (!event.isCtrlKey() && !event.isShiftKey()) { // don't interfere with multi-selection using control key String itemId = (String)event.getItemId(); CmsUUID structureId = getUUIDFromItemID(itemId); boolean openedFolder = false; if (event.getButton().equals(MouseButton.RIGHT)) { handleSelection(itemId); openContextMenu(event); } else { if ((event.getPropertyId() == null) || CmsResourceTableProperty.PROPERTY_TYPE_ICON.equals(event.getPropertyId())) { handleSelection(itemId); openContextMenu(event); } else { if (m_actionColumnProperty.equals(event.getPropertyId())) { Boolean isFolder = (Boolean)event.getItem().getItemProperty( CmsResourceTableProperty.PROPERTY_IS_FOLDER).getValue(); if ((isFolder != null) && isFolder.booleanValue()) { if (m_folderSelectHandler != null) { m_folderSelectHandler.onFolderSelect(structureId); } openedFolder = true; } else { try { CmsObject cms = A_CmsUI.getCmsObject(); CmsResource res = cms.readResource(structureId, CmsResourceFilter.IGNORE_EXPIRATION); m_currentResources = Collections.singletonList(res); I_CmsDialogContext context = m_contextProvider.getDialogContext(); I_CmsDefaultAction action = OpenCms.getWorkplaceAppManager().getDefaultAction( context, m_menuBuilder); if (action != null) { action.executeAction(context); return; } } catch (CmsVfsResourceNotFoundException e) { LOG.info(e.getLocalizedMessage(), e); } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); } } } else { I_CmsDialogContext context = m_contextProvider.getDialogContext(); if ((m_currentResources.size() == 1) && m_currentResources.get(0).getStructureId().equals(structureId) && (context instanceof I_CmsEditPropertyContext) && ((I_CmsEditPropertyContext)context).isPropertyEditable(event.getPropertyId())) { ((I_CmsEditPropertyContext)context).editProperty(event.getPropertyId()); } } } } // update the item on click to show any available changes if (!openedFolder) { update(Collections.singletonList(structureId), false); } } } /** * Rebuilds the context menu.<p> */ void rebuildMenu() { if (!getSelectedIds().isEmpty() && (m_menuBuilder != null)) { m_menu.removeAllItems(); m_menuBuilder.buildContextMenu(getContextProvider().getDialogContext(), m_menu); } } /** * Clears the current edit process.<p> */ private void clearEdit() { m_fileTable.setEditable(false); if (m_editItemId != null) { updateItem(m_editItemId, false); } m_editItemId = null; m_editProperty = null; m_editHandler = null; updateSorting(); } /** * Gets alternative width for expanding table columns which is used when there is not enough space for * all visible columns.<p> * * @param prop the table property * @return the alternative column width */ private int getAlternativeWidthForExpandingColumns(CmsResourceTableProperty prop) { if (prop.getId().equals(CmsResourceTableProperty.PROPERTY_RESOURCE_NAME.getId())) { return 200; } if (prop.getId().equals(CmsResourceTableProperty.PROPERTY_TITLE.getId())) { return 300; } if (prop.getId().equals(CmsResourceTableProperty.PROPERTY_NAVIGATION_TEXT.getId())) { return 200; } return 200; } /** * Updates the given item in the file table.<p> * * @param itemId the item id * @param remove true if the item should be removed only */ private void updateItem(CmsUUID itemId, boolean remove) { if (remove) { String idStr = itemId != null ? itemId.toString() : null; m_container.removeItem(idStr); return; } CmsObject cms = A_CmsUI.getCmsObject(); try { CmsResource resource = cms.readResource(itemId, CmsResourceFilter.ALL); fillItem(cms, resource, OpenCms.getWorkplaceManager().getWorkplaceLocale(cms)); } catch (CmsVfsResourceNotFoundException e) { m_container.removeItem(itemId); LOG.debug("Failed to update file table item, removing it from view.", e); } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); } } }
src/org/opencms/ui/components/CmsFileTable.java
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (C) Alkacon Software (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.ui.components; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_CACHE; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_COPYRIGHT; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_DATE_CREATED; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_DATE_EXPIRED; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_DATE_MODIFIED; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_DATE_RELEASED; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_INSIDE_PROJECT; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_IN_NAVIGATION; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_IS_FOLDER; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_NAVIGATION_POSITION; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_NAVIGATION_TEXT; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_PERMISSIONS; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_PROJECT; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_RELEASED_NOT_EXPIRED; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_RESOURCE_NAME; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_RESOURCE_TYPE; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_SIZE; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_STATE; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_STATE_NAME; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_TITLE; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_TYPE_ICON; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_USER_CREATED; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_USER_LOCKED; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_USER_MODIFIED; import org.opencms.db.CmsResourceState; import org.opencms.file.CmsObject; import org.opencms.file.CmsResource; import org.opencms.file.CmsResourceFilter; import org.opencms.file.CmsVfsResourceNotFoundException; import org.opencms.main.CmsException; import org.opencms.main.CmsLog; import org.opencms.main.OpenCms; import org.opencms.ui.A_CmsUI; import org.opencms.ui.CmsVaadinUtils; import org.opencms.ui.I_CmsDialogContext; import org.opencms.ui.I_CmsEditPropertyContext; import org.opencms.ui.actions.I_CmsDefaultAction; import org.opencms.ui.apps.CmsFileExplorerSettings; import org.opencms.ui.apps.I_CmsContextProvider; import org.opencms.ui.contextmenu.CmsContextMenu; import org.opencms.ui.contextmenu.CmsResourceContextMenuBuilder; import org.opencms.ui.contextmenu.I_CmsContextMenuBuilder; import org.opencms.ui.util.I_CmsItemSorter; import org.opencms.util.CmsStringUtil; import org.opencms.util.CmsUUID; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.commons.logging.Log; import com.google.common.collect.Lists; import com.vaadin.event.FieldEvents.BlurEvent; import com.vaadin.event.FieldEvents.BlurListener; import com.vaadin.event.ShortcutAction.KeyCode; import com.vaadin.event.ShortcutListener; import com.vaadin.shared.MouseEventDetails.MouseButton; import com.vaadin.ui.Component; import com.vaadin.ui.themes.ValoTheme; import com.vaadin.v7.data.Container; import com.vaadin.v7.data.Container.Filter; import com.vaadin.v7.data.Item; import com.vaadin.v7.data.Property.ValueChangeEvent; import com.vaadin.v7.data.Property.ValueChangeListener; import com.vaadin.v7.data.util.DefaultItemSorter; import com.vaadin.v7.data.util.IndexedContainer; import com.vaadin.v7.data.util.filter.Or; import com.vaadin.v7.data.util.filter.SimpleStringFilter; import com.vaadin.v7.event.ItemClickEvent; import com.vaadin.v7.event.ItemClickEvent.ItemClickListener; import com.vaadin.v7.ui.AbstractTextField.TextChangeEventMode; import com.vaadin.v7.ui.DefaultFieldFactory; import com.vaadin.v7.ui.Field; import com.vaadin.v7.ui.Table; import com.vaadin.v7.ui.Table.TableDragMode; import com.vaadin.v7.ui.TextField; /** * Table for displaying resources.<p> */ public class CmsFileTable extends CmsResourceTable { /** * File edit handler.<p> */ public class FileEditHandler implements BlurListener { /** The serial version id. */ private static final long serialVersionUID = -2286815522247807054L; /** * @see com.vaadin.event.FieldEvents.BlurListener#blur(com.vaadin.event.FieldEvents.BlurEvent) */ public void blur(BlurEvent event) { stopEdit(); } } /** * Field factory to enable inline editing of individual file properties.<p> */ public class FileFieldFactory extends DefaultFieldFactory { /** The serial version id. */ private static final long serialVersionUID = 3079590603587933576L; /** * @see com.vaadin.ui.DefaultFieldFactory#createField(com.vaadin.v7.data.Container, java.lang.Object, java.lang.Object, com.vaadin.ui.Component) */ @Override public Field<?> createField(Container container, Object itemId, Object propertyId, Component uiContext) { Field<?> result = null; if (itemId.equals(getEditItemId().toString()) && isEditProperty((CmsResourceTableProperty)propertyId)) { result = super.createField(container, itemId, propertyId, uiContext); result.addStyleName(OpenCmsTheme.INLINE_TEXTFIELD); result.addValidator(m_editHandler); if (result instanceof TextField) { ((TextField)result).setComponentError(null); ((TextField)result).addShortcutListener(new ShortcutListener("Cancel edit", KeyCode.ESCAPE, null) { private static final long serialVersionUID = 1L; @Override public void handleAction(Object sender, Object target) { cancelEdit(); } }); ((TextField)result).addShortcutListener(new ShortcutListener("Save", KeyCode.ENTER, null) { private static final long serialVersionUID = 1L; @Override public void handleAction(Object sender, Object target) { stopEdit(); } }); ((TextField)result).addBlurListener(m_fileEditHandler); ((TextField)result).setTextChangeEventMode(TextChangeEventMode.LAZY); ((TextField)result).addTextChangeListener(m_editHandler); } result.focus(); } return result; } } /** * Extends the default sorting to differentiate between files and folder when sorting by name.<p> * Also allows sorting by navPos property for the Resource icon column.<p> */ public static class FileSorter extends DefaultItemSorter implements I_CmsItemSorter { /** The serial version id. */ private static final long serialVersionUID = 1L; /** * @see org.opencms.ui.util.I_CmsItemSorter#getSortableContainerPropertyIds(com.vaadin.v7.data.Container) */ public Collection<?> getSortableContainerPropertyIds(Container container) { Set<Object> result = new HashSet<Object>(); for (Object propId : container.getContainerPropertyIds()) { Class<?> propertyType = container.getType(propId); if (Comparable.class.isAssignableFrom(propertyType) || propertyType.isPrimitive() || (propId.equals(CmsResourceTableProperty.PROPERTY_TYPE_ICON) && container.getContainerPropertyIds().contains( CmsResourceTableProperty.PROPERTY_NAVIGATION_POSITION))) { result.add(propId); } } return result; } /** * @see com.vaadin.v7.data.util.DefaultItemSorter#compareProperty(java.lang.Object, boolean, com.vaadin.v7.data.Item, com.vaadin.v7.data.Item) */ @Override protected int compareProperty(Object propertyId, boolean sortDirection, Item item1, Item item2) { if (CmsResourceTableProperty.PROPERTY_RESOURCE_NAME.equals(propertyId)) { Boolean isFolder1 = (Boolean)item1.getItemProperty( CmsResourceTableProperty.PROPERTY_IS_FOLDER).getValue(); Boolean isFolder2 = (Boolean)item2.getItemProperty( CmsResourceTableProperty.PROPERTY_IS_FOLDER).getValue(); if (!isFolder1.equals(isFolder2)) { int result = isFolder1.booleanValue() ? -1 : 1; if (!sortDirection) { result = result * (-1); } return result; } } else if ((CmsResourceTableProperty.PROPERTY_TYPE_ICON.equals(propertyId) || CmsResourceTableProperty.PROPERTY_NAVIGATION_TEXT.equals(propertyId)) && (item1.getItemProperty(CmsResourceTableProperty.PROPERTY_NAVIGATION_POSITION) != null)) { int result; Float pos1 = (Float)item1.getItemProperty( CmsResourceTableProperty.PROPERTY_NAVIGATION_POSITION).getValue(); Float pos2 = (Float)item2.getItemProperty( CmsResourceTableProperty.PROPERTY_NAVIGATION_POSITION).getValue(); if (pos1 == null) { result = pos2 == null ? compareProperty(CmsResourceTableProperty.PROPERTY_RESOURCE_NAME, true, item1, item2) : 1; } else { result = pos2 == null ? -1 : Float.compare(pos1.floatValue(), pos2.floatValue()); } if (!sortDirection) { result = result * (-1); } return result; } return super.compareProperty(propertyId, sortDirection, item1, item2); } } /** * Handles folder selects in the file table.<p> */ public interface I_FolderSelectHandler { /** * Called when the folder name is left clicked.<p> * * @param folderId the selected folder id */ void onFolderSelect(CmsUUID folderId); } /** The default file table columns. */ public static final Map<CmsResourceTableProperty, Integer> DEFAULT_TABLE_PROPERTIES; /** The logger instance for this class. */ static final Log LOG = CmsLog.getLog(CmsFileTable.class); /** The serial version id. */ private static final long serialVersionUID = 5460048685141699277L; /** The selected resources. */ protected List<CmsResource> m_currentResources = new ArrayList<CmsResource>(); /** The default action column property. */ CmsResourceTableProperty m_actionColumnProperty; /** The additional cell style generators. */ List<Table.CellStyleGenerator> m_additionalStyleGenerators; /** The current file property edit handler. */ I_CmsFilePropertyEditHandler m_editHandler; /** File edit event handler. */ FileEditHandler m_fileEditHandler = new FileEditHandler(); /** The context menu. */ CmsContextMenu m_menu; /** The context menu builder. */ I_CmsContextMenuBuilder m_menuBuilder; /** The table drag mode, stored during item editing. */ private TableDragMode m_beforEditDragMode; /** The dialog context provider. */ private I_CmsContextProvider m_contextProvider; /** The edited item id. */ private CmsUUID m_editItemId; /** The edited property id. */ private CmsResourceTableProperty m_editProperty; /** Saved container filters. */ private Collection<Filter> m_filters = Collections.emptyList(); /** The folder select handler. */ private I_FolderSelectHandler m_folderSelectHandler; /** The original edit value. */ private String m_originalEditValue; /** * Default constructor.<p> * * @param contextProvider the dialog context provider */ public CmsFileTable(I_CmsContextProvider contextProvider) { this(contextProvider, DEFAULT_TABLE_PROPERTIES); } /** * Default constructor.<p> * * @param contextProvider the dialog context provider * @param tableColumns the table columns to show */ public CmsFileTable(I_CmsContextProvider contextProvider, Map<CmsResourceTableProperty, Integer> tableColumns) { super(); m_additionalStyleGenerators = new ArrayList<Table.CellStyleGenerator>(); m_actionColumnProperty = PROPERTY_RESOURCE_NAME; m_contextProvider = contextProvider; m_container.setItemSorter(new FileSorter()); m_fileTable.addStyleName(ValoTheme.TABLE_BORDERLESS); m_fileTable.addStyleName(OpenCmsTheme.SIMPLE_DRAG); m_fileTable.setSizeFull(); m_fileTable.setColumnCollapsingAllowed(true); m_fileTable.setSelectable(true); m_fileTable.setMultiSelect(true); m_fileTable.setTableFieldFactory(new FileFieldFactory()); ColumnBuilder builder = new ColumnBuilder(); for (Entry<CmsResourceTableProperty, Integer> entry : tableColumns.entrySet()) { builder.column(entry.getKey(), entry.getValue().intValue()); } builder.buildColumns(); m_fileTable.setSortContainerPropertyId(CmsResourceTableProperty.PROPERTY_RESOURCE_NAME); m_menu = new CmsContextMenu(); m_fileTable.addValueChangeListener(new ValueChangeListener() { private static final long serialVersionUID = 1L; public void valueChange(ValueChangeEvent event) { @SuppressWarnings("unchecked") Set<String> selectedIds = (Set<String>)event.getProperty().getValue(); List<CmsResource> selectedResources = new ArrayList<CmsResource>(); for (String id : selectedIds) { try { CmsResource resource = A_CmsUI.getCmsObject().readResource( getUUIDFromItemID(id), CmsResourceFilter.ALL); selectedResources.add(resource); } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); } } m_currentResources = selectedResources; rebuildMenu(); } }); m_fileTable.addItemClickListener(new ItemClickListener() { private static final long serialVersionUID = 1L; public void itemClick(ItemClickEvent event) { handleFileItemClick(event); } }); m_fileTable.setCellStyleGenerator(new Table.CellStyleGenerator() { private static final long serialVersionUID = 1L; public String getStyle(Table source, Object itemId, Object propertyId) { Item item = m_container.getItem(itemId); String style = getStateStyle(item); if (m_actionColumnProperty == propertyId) { style += " " + OpenCmsTheme.HOVER_COLUMN; } else if ((CmsResourceTableProperty.PROPERTY_NAVIGATION_TEXT == propertyId) || (CmsResourceTableProperty.PROPERTY_TITLE == propertyId)) { if ((item.getItemProperty(CmsResourceTableProperty.PROPERTY_IN_NAVIGATION) != null) && ((Boolean)item.getItemProperty( CmsResourceTableProperty.PROPERTY_IN_NAVIGATION).getValue()).booleanValue()) { style += " " + OpenCmsTheme.IN_NAVIGATION; } } for (Table.CellStyleGenerator generator : m_additionalStyleGenerators) { String additional = generator.getStyle(source, itemId, propertyId); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(additional)) { style += " " + additional; } } return style; } }); m_menu.setAsTableContextMenu(m_fileTable); } static { Map<CmsResourceTableProperty, Integer> defaultProps = new LinkedHashMap<CmsResourceTableProperty, Integer>(); defaultProps.put(PROPERTY_TYPE_ICON, Integer.valueOf(0)); defaultProps.put(PROPERTY_PROJECT, Integer.valueOf(COLLAPSED)); defaultProps.put(PROPERTY_RESOURCE_NAME, Integer.valueOf(0)); defaultProps.put(PROPERTY_TITLE, Integer.valueOf(0)); defaultProps.put(PROPERTY_NAVIGATION_TEXT, Integer.valueOf(COLLAPSED)); defaultProps.put(PROPERTY_NAVIGATION_POSITION, Integer.valueOf(INVISIBLE)); defaultProps.put(PROPERTY_IN_NAVIGATION, Integer.valueOf(INVISIBLE)); defaultProps.put(PROPERTY_COPYRIGHT, Integer.valueOf(COLLAPSED)); defaultProps.put(PROPERTY_CACHE, Integer.valueOf(COLLAPSED)); defaultProps.put(PROPERTY_RESOURCE_TYPE, Integer.valueOf(0)); defaultProps.put(PROPERTY_SIZE, Integer.valueOf(0)); defaultProps.put(PROPERTY_PERMISSIONS, Integer.valueOf(COLLAPSED)); defaultProps.put(PROPERTY_DATE_MODIFIED, Integer.valueOf(0)); defaultProps.put(PROPERTY_USER_MODIFIED, Integer.valueOf(COLLAPSED)); defaultProps.put(PROPERTY_DATE_CREATED, Integer.valueOf(COLLAPSED)); defaultProps.put(PROPERTY_USER_CREATED, Integer.valueOf(COLLAPSED)); defaultProps.put(PROPERTY_DATE_RELEASED, Integer.valueOf(0)); defaultProps.put(PROPERTY_DATE_EXPIRED, Integer.valueOf(0)); defaultProps.put(PROPERTY_STATE_NAME, Integer.valueOf(0)); defaultProps.put(PROPERTY_USER_LOCKED, Integer.valueOf(0)); defaultProps.put(PROPERTY_IS_FOLDER, Integer.valueOf(INVISIBLE)); defaultProps.put(PROPERTY_STATE, Integer.valueOf(INVISIBLE)); defaultProps.put(PROPERTY_INSIDE_PROJECT, Integer.valueOf(INVISIBLE)); defaultProps.put(PROPERTY_RELEASED_NOT_EXPIRED, Integer.valueOf(INVISIBLE)); DEFAULT_TABLE_PROPERTIES = Collections.unmodifiableMap(defaultProps); } /** * Returns the resource state specific style name.<p> * * @param resourceItem the resource item * * @return the style name */ public static String getStateStyle(Item resourceItem) { String result = ""; if (resourceItem != null) { if ((resourceItem.getItemProperty(PROPERTY_INSIDE_PROJECT) == null) || ((Boolean)resourceItem.getItemProperty(PROPERTY_INSIDE_PROJECT).getValue()).booleanValue()) { CmsResourceState state = (CmsResourceState)resourceItem.getItemProperty( CmsResourceTableProperty.PROPERTY_STATE).getValue(); result = getStateStyle(state); } else { result = OpenCmsTheme.PROJECT_OTHER; } if ((resourceItem.getItemProperty(PROPERTY_RELEASED_NOT_EXPIRED) != null) && !((Boolean)resourceItem.getItemProperty(PROPERTY_RELEASED_NOT_EXPIRED).getValue()).booleanValue()) { result += " " + OpenCmsTheme.EXPIRED; } if ((resourceItem.getItemProperty(CmsResourceTableProperty.PROPERTY_DISABLED) != null) && ((Boolean)resourceItem.getItemProperty( CmsResourceTableProperty.PROPERTY_DISABLED).getValue()).booleanValue()) { result += " " + OpenCmsTheme.DISABLED; } } return result; } /** * Adds an additional cell style generator.<p> * * @param styleGenerator the cell style generator */ public void addAdditionalStyleGenerator(Table.CellStyleGenerator styleGenerator) { m_additionalStyleGenerators.add(styleGenerator); } /** * Applies settings generally used within workplace app file lists.<p> */ public void applyWorkplaceAppSettings() { // add site path property to container m_container.addContainerProperty( CmsResourceTableProperty.PROPERTY_SITE_PATH, CmsResourceTableProperty.PROPERTY_SITE_PATH.getColumnType(), CmsResourceTableProperty.PROPERTY_SITE_PATH.getDefaultValue()); // replace the resource name column with the path column Object[] visibleCols = m_fileTable.getVisibleColumns(); for (int i = 0; i < visibleCols.length; i++) { if (CmsResourceTableProperty.PROPERTY_RESOURCE_NAME.equals(visibleCols[i])) { visibleCols[i] = CmsResourceTableProperty.PROPERTY_SITE_PATH; } } m_fileTable.setVisibleColumns(visibleCols); m_fileTable.setColumnCollapsible(CmsResourceTableProperty.PROPERTY_SITE_PATH, false); m_fileTable.setColumnHeader( CmsResourceTableProperty.PROPERTY_SITE_PATH, CmsVaadinUtils.getMessageText(CmsResourceTableProperty.PROPERTY_SITE_PATH.getHeaderKey())); // update column visibility according to the latest file explorer settings CmsFileExplorerSettings settings; try { settings = OpenCms.getWorkplaceAppManager().getAppSettings( A_CmsUI.getCmsObject(), CmsFileExplorerSettings.class); setTableState(settings); } catch (Exception e) { LOG.error("Error while reading file explorer settings from user.", e); } m_fileTable.setSortContainerPropertyId(CmsResourceTableProperty.PROPERTY_SITE_PATH); setActionColumnProperty(CmsResourceTableProperty.PROPERTY_SITE_PATH); setMenuBuilder(new CmsResourceContextMenuBuilder()); } /** * Clears all container filters. */ public void clearFilters() { IndexedContainer container = (IndexedContainer)m_fileTable.getContainerDataSource(); container.removeAllContainerFilters(); } /** * Filters the displayed resources.<p> * Only resources where either the resource name, the title or the nav-text contains the given substring are shown.<p> * * @param search the search term */ public void filterTable(String search) { m_container.removeAllContainerFilters(); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(search)) { m_container.addContainerFilter( new Or( new SimpleStringFilter(CmsResourceTableProperty.PROPERTY_RESOURCE_NAME, search, true, false), new SimpleStringFilter(CmsResourceTableProperty.PROPERTY_NAVIGATION_TEXT, search, true, false), new SimpleStringFilter(CmsResourceTableProperty.PROPERTY_TITLE, search, true, false))); } if ((m_fileTable.getValue() != null) & !((Set<?>)m_fileTable.getValue()).isEmpty()) { m_fileTable.setCurrentPageFirstItemId(((Set<?>)m_fileTable.getValue()).iterator().next()); } } /** * Returns the index of the first visible item.<p> * * @return the first visible item */ public int getFirstVisibleItemIndex() { return m_fileTable.getCurrentPageFirstItemIndex(); } /** * Gets the selected structure ids.<p> * * @return the set of selected structure ids */ @SuppressWarnings("unchecked") public Collection<CmsUUID> getSelectedIds() { return itemIdsToUUIDs((Collection<String>)m_fileTable.getValue()); } /** * Gets the list of selected resources.<p> * * @return the list of selected resources */ public List<CmsResource> getSelectedResources() { return m_currentResources; } /** * Returns the current table state.<p> * * @return the table state */ public CmsFileExplorerSettings getTableSettings() { CmsFileExplorerSettings fileTableState = new CmsFileExplorerSettings(); fileTableState.setSortAscending(m_fileTable.isSortAscending()); fileTableState.setSortColumnId((CmsResourceTableProperty)m_fileTable.getSortContainerPropertyId()); List<CmsResourceTableProperty> collapsedCollumns = new ArrayList<CmsResourceTableProperty>(); Object[] visibleCols = m_fileTable.getVisibleColumns(); for (int i = 0; i < visibleCols.length; i++) { if (m_fileTable.isColumnCollapsed(visibleCols[i])) { collapsedCollumns.add((CmsResourceTableProperty)visibleCols[i]); } } fileTableState.setCollapsedColumns(collapsedCollumns); return fileTableState; } /** * Handles the item selection.<p> * * @param itemId the selected item id */ public void handleSelection(String itemId) { Collection<?> selection = (Collection<?>)m_fileTable.getValue(); if (selection == null) { m_fileTable.select(itemId); } else if (!selection.contains(itemId)) { m_fileTable.setValue(null); m_fileTable.select(itemId); } } /** * Returns if a file property is being edited.<p> * @return <code>true</code> if a file property is being edited */ public boolean isEditing() { return m_editItemId != null; } /** * Returns if the given property is being edited.<p> * * @param propertyId the property id * * @return <code>true</code> if the given property is being edited */ public boolean isEditProperty(CmsResourceTableProperty propertyId) { return (m_editProperty != null) && m_editProperty.equals(propertyId); } /** * Opens the context menu.<p> * * @param event the click event */ public void openContextMenu(ItemClickEvent event) { m_menu.openForTable(event, m_fileTable); } /** * Removes the given cell style generator.<p> * * @param styleGenerator the cell style generator to remove */ public void removeAdditionalStyleGenerator(Table.CellStyleGenerator styleGenerator) { m_additionalStyleGenerators.remove(styleGenerator); } /** * Restores container filters to the ones previously saved via saveFilters(). */ public void restoreFilters() { IndexedContainer container = (IndexedContainer)m_fileTable.getContainerDataSource(); container.removeAllContainerFilters(); for (Filter filter : m_filters) { container.addContainerFilter(filter); } } /** * Saves currently active filters.<p> */ public void saveFilters() { IndexedContainer container = (IndexedContainer)m_fileTable.getContainerDataSource(); m_filters = container.getContainerFilters(); } /** * Sets the default action column property.<p> * * @param actionColumnProperty the default action column property */ public void setActionColumnProperty(CmsResourceTableProperty actionColumnProperty) { m_actionColumnProperty = actionColumnProperty; } /** * Sets the dialog context provider.<p> * * @param provider the dialog context provider */ public void setContextProvider(I_CmsContextProvider provider) { m_contextProvider = provider; } /** * Sets the first visible item index.<p> * * @param i the item index */ public void setFirstVisibleItemIndex(int i) { m_fileTable.setCurrentPageFirstItemIndex(i); } /** * Sets the folder select handler.<p> * * @param folderSelectHandler the folder select handler */ public void setFolderSelectHandler(I_FolderSelectHandler folderSelectHandler) { m_folderSelectHandler = folderSelectHandler; } /** * Sets the menu builder.<p> * * @param builder the menu builder */ public void setMenuBuilder(I_CmsContextMenuBuilder builder) { m_menuBuilder = builder; } /** * Sets the table state.<p> * * @param state the table state */ public void setTableState(CmsFileExplorerSettings state) { if (state != null) { m_fileTable.setSortContainerPropertyId(state.getSortColumnId()); m_fileTable.setSortAscending(state.isSortAscending()); Object[] visibleCols = m_fileTable.getVisibleColumns(); for (int i = 0; i < visibleCols.length; i++) { m_fileTable.setColumnCollapsed(visibleCols[i], state.getCollapsedColumns().contains(visibleCols[i])); } } } /** * Starts inline editing of the given file property.<p> * * @param itemId the item resource structure id * @param propertyId the property to edit * @param editHandler the edit handler */ public void startEdit( CmsUUID itemId, CmsResourceTableProperty propertyId, I_CmsFilePropertyEditHandler editHandler) { m_editItemId = itemId; m_editProperty = propertyId; m_originalEditValue = (String)m_container.getItem(m_editItemId.toString()).getItemProperty( m_editProperty).getValue(); m_editHandler = editHandler; // storing current drag mode and setting it to none to avoid text selection issues in IE11 m_beforEditDragMode = m_fileTable.getDragMode(); m_fileTable.setDragMode(TableDragMode.NONE); m_fileTable.setEditable(true); } /** * Stops the current edit process to save the changed property value.<p> */ public void stopEdit() { if (m_editHandler != null) { String value = (String)m_container.getItem(m_editItemId.toString()).getItemProperty( m_editProperty).getValue(); if (!value.equals(m_originalEditValue)) { m_editHandler.validate(value); m_editHandler.save(value); } else { // call cancel to ensure unlock m_editHandler.cancel(); } } clearEdit(); // restoring drag mode m_fileTable.setDragMode(m_beforEditDragMode); m_beforEditDragMode = null; } /** * Updates all items with ids from the given list.<p> * * @param ids the resource structure ids to update * @param remove true if the item should be removed only */ public void update(Collection<CmsUUID> ids, boolean remove) { for (CmsUUID id : ids) { updateItem(id, remove); } rebuildMenu(); } /** * Updates the column widths.<p> * * The reason this is needed is that the Vaadin table does not support minimum widths for columns, * so expanding columns get squished when most of the horizontal space is used by other columns. * So we try to determine whether the expanded columns would have enough space, and if not, give them a * fixed width. * * @param estimatedSpace the estimated horizontal space available for the table. */ public void updateColumnWidths(int estimatedSpace) { Object[] cols = m_fileTable.getVisibleColumns(); List<CmsResourceTableProperty> expandCols = Lists.newArrayList(); int nonExpandWidth = 0; int totalExpandMinWidth = 0; for (Object colObj : cols) { if (m_fileTable.isColumnCollapsed(colObj)) { continue; } CmsResourceTableProperty prop = (CmsResourceTableProperty)colObj; if (0 < m_fileTable.getColumnExpandRatio(prop)) { expandCols.add(prop); totalExpandMinWidth += getAlternativeWidthForExpandingColumns(prop); } else { nonExpandWidth += prop.getColumnWidth(); } } if (estimatedSpace < (totalExpandMinWidth + nonExpandWidth)) { for (CmsResourceTableProperty expandCol : expandCols) { m_fileTable.setColumnWidth(expandCol, getAlternativeWidthForExpandingColumns(expandCol)); } } } /** * Updates the file table sorting.<p> */ public void updateSorting() { m_fileTable.sort(); } /** * Cancels the current edit process.<p> */ void cancelEdit() { if (m_editHandler != null) { m_editHandler.cancel(); } clearEdit(); } /** * Returns the dialog context provider.<p> * * @return the dialog context provider */ I_CmsContextProvider getContextProvider() { return m_contextProvider; } /** * Returns the edit item id.<p> * * @return the edit item id */ CmsUUID getEditItemId() { return m_editItemId; } /** * Returns the edit property id.<p> * * @return the edit property id */ CmsResourceTableProperty getEditProperty() { return m_editProperty; } /** * Handles the file table item click.<p> * * @param event the click event */ void handleFileItemClick(ItemClickEvent event) { if (isEditing()) { stopEdit(); } else if (!event.isCtrlKey() && !event.isShiftKey()) { // don't interfere with multi-selection using control key String itemId = (String)event.getItemId(); CmsUUID structureId = getUUIDFromItemID(itemId); boolean openedFolder = false; if (event.getButton().equals(MouseButton.RIGHT)) { handleSelection(itemId); openContextMenu(event); } else { if ((event.getPropertyId() == null) || CmsResourceTableProperty.PROPERTY_TYPE_ICON.equals(event.getPropertyId())) { handleSelection(itemId); openContextMenu(event); } else { if (m_actionColumnProperty.equals(event.getPropertyId())) { Boolean isFolder = (Boolean)event.getItem().getItemProperty( CmsResourceTableProperty.PROPERTY_IS_FOLDER).getValue(); if ((isFolder != null) && isFolder.booleanValue()) { if (m_folderSelectHandler != null) { m_folderSelectHandler.onFolderSelect(structureId); } openedFolder = true; } else { try { CmsObject cms = A_CmsUI.getCmsObject(); CmsResource res = cms.readResource(structureId, CmsResourceFilter.IGNORE_EXPIRATION); m_currentResources = Collections.singletonList(res); I_CmsDialogContext context = m_contextProvider.getDialogContext(); I_CmsDefaultAction action = OpenCms.getWorkplaceAppManager().getDefaultAction( context, m_menuBuilder); if (action != null) { action.executeAction(context); return; } } catch (CmsVfsResourceNotFoundException e) { LOG.info(e.getLocalizedMessage(), e); } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); } } } else { I_CmsDialogContext context = m_contextProvider.getDialogContext(); if ((m_currentResources.size() == 1) && m_currentResources.get(0).getStructureId().equals(structureId) && (context instanceof I_CmsEditPropertyContext) && ((I_CmsEditPropertyContext)context).isPropertyEditable(event.getPropertyId())) { ((I_CmsEditPropertyContext)context).editProperty(event.getPropertyId()); } } } } // update the item on click to show any available changes if (!openedFolder) { update(Collections.singletonList(structureId), false); } } } /** * Rebuilds the context menu.<p> */ void rebuildMenu() { if (!getSelectedIds().isEmpty() && (m_menuBuilder != null)) { m_menu.removeAllItems(); m_menuBuilder.buildContextMenu(getContextProvider().getDialogContext(), m_menu); } } /** * Clears the current edit process.<p> */ private void clearEdit() { m_fileTable.setEditable(false); if (m_editItemId != null) { updateItem(m_editItemId, false); } m_editItemId = null; m_editProperty = null; m_editHandler = null; updateSorting(); } /** * Gets alternative width for expanding table columns which is used when there is not enough space for * all visible columns.<p> * * @param prop the table property * @return the alternative column width */ private int getAlternativeWidthForExpandingColumns(CmsResourceTableProperty prop) { if (prop.getId().equals(CmsResourceTableProperty.PROPERTY_RESOURCE_NAME.getId())) { return 200; } if (prop.getId().equals(CmsResourceTableProperty.PROPERTY_TITLE.getId())) { return 300; } if (prop.getId().equals(CmsResourceTableProperty.PROPERTY_NAVIGATION_TEXT.getId())) { return 200; } return 200; } /** * Updates the given item in the file table.<p> * * @param itemId the item id * @param remove true if the item should be removed only */ private void updateItem(CmsUUID itemId, boolean remove) { if (remove) { String idStr = itemId != null ? itemId.toString() : null; m_container.removeItem(idStr); return; } CmsObject cms = A_CmsUI.getCmsObject(); try { CmsResource resource = cms.readResource(itemId, CmsResourceFilter.ALL); fillItem(cms, resource, OpenCms.getWorkplaceManager().getWorkplaceLocale(cms)); } catch (CmsVfsResourceNotFoundException e) { m_container.removeItem(itemId); LOG.debug("Failed to update file table item, removing it from view.", e); } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); } } }
Improved sorting for String properties in file tables.
src/org/opencms/ui/components/CmsFileTable.java
Improved sorting for String properties in file tables.
<ide><path>rc/org/opencms/ui/components/CmsFileTable.java <ide> import org.opencms.util.CmsStringUtil; <ide> import org.opencms.util.CmsUUID; <ide> <add>import java.text.Collator; <ide> import java.util.ArrayList; <ide> import java.util.Collection; <ide> import java.util.Collections; <ide> result = result * (-1); <ide> } <ide> return result; <add> } else if (((CmsResourceTableProperty)propertyId).getColumnType().equals(String.class)) { <add> String value1 = (String)item1.getItemProperty(propertyId).getValue(); <add> String value2 = (String)item2.getItemProperty(propertyId).getValue(); <add> Collator collator = Collator.getInstance( <add> OpenCms.getWorkplaceManager().getWorkplaceLocale(A_CmsUI.getCmsObject())); <add> return collator.compare(value1, value2); <ide> } <ide> return super.compareProperty(propertyId, sortDirection, item1, item2); <ide> } <ide> <ide> /** The serial version id. */ <ide> private static final long serialVersionUID = 5460048685141699277L; <del> <del> /** The selected resources. */ <del> protected List<CmsResource> m_currentResources = new ArrayList<CmsResource>(); <del> <del> /** The default action column property. */ <del> CmsResourceTableProperty m_actionColumnProperty; <del> <del> /** The additional cell style generators. */ <del> List<Table.CellStyleGenerator> m_additionalStyleGenerators; <del> <del> /** The current file property edit handler. */ <del> I_CmsFilePropertyEditHandler m_editHandler; <del> <del> /** File edit event handler. */ <del> FileEditHandler m_fileEditHandler = new FileEditHandler(); <del> <del> /** The context menu. */ <del> CmsContextMenu m_menu; <del> <del> /** The context menu builder. */ <del> I_CmsContextMenuBuilder m_menuBuilder; <del> <del> /** The table drag mode, stored during item editing. */ <del> private TableDragMode m_beforEditDragMode; <del> <del> /** The dialog context provider. */ <del> private I_CmsContextProvider m_contextProvider; <del> <del> /** The edited item id. */ <del> private CmsUUID m_editItemId; <del> <del> /** The edited property id. */ <del> private CmsResourceTableProperty m_editProperty; <del> <del> /** Saved container filters. */ <del> private Collection<Filter> m_filters = Collections.emptyList(); <del> <del> /** The folder select handler. */ <del> private I_FolderSelectHandler m_folderSelectHandler; <del> <del> /** The original edit value. */ <del> private String m_originalEditValue; <del> <del> /** <del> * Default constructor.<p> <del> * <del> * @param contextProvider the dialog context provider <del> */ <del> public CmsFileTable(I_CmsContextProvider contextProvider) { <del> <del> this(contextProvider, DEFAULT_TABLE_PROPERTIES); <del> } <del> <del> /** <del> * Default constructor.<p> <del> * <del> * @param contextProvider the dialog context provider <del> * @param tableColumns the table columns to show <del> */ <del> public CmsFileTable(I_CmsContextProvider contextProvider, Map<CmsResourceTableProperty, Integer> tableColumns) { <del> <del> super(); <del> m_additionalStyleGenerators = new ArrayList<Table.CellStyleGenerator>(); <del> m_actionColumnProperty = PROPERTY_RESOURCE_NAME; <del> m_contextProvider = contextProvider; <del> m_container.setItemSorter(new FileSorter()); <del> m_fileTable.addStyleName(ValoTheme.TABLE_BORDERLESS); <del> m_fileTable.addStyleName(OpenCmsTheme.SIMPLE_DRAG); <del> m_fileTable.setSizeFull(); <del> m_fileTable.setColumnCollapsingAllowed(true); <del> m_fileTable.setSelectable(true); <del> m_fileTable.setMultiSelect(true); <del> <del> m_fileTable.setTableFieldFactory(new FileFieldFactory()); <del> ColumnBuilder builder = new ColumnBuilder(); <del> for (Entry<CmsResourceTableProperty, Integer> entry : tableColumns.entrySet()) { <del> builder.column(entry.getKey(), entry.getValue().intValue()); <del> } <del> builder.buildColumns(); <del> <del> m_fileTable.setSortContainerPropertyId(CmsResourceTableProperty.PROPERTY_RESOURCE_NAME); <del> m_menu = new CmsContextMenu(); <del> m_fileTable.addValueChangeListener(new ValueChangeListener() { <del> <del> private static final long serialVersionUID = 1L; <del> <del> public void valueChange(ValueChangeEvent event) { <del> <del> @SuppressWarnings("unchecked") <del> Set<String> selectedIds = (Set<String>)event.getProperty().getValue(); <del> List<CmsResource> selectedResources = new ArrayList<CmsResource>(); <del> for (String id : selectedIds) { <del> try { <del> CmsResource resource = A_CmsUI.getCmsObject().readResource( <del> getUUIDFromItemID(id), <del> CmsResourceFilter.ALL); <del> selectedResources.add(resource); <del> } catch (CmsException e) { <del> LOG.error(e.getLocalizedMessage(), e); <del> } <del> <del> } <del> m_currentResources = selectedResources; <del> <del> rebuildMenu(); <del> } <del> }); <del> <del> m_fileTable.addItemClickListener(new ItemClickListener() { <del> <del> private static final long serialVersionUID = 1L; <del> <del> public void itemClick(ItemClickEvent event) { <del> <del> handleFileItemClick(event); <del> } <del> }); <del> <del> m_fileTable.setCellStyleGenerator(new Table.CellStyleGenerator() { <del> <del> private static final long serialVersionUID = 1L; <del> <del> public String getStyle(Table source, Object itemId, Object propertyId) { <del> <del> Item item = m_container.getItem(itemId); <del> String style = getStateStyle(item); <del> if (m_actionColumnProperty == propertyId) { <del> style += " " + OpenCmsTheme.HOVER_COLUMN; <del> } else if ((CmsResourceTableProperty.PROPERTY_NAVIGATION_TEXT == propertyId) <del> || (CmsResourceTableProperty.PROPERTY_TITLE == propertyId)) { <del> if ((item.getItemProperty(CmsResourceTableProperty.PROPERTY_IN_NAVIGATION) != null) <del> && ((Boolean)item.getItemProperty( <del> CmsResourceTableProperty.PROPERTY_IN_NAVIGATION).getValue()).booleanValue()) { <del> style += " " + OpenCmsTheme.IN_NAVIGATION; <del> } <del> } <del> for (Table.CellStyleGenerator generator : m_additionalStyleGenerators) { <del> String additional = generator.getStyle(source, itemId, propertyId); <del> if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(additional)) { <del> style += " " + additional; <del> } <del> } <del> return style; <del> } <del> }); <del> <del> m_menu.setAsTableContextMenu(m_fileTable); <del> } <ide> <ide> static { <ide> Map<CmsResourceTableProperty, Integer> defaultProps = new LinkedHashMap<CmsResourceTableProperty, Integer>(); <ide> defaultProps.put(PROPERTY_INSIDE_PROJECT, Integer.valueOf(INVISIBLE)); <ide> defaultProps.put(PROPERTY_RELEASED_NOT_EXPIRED, Integer.valueOf(INVISIBLE)); <ide> DEFAULT_TABLE_PROPERTIES = Collections.unmodifiableMap(defaultProps); <add> } <add> <add> /** The selected resources. */ <add> protected List<CmsResource> m_currentResources = new ArrayList<CmsResource>(); <add> <add> /** The default action column property. */ <add> CmsResourceTableProperty m_actionColumnProperty; <add> <add> /** The additional cell style generators. */ <add> List<Table.CellStyleGenerator> m_additionalStyleGenerators; <add> <add> /** The current file property edit handler. */ <add> I_CmsFilePropertyEditHandler m_editHandler; <add> <add> /** File edit event handler. */ <add> FileEditHandler m_fileEditHandler = new FileEditHandler(); <add> <add> /** The context menu. */ <add> CmsContextMenu m_menu; <add> <add> /** The context menu builder. */ <add> I_CmsContextMenuBuilder m_menuBuilder; <add> <add> /** The table drag mode, stored during item editing. */ <add> private TableDragMode m_beforEditDragMode; <add> <add> /** The dialog context provider. */ <add> private I_CmsContextProvider m_contextProvider; <add> <add> /** The edited item id. */ <add> private CmsUUID m_editItemId; <add> <add> /** The edited property id. */ <add> private CmsResourceTableProperty m_editProperty; <add> <add> /** Saved container filters. */ <add> private Collection<Filter> m_filters = Collections.emptyList(); <add> <add> /** The folder select handler. */ <add> private I_FolderSelectHandler m_folderSelectHandler; <add> <add> /** The original edit value. */ <add> private String m_originalEditValue; <add> <add> /** <add> * Default constructor.<p> <add> * <add> * @param contextProvider the dialog context provider <add> */ <add> public CmsFileTable(I_CmsContextProvider contextProvider) { <add> <add> this(contextProvider, DEFAULT_TABLE_PROPERTIES); <add> } <add> <add> /** <add> * Default constructor.<p> <add> * <add> * @param contextProvider the dialog context provider <add> * @param tableColumns the table columns to show <add> */ <add> public CmsFileTable(I_CmsContextProvider contextProvider, Map<CmsResourceTableProperty, Integer> tableColumns) { <add> <add> super(); <add> m_additionalStyleGenerators = new ArrayList<Table.CellStyleGenerator>(); <add> m_actionColumnProperty = PROPERTY_RESOURCE_NAME; <add> m_contextProvider = contextProvider; <add> m_container.setItemSorter(new FileSorter()); <add> m_fileTable.addStyleName(ValoTheme.TABLE_BORDERLESS); <add> m_fileTable.addStyleName(OpenCmsTheme.SIMPLE_DRAG); <add> m_fileTable.setSizeFull(); <add> m_fileTable.setColumnCollapsingAllowed(true); <add> m_fileTable.setSelectable(true); <add> m_fileTable.setMultiSelect(true); <add> <add> m_fileTable.setTableFieldFactory(new FileFieldFactory()); <add> ColumnBuilder builder = new ColumnBuilder(); <add> for (Entry<CmsResourceTableProperty, Integer> entry : tableColumns.entrySet()) { <add> builder.column(entry.getKey(), entry.getValue().intValue()); <add> } <add> builder.buildColumns(); <add> <add> m_fileTable.setSortContainerPropertyId(CmsResourceTableProperty.PROPERTY_RESOURCE_NAME); <add> m_menu = new CmsContextMenu(); <add> m_fileTable.addValueChangeListener(new ValueChangeListener() { <add> <add> private static final long serialVersionUID = 1L; <add> <add> public void valueChange(ValueChangeEvent event) { <add> <add> @SuppressWarnings("unchecked") <add> Set<String> selectedIds = (Set<String>)event.getProperty().getValue(); <add> List<CmsResource> selectedResources = new ArrayList<CmsResource>(); <add> for (String id : selectedIds) { <add> try { <add> CmsResource resource = A_CmsUI.getCmsObject().readResource( <add> getUUIDFromItemID(id), <add> CmsResourceFilter.ALL); <add> selectedResources.add(resource); <add> } catch (CmsException e) { <add> LOG.error(e.getLocalizedMessage(), e); <add> } <add> <add> } <add> m_currentResources = selectedResources; <add> <add> rebuildMenu(); <add> } <add> }); <add> <add> m_fileTable.addItemClickListener(new ItemClickListener() { <add> <add> private static final long serialVersionUID = 1L; <add> <add> public void itemClick(ItemClickEvent event) { <add> <add> handleFileItemClick(event); <add> } <add> }); <add> <add> m_fileTable.setCellStyleGenerator(new Table.CellStyleGenerator() { <add> <add> private static final long serialVersionUID = 1L; <add> <add> public String getStyle(Table source, Object itemId, Object propertyId) { <add> <add> Item item = m_container.getItem(itemId); <add> String style = getStateStyle(item); <add> if (m_actionColumnProperty == propertyId) { <add> style += " " + OpenCmsTheme.HOVER_COLUMN; <add> } else if ((CmsResourceTableProperty.PROPERTY_NAVIGATION_TEXT == propertyId) <add> || (CmsResourceTableProperty.PROPERTY_TITLE == propertyId)) { <add> if ((item.getItemProperty(CmsResourceTableProperty.PROPERTY_IN_NAVIGATION) != null) <add> && ((Boolean)item.getItemProperty( <add> CmsResourceTableProperty.PROPERTY_IN_NAVIGATION).getValue()).booleanValue()) { <add> style += " " + OpenCmsTheme.IN_NAVIGATION; <add> } <add> } <add> for (Table.CellStyleGenerator generator : m_additionalStyleGenerators) { <add> String additional = generator.getStyle(source, itemId, propertyId); <add> if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(additional)) { <add> style += " " + additional; <add> } <add> } <add> return style; <add> } <add> }); <add> <add> m_menu.setAsTableContextMenu(m_fileTable); <ide> } <ide> <ide> /**
Java
apache-2.0
a90cc83cbadd370fe54e414c8b16ab8743b79069
0
toomasr/sgf4j-gui,toomasr/sgf4j-gui
package com.toomasr.sgf4j.gui; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import com.toomasr.sgf4j.Sgf; import com.toomasr.sgf4j.SgfProperties; import com.toomasr.sgf4j.board.BoardStone; import com.toomasr.sgf4j.board.CoordinateSquare; import com.toomasr.sgf4j.board.GuiBoardListener; import com.toomasr.sgf4j.board.StoneState; import com.toomasr.sgf4j.board.VirtualBoard; import com.toomasr.sgf4j.filetree.FileTreeView; import com.toomasr.sgf4j.movetree.EmptyTriangle; import com.toomasr.sgf4j.movetree.GlueStone; import com.toomasr.sgf4j.movetree.GlueStoneType; import com.toomasr.sgf4j.movetree.TreeStone; import com.toomasr.sgf4j.parser.Game; import com.toomasr.sgf4j.parser.GameNode; import com.toomasr.sgf4j.parser.Util; import com.toomasr.sgf4j.properties.AppState; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.control.ScrollPane.ScrollBarPolicy; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeView; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.TilePane; import javafx.scene.layout.VBox; public class MainUI { private Button nextButton; private GameNode currentMove = null; private GameNode prevMove = null; private Game game; private VirtualBoard virtualBoard; private BoardStone[][] board; private GridPane movePane; private GridPane boardPane = new GridPane(); private Map<GameNode, TreeStone> nodeToTreeStone = new HashMap<>(); private TextArea commentArea; private Button previousButton; private ScrollPane treePaneScrollPane; private Label whitePlayerName; private Label blackPlayerName; private Label label; public MainUI() { board = new BoardStone[19][19]; virtualBoard = new VirtualBoard(); virtualBoard.addBoardListener(new GuiBoardListener(this)); } public Pane buildUI() throws Exception { /* * -------------------------- * | | | | * | left | center | right | * | | | | * -------------------------- */ Insets paneInsets = new Insets(5, 0, 0, 0); VBox leftVBox = new VBox(5); leftVBox.setPadding(paneInsets); VBox centerVBox = new VBox(5); centerVBox.setPadding(paneInsets); VBox rightVBox = new VBox(5); rightVBox.setPadding(paneInsets); // constructing the left box VBox fileTreePane = generateFileTreePane(); leftVBox.getChildren().addAll(fileTreePane); // constructing the center box centerVBox.setMaxWidth(640); centerVBox.setMinWidth(640); boardPane = generateBoardPane(boardPane); TilePane buttonPane = generateButtonPane(); ScrollPane treePane = generateMoveTreePane(); centerVBox.getChildren().addAll(boardPane, buttonPane, treePane); // constructing the right box VBox gameMetaInfo = generateGameMetaInfo(); TextArea commentArea = generateCommentPane(); rightVBox.getChildren().addAll(gameMetaInfo, commentArea); HBox rootHBox = new HBox(); enableKeyboardShortcuts(rootHBox); rootHBox.getChildren().addAll(leftVBox, centerVBox, rightVBox); VBox rootVbox = new VBox(); HBox statusBar = generateStatusBar(); rootVbox.getChildren().addAll(rootHBox, statusBar); return rootVbox; } private HBox generateStatusBar() { HBox rtrn = new HBox(); label = new Label("MainUI loaded"); rtrn.getChildren().add(label); return rtrn; } public void updateStatus(String update) { this.label.setText(update); } public void initGame() { String game = "src/main/resources/game.sgf"; Path path = Paths.get(game); // in development it is nice to have a game open on start if (path.toFile().exists()) { initializeGame(Paths.get(game)); } } private VBox generateGameMetaInfo() { VBox vbox = new VBox(); vbox.setMinWidth(250); GridPane pane = new GridPane(); Label blackPlayerLabel = new Label("Black:"); GridPane.setConstraints(blackPlayerLabel, 1, 0); blackPlayerName = new Label("Unknown"); GridPane.setConstraints(blackPlayerName, 2, 0); Label whitePlayerLabel = new Label("White:"); GridPane.setConstraints(whitePlayerLabel, 1, 1); whitePlayerName = new Label("Unknown"); GridPane.setConstraints(whitePlayerName, 2, 1); pane.getChildren().addAll(blackPlayerLabel, blackPlayerName, whitePlayerLabel, whitePlayerName); vbox.getChildren().add(pane); return vbox; } private TextArea generateCommentPane() { commentArea = new TextArea(); commentArea.setFocusTraversable(false); commentArea.setWrapText(true); commentArea.setPrefSize(300, 600); return commentArea; } private void initializeGame(Path pathToSgf) { this.game = Sgf.createFromPath(pathToSgf); currentMove = this.game.getRootNode(); prevMove = null; // reset our virtual board and actual board virtualBoard = new VirtualBoard(); virtualBoard.addBoardListener(new GuiBoardListener(this)); initEmptyBoard(); // construct the tree of the moves nodeToTreeStone = new HashMap<>(); movePane.getChildren().clear(); movePane.add(new EmptyTriangle(), 0, 0); GameNode rootNode = game.getRootNode(); populateMoveTreePane(rootNode, 0); showMarkersForMove(rootNode); showCommentForMove(rootNode); showMetaInfoForGame(this.game); treePaneScrollPane.setHvalue(0); treePaneScrollPane.setVvalue(0); } private void showMetaInfoForGame(Game game) { whitePlayerName.setText(game.getProperty(SgfProperties.WHITE_PLAYER_NAME)); blackPlayerName.setText(game.getProperty(SgfProperties.BLACK_PLAYER_NAME)); } public void initEmptyBoard() { generateBoardPane(boardPane); placePreGameStones(game); } private void placePreGameStones(Game game) { String blackStones = game.getProperty("AB", ""); String whiteStones = game.getProperty("AW", ""); placePreGameStones(blackStones, whiteStones); } private void placePreGameStones(GameNode node) { String blackStones = node.getProperty("AB", ""); String whiteStones = node.getProperty("AW", ""); placePreGameStones(blackStones, whiteStones); } private void placePreGameStones(String addBlack, String addWhite) { if (addBlack.length() > 0) { String[] blackStones = addBlack.split(","); for (int i = 0; i < blackStones.length; i++) { int[] moveCoords = Util.alphaToCoords(blackStones[i]); virtualBoard.placeStone(StoneState.BLACK, moveCoords[0], moveCoords[1]); } } if (addWhite.length() > 0) { String[] whiteStones = addWhite.split(","); for (int i = 0; i < whiteStones.length; i++) { int[] moveCoords = Util.alphaToCoords(whiteStones[i]); virtualBoard.placeStone(StoneState.WHITE, moveCoords[0], moveCoords[1]); } } } private void populateMoveTreePane(GameNode node, int depth) { // we draw out only actual moves if (node.isMove()) { TreeStone treeStone = TreeStone.create(node); movePane.add(treeStone, node.getMoveNo(), node.getVisualDepth()); nodeToTreeStone.put(node, treeStone); treeStone.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { TreeStone stone = (TreeStone) event.getSource(); fastForwardTo(stone.getMove()); } }); } // and recursively draw the next node on this line of play if (node.getNextNode() != null) { populateMoveTreePane(node.getNextNode(), depth + node.getVisualDepth()); } // populate the children also if (node.hasChildren()) { Set<GameNode> children = node.getChildren(); // will determine whether the glue stone should be a single // diagonal or a multiple (diagonal and vertical) GlueStoneType gStoneType = children.size() > 1 ? GlueStoneType.MULTIPLE : GlueStoneType.DIAGONAL; for (Iterator<GameNode> ite = children.iterator(); ite.hasNext();) { GameNode childNode = ite.next(); // the last glue shouldn't be a MULTIPLE if (GlueStoneType.MULTIPLE.equals(gStoneType) && !ite.hasNext()) { gStoneType = GlueStoneType.DIAGONAL; } // the visual lines can also be under a the first triangle int nodeVisualDepth = node.getVisualDepth(); int moveNo = node.getMoveNo(); if (moveNo == -1) { moveNo = 0; nodeVisualDepth = 0; } // also draw all the "missing" glue stones for (int i = nodeVisualDepth + 1; i < childNode.getVisualDepth(); i++) { movePane.add(new GlueStone(GlueStoneType.VERTICAL), moveNo, i); } // glue stone for the node movePane.add(new GlueStone(gStoneType), moveNo, childNode.getVisualDepth()); // and recursively draw the actual node populateMoveTreePane(childNode, depth + childNode.getVisualDepth()); } } } /* * Generates the boilerplate for the move tree pane. The * pane is actually populated during game initialization. */ private ScrollPane generateMoveTreePane() { movePane = new GridPane(); movePane.setPadding(new Insets(0, 0, 0, 0)); movePane.setStyle("-fx-background-color: white"); treePaneScrollPane = new ScrollPane(movePane); treePaneScrollPane.setPrefHeight(150); treePaneScrollPane.setHbarPolicy(ScrollBarPolicy.AS_NEEDED); treePaneScrollPane.setVbarPolicy(ScrollBarPolicy.AS_NEEDED); movePane.setMinWidth(640); return treePaneScrollPane; } private void fastForwardTo(GameNode move) { // clear the board for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[i].length; j++) { board[i][j].removeStone(); } } placePreGameStones(game); deHighLightStoneInTree(currentMove); removeMarkersForNode(currentMove); virtualBoard.fastForwardTo(move); highLightStoneOnBoard(move); } private VBox generateFileTreePane() { VBox vbox = new VBox(); vbox.setMinWidth(250); TreeView<File> treeView = new FileTreeView(); treeView.setFocusTraversable(false); Label label = new Label("Choose SGF File"); vbox.getChildren().addAll(label, treeView); treeView.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { if (event.getClickCount() == 2) { TreeItem<File> item = treeView.getSelectionModel().getSelectedItem(); File file = item.getValue().toPath().toFile(); if (file.isFile()) { initializeGame(item.getValue().toPath()); } AppState.getInstance().addProperty(AppState.CURRENT_FILE, file.getAbsolutePath()); } } }); return vbox; } private TilePane generateButtonPane() { TilePane pane = new TilePane(); pane.setAlignment(Pos.CENTER); pane.getStyleClass().add("bordered"); TextField moveNoField = new TextField("0"); moveNoField.setFocusTraversable(false); moveNoField.setMaxWidth(40); moveNoField.setEditable(false); nextButton = new Button("Next"); nextButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { handleNextPressed(); } }); previousButton = new Button("Previous"); previousButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { handlePreviousPressed(); } }); pane.setPrefColumns(1); pane.getChildren().add(previousButton); pane.getChildren().add(moveNoField); pane.getChildren().add(nextButton); return pane; } private void handleNextPressed() { if (currentMove.getNextNode() != null) { prevMove = currentMove; currentMove = currentMove.getNextNode(); virtualBoard.makeMove(currentMove, prevMove); // scroll the scrollpane to make // the highlighted move visible ensureVisibleForActiveTreeNode(currentMove); } } private void handleNextBranch() { if (currentMove.hasChildren()) { prevMove = currentMove; currentMove = currentMove.getChildren().iterator().next(); virtualBoard.makeMove(currentMove, prevMove); // scroll the scrollpane to make // the highlighted move visible ensureVisibleForActiveTreeNode(currentMove); } } public void handlePreviousPressed() { if (currentMove.getParentNode() != null) { prevMove = currentMove; currentMove = currentMove.getParentNode(); virtualBoard.undoMove(prevMove, currentMove); } } public void playMove(GameNode move, GameNode prevMove) { this.currentMove = move; this.prevMove = prevMove; // we actually have a previous move! if (prevMove != null) { // de-highlight previously highlighted move if (prevMove.isMove() && !prevMove.isPass()) { deHighLightStoneOnBoard(prevMove); } // even non moves can haver markers removeMarkersForNode(prevMove); } if (move != null && !move.isPass() && !move.isPlacementMove()) { highLightStoneOnBoard(move); } // highlight stone in the tree pane deHighLightStoneInTree(prevMove); highLightStoneInTree(move); if (move != null && (move.getProperty("AB") != null || move.getProperty("AW") != null)) { placePreGameStones(move); } // show the associated comment showCommentForMove(move); // handle the prev and new markers showMarkersForMove(move); nextButton.requestFocus(); } public void undoMove(GameNode move, GameNode prevMove) { this.currentMove = prevMove; this.prevMove = move; if (move != null) { removeMarkersForNode(move); } if (prevMove != null) { showMarkersForMove(prevMove); showCommentForMove(prevMove); if (prevMove.isMove() && !prevMove.isPass()) highLightStoneOnBoard(prevMove); } deHighLightStoneInTree(move); highLightStoneInTree(prevMove); ensureVisibleForActiveTreeNode(prevMove); // rather have previous move button have focus previousButton.requestFocus(); } private void ensureVisibleForActiveTreeNode(GameNode move) { if (move != null && move.isMove()) { TreeStone stone = nodeToTreeStone.get(move); // the move tree is not yet fully operational and some // points don't exist in the map yet if (stone == null) return; double width = treePaneScrollPane.getContent().getBoundsInLocal().getWidth(); double x = stone.getBoundsInParent().getMaxX(); double scrollTo = ((x) - 11 * 30) / (width - 21 * 30); treePaneScrollPane.setHvalue(scrollTo); // adjust the vertical scroll double height = treePaneScrollPane.getContent().getBoundsInLocal().getHeight(); double y = stone.getBoundsInParent().getMaxY(); double scrollToY = y / height; if (move.getVisualDepth() == 0) { scrollToY = 0d; } treePaneScrollPane.setVvalue(scrollToY); } } private void highLightStoneInTree(GameNode move) { TreeStone stone = nodeToTreeStone.get(move); // can remove the null check at one point when the // tree is fully implemented if (stone != null) { stone.highLight(); stone.requestFocus(); } } private void deHighLightStoneInTree(GameNode node) { if (node != null && node.isMove()) { TreeStone stone = nodeToTreeStone.get(node); if (stone != null) { stone.deHighLight(); } else { throw new RuntimeException("Unable to find node for move " + node); } } } private void showCommentForMove(GameNode move) { String comment = move.getProperty("C"); if (comment == null) { comment = ""; } // some helpers I used for parsing needs to be undone - see the Parser.java // in sgf4j project comment = comment.replaceAll("@@@@@", "\\\\\\["); comment = comment.replaceAll("#####", "\\\\\\]"); // lets do some replacing - see http://www.red-bean.com/sgf/sgf4.html#text comment = comment.replaceAll("\\\\\n", ""); comment = comment.replaceAll("\\\\:", ":"); comment = comment.replaceAll("\\\\\\]", "]"); comment = comment.replaceAll("\\\\\\[", "["); commentArea.setText(comment); } private void showMarkersForMove(GameNode move) { // the L property is actually not used in FF3 and FF4 // but I own many SGFs that still have it String markerProp = move.getProperty("L"); if (markerProp != null) { int alphaIdx = 0; String[] markers = markerProp.split("\\]\\["); for (int i = 0; i < markers.length; i++) { int[] coords = Util.alphaToCoords(markers[i]); board[coords[0]][coords[1]].addOverlayText(Util.alphabet[alphaIdx++]); } } // also handle the LB labels Map<String, String> labels = Util.extractLabels(move.getProperty("LB")); for (Iterator<Map.Entry<String, String>> ite = labels.entrySet().iterator(); ite.hasNext();) { Map.Entry<String, String> entry = ite.next(); int[] coords = Util.alphaToCoords(entry.getKey()); board[coords[0]][coords[1]].addOverlayText(entry.getValue()); } } private void removeMarkersForNode(GameNode node) { // the L property is actually not used in FF3 and FF4 // but I own many SGFs that still have it String markerProp = node.getProperty("L"); if (markerProp != null) { String[] markers = markerProp.split("\\]\\["); for (int i = 0; i < markers.length; i++) { int[] coords = Util.alphaToCoords(markers[i]); board[coords[0]][coords[1]].removeOverlayText(); } } // also handle the LB labels Map<String, String> labels = Util.extractLabels(node.getProperty("LB")); for (Iterator<Map.Entry<String, String>> ite = labels.entrySet().iterator(); ite.hasNext();) { Map.Entry<String, String> entry = ite.next(); int[] coords = Util.alphaToCoords(entry.getKey()); board[coords[0]][coords[1]].removeOverlayText(); } } private void highLightStoneOnBoard(GameNode move) { String currentMove = move.getMoveString(); int[] moveCoords = Util.alphaToCoords(currentMove); board[moveCoords[0]][moveCoords[1]].highLightStone(); } private void deHighLightStoneOnBoard(GameNode prevMove) { String prevMoveAsStr = prevMove.getMoveString(); int[] moveCoords = Util.alphaToCoords(prevMoveAsStr); board[moveCoords[0]][moveCoords[1]].deHighLightStone(); } private GridPane generateBoardPane(GridPane boardPane) { boardPane.getChildren().clear(); for (int i = 0; i < 21; i++) { if (i > 1 && i < 20) { board[i - 1] = new BoardStone[19]; } for (int j = 0; j < 21; j++) { if (i == 0 || j == 0 || i == 20 || j == 20) { CoordinateSquare btn = new CoordinateSquare(i, j); boardPane.add(btn, i, j); } else { BoardStone btn = new BoardStone(i, j); boardPane.add(btn, i, j); board[i - 1][j - 1] = btn; } } } return boardPane; } private void enableKeyboardShortcuts(HBox topHBox) { topHBox.setOnKeyPressed(new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent event) { if (event.getEventType().equals(KeyEvent.KEY_PRESSED)) { if (event.getCode().equals(KeyCode.LEFT)) { handlePreviousPressed(); } else if (event.getCode().equals(KeyCode.RIGHT)) { handleNextPressed(); } else if (event.getCode().equals(KeyCode.DOWN)) { handleNextBranch(); } } } }); } public BoardStone[][] getBoard() { return this.board; } }
src/main/java/com/toomasr/sgf4j/gui/MainUI.java
package com.toomasr.sgf4j.gui; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import com.toomasr.sgf4j.Sgf; import com.toomasr.sgf4j.SgfProperties; import com.toomasr.sgf4j.board.BoardStone; import com.toomasr.sgf4j.board.CoordinateSquare; import com.toomasr.sgf4j.board.GuiBoardListener; import com.toomasr.sgf4j.board.StoneState; import com.toomasr.sgf4j.board.VirtualBoard; import com.toomasr.sgf4j.filetree.FileTreeView; import com.toomasr.sgf4j.movetree.EmptyTriangle; import com.toomasr.sgf4j.movetree.GlueStone; import com.toomasr.sgf4j.movetree.GlueStoneType; import com.toomasr.sgf4j.movetree.TreeStone; import com.toomasr.sgf4j.parser.Game; import com.toomasr.sgf4j.parser.GameNode; import com.toomasr.sgf4j.parser.Util; import com.toomasr.sgf4j.properties.AppState; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.control.ScrollPane.ScrollBarPolicy; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeView; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.TilePane; import javafx.scene.layout.VBox; public class MainUI { private Button nextButton; private GameNode currentMove = null; private GameNode prevMove = null; private Game game; private VirtualBoard virtualBoard; private BoardStone[][] board; private GridPane movePane; private GridPane boardPane = new GridPane(); private Map<GameNode, TreeStone> nodeToTreeStone = new HashMap<>(); private TextArea commentArea; private Button previousButton; private ScrollPane treePaneScrollPane; private Label whitePlayerName; private Label blackPlayerName; private Label label; public MainUI() { board = new BoardStone[19][19]; virtualBoard = new VirtualBoard(); virtualBoard.addBoardListener(new GuiBoardListener(this)); } public Pane buildUI() throws Exception { /* * -------------------------- * | | | | * | left | center | right | * | | | | * -------------------------- */ Insets paneInsets = new Insets(5, 0, 0, 0); VBox leftVBox = new VBox(5); leftVBox.setPadding(paneInsets); VBox centerVBox = new VBox(5); centerVBox.setPadding(paneInsets); VBox rightVBox = new VBox(5); rightVBox.setPadding(paneInsets); // constructing the left box VBox fileTreePane = generateFileTreePane(); leftVBox.getChildren().addAll(fileTreePane); // constructing the center box centerVBox.setMaxWidth(640); centerVBox.setMinWidth(640); boardPane = generateBoardPane(boardPane); TilePane buttonPane = generateButtonPane(); ScrollPane treePane = generateMoveTreePane(); centerVBox.getChildren().addAll(boardPane, buttonPane, treePane); // constructing the right box VBox gameMetaInfo = generateGameMetaInfo(); TextArea commentArea = generateCommentPane(); rightVBox.getChildren().addAll(gameMetaInfo, commentArea); HBox rootHBox = new HBox(); enableKeyboardShortcuts(rootHBox); rootHBox.getChildren().addAll(leftVBox, centerVBox, rightVBox); VBox rootVbox = new VBox(); HBox statusBar = generateStatusBar(); rootVbox.getChildren().addAll(rootHBox, statusBar); return rootVbox; } private HBox generateStatusBar() { HBox rtrn = new HBox(); label = new Label("MainUI loaded"); rtrn.getChildren().add(label); return rtrn; } public void updateStatus(String update) { this.label.setText(update); } public void initGame() { String game = "src/main/resources/game.sgf"; Path path = Paths.get(game); // in development it is nice to have a game open on start if (path.toFile().exists()) { initializeGame(Paths.get(game)); } } private VBox generateGameMetaInfo() { VBox vbox = new VBox(); vbox.setMinWidth(250); GridPane pane = new GridPane(); Label blackPlayerLabel = new Label("Black:"); GridPane.setConstraints(blackPlayerLabel, 1, 0); blackPlayerName = new Label("Unknown"); GridPane.setConstraints(blackPlayerName, 2, 0); Label whitePlayerLabel = new Label("White:"); GridPane.setConstraints(whitePlayerLabel, 1, 1); whitePlayerName = new Label("Unknown"); GridPane.setConstraints(whitePlayerName, 2, 1); pane.getChildren().addAll(blackPlayerLabel, blackPlayerName, whitePlayerLabel, whitePlayerName); vbox.getChildren().add(pane); return vbox; } private TextArea generateCommentPane() { commentArea = new TextArea(); commentArea.setFocusTraversable(false); commentArea.setWrapText(true); commentArea.setPrefSize(300, 600); return commentArea; } private void initializeGame(Path pathToSgf) { this.game = Sgf.createFromPath(pathToSgf); currentMove = this.game.getRootNode(); prevMove = null; // reset our virtual board and actual board virtualBoard = new VirtualBoard(); virtualBoard.addBoardListener(new GuiBoardListener(this)); initEmptyBoard(); // construct the tree of the moves nodeToTreeStone = new HashMap<>(); movePane.getChildren().clear(); movePane.add(new EmptyTriangle(), 0, 0); GameNode rootNode = game.getRootNode(); populateMoveTreePane(rootNode, 0); showMarkersForMove(rootNode); showCommentForMove(rootNode); showMetaInfoForGame(this.game); treePaneScrollPane.setHvalue(0); treePaneScrollPane.setVvalue(0); } private void showMetaInfoForGame(Game game) { whitePlayerName.setText(game.getProperty(SgfProperties.WHITE_PLAYER_NAME)); blackPlayerName.setText(game.getProperty(SgfProperties.BLACK_PLAYER_NAME)); } public void initEmptyBoard() { generateBoardPane(boardPane); placePreGameStones(game); } private void placePreGameStones(Game game) { String blackStones = game.getProperty("AB", ""); String whiteStones = game.getProperty("AW", ""); placePreGameStones(blackStones, whiteStones); } private void placePreGameStones(GameNode node) { String blackStones = node.getProperty("AB", ""); String whiteStones = node.getProperty("AW", ""); placePreGameStones(blackStones, whiteStones); } private void placePreGameStones(String addBlack, String addWhite) { if (addBlack.length() > 0) { String[] blackStones = addBlack.split(","); for (int i = 0; i < blackStones.length; i++) { int[] moveCoords = Util.alphaToCoords(blackStones[i]); virtualBoard.placeStone(StoneState.BLACK, moveCoords[0], moveCoords[1]); } } if (addWhite.length() > 0) { String[] whiteStones = addWhite.split(","); for (int i = 0; i < whiteStones.length; i++) { int[] moveCoords = Util.alphaToCoords(whiteStones[i]); virtualBoard.placeStone(StoneState.WHITE, moveCoords[0], moveCoords[1]); } } } private void populateMoveTreePane(GameNode node, int depth) { // we draw out only actual moves if (node.isMove()) { TreeStone treeStone = TreeStone.create(node); movePane.add(treeStone, node.getMoveNo(), node.getVisualDepth()); nodeToTreeStone.put(node, treeStone); treeStone.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { TreeStone stone = (TreeStone) event.getSource(); fastForwardTo(stone.getMove()); } }); } // and recursively draw the next node on this line of play if (node.getNextNode() != null) { populateMoveTreePane(node.getNextNode(), depth + node.getVisualDepth()); } // populate the children also if (node.hasChildren()) { Set<GameNode> children = node.getChildren(); // will determine whether the glue stone should be a single // diagonal or a multiple (diagonal and vertical) GlueStoneType gStoneType = children.size() > 1 ? GlueStoneType.MULTIPLE : GlueStoneType.DIAGONAL; for (Iterator<GameNode> ite = children.iterator(); ite.hasNext();) { GameNode childNode = ite.next(); // the last glue shouldn't be a MULTIPLE if (GlueStoneType.MULTIPLE.equals(gStoneType) && !ite.hasNext()) { gStoneType = GlueStoneType.DIAGONAL; } // the visual lines can also be under a the first triangle int nodeVisualDepth = node.getVisualDepth(); int moveNo = node.getMoveNo(); if (moveNo == -1) { moveNo = 0; nodeVisualDepth = 0; } // also draw all the "missing" glue stones for (int i = nodeVisualDepth + 1; i < childNode.getVisualDepth(); i++) { movePane.add(new GlueStone(GlueStoneType.VERTICAL), moveNo, i); } // glue stone for the node movePane.add(new GlueStone(gStoneType), moveNo, childNode.getVisualDepth()); // and recursively draw the actual node populateMoveTreePane(childNode, depth + childNode.getVisualDepth()); } } } /* * Generates the boilerplate for the move tree pane. The * pane is actually populated during game initialization. */ private ScrollPane generateMoveTreePane() { movePane = new GridPane(); movePane.setPadding(new Insets(0, 0, 0, 0)); movePane.setStyle("-fx-background-color: white"); treePaneScrollPane = new ScrollPane(movePane); treePaneScrollPane.setPrefHeight(150); treePaneScrollPane.setHbarPolicy(ScrollBarPolicy.ALWAYS); treePaneScrollPane.setVbarPolicy(ScrollBarPolicy.AS_NEEDED); return treePaneScrollPane; } private void fastForwardTo(GameNode move) { // clear the board for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[i].length; j++) { board[i][j].removeStone(); } } placePreGameStones(game); deHighLightStoneInTree(currentMove); removeMarkersForNode(currentMove); virtualBoard.fastForwardTo(move); highLightStoneOnBoard(move); } private VBox generateFileTreePane() { VBox vbox = new VBox(); vbox.setMinWidth(250); TreeView<File> treeView = new FileTreeView(); treeView.setFocusTraversable(false); Label label = new Label("Choose SGF File"); vbox.getChildren().addAll(label, treeView); treeView.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { if (event.getClickCount() == 2) { TreeItem<File> item = treeView.getSelectionModel().getSelectedItem(); File file = item.getValue().toPath().toFile(); if (file.isFile()) { initializeGame(item.getValue().toPath()); } AppState.getInstance().addProperty(AppState.CURRENT_FILE, file.getAbsolutePath()); } } }); return vbox; } private TilePane generateButtonPane() { TilePane pane = new TilePane(); pane.setAlignment(Pos.CENTER); pane.getStyleClass().add("bordered"); TextField moveNoField = new TextField("0"); moveNoField.setFocusTraversable(false); moveNoField.setMaxWidth(40); moveNoField.setEditable(false); nextButton = new Button("Next"); nextButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { handleNextPressed(); } }); previousButton = new Button("Previous"); previousButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { handlePreviousPressed(); } }); pane.setPrefColumns(1); pane.getChildren().add(previousButton); pane.getChildren().add(moveNoField); pane.getChildren().add(nextButton); return pane; } private void handleNextPressed() { if (currentMove.getNextNode() != null) { prevMove = currentMove; currentMove = currentMove.getNextNode(); virtualBoard.makeMove(currentMove, prevMove); // scroll the scrollpane to make // the highlighted move visible ensureVisibleForActiveTreeNode(currentMove); } } private void handleNextBranch() { if (currentMove.hasChildren()) { prevMove = currentMove; currentMove = currentMove.getChildren().iterator().next(); virtualBoard.makeMove(currentMove, prevMove); // scroll the scrollpane to make // the highlighted move visible ensureVisibleForActiveTreeNode(currentMove); } } public void handlePreviousPressed() { if (currentMove.getParentNode() != null) { prevMove = currentMove; currentMove = currentMove.getParentNode(); virtualBoard.undoMove(prevMove, currentMove); } } public void playMove(GameNode move, GameNode prevMove) { this.currentMove = move; this.prevMove = prevMove; // we actually have a previous move! if (prevMove != null) { // de-highlight previously highlighted move if (prevMove.isMove() && !prevMove.isPass()) { deHighLightStoneOnBoard(prevMove); } // even non moves can haver markers removeMarkersForNode(prevMove); } if (move != null && !move.isPass() && !move.isPlacementMove()) { highLightStoneOnBoard(move); } // highlight stone in the tree pane deHighLightStoneInTree(prevMove); highLightStoneInTree(move); if (move != null && (move.getProperty("AB") != null || move.getProperty("AW") != null)) { placePreGameStones(move); } // show the associated comment showCommentForMove(move); // handle the prev and new markers showMarkersForMove(move); nextButton.requestFocus(); } public void undoMove(GameNode move, GameNode prevMove) { this.currentMove = prevMove; this.prevMove = move; if (move != null) { removeMarkersForNode(move); } if (prevMove != null) { showMarkersForMove(prevMove); showCommentForMove(prevMove); if (prevMove.isMove() && !prevMove.isPass()) highLightStoneOnBoard(prevMove); } deHighLightStoneInTree(move); highLightStoneInTree(prevMove); ensureVisibleForActiveTreeNode(prevMove); // rather have previous move button have focus previousButton.requestFocus(); } private void ensureVisibleForActiveTreeNode(GameNode move) { if (move != null && move.isMove()) { TreeStone stone = nodeToTreeStone.get(move); // the move tree is not yet fully operational and some // points don't exist in the map yet if (stone == null) return; double width = treePaneScrollPane.getContent().getBoundsInLocal().getWidth(); double x = stone.getBoundsInParent().getMaxX(); double scrollTo = ((x) - 11 * 30) / (width - 21 * 30); treePaneScrollPane.setHvalue(scrollTo); // adjust the vertical scroll double height = treePaneScrollPane.getContent().getBoundsInLocal().getHeight(); double y = stone.getBoundsInParent().getMaxY(); double scrollToY = y / height; if (move.getVisualDepth() == 0) { scrollToY = 0d; } treePaneScrollPane.setVvalue(scrollToY); } } private void highLightStoneInTree(GameNode move) { TreeStone stone = nodeToTreeStone.get(move); // can remove the null check at one point when the // tree is fully implemented if (stone != null) { stone.highLight(); stone.requestFocus(); } } private void deHighLightStoneInTree(GameNode node) { if (node != null && node.isMove()) { TreeStone stone = nodeToTreeStone.get(node); if (stone != null) { stone.deHighLight(); } else { throw new RuntimeException("Unable to find node for move " + node); } } } private void showCommentForMove(GameNode move) { String comment = move.getProperty("C"); if (comment == null) { comment = ""; } // some helpers I used for parsing needs to be undone - see the Parser.java // in sgf4j project comment = comment.replaceAll("@@@@@", "\\\\\\["); comment = comment.replaceAll("#####", "\\\\\\]"); // lets do some replacing - see http://www.red-bean.com/sgf/sgf4.html#text comment = comment.replaceAll("\\\\\n", ""); comment = comment.replaceAll("\\\\:", ":"); comment = comment.replaceAll("\\\\\\]", "]"); comment = comment.replaceAll("\\\\\\[", "["); commentArea.setText(comment); } private void showMarkersForMove(GameNode move) { // the L property is actually not used in FF3 and FF4 // but I own many SGFs that still have it String markerProp = move.getProperty("L"); if (markerProp != null) { int alphaIdx = 0; String[] markers = markerProp.split("\\]\\["); for (int i = 0; i < markers.length; i++) { int[] coords = Util.alphaToCoords(markers[i]); board[coords[0]][coords[1]].addOverlayText(Util.alphabet[alphaIdx++]); } } // also handle the LB labels Map<String, String> labels = Util.extractLabels(move.getProperty("LB")); for (Iterator<Map.Entry<String, String>> ite = labels.entrySet().iterator(); ite.hasNext();) { Map.Entry<String, String> entry = ite.next(); int[] coords = Util.alphaToCoords(entry.getKey()); board[coords[0]][coords[1]].addOverlayText(entry.getValue()); } } private void removeMarkersForNode(GameNode node) { // the L property is actually not used in FF3 and FF4 // but I own many SGFs that still have it String markerProp = node.getProperty("L"); if (markerProp != null) { String[] markers = markerProp.split("\\]\\["); for (int i = 0; i < markers.length; i++) { int[] coords = Util.alphaToCoords(markers[i]); board[coords[0]][coords[1]].removeOverlayText(); } } // also handle the LB labels Map<String, String> labels = Util.extractLabels(node.getProperty("LB")); for (Iterator<Map.Entry<String, String>> ite = labels.entrySet().iterator(); ite.hasNext();) { Map.Entry<String, String> entry = ite.next(); int[] coords = Util.alphaToCoords(entry.getKey()); board[coords[0]][coords[1]].removeOverlayText(); } } private void highLightStoneOnBoard(GameNode move) { String currentMove = move.getMoveString(); int[] moveCoords = Util.alphaToCoords(currentMove); board[moveCoords[0]][moveCoords[1]].highLightStone(); } private void deHighLightStoneOnBoard(GameNode prevMove) { String prevMoveAsStr = prevMove.getMoveString(); int[] moveCoords = Util.alphaToCoords(prevMoveAsStr); board[moveCoords[0]][moveCoords[1]].deHighLightStone(); } private GridPane generateBoardPane(GridPane boardPane) { boardPane.getChildren().clear(); for (int i = 0; i < 21; i++) { if (i > 1 && i < 20) { board[i - 1] = new BoardStone[19]; } for (int j = 0; j < 21; j++) { if (i == 0 || j == 0 || i == 20 || j == 20) { CoordinateSquare btn = new CoordinateSquare(i, j); boardPane.add(btn, i, j); } else { BoardStone btn = new BoardStone(i, j); boardPane.add(btn, i, j); board[i - 1][j - 1] = btn; } } } return boardPane; } private void enableKeyboardShortcuts(HBox topHBox) { topHBox.setOnKeyPressed(new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent event) { if (event.getEventType().equals(KeyEvent.KEY_PRESSED)) { if (event.getCode().equals(KeyCode.LEFT)) { handlePreviousPressed(); } else if (event.getCode().equals(KeyCode.RIGHT)) { handleNextPressed(); } else if (event.getCode().equals(KeyCode.DOWN)) { handleNextBranch(); } } } }); } public BoardStone[][] getBoard() { return this.board; } }
Set minimum size for movepane to avoid weird scrolling issues
src/main/java/com/toomasr/sgf4j/gui/MainUI.java
Set minimum size for movepane to avoid weird scrolling issues
<ide><path>rc/main/java/com/toomasr/sgf4j/gui/MainUI.java <ide> <ide> treePaneScrollPane = new ScrollPane(movePane); <ide> treePaneScrollPane.setPrefHeight(150); <del> treePaneScrollPane.setHbarPolicy(ScrollBarPolicy.ALWAYS); <add> treePaneScrollPane.setHbarPolicy(ScrollBarPolicy.AS_NEEDED); <ide> treePaneScrollPane.setVbarPolicy(ScrollBarPolicy.AS_NEEDED); <add> <add> movePane.setMinWidth(640); <ide> <ide> return treePaneScrollPane; <ide> }
Java
apache-2.0
6552cc645ba12e68dff2415f99f0ab3c3ba9210d
0
objectiser/overlord-commons,Governance/overlord-commons,objectiser/overlord-commons,Governance/overlord-commons,objectiser/overlord-commons
/* * Copyright 2014 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.overlord.commons.karaf.commands.configure; import java.io.File; import java.io.FileOutputStream; import java.util.Properties; import org.apache.felix.gogo.commands.Argument; import org.overlord.commons.codec.AesEncrypter; import org.overlord.commons.karaf.commands.AbstractFabricCommand; import org.overlord.commons.karaf.commands.CommandConstants; import org.overlord.commons.karaf.commands.i18n.Messages; import org.overlord.commons.karaf.commands.saml.GenerateSamlKeystoreUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Abstract Karaf console command for use within JBoss Fuse. It * generates/overwrites the overlord-saml.keystore file and configures all * properties within the commons and sramp Fabric profiles. Call it w/ the * keystore password as an argument. * * Note that this uses the BouncyCastle library to encrypt the keystore file. It * was not possible to directly use sun.security as it does not support OSGi * environments. * * @author David Virgil Naranjo */ abstract public class AbstractConfigureFabricCommand extends AbstractFabricCommand { private static String OVERLORD_COMMONS_PROFILE_PATH; @Argument(index = 0, name = "password", required = true, multiValued = false) protected String password = null; boolean allowedPasswordOverwrite; private static final Logger logger = LoggerFactory.getLogger(AbstractConfigureFabricCommand.class); static { if (File.separator.equals("/")) { //$NON-NLS-1$ OVERLORD_COMMONS_PROFILE_PATH = "overlord/commons.profile"; //$NON-NLS-1$ } else { OVERLORD_COMMONS_PROFILE_PATH = "overlord\\commons.profile"; //$NON-NLS-1$ } } public AbstractConfigureFabricCommand() { allowedPasswordOverwrite = false; } @Override protected Object doExecute() throws Exception { String fuse_config_path = getOverlordProfilePath(); String file = fuse_config_path + CommandConstants.OverlordProperties.FILE_KEYSTORE_NAME; File keystore = new File(file); if (allowedPasswordOverwrite || !keystore.exists()) { logger.info(Messages.getString("generate.saml.keystore.command.correctly.begin")); //$NON-NLS-1$ GenerateSamlKeystoreUtil util = new GenerateSamlKeystoreUtil(); util.generate(password, keystore); // Once the keystore file is generated the references to the saml // password existing in the overlord.properties file should be // updated. updateOverlordProperties(); logger.info(Messages.getString("generate.saml.keystore.command.correctly.created")); //$NON-NLS-1$ } else { String message = Messages.getString("overlord.commons.fabric.configured.already");//$NON-NLS-1$ logger.info(message); System.out.println(message); } return null; } /** * Gets the fabric overlord profile path * * @return the fuse config path */ public String getOverlordProfilePath() { StringBuilder fuse_config_path = new StringBuilder(); fuse_config_path.append(getFabricProfilesPath()).append(OVERLORD_COMMONS_PROFILE_PATH).append(File.separator); return fuse_config_path.toString(); } /** * Update the overlord properties with the new password introduced. * * @throws Exception * the exception */ protected void updateOverlordProperties() throws Exception { String filePath = getOverlordPropertiesFilePath(); Properties props = new Properties(); FileOutputStream out = null; String aesEncryptedValue = AesEncrypter.encrypt(password); StringBuilder aesEncrypterBuilder = new StringBuilder(); aesEncrypterBuilder.append("${crypt:").append(aesEncryptedValue).append("}"); //$NON-NLS-1$ //$NON-NLS-2$ aesEncryptedValue = aesEncrypterBuilder.toString(); try { out = new FileOutputStream(filePath); props.setProperty(CommandConstants.OverlordProperties.OVERLORD_BASE_URL, CommandConstants.OverlordProperties.OVERLORD_BASE_URL_VALUE); props.setProperty(CommandConstants.OverlordProperties.OVERLORD_SAML_KEYSTORE, CommandConstants.OverlordProperties.OVERLORD_SAML_KEYSTORE_FABRIC_VALUE); props.setProperty(CommandConstants.OverlordProperties.OVERLORD_SAML_ALIAS, CommandConstants.OverlordProperties.OVERLORD_SAML_ALIAS_VALUE); props.setProperty(CommandConstants.OverlordProperties.OVERLORD_KEYSTORE_ALIAS_PASSWORD_KEY, aesEncryptedValue); props.setProperty(CommandConstants.OverlordProperties.OVERLORD_KEYSTORE_PASSWORD_KEY, aesEncryptedValue); props.store(out, null); } finally { out.close(); } } /** * Gets the overlord properties file path. * * @return the overlord properties file path */ protected String getOverlordPropertiesFilePath() { StringBuilder fuse_config_path = new StringBuilder(); fuse_config_path.append(getOverlordProfilePath()) .append(CommandConstants.OverlordProperties.OVERLORD_PROPERTIES_FILE_NAME); return fuse_config_path.toString(); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public boolean isAllowedPasswordOverwrite() { return allowedPasswordOverwrite; } public void setAllowedPasswordOverwrite(boolean allowedPasswordOverwrite) { this.allowedPasswordOverwrite = allowedPasswordOverwrite; } }
overlord-commons-karaf-commands/src/main/java/org/overlord/commons/karaf/commands/configure/AbstractConfigureFabricCommand.java
/* * Copyright 2014 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.overlord.commons.karaf.commands.configure; import java.io.File; import java.io.FileOutputStream; import java.util.Properties; import org.apache.felix.gogo.commands.Argument; import org.overlord.commons.karaf.commands.AbstractFabricCommand; import org.overlord.commons.karaf.commands.CommandConstants; import org.overlord.commons.karaf.commands.i18n.Messages; import org.overlord.commons.karaf.commands.saml.GenerateSamlKeystoreUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Abstract Karaf console command for use within JBoss Fuse. It * generates/overwrites the overlord-saml.keystore file and configures all * properties within the commons and sramp Fabric profiles. Call it w/ the * keystore password as an argument. * * Note that this uses the BouncyCastle library to encrypt the keystore file. It * was not possible to directly use sun.security as it does not support OSGi * environments. * * @author David Virgil Naranjo */ abstract public class AbstractConfigureFabricCommand extends AbstractFabricCommand { private static String OVERLORD_COMMONS_PROFILE_PATH; @Argument(index = 0, name = "password", required = true, multiValued = false) protected String password = null; boolean allowedPasswordOverwrite; private static final Logger logger = LoggerFactory.getLogger(AbstractConfigureFabricCommand.class); static { if (File.separator.equals("/")) { //$NON-NLS-1$ OVERLORD_COMMONS_PROFILE_PATH = "overlord/commons.profile"; //$NON-NLS-1$ } else { OVERLORD_COMMONS_PROFILE_PATH = "overlord\\commons.profile"; //$NON-NLS-1$ } } public AbstractConfigureFabricCommand() { allowedPasswordOverwrite = false; } @Override protected Object doExecute() throws Exception { String fuse_config_path = getOverlordProfilePath(); String file = fuse_config_path + CommandConstants.OverlordProperties.FILE_KEYSTORE_NAME; File keystore = new File(file); if (allowedPasswordOverwrite || !keystore.exists()) { logger.info(Messages.getString("generate.saml.keystore.command.correctly.begin")); //$NON-NLS-1$ GenerateSamlKeystoreUtil util = new GenerateSamlKeystoreUtil(); util.generate(password, keystore); // Once the keystore file is generated the references to the saml // password existing in the overlord.properties file should be // updated. updateOverlordProperties(); logger.info(Messages.getString("generate.saml.keystore.command.correctly.created")); //$NON-NLS-1$ } else { String message = Messages.getString("overlord.commons.fabric.configured.already");//$NON-NLS-1$ logger.info(message); System.out.println(message); } return null; } /** * Gets the fabric overlord profile path * * @return the fuse config path */ public String getOverlordProfilePath() { StringBuilder fuse_config_path = new StringBuilder(); fuse_config_path.append(getFabricProfilesPath()).append(OVERLORD_COMMONS_PROFILE_PATH).append(File.separator); return fuse_config_path.toString(); } /** * Update the overlord properties with the new password introduced. * * @throws Exception * the exception */ protected void updateOverlordProperties() throws Exception { String filePath = getOverlordPropertiesFilePath(); Properties props = new Properties(); FileOutputStream out = null; try { out = new FileOutputStream(filePath); props.setProperty(CommandConstants.OverlordProperties.OVERLORD_BASE_URL, CommandConstants.OverlordProperties.OVERLORD_BASE_URL_VALUE); props.setProperty(CommandConstants.OverlordProperties.OVERLORD_SAML_KEYSTORE, CommandConstants.OverlordProperties.OVERLORD_SAML_KEYSTORE_FABRIC_VALUE); props.setProperty(CommandConstants.OverlordProperties.OVERLORD_SAML_ALIAS, CommandConstants.OverlordProperties.OVERLORD_SAML_ALIAS_VALUE); props.setProperty(CommandConstants.OverlordProperties.OVERLORD_KEYSTORE_ALIAS_PASSWORD_KEY, password); props.setProperty(CommandConstants.OverlordProperties.OVERLORD_KEYSTORE_PASSWORD_KEY, password); props.store(out, null); } finally { out.close(); } } /** * Gets the overlord properties file path. * * @return the overlord properties file path */ protected String getOverlordPropertiesFilePath() { StringBuilder fuse_config_path = new StringBuilder(); fuse_config_path.append(getOverlordProfilePath()) .append(CommandConstants.OverlordProperties.OVERLORD_PROPERTIES_FILE_NAME); return fuse_config_path.toString(); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public boolean isAllowedPasswordOverwrite() { return allowedPasswordOverwrite; } public void setAllowedPasswordOverwrite(boolean allowedPasswordOverwrite) { this.allowedPasswordOverwrite = allowedPasswordOverwrite; } }
SRAMP-588 Fuse Fabric Karaf Command Encrypt Aes Password
overlord-commons-karaf-commands/src/main/java/org/overlord/commons/karaf/commands/configure/AbstractConfigureFabricCommand.java
SRAMP-588 Fuse Fabric Karaf Command Encrypt Aes Password
<ide><path>verlord-commons-karaf-commands/src/main/java/org/overlord/commons/karaf/commands/configure/AbstractConfigureFabricCommand.java <ide> import java.util.Properties; <ide> <ide> import org.apache.felix.gogo.commands.Argument; <add>import org.overlord.commons.codec.AesEncrypter; <ide> import org.overlord.commons.karaf.commands.AbstractFabricCommand; <ide> import org.overlord.commons.karaf.commands.CommandConstants; <ide> import org.overlord.commons.karaf.commands.i18n.Messages; <ide> <ide> Properties props = new Properties(); <ide> FileOutputStream out = null; <add> String aesEncryptedValue = AesEncrypter.encrypt(password); <add> StringBuilder aesEncrypterBuilder = new StringBuilder(); <add> aesEncrypterBuilder.append("${crypt:").append(aesEncryptedValue).append("}"); //$NON-NLS-1$ //$NON-NLS-2$ <add> aesEncryptedValue = aesEncrypterBuilder.toString(); <ide> try { <ide> out = new FileOutputStream(filePath); <ide> props.setProperty(CommandConstants.OverlordProperties.OVERLORD_BASE_URL, CommandConstants.OverlordProperties.OVERLORD_BASE_URL_VALUE); <ide> props.setProperty(CommandConstants.OverlordProperties.OVERLORD_SAML_KEYSTORE, <ide> CommandConstants.OverlordProperties.OVERLORD_SAML_KEYSTORE_FABRIC_VALUE); <ide> props.setProperty(CommandConstants.OverlordProperties.OVERLORD_SAML_ALIAS, CommandConstants.OverlordProperties.OVERLORD_SAML_ALIAS_VALUE); <del> props.setProperty(CommandConstants.OverlordProperties.OVERLORD_KEYSTORE_ALIAS_PASSWORD_KEY, password); <del> props.setProperty(CommandConstants.OverlordProperties.OVERLORD_KEYSTORE_PASSWORD_KEY, password); <add> props.setProperty(CommandConstants.OverlordProperties.OVERLORD_KEYSTORE_ALIAS_PASSWORD_KEY, aesEncryptedValue); <add> props.setProperty(CommandConstants.OverlordProperties.OVERLORD_KEYSTORE_PASSWORD_KEY, aesEncryptedValue); <ide> props.store(out, null); <ide> <ide> } finally {
JavaScript
mit
96920c4110bb1433f9e7f163d0ab9a00d0cb35de
0
dannyhecht/ams-air-quality,dannyhecht/ams-air-quality
/* MAPBOXGL // Add geolocate control to the map. map.addControl(new mapboxgl.GeolocateControl({ positionOptions: { enableHighAccuracy: true }, trackUserLocation: true })); */ // LEAFLET var osmUrl='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'; var osmAttrib='Map data © <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'; var osm = new L.TileLayer(osmUrl, { attribution: osmAttrib, detectRetina: true }); // please replace this with your own mapbox token! var token = 'pk.eyJ1IjoiZGhlY2h0IiwiYSI6ImNqNHRueTVyeDA3ZmYyd3FuY2NmYW9tNmoifQ.FetU2-IBDcrhTmSKBpFIfA'; var mapboxUrl = 'https://api.mapbox.com/styles/v1/mapbox/streets-v10/tiles/{z}/{x}/{y}@2x?access_token=' + token; var mapboxAttrib = 'Map data © <a href="http://osm.org/copyright">OpenStreetMap</a> contributors. Tiles from <a href="https://www.mapbox.com">Mapbox</a>.'; var mapbox = new L.TileLayer(mapboxUrl, { attribution: mapboxAttrib, tileSize: 512, zoomOffset: -1 }); var map = new L.Map('map', { layers: [mapbox], center: [52.35963, 4.885431], zoom: 11.5, zoomControl: true }); // add location control to global name space for testing only // on a production site, omit the "lc = "! lc = L.control.locate({ strings: { title: "Show me where I am, yo!" } }).addTo(map);
js/geolocate.js
/* MAPBOXGL // Add geolocate control to the map. map.addControl(new mapboxgl.GeolocateControl({ positionOptions: { enableHighAccuracy: true }, trackUserLocation: true })); */ // LEAFLET var osmUrl='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'; var osmAttrib='Map data © <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'; var osm = new L.TileLayer(osmUrl, { attribution: osmAttrib, detectRetina: true }); // please replace this with your own mapbox token! var token = 'pk.eyJ1IjoiZGhlY2h0IiwiYSI6ImNqNHRueTVyeDA3ZmYyd3FuY2NmYW9tNmoifQ.FetU2-IBDcrhTmSKBpFIfA'; var mapboxUrl = 'https://api.mapbox.com/styles/v1/mapbox/streets-v10/tiles/{z}/{x}/{y}@2x?access_token=' + token; var mapboxAttrib = 'Map data © <a href="http://osm.org/copyright">OpenStreetMap</a> contributors. Tiles from <a href="https://www.mapbox.com">Mapbox</a>.'; var mapbox = new L.TileLayer(mapboxUrl, { attribution: mapboxAttrib, tileSize: 512, zoomOffset: -1 }); // add location control to global name space for testing only // on a production site, omit the "lc = "! lc = L.control.locate({ strings: { title: "Show me where I am, yo!" } }).addTo(map);
Update geolocate.js
js/geolocate.js
Update geolocate.js
<ide><path>s/geolocate.js <ide> zoomOffset: -1 <ide> }); <ide> <add>var map = new L.Map('map', { <add> layers: [mapbox], <add> center: [52.35963, 4.885431], <add> zoom: 11.5, <add> zoomControl: true <add>}); <add> <ide> // add location control to global name space for testing only <ide> // on a production site, omit the "lc = "! <ide> lc = L.control.locate({
Java
apache-2.0
029d2b02ee0db79423086e593b5ad3c29f61676b
0
businesscode/BCD-UI,businesscode/BCD-UI,businesscode/BCD-UI
/* Copyright 2010-2017 BusinessCode GmbH, Germany Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package de.businesscode.bcdui.menu; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import org.apache.log4j.Logger; import org.apache.shiro.SecurityUtils; import org.apache.shiro.UnavailableSecurityManagerException; import org.apache.shiro.subject.Subject; import de.businesscode.bcdui.menu.config.Entry; import de.businesscode.bcdui.menu.config.Include; import de.businesscode.bcdui.menu.config.Menu; import de.businesscode.bcdui.toolbox.Configuration; /** * A singleton container class for all the menus defined in the application.<br> * These menus are defined in static XML files under "/WEB-INF/bcdui/menu/" and read <br> * **/ public class Menus { private static final Logger log = Logger.getLogger(MenuServlet.class); private static final String defaultMenuFolderPath = "menu"; private Map<String, Menu> menuMap; private static Menus instance=null; /** * * Constructor * @throws JAXBException * @throws IOException */ private Menus() throws JAXBException, IOException{ menuMap = new HashMap<String, Menu>(); JAXBContext jaxbCon = JAXBContext.newInstance(Menu.class.getPackage().getName()); Unmarshaller jaxbUnmarsh = jaxbCon.createUnmarshaller(); readConfigFiles(null, jaxbUnmarsh); } /** * * Method getInstance * @throws JAXBException * @throws IOException * @return */ public static synchronized Menus getInstance() throws JAXBException, IOException { if(instance == null || Configuration.isCacheDisabled()){ Menus ins = new Menus(); instance = ins; } return instance; } /** * gets Menu by ID or default menu if parameter menuId is null or empty * if the application contains security subject - the menu will be filtered * according to subject security settings * @param menuId * @return */ public Menu getMenuByIdOrDefault(String menuId) { Menu menu = null; if(menuId == null || menuId == "") menu = getDefaultMenu(); else menu = menuMap.get(menuId); try { Subject subject = SecurityUtils.getSubject(); if(subject != null && menu != null){// build secure menu Menu secMenu = new Menu(); secMenu.getEntry().addAll(checkUserPermissions(menu.getEntry(), subject)); secMenu.setId( menu.getId() ); secMenu.setIsDefault( menu.isIsDefault()); return secMenu; } } catch (UnavailableSecurityManagerException e) { /* shiro isn't used at all */ } return menu; } /** * returns default menu or null if no default menu is defined */ private Menu getDefaultMenu(){ Menu defMenu=null; Set<String> keys = menuMap.keySet(); Object[] allMenKeys = keys.toArray(); for (int i = 0; i < allMenKeys.length; i++) { if( menuMap.get(allMenKeys[i]).isIsDefault() != null && menuMap.get(allMenKeys[i]).isIsDefault()) defMenu = menuMap.get(allMenKeys[i]); } return defMenu; } /** * * Method checkUserPermissions * @param menuEntry * @param secMenuEntry * @param userSubject */ private List<Entry> checkUserPermissions(List<Entry> menuEntry, Subject userSubject) { ArrayList<Entry> allPermEntries = new ArrayList<Entry>(); for (int i = 0; i < menuEntry.size(); i++) { Entry curEntry = menuEntry.get(i); if( curEntry.getRights() == null || curEntry.getRights().equals("") || userSubject.isPermitted(curEntry.getRights())){ Entry permEntry = new Entry(); permEntry = copyEntry(curEntry, permEntry); permEntry = copyAllPermittedChildren(curEntry, permEntry, userSubject); if (permEntry != null) allPermEntries.add(permEntry); } } return allPermEntries; } /** * 1. not permitted Entry or null if all are permitted * * Method getFirstNonepermited * * @param entryNotNull * @param userSubject * @return */ private Entry copyAllPermittedChildren(Entry entry, Entry parentEntry, Subject userSubject){ int before = parentEntry != null ? parentEntry.getEntryOrInclude().size() : 0; if(entry != null){ for (int i = 0; i < entry.getEntryOrInclude().size(); i++) { Object obj = entry.getEntryOrInclude().get(i); if(obj instanceof Entry){ Entry curEntry = (Entry)obj; if( curEntry.getRights() == null || curEntry.getRights().equals("") || userSubject.isPermitted(curEntry.getRights())){ Entry permEntry = new Entry(); permEntry = copyEntry(curEntry, permEntry); if(parentEntry != null) parentEntry.getEntryOrInclude().add(permEntry); if(curEntry.getEntryOrInclude().size() > 0){ Entry permEntAdd = copyAllPermittedChildren(curEntry, permEntry,userSubject);// go through all children // in case we don't have any children entries, we remove the recently added one if (permEntAdd == null) { parentEntry.getEntryOrInclude().remove(permEntry); } } } } else if(obj instanceof Include){ if(parentEntry != null){ parentEntry.getEntryOrInclude().add(obj); } } } } // check if we've added a entry, if not (and parent doesn't hold a href on its own) signal "null" as "don't show this entry int after = parentEntry != null ? parentEntry.getEntryOrInclude().size() : 0; if (before == after && (parentEntry.getHref() == null || parentEntry.getHref().isEmpty())) { return null; } return parentEntry; } /** * * Method copyEntry * @param entry * @param newEntry * @return */ private Entry copyEntry(Entry entry, Entry newEntry){ newEntry.setCaption(entry.getCaption()); newEntry.setDisable(entry.isDisable()); newEntry.setHide(entry.isHide()); newEntry.setHref(entry.getHref()); newEntry.setId(entry.getId()); newEntry.setNewWindow(entry.isNewWindow()); newEntry.setOnClick(entry.getOnClick()); newEntry.setRights(entry.getRights()); newEntry.setTitle(entry.getTitle()); return newEntry; } /** * if the Menu map is empty * @return */ public boolean isEmpty() { return this.menuMap.isEmpty(); } /** * * Method readConfigFiles * @param folder * @throws JAXBException * @throws IOException */ private void readConfigFiles(String folder, Unmarshaller jaxbUnmarshaller ) throws JAXBException, IOException{ if(folder == null) folder = (String)Configuration.getInstance().getConfigurationParameter(Configuration.CONFIG_FILE_PATH_KEY)+File.separator+defaultMenuFolderPath; File[] menuFiles = (new File(folder)).listFiles(); if (menuFiles == null) { throw new RuntimeException("Can not read menu files from " + defaultMenuFolderPath + ". The path is not a directory."); } for (int i = 0; i < menuFiles.length; i++) { if (menuFiles[i].isDirectory()) { readConfigFiles(menuFiles[i].getAbsolutePath(),jaxbUnmarshaller); continue; } if (!menuFiles[i].isFile() || !menuFiles[i].canRead() || !menuFiles[i].getName().toLowerCase().endsWith(".xml")) continue; FileInputStream fi = null; try { fi = new FileInputStream(menuFiles[i]); Menu curMenu = (Menu)jaxbUnmarshaller.unmarshal(fi); menuMap.put(curMenu.getId(), curMenu); } finally{if(fi != null)fi.close();} } } }
Server/src/main/java/de/businesscode/bcdui/menu/Menus.java
/* Copyright 2010-2017 BusinessCode GmbH, Germany Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package de.businesscode.bcdui.menu; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import org.apache.log4j.Logger; import org.apache.shiro.SecurityUtils; import org.apache.shiro.UnavailableSecurityManagerException; import org.apache.shiro.subject.Subject; import de.businesscode.bcdui.menu.config.Entry; import de.businesscode.bcdui.menu.config.Include; import de.businesscode.bcdui.menu.config.Menu; import de.businesscode.bcdui.toolbox.Configuration; /** * A singleton container class for all the menus defined in the application.<br> * These menus are defined in static XML files under "/WEB-INF/bcdui/menu/" and read <br> * **/ public class Menus { private static final Logger log = Logger.getLogger(MenuServlet.class); private static final String defaultMenuFolderPath = "menu"; private Map<String, Menu> menuMap; private static Menus instance=null; /** * * Constructor * @throws JAXBException * @throws IOException */ private Menus() throws JAXBException, IOException{ menuMap = new HashMap<String, Menu>(); JAXBContext jaxbCon = JAXBContext.newInstance(Menu.class.getPackage().getName()); Unmarshaller jaxbUnmarsh = jaxbCon.createUnmarshaller(); readConfigFiles(null, jaxbUnmarsh); } /** * * Method getInstance * @throws JAXBException * @throws IOException * @return */ public static synchronized Menus getInstance() throws JAXBException, IOException { if(instance == null || Configuration.isCacheDisabled()){ Menus ins = new Menus(); instance = ins; } return instance; } /** * gets Menu by ID or default menu if parameter menuId is null or empty * if the application contains security subject - the menu will be filtered * according to subject security settings * @param menuId * @return */ public Menu getMenuByIdOrDefault(String menuId) { Menu menu = null; if(menuId == null || menuId == "") menu = getDefaultMenu(); else menu = menuMap.get(menuId); try { Subject subject = SecurityUtils.getSubject(); if(subject != null && menu != null){// build secure menu Menu secMenu = new Menu(); secMenu.getEntry().addAll(checkUserPermissions(menu.getEntry(), subject)); secMenu.setId( menu.getId() ); secMenu.setIsDefault( menu.isIsDefault()); return secMenu; } } catch (UnavailableSecurityManagerException e) { /* shiro isn't used at all */ } return menu; } /** * returns default menu or null if no default menu is defined */ private Menu getDefaultMenu(){ Menu defMenu=null; Set<String> keys = menuMap.keySet(); Object[] allMenKeys = keys.toArray(); for (int i = 0; i < allMenKeys.length; i++) { if( menuMap.get(allMenKeys[i]).isIsDefault() != null && menuMap.get(allMenKeys[i]).isIsDefault()) defMenu = menuMap.get(allMenKeys[i]); } return defMenu; } /** * * Method checkUserPermissions * @param menuEntry * @param secMenuEntry * @param userSubject */ private List<Entry> checkUserPermissions(List<Entry> menuEntry, Subject userSubject) { ArrayList<Entry> allPermEntries = new ArrayList<Entry>(); for (int i = 0; i < menuEntry.size(); i++) { Entry curEntry = menuEntry.get(i); if( curEntry.getRights() == null || curEntry.getRights().equals("") || userSubject.isPermitted(curEntry.getRights())){ Entry permEntry = new Entry(); permEntry = copyEntry(curEntry, permEntry); permEntry = copyAllPermittedChildren(curEntry, permEntry, userSubject); if (permEntry != null) allPermEntries.add(permEntry); } } return allPermEntries; } /** * 1. not permitted Entry or null if all are permitted * * Method getFirstNonepermited * * @param entryNotNull * @param userSubject * @return */ private Entry copyAllPermittedChildren(Entry entry, Entry parentEntry, Subject userSubject){ int before = parentEntry != null ? parentEntry.getEntryOrInclude().size() : 0; if(entry != null){ for (int i = 0; i < entry.getEntryOrInclude().size(); i++) { Object obj = entry.getEntryOrInclude().get(i); if(obj instanceof Entry){ Entry curEntry = (Entry)obj; if( curEntry.getRights() == null || curEntry.getRights().equals("") || userSubject.isPermitted(curEntry.getRights())){ Entry permEntry = new Entry(); permEntry = copyEntry(curEntry, permEntry); if(parentEntry != null) parentEntry.getEntryOrInclude().add(permEntry); if(curEntry.getEntryOrInclude().size() > 0){ Entry permEntAdd = copyAllPermittedChildren(curEntry, permEntry,userSubject);// go through all children // in case we don't have any children entries, we remove the recently added one if (permEntAdd == null) { parentEntry.getEntryOrInclude().remove(permEntry); } } } } else if(obj instanceof Include){ if(parentEntry != null){ parentEntry.getEntryOrInclude().add(obj); } } } } // check if we've added a entry, if not (and parent doesn't hold a href on its own) signal "null" as "don't show this entry int after = parentEntry != null ? parentEntry.getEntryOrInclude().size() : 0; if (before == after && (parentEntry.getHref() == null || parentEntry.getHref().isEmpty())) { return null; } return parentEntry; } /** * * Method copyEntry * @param entry * @param newEntry * @return */ private Entry copyEntry(Entry entry, Entry newEntry){ newEntry.setCaption(entry.getCaption()); newEntry.setDisable(entry.isDisable()); newEntry.setHide(entry.isHide()); newEntry.setHref(entry.getHref()); newEntry.setId(entry.getId()); newEntry.setNewWindow(entry.isNewWindow()); newEntry.setOnClick(entry.getOnClick()); newEntry.setRights(entry.getRights()); newEntry.setTitle(entry.getTitle()); newEntry.setBcdTranslate(entry.getBcdTranslate()); return newEntry; } /** * if the Menu map is empty * @return */ public boolean isEmpty() { return this.menuMap.isEmpty(); } /** * * Method readConfigFiles * @param folder * @throws JAXBException * @throws IOException */ private void readConfigFiles(String folder, Unmarshaller jaxbUnmarshaller ) throws JAXBException, IOException{ if(folder == null) folder = (String)Configuration.getInstance().getConfigurationParameter(Configuration.CONFIG_FILE_PATH_KEY)+File.separator+defaultMenuFolderPath; File[] menuFiles = (new File(folder)).listFiles(); if (menuFiles == null) { throw new RuntimeException("Can not read menu files from " + defaultMenuFolderPath + ". The path is not a directory."); } for (int i = 0; i < menuFiles.length; i++) { if (menuFiles[i].isDirectory()) { readConfigFiles(menuFiles[i].getAbsolutePath(),jaxbUnmarshaller); continue; } if (!menuFiles[i].isFile() || !menuFiles[i].canRead() || !menuFiles[i].getName().toLowerCase().endsWith(".xml")) continue; FileInputStream fi = null; try { fi = new FileInputStream(menuFiles[i]); Menu curMenu = (Menu)jaxbUnmarshaller.unmarshal(fi); menuMap.put(curMenu.getId(), curMenu); } finally{if(fi != null)fi.close();} } } }
grid page cleanup
Server/src/main/java/de/businesscode/bcdui/menu/Menus.java
grid page cleanup
<ide><path>erver/src/main/java/de/businesscode/bcdui/menu/Menus.java <ide> newEntry.setOnClick(entry.getOnClick()); <ide> newEntry.setRights(entry.getRights()); <ide> newEntry.setTitle(entry.getTitle()); <del> newEntry.setBcdTranslate(entry.getBcdTranslate()); <ide> <ide> return newEntry; <ide> }
Java
mit
295fbd54e9ffa626ea727f0633b1c3e917886209
0
nallar/TickThreading
package me.nallar.tickthreading.patcher; import javax.xml.transform.TransformerException; import java.io.File; import java.io.IOException; import java.util.Arrays; import me.nallar.tickthreading.Log; import me.nallar.tickthreading.mappings.MCPMappings; import me.nallar.tickthreading.mappings.Mappings; import org.xml.sax.SAXException; public class PatchMain { private static String location; public static void main(String[] argv) { if (argv.length == 1) { Log.severe("Type must be passed"); } location = argv[0]; String type = argv[1]; String[] args = Arrays.copyOfRange(argv, 1, argv.length); if (type.equalsIgnoreCase("obfuscator")) { obfuscator(args); } else if (type.equalsIgnoreCase("patcher")) { patcher(args); } } public static void obfuscator(String[] args) { String mcpConfigPath = args.length > 0 ? args[0] : "build/forge/mcp/conf"; String inputPatchPath = args.length > 1 ? args[1] : "resources/patches-unobfuscated.xml"; String outputPatchPath = args.length > 2 ? args[2] : "build/classes/patches.xml"; Log.info("Obfuscating " + inputPatchPath + " to " + outputPatchPath + " via " + mcpConfigPath); try { Mappings mcpMappings = new MCPMappings(new File(mcpConfigPath)); PatchManager patchManager = new PatchManager(new File(inputPatchPath), Patches.class); try { patchManager.obfuscate(mcpMappings); patchManager.save(new File(outputPatchPath)); } catch (TransformerException e) { Log.severe("Failed to save obfuscated patch"); } } catch (IOException e) { Log.severe("Failed to read input file", e); } catch (SAXException e) { Log.severe("Failed to parse input file", e); } } public static void patcher(String[] args) { } }
src/common/me/nallar/tickthreading/patcher/PatchMain.java
package me.nallar.tickthreading.patcher; import javax.xml.transform.TransformerException; import java.io.File; import java.io.IOException; import java.util.Arrays; import me.nallar.tickthreading.Log; import me.nallar.tickthreading.mappings.MCPMappings; import me.nallar.tickthreading.mappings.Mappings; import org.xml.sax.SAXException; public class PatchMain { private static String location; public static void main(String[] argv) { if (argv.length == 1) { Log.severe("Type must be passed"); } location = argv[0]; String type = argv[1]; String[] args = Arrays.copyOfRange(argv, 1, argv.length - 1); if (type.equalsIgnoreCase("obfuscator")) { obfuscator(args); } else if (type.equalsIgnoreCase("patcher")) { patcher(args); } } public static void obfuscator(String[] args) { String mcpConfigPath = args.length > 0 ? args[0] : "build/forge/mcp/conf"; String inputPatchPath = args.length > 1 ? args[1] : "resources/patches-unobfuscated.xml"; String outputPatchPath = args.length > 2 ? args[2] : "build/classes/patches.xml"; Log.info("Obfuscating " + inputPatchPath + " to " + outputPatchPath + " via " + mcpConfigPath); try { Mappings mcpMappings = new MCPMappings(new File(mcpConfigPath)); PatchManager patchManager = new PatchManager(new File(inputPatchPath), Patches.class); try { patchManager.obfuscate(mcpMappings); patchManager.save(new File(outputPatchPath)); } catch (TransformerException e) { Log.severe("Failed to save obfuscated patch"); } } catch (IOException e) { Log.severe("Failed to read input file", e); } catch (SAXException e) { Log.severe("Failed to parse input file", e); } } public static void patcher(String[] args) { } }
Corrected usage of copyOfRange (endIndex is exclusive) Signed-off-by: Ross Allan <[email protected]>
src/common/me/nallar/tickthreading/patcher/PatchMain.java
Corrected usage of copyOfRange (endIndex is exclusive)
<ide><path>rc/common/me/nallar/tickthreading/patcher/PatchMain.java <ide> } <ide> location = argv[0]; <ide> String type = argv[1]; <del> String[] args = Arrays.copyOfRange(argv, 1, argv.length - 1); <add> String[] args = Arrays.copyOfRange(argv, 1, argv.length); <ide> if (type.equalsIgnoreCase("obfuscator")) { <ide> obfuscator(args); <ide> } else if (type.equalsIgnoreCase("patcher")) {
Java
mit
396dd632f91607c284dfd191241b56135590e57f
0
SleepyTonic/cordova-notification-bar-plugin,SleepyTonic/cordova-notification-bar-plugin
// This class is used on all Androids below Honeycomb package org.sleepytonic.cordova.plugins.notification; import android.app.Notification; import android.app.Notification.Builder; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; //change this to your application's Java package import com.your.app.R; public class StatusNotificationIntent { public static Notification buildNotification( Context context, CharSequence tag, CharSequence contentTitle, CharSequence contentText, int flag ) { int icon = R.drawable.notification; long when = System.currentTimeMillis(); //Notification noti = new Notification(icon, contentTitle, when); //noti.flags |= flag; //http://developer.android.com/reference/android/app/Notification.Builder.html //http://stackoverflow.com/questions/18918336/android-notification-remoteserviceexception Notification noti = new Notification.Builder(context) .setContentTitle(contentTitle) .setContentText(contentText) .setSmallIcon(R.drawable.notification) .build(); //.setLargeIcon(aBitmap) PackageManager pm = context.getPackageManager(); Intent notificationIntent = pm.getLaunchIntentForPackage(context.getPackageName()); notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); notificationIntent.putExtra("notificationTag", tag); PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0); noti.setLatestEventInfo(context, contentTitle, contentText, contentIntent); return noti; } }
src/android/StatusNotificationIntent.java
// This class is used on all Androids below Honeycomb package org.sleepytonic.cordova.plugins.notification; import android.app.Notification; import android.app.Notification.Builder; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import org.sleepytonic.HelloCordovaTouch.R; public class StatusNotificationIntent { public static Notification buildNotification( Context context, CharSequence tag, CharSequence contentTitle, CharSequence contentText, int flag ) { int icon = R.drawable.notification; long when = System.currentTimeMillis(); //Notification noti = new Notification(icon, contentTitle, when); //noti.flags |= flag; //http://developer.android.com/reference/android/app/Notification.Builder.html //http://stackoverflow.com/questions/18918336/android-notification-remoteserviceexception Notification noti = new Notification.Builder(context) .setContentTitle(contentTitle) .setContentText(contentText) .setSmallIcon(R.drawable.notification) .build(); //.setLargeIcon(aBitmap) PackageManager pm = context.getPackageManager(); Intent notificationIntent = pm.getLaunchIntentForPackage(context.getPackageName()); notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); notificationIntent.putExtra("notificationTag", tag); PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0); noti.setLatestEventInfo(context, contentTitle, contentText, contentIntent); return noti; } }
use a dummy R class import
src/android/StatusNotificationIntent.java
use a dummy R class import
<ide><path>rc/android/StatusNotificationIntent.java <ide> import android.content.Intent; <ide> import android.content.pm.PackageManager; <ide> <del>import org.sleepytonic.HelloCordovaTouch.R; <add>//change this to your application's Java package <add>import com.your.app.R; <ide> <ide> public class StatusNotificationIntent { <ide> public static Notification buildNotification( Context context, CharSequence tag, CharSequence contentTitle, CharSequence contentText, int flag ) {
Java
mit
be3705f85b9aa1ec6b0254127a500885bd0d4796
0
hunny/xplus,hunny/xplus,hunny/xplus,hunny/xplus,hunny/xplus
package com.example.bootweb.pg.logging; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpRequest; import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.ClientHttpResponse; @SuppressWarnings("static-method") public class LoggingRestTemplate implements ClientHttpRequestInterceptor { private final static Logger LOGGER = LoggerFactory.getLogger(LoggingRestTemplate.class); @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { traceRequest(request, body); ClientHttpResponse response = execution.execute(request, body); return traceResponse(response); } private void traceRequest(HttpRequest request, byte[] body) throws IOException { if (!LOGGER.isDebugEnabled()) { return; } LOGGER.debug( "==========================request begin=============================================="); LOGGER.debug("URI : {}", request.getURI()); LOGGER.debug("Method : {}", request.getMethod()); LOGGER.debug("Headers : {}", request.getHeaders()); LOGGER.debug("Request body: {}", new String(body, "UTF-8")); LOGGER.debug( "==========================request end================================================"); } private ClientHttpResponse traceResponse(ClientHttpResponse response) throws IOException { if (!LOGGER.isDebugEnabled()) { return response; } final ClientHttpResponse responseWrapper = new BufferingClientHttpResponseWrapper(response); StringBuilder inputStringBuilder = new StringBuilder(); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(responseWrapper.getBody(), "UTF-8")); String line = bufferedReader.readLine(); while (line != null) { inputStringBuilder.append(line); inputStringBuilder.append('\n'); line = bufferedReader.readLine(); } LOGGER.debug( "==========================response begin============================================="); LOGGER.debug("Status code : {}", responseWrapper.getStatusCode()); LOGGER.debug("Status text : {}", responseWrapper.getStatusText()); LOGGER.debug("Headers : {}", responseWrapper.getHeaders()); LOGGER.debug("Response body: {}", inputStringBuilder.toString()); // LOGGER.debug("Response body: {}", // IOUtils.toString(responseCopy.getBody())); LOGGER.debug( "==========================response end==============================================="); return responseWrapper; } }
bootweb/trunk/bootweb-pg/src/main/java/com/example/bootweb/pg/logging/LoggingRestTemplate.java
package com.example.bootweb.pg.logging; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpRequest; import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.ClientHttpResponse; @SuppressWarnings("static-method") public class LoggingRestTemplate implements ClientHttpRequestInterceptor { private final static Logger LOGGER = LoggerFactory.getLogger(LoggingRestTemplate.class); @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { traceRequest(request, body); ClientHttpResponse response = execution.execute(request, body); return traceResponse(response); } private void traceRequest(HttpRequest request, byte[] body) throws IOException { if (!LOGGER.isDebugEnabled()) { return; } LOGGER.debug( "==========================request begin=============================================="); LOGGER.debug("URI : {}", request.getURI()); LOGGER.debug("Method : {}", request.getMethod()); LOGGER.debug("Headers : {}", request.getHeaders()); LOGGER.debug("Request body: {}", new String(body, "UTF-8")); LOGGER.debug( "==========================request end================================================"); } private ClientHttpResponse traceResponse(ClientHttpResponse response) throws IOException { if (!LOGGER.isDebugEnabled()) { return response; } final ClientHttpResponse responseCopy = new BufferingClientHttpResponseWrapper(response); StringBuilder inputStringBuilder = new StringBuilder(); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(responseCopy.getBody(), "UTF-8")); String line = bufferedReader.readLine(); while (line != null) { inputStringBuilder.append(line); inputStringBuilder.append('\n'); line = bufferedReader.readLine(); } // responseCopy.close(); LOGGER.debug( "==========================response begin============================================="); LOGGER.debug("Status code : {}", responseCopy.getStatusCode()); LOGGER.debug("Status text : {}", responseCopy.getStatusText()); LOGGER.debug("Headers : {}", responseCopy.getHeaders()); LOGGER.debug("Response body: {}", inputStringBuilder.toString()); // LOGGER.debug("Response body: {}", // IOUtils.toString(responseCopy.getBody())); LOGGER.debug( "==========================response end==============================================="); return responseCopy; } }
Optimize.
bootweb/trunk/bootweb-pg/src/main/java/com/example/bootweb/pg/logging/LoggingRestTemplate.java
Optimize.
<ide><path>ootweb/trunk/bootweb-pg/src/main/java/com/example/bootweb/pg/logging/LoggingRestTemplate.java <ide> if (!LOGGER.isDebugEnabled()) { <ide> return response; <ide> } <del> final ClientHttpResponse responseCopy = new BufferingClientHttpResponseWrapper(response); <add> final ClientHttpResponse responseWrapper = new BufferingClientHttpResponseWrapper(response); <ide> StringBuilder inputStringBuilder = new StringBuilder(); <ide> BufferedReader bufferedReader = new BufferedReader( <del> new InputStreamReader(responseCopy.getBody(), "UTF-8")); <add> new InputStreamReader(responseWrapper.getBody(), "UTF-8")); <ide> String line = bufferedReader.readLine(); <ide> while (line != null) { <ide> inputStringBuilder.append(line); <ide> inputStringBuilder.append('\n'); <ide> line = bufferedReader.readLine(); <ide> } <del>// responseCopy.close(); <ide> LOGGER.debug( <ide> "==========================response begin============================================="); <del> LOGGER.debug("Status code : {}", responseCopy.getStatusCode()); <del> LOGGER.debug("Status text : {}", responseCopy.getStatusText()); <del> LOGGER.debug("Headers : {}", responseCopy.getHeaders()); <add> LOGGER.debug("Status code : {}", responseWrapper.getStatusCode()); <add> LOGGER.debug("Status text : {}", responseWrapper.getStatusText()); <add> LOGGER.debug("Headers : {}", responseWrapper.getHeaders()); <ide> LOGGER.debug("Response body: {}", inputStringBuilder.toString()); <ide> // LOGGER.debug("Response body: {}", <ide> // IOUtils.toString(responseCopy.getBody())); <ide> LOGGER.debug( <ide> "==========================response end==============================================="); <del> return responseCopy; <add> return responseWrapper; <ide> } <ide> <ide> }
JavaScript
mit
c7f600a349f50abcfdd6443521d642e2777db89c
0
halfalpine/simon,halfalpine/simon,halfalpine/simon
$(".document").ready(function() { let timerID; let data = { sequence: null, compSeq: [], humanSeq: [], ms: [1200, 1000, 800], colors: [green, red, yellow, blue], turns: 0 }; let controller = { init: function() { view.init(); }, /* play: function(){ // Add function: check for winner, call victory() and return true simon.playSeq(data.compSeq); events.activateHumanEvents(); }, */ start: function() { data.sequence = simon.makeSequence(); data.compSeq.push(data.sequence[data.turns]); simon.turn(); }, strict: function() { $('#strict-display').toggleClass('strict-on'); } }; // This function should togggle all event listeners on and off let events = { activateEvents: function() { $('#start-button').on('mousedown', controller.start); $('#strict-button').on('click', controller.strict); $('#green').on('mousedown', press.green); $('#red').on('mousedown', press.red); $('#yellow').on('mousedown', press.yellow); $('#blue').on('mousedown', press.blue); }, deactivateEvents: function() { $('#test').off('click', controller.init); $('#start-button').off('click', controller.start); $('#strict-button').off('click', controller.strict); $('#green').off('mousedown', press.green); $('#red').off('mousedown', press.red); $('#yellow').off('mousedown', press.yellow); $('#blue').off('mousedown', press.blue); }, activateHumanEvents: function() { $('.button').on('mousedown', simon.humanResponse); $('.button').toggleClass('lockout'); console.log('activated'); }, deactivateHumanEvents: function() { $('.button').off('mousedown', simon.humanResponse); $('.button').toggleClass('lockout'); console.log('deactivated'); }, togglePower: function() { this.checked ? events.activateEvents() : events.deactivateEvents(); } }; let press = { green: function() { let greenSound = document.getElementById('green-sound'); let newSound = greenSound.cloneNode(); newSound.play(); newSound.remove(); $('#green').addClass('press'); setTimeout(() => {press.removeOpacity('#green')}, 200); }, red: function() { let redSound = document.getElementById('red-sound'); let newSound = redSound.cloneNode(); newSound.play(); newSound.remove(); $('#red').addClass('press'); setTimeout(() => {press.removeOpacity('#red')}, 200) }, yellow: function() { let yellowSound = document.getElementById('yellow-sound'); let newSound = yellowSound.cloneNode(); newSound.play(); newSound.remove(); $('#yellow').addClass('press'); setTimeout(() => {press.removeOpacity('#yellow')}, 200) }, blue: function() { let blueSound = document.getElementById('blue-sound'); let newSound = blueSound.cloneNode(); newSound.play(); newSound.remove(); $('#blue').addClass('press'); setTimeout(() => {press.removeOpacity('#blue')}, 200) }, removeOpacity: function(x) { $(x).removeClass('press').bind(press.green); }, }; // The 'simon' object contains helper functions let simon = { getColorCode: function(button){ return $(button).data().button; }, hasWinner: function(humArr, compArr){ return humArr.every((value, index) => compArr[index] === humArr[index]); }, humanResponse: function(){ let x = simon.getColorCode(this); data.humanSeq.push(x); console.log("humanResponse", "compSeq", data.compSeq); console.log("humanResponse", "humanSeq", data.humanSeq); // If both arrays are equal... if (data.humanSeq.every((el, i) => el === data.compSeq[i])) { console.log('match'); if (data.compSeq.every((el, i) => el === data.humanSeq[i])) { console.log('nice!'); } } else { console.log('fail!'); data.humanSeq = []; simon.turn(data.compSeq); } /* if (data.humanSeq.every((el, i) => {el === data.compSeq[i]})) { console.log('match'); } */ }, makeSequence: function() { //Return an array of 20 numbers between 0 and 3 let arr = new Array(20); for (let i = 0; i < arr.length; i++) { let rand = Math.floor(Math.random() * 4); arr[i] = rand; } return arr; }, playback: function(){ }, pushButton: function(value, index, array) { if (value === 0) press.green(); else if (value === 1) press.red(); else if (value === 2) press.yellow() else press.blue(); }, translateToColor: function(num) { return data.colors[num]; }, turn: function(arr) { // arr is data.compSeq let index = 0; // Adjust playback speed, depending on number of turns events.deactivateHumanEvents(); timerID = setInterval(function(){ // console.log('turns', data.turns, 'index', index); // Playback logic simon.pushButton(data.compSeq[index]); if (index === data.turns) { events.activateHumanEvents(); clearInterval(timerID); } else { index++; } }, 1000); } } let view = { init: function() { $('#power').change(events.togglePower); //events.deactivateHumanEvents(); } }; controller.init(); });
js/index.js
$(".document").ready(function() { let timerID; let data = { sequence: null, compSeq: [], humanSeq: [], ms: [1200, 1000, 800], colors: [green, red, yellow, blue], turns: 0 }; let controller = { init: function() { view.init(); }, /* play: function(){ // Add function: check for winner, call victory() and return true simon.playSeq(data.compSeq); events.activateHumanEvents(); }, */ start: function() { data.sequence = simon.makeSequence(); console.log(data.sequence) //data.compSeq.push(data.sequence[0]); simon.turn(); }, strict: function() { $('#strict-display').toggleClass('strict-on'); } }; // This function should togggle all event listeners on and off let events = { activateEvents: function() { $('#start-button').on('mousedown', controller.start); $('#strict-button').on('click', controller.strict); $('#green').on('mousedown', press.green); $('#red').on('mousedown', press.red); $('#yellow').on('mousedown', press.yellow); $('#blue').on('mousedown', press.blue); }, deactivateEvents: function() { $('#test').off('click', controller.init); $('#start-button').off('click', controller.start); $('#strict-button').off('click', controller.strict); $('#green').off('mousedown', press.green); $('#red').off('mousedown', press.red); $('#yellow').off('mousedown', press.yellow); $('#blue').off('mousedown', press.blue); }, activateHumanEvents: function() { $('.button').on('mousedown', simon.humanResponse); $('.button').toggleClass('lockout'); console.log('activated'); }, deactivateHumanEvents: function() { $('.button').off('mousedown', simon.humanResponse); $('.button').toggleClass('lockout'); console.log('deactivated'); }, togglePower: function() { this.checked ? events.activateEvents() : events.deactivateEvents(); } }; let press = { green: function() { let greenSound = document.getElementById('green-sound'); let newSound = greenSound.cloneNode(); newSound.play(); newSound.remove(); $('#green').addClass('press'); setTimeout(() => {press.removeOpacity('#green')}, 200); }, red: function() { let redSound = document.getElementById('red-sound'); let newSound = redSound.cloneNode(); newSound.play(); newSound.remove(); $('#red').addClass('press'); setTimeout(() => {press.removeOpacity('#red')}, 200) }, yellow: function() { let yellowSound = document.getElementById('yellow-sound'); let newSound = yellowSound.cloneNode(); newSound.play(); newSound.remove(); $('#yellow').addClass('press'); setTimeout(() => {press.removeOpacity('#yellow')}, 200) }, blue: function() { let blueSound = document.getElementById('blue-sound'); let newSound = blueSound.cloneNode(); newSound.play(); newSound.remove(); $('#blue').addClass('press'); setTimeout(() => {press.removeOpacity('#blue')}, 200) }, removeOpacity: function(x) { $(x).removeClass('press').bind(press.green); }, }; // The 'simon' object contains helper functions let simon = { getColorCode: function(button){ return $(button).data().button; }, hasWinner: function(humArr, compArr){ return humArr.every((value, index) => compArr[index] === humArr[index]); }, humanResponse: function(){ let x = simon.getColorCode(this); data.humanSeq.push(x); console.log("humanResponse", "compSeq", data.compSeq); console.log("humanResponse", "humanSeq", data.humanSeq); // If both arrays are equal... if (data.humanSeq.every((el, i) => el === data.compSeq[i])) { console.log('match'); if (data.compSeq.every((el, i) => el === data.humanSeq[i])) { console.log('nice!'); } } else { console.log('fail!'); data.humanSeq = []; simon.turn(data.compSeq); } /* if (data.humanSeq.every((el, i) => {el === data.compSeq[i]})) { console.log('match'); } */ }, makeSequence: function() { //Return an array of 20 numbers between 0 and 3 let arr = new Array(20); for (let i = 0; i < arr.length; i++) { let rand = Math.floor(Math.random() * 4); arr[i] = rand; } return arr; }, playback: function(){ }, pushButton: function(value, index, array) { if (value === 0) press.green(); else if (value === 1) press.red(); else if (value === 2) press.yellow() else press.blue(); }, translateToColor: function(num) { return data.colors[num]; }, turn: function(arr) { // arr is data.compSeq let index = 0; data.compSeq.push(data.sequence[data.turns]); // Adjust playback speed, depending on number of turns events.deactivateHumanEvents(); timerID = setInterval(function(){ // console.log('turns', data.turns, 'index', index); // Playback logic simon.pushButton(data.compSeq[index]); if (index === data.turns) { events.activateHumanEvents(); clearInterval(timerID); } else { index++; } }, 1000); } } let view = { init: function() { $('#power').change(events.togglePower); //events.deactivateHumanEvents(); } }; controller.init(); });
Removed push to compSeq from .turn()
js/index.js
Removed push to compSeq from .turn()
<ide><path>s/index.js <ide> <ide> start: function() { <ide> data.sequence = simon.makeSequence(); <del> console.log(data.sequence) <del> //data.compSeq.push(data.sequence[0]); <add> data.compSeq.push(data.sequence[data.turns]); <ide> simon.turn(); <ide> }, <ide> <ide> <ide> turn: function(arr) { // arr is data.compSeq <ide> let index = 0; <del> data.compSeq.push(data.sequence[data.turns]); <ide> // Adjust playback speed, depending on number of turns <ide> events.deactivateHumanEvents(); <ide> timerID = setInterval(function(){
Java
apache-2.0
4936c4092a4b4f4dc5eff51aa98372e0b004bd79
0
kalaspuffar/pdfbox,apache/pdfbox,kalaspuffar/pdfbox,apache/pdfbox
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.pdfbox.pdmodel.graphics.image; import java.awt.color.ColorSpace; import java.awt.color.ICC_Profile; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.MemoryCacheImageInputStream; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.pdfbox.cos.COSArray; import org.apache.pdfbox.cos.COSDictionary; import org.apache.pdfbox.cos.COSInteger; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.cos.COSStream; import org.apache.pdfbox.filter.Filter; import org.apache.pdfbox.filter.FilterFactory; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.common.PDStream; import org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace; import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceGray; import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB; import org.apache.pdfbox.pdmodel.graphics.color.PDICCBased; import org.apache.pdfbox.pdmodel.graphics.color.PDIndexed; /** * This factory tries to encode a PNG given as byte array into a PDImageXObject * by directly coping the image data into the PDF streams without * decoding/encoding and re-compressing the PNG data. * <p> * If this is for any reason not possible, the factory will return null. You * must then encode the image by loading it and using the LosslessFactory. * <p> * The W3C PNG spec was used to implement this class: * https://www.w3.org/TR/2003/REC-PNG-20031110 * * @author Emmeran Seehuber */ final class PNGConverter { private static final Log LOG = LogFactory.getLog(PNGConverter.class); // Chunk Type definitions. The bytes in the comments are the bytes in the spec. private static final int CHUNK_IHDR = 0x49484452; // IHDR: 73 72 68 82 private static final int CHUNK_IDAT = 0x49444154; // IDAT: 73 68 65 84 private static final int CHUNK_PLTE = 0x504C5445; // PLTE: 80 76 84 69 private static final int CHUNK_IEND = 0x49454E44; // IEND: 73 69 78 68 private static final int CHUNK_TRNS = 0x74524E53; // tRNS: 116 82 78 83 private static final int CHUNK_CHRM = 0x6348524D; // cHRM: 99 72 82 77 private static final int CHUNK_GAMA = 0x67414D41; // gAMA: 103 65 77 65 private static final int CHUNK_ICCP = 0x69434350; // iCCP: 105 67 67 80 private static final int CHUNK_SBIT = 0x73424954; // sBIT: 115 66 73 84 private static final int CHUNK_SRGB = 0x73524742; // sRGB: 115 82 71 66 private static final int CHUNK_TEXT = 0x74455874; // tEXt: 116 69 88 116 private static final int CHUNK_ZTXT = 0x7A545874; // zTXt: 122 84 88 116 private static final int CHUNK_ITXT = 0x69545874; // iTXt: 105 84 88 116 private static final int CHUNK_KBKG = 0x6B424B47; // kBKG: 107 66 75 71 private static final int CHUNK_HIST = 0x68495354; // hIST: 104 73 83 84 private static final int CHUNK_PHYS = 0x70485973; // pHYs: 112 72 89 115 private static final int CHUNK_SPLT = 0x73504C54; // sPLT: 115 80 76 84 private static final int CHUNK_TIME = 0x74494D45; // tIME: 116 73 77 69 // CRC Reference Implementation, see // https://www.w3.org/TR/2003/REC-PNG-20031110/#D-CRCAppendix // for details /* Table of CRCs of all 8-bit messages. */ private static final int[] CRC_TABLE = new int[256]; static { makeCrcTable(); } private PNGConverter() { } /** * Try to convert a PNG into a PDImageXObject. If for any reason the PNG can not * be converted, null is returned. * <p> * This usually means the PNG structure is damaged (CRC error, etc.) or it uses * some features which can not be mapped to PDF. * * @param doc the document to put the image in * @param imageData the byte data of the PNG * @return null or the PDImageXObject built from the png */ static PDImageXObject convertPNGImage(PDDocument doc, byte[] imageData) throws IOException { PNGConverterState state = parsePNGChunks(imageData); if (!checkConverterState(state)) { // There is something wrong, we can't convert this PNG return null; } return convertPng(doc, state); } /** * Convert the image using the state. * * @param doc the document to put the image in * @param state the parser state containing the PNG chunks. * @return null or the converted image */ private static PDImageXObject convertPng(PDDocument doc, PNGConverterState state) throws IOException { Chunk ihdr = state.IHDR; int ihdrStart = ihdr.start; int width = readInt(ihdr.bytes, ihdrStart); int height = readInt(ihdr.bytes, ihdrStart + 4); int bitDepth = ihdr.bytes[ihdrStart + 8] & 0xFF; int colorType = ihdr.bytes[ihdrStart + 9] & 0xFF; int compressionMethod = ihdr.bytes[ihdrStart + 10] & 0xFF; int filterMethod = ihdr.bytes[ihdrStart + 11] & 0xFF; int interlaceMethod = ihdr.bytes[ihdrStart + 12] & 0xFF; if (bitDepth != 1 && bitDepth != 2 && bitDepth != 4 && bitDepth != 8 && bitDepth != 16) { LOG.error(String.format("Invalid bit depth %d.", bitDepth)); return null; } if (width <= 0 || height <= 0) { LOG.error(String.format("Invalid image size %d x %d", width, height)); return null; } if (compressionMethod != 0) { LOG.error(String.format("Unknown PNG compression method %d.", compressionMethod)); return null; } if (filterMethod != 0) { LOG.error(String.format("Unknown PNG filtering method %d.", compressionMethod)); return null; } if (interlaceMethod != 0) { LOG.debug(String.format("Can't handle interlace method %d.", interlaceMethod)); return null; } state.width = width; state.height = height; state.bitsPerComponent = bitDepth; switch (colorType) { case 0: // Grayscale LOG.debug("Can't handle grayscale yet."); return null; case 2: // Truecolor if (state.tRNS != null) { LOG.debug("Can't handle images with transparent colors."); return null; } return buildImageObject(doc, state); case 3: // Indexed image return buildIndexImage(doc, state); case 4: // Grayscale with alpha. LOG.debug( "Can't handle grayscale with alpha, would need to separate alpha from image data"); return null; case 6: // Truecolor with alpha. LOG.debug( "Can't handle truecolor with alpha, would need to separate alpha from image data"); return null; default: LOG.error("Unknown PNG color type " + colorType); return null; } } /** * Build a indexed image */ private static PDImageXObject buildIndexImage(PDDocument doc, PNGConverterState state) throws IOException { Chunk plte = state.PLTE; if (plte == null) { LOG.error("Indexed image without PLTE chunk."); return null; } if (plte.length % 3 != 0) { LOG.error("PLTE table corrupted, last (r,g,b) tuple is not complete."); return null; } if (state.bitsPerComponent > 8) { LOG.debug(String.format("Can only convert indexed images with bit depth <= 8, not %d.", state.bitsPerComponent)); return null; } PDImageXObject image = buildImageObject(doc, state); if (image == null) { return null; } int highVal = (plte.length / 3) - 1; if (highVal > 255) { LOG.error(String.format("To much colors in PLTE, only 256 allowed, found %d colors.", highVal + 1)); return null; } setupIndexedColorSpace(doc, plte, image, highVal); if (state.tRNS != null) { image.getCOSObject().setItem(COSName.SMASK, buildTransparencyMaskFromIndexedData(doc, image, state)); } return image; } private static PDImageXObject buildTransparencyMaskFromIndexedData(PDDocument doc, PDImageXObject image, PNGConverterState state) throws IOException { Filter flateDecode = FilterFactory.INSTANCE.getFilter(COSName.FLATE_DECODE); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); COSDictionary decodeParams = buildDecodeParams(state, PDDeviceGray.INSTANCE); COSDictionary imageDict = new COSDictionary(); imageDict.setItem(COSName.FILTER, COSName.FLATE_DECODE); imageDict.setItem(COSName.DECODE_PARMS, decodeParams); flateDecode.decode(getIDATInputStream(state), outputStream, imageDict, 0); int length = image.getWidth() * image.getHeight(); byte[] bytes = new byte[length]; byte[] transparencyTable = state.tRNS.getData(); byte[] decodedIDAT = outputStream.toByteArray(); try (ImageInputStream iis = new MemoryCacheImageInputStream( new ByteArrayInputStream(decodedIDAT))) { int bitsPerComponent = state.bitsPerComponent; int w = 0; int neededBits = bitsPerComponent * state.width; int bitPadding = neededBits % 8; for (int i = 0; i < bytes.length; i++) { int idx = (int) iis.readBits(bitsPerComponent); byte v; if (idx < transparencyTable.length) { // Inside the table, use the transparency value v = transparencyTable[idx]; } else { // Outside the table -> transparent value is 0xFF here. v = (byte) 0xFF; } bytes[i] = v; w++; if (w == state.width) { w = 0; iis.readBits(bitPadding); } } } return LosslessFactory .prepareImageXObject(doc, bytes, image.getWidth(), image.getHeight(), 8, PDDeviceGray.INSTANCE); } private static void setupIndexedColorSpace(PDDocument doc, Chunk lookupTable, PDImageXObject image, int highVal) throws IOException { COSArray indexedArray = new COSArray(); indexedArray.add(COSName.INDEXED); indexedArray.add(image.getColorSpace()); ((COSDictionary) image.getCOSObject().getItem(COSName.DECODE_PARMS)) .setItem(COSName.COLORS, COSInteger.ONE); indexedArray.add(COSInteger.get(highVal)); PDStream colorTable = new PDStream(doc); try (OutputStream colorTableStream = colorTable.createOutputStream(COSName.FLATE_DECODE)) { colorTableStream.write(lookupTable.bytes, lookupTable.start, lookupTable.length); } indexedArray.add(colorTable); PDIndexed indexed = new PDIndexed(indexedArray); image.setColorSpace(indexed); } /** * Build the base image object from the IDATs and profile information */ private static PDImageXObject buildImageObject(PDDocument document, PNGConverterState state) throws IOException { InputStream encodedByteStream = getIDATInputStream(state); PDColorSpace colorSpace = PDDeviceRGB.INSTANCE; PDImageXObject imageXObject = new PDImageXObject(document, encodedByteStream, COSName.FLATE_DECODE, state.width, state.height, state.bitsPerComponent, colorSpace); COSDictionary decodeParams = buildDecodeParams(state, colorSpace); imageXObject.getCOSObject().setItem(COSName.DECODE_PARMS, decodeParams); // We ignore gAMA and cHRM chunks if we have a ICC profile, as the ICC profile // takes preference boolean hasICCColorProfile = state.sRGB != null || state.iCCP != null; if (state.gAMA != null && !hasICCColorProfile) { if (state.gAMA.length != 4) { LOG.error("Invalid gAMA chunk length " + state.gAMA.length); return null; } float gamma = readPNGFloat(state.gAMA.bytes, state.gAMA.start); // If the gamma is 2.2 for sRGB everything is fine. Otherwise bail out. // The gamma is stored as 1 / gamma. if (Math.abs(gamma - (1 / 2.2f)) > 0.00001) { LOG.debug(String.format("We can't handle gamma of %f yet.", gamma)); return null; } } if (state.sRGB != null) { if (state.sRGB.length != 1) { LOG.error( String.format("sRGB chunk has an invalid length of %d", state.sRGB.length)); return null; } // Store the specified rendering intent int renderIntent = state.sRGB.bytes[state.sRGB.start]; COSName value = mapPNGRenderIntent(renderIntent); imageXObject.getCOSObject().setItem(COSName.INTENT, value); } if (state.cHRM != null && !hasICCColorProfile) { if (state.cHRM.length != 32) { LOG.error("Invalid cHRM chunk length " + state.cHRM.length); return null; } LOG.debug("We can not handle cHRM chunks yet."); return null; } // If possible we prefer a ICCBased color profile, just because its way faster // to decode ... if (state.iCCP != null || state.sRGB != null) { // We have got a color profile, which we must attach PDICCBased profile = new PDICCBased(document); COSStream cosStream = profile.getPDStream().getCOSObject(); cosStream.setInt(COSName.N, colorSpace.getNumberOfComponents()); cosStream.setItem(COSName.ALTERNATE, colorSpace.getNumberOfComponents() == 1 ? COSName.DEVICEGRAY : COSName.DEVICERGB); if (state.iCCP != null) { cosStream.setItem(COSName.FILTER, COSName.FLATE_DECODE); // We need to skip over the name int iccProfileDataStart = 0; while (iccProfileDataStart < 80 && iccProfileDataStart < state.iCCP.length) { if (state.iCCP.bytes[state.iCCP.start + iccProfileDataStart] == 0) break; iccProfileDataStart++; } iccProfileDataStart++; if (iccProfileDataStart >= state.iCCP.length) { LOG.error("Invalid iCCP chunk, to few bytes"); return null; } byte compressionMethod = state.iCCP.bytes[state.iCCP.start + iccProfileDataStart]; if (compressionMethod != 0) { LOG.error(String.format("iCCP chunk: invalid compression method %d", compressionMethod)); return null; } // Skip over the compression method iccProfileDataStart++; try (OutputStream rawOutputStream = cosStream.createRawOutputStream()) { rawOutputStream.write(state.iCCP.bytes, state.iCCP.start + iccProfileDataStart, state.iCCP.length - iccProfileDataStart); } } else { // We tag the image with the sRGB profile ICC_Profile rgbProfile = ICC_Profile.getInstance(ColorSpace.CS_sRGB); try (OutputStream outputStream = cosStream.createRawOutputStream()) { outputStream.write(rgbProfile.getData()); } } imageXObject.setColorSpace(profile); } return imageXObject; } private static COSDictionary buildDecodeParams(PNGConverterState state, PDColorSpace colorSpace) { COSDictionary decodeParms = new COSDictionary(); decodeParms.setItem(COSName.BITS_PER_COMPONENT, COSInteger.get(state.bitsPerComponent)); decodeParms.setItem(COSName.PREDICTOR, COSInteger.get(15)); decodeParms.setItem(COSName.COLUMNS, COSInteger.get(state.width)); decodeParms.setItem(COSName.COLORS, COSInteger.get(colorSpace.getNumberOfComponents())); return decodeParms; } /** * Build an input stream for the IDAT data. May need to concat multiple IDAT * chunks. * * @param state the converter state. * @return a input stream with the IDAT data. */ private static InputStream getIDATInputStream(PNGConverterState state) { MultipleInputStream inputStream = new MultipleInputStream(); for (Chunk idat : state.IDATs) { inputStream.inputStreams .add(new ByteArrayInputStream(idat.bytes, idat.start, idat.length)); } return inputStream; } private static class MultipleInputStream extends InputStream { List<InputStream> inputStreams = new ArrayList<>(); int currentStreamIdx; InputStream currentStream; private boolean ensureStream() { if (currentStream == null) { if (currentStreamIdx >= inputStreams.size()) { return false; } currentStream = inputStreams.get(currentStreamIdx++); } return true; } @Override public int read() throws IOException { if (!ensureStream()) { return -1; } int ret = currentStream.read(); if (ret == -1) { currentStream = null; return read(); } return ret; } @Override public int available() throws IOException { if (!ensureStream()) { return 0; } return 1; } @Override public int read(byte[] b, int off, int len) throws IOException { if (!ensureStream()) { return -1; } int ret = currentStream.read(b, off, len); if (ret == -1) { currentStream = null; return read(b, off, len); } return ret; } } /** * Map the renderIntent int to a PDF render intent. See also * https://www.w3.org/TR/2003/REC-PNG-20031110/#11sRGB * * @param renderIntent the PNG render intent * @return the matching PDF Render Intent or null */ static COSName mapPNGRenderIntent(int renderIntent) { COSName value; switch (renderIntent) { case 0: value = COSName.PERCEPTUAL; break; case 1: value = COSName.RELATIVE_COLORIMETRIC; break; case 2: value = COSName.SATURATION; break; case 3: value = COSName.ABSOLUTE_COLORIMETRIC; break; default: value = null; break; } return value; } /** * Check if the converter state is sane. * * @param state the parsed converter state * @return true if the state seems plausible */ static boolean checkConverterState(PNGConverterState state) { if (state == null) { return false; } if (state.IHDR == null || !checkChunkSane(state.IHDR)) { LOG.error("Invalid IHDR chunk."); return false; } if (!checkChunkSane(state.PLTE)) { LOG.error("Invalid PLTE chunk."); return false; } if (!checkChunkSane(state.iCCP)) { LOG.error("Invalid iCCP chunk."); return false; } if (!checkChunkSane(state.tRNS)) { LOG.error("Invalid tRNS chunk."); return false; } if (!checkChunkSane(state.sRGB)) { LOG.error("Invalid sRGB chunk."); return false; } if (!checkChunkSane(state.cHRM)) { LOG.error("Invalid cHRM chunk."); return false; } if (!checkChunkSane(state.gAMA)) { LOG.error("Invalid gAMA chunk."); return false; } // Check the IDATs if (state.IDATs.isEmpty()) { LOG.error("No IDAT chunks."); return false; } for (Chunk idat : state.IDATs) { if (!checkChunkSane(idat)) { LOG.error("Invalid IDAT chunk."); return false; } } return true; } /** * Check if the chunk is sane, i.e. CRC matches and offsets and lengths in the * byte array */ static boolean checkChunkSane(Chunk chunk) { if (chunk == null) { // If the chunk does not exist, it can not be wrong... return true; } if (chunk.start + chunk.length > chunk.bytes.length) { return false; } if (chunk.start < 4) { return false; } // We must include the chunk type in the CRC calculation int ourCRC = crc(chunk.bytes, chunk.start - 4, chunk.length + 4); if (ourCRC != chunk.crc) { LOG.error(String.format("Invalid CRC %08X on chunk %08X, expected %08X.", ourCRC, chunk.chunkType, chunk.crc)); return false; } return true; } /** * Holds the information about a chunks */ static final class Chunk { /** * This field holds the whole byte array; In that it's redundant, as all chunks * will have the same byte array. But have this byte array per chunk makes it * easier to validate and pass around. And we won't have that many chunks, so * those 8 bytes for the pointer (on 64-bit systems) don't matter. */ byte[] bytes; /** * The chunk type, see the CHUNK_??? constants. */ int chunkType; /** * The crc of the chunk data, as stored in the PNG stream. */ int crc; /** * The start index of the chunk data within bytes. */ int start; /** * The length of the data within the byte array. */ int length; /** * Get the data of this chunk as a byte array * * @return a byte-array with only the data of the chunk */ byte[] getData() { return Arrays.copyOfRange(bytes, start, start + length); } } /** * Holds all relevant chunks of the PNG */ static final class PNGConverterState { List<Chunk> IDATs = new ArrayList<>(); @SuppressWarnings("SpellCheckingInspection") Chunk IHDR; @SuppressWarnings("SpellCheckingInspection") Chunk PLTE; Chunk iCCP; Chunk tRNS; Chunk sRGB; Chunk gAMA; Chunk cHRM; // Parsed header fields int width; int height; int bitsPerComponent; } private static int readInt(byte[] data, int offset) { int b1 = (data[offset] & 0xFF) << 24; int b2 = (data[offset + 1] & 0xFF) << 16; int b3 = (data[offset + 2] & 0xFF) << 8; int b4 = (data[offset + 3] & 0xFF); return b1 | b2 | b3 | b4; } private static float readPNGFloat(byte[] bytes, int offset) { int v = readInt(bytes, offset); return v / 100000f; } /** * Parse the PNG structure into the PNGConverterState. If we can't handle * something, this method will return null. * * @param imageData the byte array with the PNG data * @return null or the converter state with all relevant chunks */ private static PNGConverterState parsePNGChunks(byte[] imageData) { if (imageData.length < 20) { LOG.error("ByteArray way to small: " + imageData.length); return null; } PNGConverterState state = new PNGConverterState(); int ptr = 8; int firstChunkType = readInt(imageData, ptr + 4); if (firstChunkType != CHUNK_IHDR) { LOG.error(String.format("First Chunktype was %08X, not IHDR", firstChunkType)); return null; } while (ptr + 12 <= imageData.length) { int chunkLength = readInt(imageData, ptr); int chunkType = readInt(imageData, ptr + 4); ptr += 8; if (ptr + chunkLength + 4 > imageData.length) { LOG.error("Not enough bytes. At offset " + ptr + " are " + chunkLength + " bytes expected. Overall length is " + imageData.length); return null; } Chunk chunk = new Chunk(); chunk.chunkType = chunkType; chunk.bytes = imageData; chunk.start = ptr; chunk.length = chunkLength; switch (chunkType) { case CHUNK_IHDR: if (state.IHDR != null) { LOG.error("Two IHDR chunks? There is something wrong."); return null; } state.IHDR = chunk; break; case CHUNK_IDAT: // The image data itself state.IDATs.add(chunk); break; case CHUNK_PLTE: // For indexed images the palette table if (state.PLTE != null) { LOG.error("Two PLTE chunks? There is something wrong."); return null; } state.PLTE = chunk; break; case CHUNK_IEND: // We are done, return the state return state; case CHUNK_TRNS: // For indexed images the alpha transparency table if (state.tRNS != null) { LOG.error("Two tRNS chunks? There is something wrong."); return null; } state.tRNS = chunk; break; case CHUNK_GAMA: // Gama state.gAMA = chunk; break; case CHUNK_CHRM: // Chroma state.cHRM = chunk; break; case CHUNK_ICCP: // ICC Profile state.iCCP = chunk; break; case CHUNK_SBIT: LOG.debug("Can't convert PNGs with sBIT chunk."); break; case CHUNK_SRGB: // We use the rendering intent from the chunk state.sRGB = chunk; break; case CHUNK_TEXT: case CHUNK_ZTXT: case CHUNK_ITXT: // We don't care about this text infos / metadata break; case CHUNK_KBKG: // As we can handle transparency we don't need the background color information. break; case CHUNK_HIST: // We don't need the color histogram break; case CHUNK_PHYS: // The PDImageXObject will be placed by the user however he wants, // so we can not enforce the physical dpi information stored here. // We just ignore it. break; case CHUNK_SPLT: // This palette stuff seems editor related, we don't need it. break; case CHUNK_TIME: // We don't need the last image change time either break; default: LOG.debug(String.format("Unknown chunk type %08X, skipping.", chunkType)); break; } ptr += chunkLength; // Read the CRC chunk.crc = readInt(imageData, ptr); ptr += 4; } LOG.error("No IEND chunk found."); return null; } /* Make the table for a fast CRC. */ private static void makeCrcTable() { int c; for (int n = 0; n < 256; n++) { c = n; for (int k = 0; k < 8; k++) { if ((c & 1) != 0) { c = 0xEDB88320 ^ (c >>> 1); } else { c = c >>> 1; } } CRC_TABLE[n] = c; } } /* * Update a running CRC with the bytes buf[0..len-1]--the CRC should be * initialized to all 1's, and the transmitted value is the 1's complement of * the final running CRC (see the crc() routine below). */ private static int updateCrc(byte[] buf, int offset, int len) { int c = -1; int end = offset + len; for (int n = offset; n < end; n++) { c = CRC_TABLE[(c ^ buf[n]) & 0xff] ^ (c >>> 8); } return c; } /* Return the CRC of the bytes buf[offset..(offset+len-1)]. */ static int crc(byte[] buf, int offset, int len) { return ~updateCrc(buf, offset, len); } }
pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/image/PNGConverter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.pdfbox.pdmodel.graphics.image; import java.awt.color.ColorSpace; import java.awt.color.ICC_Profile; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.MemoryCacheImageInputStream; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.pdfbox.cos.COSArray; import org.apache.pdfbox.cos.COSDictionary; import org.apache.pdfbox.cos.COSInteger; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.cos.COSStream; import org.apache.pdfbox.filter.Filter; import org.apache.pdfbox.filter.FilterFactory; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.common.PDStream; import org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace; import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceGray; import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB; import org.apache.pdfbox.pdmodel.graphics.color.PDICCBased; import org.apache.pdfbox.pdmodel.graphics.color.PDIndexed; /** * This factory tries to encode a PNG given as byte array into a PDImageXObject * by directly coping the image data into the PDF streams without * decoding/encoding and re-compressing the PNG data. * <p> * If this is for any reason not possible, the factory will return null. You * must then encode the image by loading it and using the LosslessFactory. * <p> * The W3C PNG spec was used to implement this class: * https://www.w3.org/TR/2003/REC-PNG-20031110 * * @author Emmeran Seehuber */ final class PNGConverter { private static final Log LOG = LogFactory.getLog(PNGConverter.class); // Chunk Type definitions. The bytes in the comments are the bytes in the spec. private static final int CHUNK_IHDR = 0x49484452; // IHDR: 73 72 68 82 private static final int CHUNK_IDAT = 0x49444154; // IDAT: 73 68 65 84 private static final int CHUNK_PLTE = 0x504C5445; // PLTE: 80 76 84 69 private static final int CHUNK_IEND = 0x49454E44; // IEND: 73 69 78 68 private static final int CHUNK_TRNS = 0x74524E53; // tRNS: 116 82 78 83 private static final int CHUNK_CHRM = 0x6348524D; // cHRM: 99 72 82 77 private static final int CHUNK_GAMA = 0x67414D41; // gAMA: 103 65 77 65 private static final int CHUNK_ICCP = 0x69434350; // iCCP: 105 67 67 80 private static final int CHUNK_SBIT = 0x73424954; // sBIT: 115 66 73 84 private static final int CHUNK_SRGB = 0x73524742; // sRGB: 115 82 71 66 private static final int CHUNK_TEXT = 0x74455874; // tEXt: 116 69 88 116 private static final int CHUNK_ZTXT = 0x7A545874; // zTXt: 122 84 88 116 private static final int CHUNK_ITXT = 0x69545874; // iTXt: 105 84 88 116 private static final int CHUNK_KBKG = 0x6B424B47; // kBKG: 107 66 75 71 private static final int CHUNK_HIST = 0x68495354; // hIST: 104 73 83 84 private static final int CHUNK_PHYS = 0x70485973; // pHYs: 112 72 89 115 private static final int CHUNK_SPLT = 0x73504C54; // sPLT: 115 80 76 84 private static final int CHUNK_TIME = 0x74494D45; // tIME: 116 73 77 69 // CRC Reference Implementation, see // https://www.w3.org/TR/2003/REC-PNG-20031110/#D-CRCAppendix // for details /* Table of CRCs of all 8-bit messages. */ private static final int[] CRC_TABLE = new int[256]; static { makeCrcTable(); } private PNGConverter() { } /** * Try to convert a PNG into a PDImageXObject. If for any reason the PNG can not * be converted, null is returned. * <p> * This usually means the PNG structure is damaged (CRC error, etc.) or it uses * some features which can not be mapped to PDF. * * @param doc the document to put the image in * @param imageData the byte data of the PNG * @return null or the PDImageXObject built from the png */ static PDImageXObject convertPNGImage(PDDocument doc, byte[] imageData) throws IOException { PNGConverterState state = parsePNGChunks(imageData); if (!checkConverterState(state)) { // There is something wrong, we can't convert this PNG return null; } return convertPng(doc, state); } /** * Convert the image using the state. * * @param doc the document to put the image in * @param state the parser state containing the PNG chunks. * @return null or the converted image */ private static PDImageXObject convertPng(PDDocument doc, PNGConverterState state) throws IOException { Chunk ihdr = state.IHDR; int ihdrStart = ihdr.start; int width = readInt(ihdr.bytes, ihdrStart); int height = readInt(ihdr.bytes, ihdrStart + 4); int bitDepth = ihdr.bytes[ihdrStart + 8] & 0xFF; int colorType = ihdr.bytes[ihdrStart + 9] & 0xFF; int compressionMethod = ihdr.bytes[ihdrStart + 10] & 0xFF; int filterMethod = ihdr.bytes[ihdrStart + 11] & 0xFF; int interlaceMethod = ihdr.bytes[ihdrStart + 12] & 0xFF; if (bitDepth != 1 && bitDepth != 2 && bitDepth != 4 && bitDepth != 8 && bitDepth != 16) { LOG.error(String.format("Invalid bit depth %d.", bitDepth)); return null; } if (width <= 0 || height <= 0) { LOG.error(String.format("Invalid image size %d x %d", width, height)); return null; } if (compressionMethod != 0) { LOG.error(String.format("Unknown PNG compression method %d.", compressionMethod)); return null; } if (filterMethod != 0) { LOG.error(String.format("Unknown PNG filtering method %d.", compressionMethod)); return null; } if (interlaceMethod != 0) { LOG.debug(String.format("Can't handle interlace method %d.", interlaceMethod)); return null; } state.width = width; state.height = height; state.bitsPerComponent = bitDepth; switch (colorType) { case 0: // Grayscale LOG.debug("Can't handle grayscale yet."); return null; case 2: // Truecolor if (state.tRNS != null) { LOG.debug("Can't handle images with transparent colors."); return null; } return buildImageObject(doc, state); case 3: // Indexed image return buildIndexImage(doc, state); case 4: // Grayscale with alpha. LOG.debug( "Can't handle grayscale with alpha, would need to separate alpha from image data"); return null; case 6: // Truecolor with alpha. LOG.debug( "Can't handle truecolor with alpha, would need to separate alpha from image data"); return null; default: LOG.error("Unknown PNG color type " + colorType); return null; } } /** * Build a indexed image */ private static PDImageXObject buildIndexImage(PDDocument doc, PNGConverterState state) throws IOException { Chunk plte = state.PLTE; if (plte == null) { LOG.error("Indexed image without PLTE chunk."); return null; } if (plte.length % 3 != 0) { LOG.error("PLTE table corrupted, last (r,g,b) tuple is not complete."); return null; } if (state.bitsPerComponent > 8) { LOG.debug(String.format("Can only convert indexed images with bit depth <= 8, not %d.", state.bitsPerComponent)); return null; } PDImageXObject image = buildImageObject(doc, state); if (image == null) { return null; } int highVal = (plte.length / 3) - 1; if (highVal > 255) { LOG.error(String.format("To much colors in PLTE, only 256 allowed, found %d colors.", highVal + 1)); return null; } setupIndexedColorSpace(doc, plte, image, highVal); if (state.tRNS != null) { image.getCOSObject().setItem(COSName.SMASK, buildTransparencyMaskFromIndexedData(doc, image, state)); } return image; } private static PDImageXObject buildTransparencyMaskFromIndexedData(PDDocument doc, PDImageXObject image, PNGConverterState state) throws IOException { Filter flateDecode = FilterFactory.INSTANCE.getFilter(COSName.FLATE_DECODE); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); COSDictionary decodeParams = buildDecodeParams(state, PDDeviceGray.INSTANCE); COSDictionary imageDict = new COSDictionary(); imageDict.setItem(COSName.FILTER, COSName.FLATE_DECODE); imageDict.setItem(COSName.DECODE_PARMS, decodeParams); flateDecode.decode(getIDATInputStream(state), outputStream, imageDict, 0); int length = image.getWidth() * image.getHeight(); byte[] bytes = new byte[length]; byte[] transparencyTable = state.tRNS.getData(); byte[] decodedIDAT = outputStream.toByteArray(); try (ImageInputStream iis = new MemoryCacheImageInputStream( new ByteArrayInputStream(decodedIDAT))) { int bitsPerComponent = state.bitsPerComponent; int w = 0; int neededBits = bitsPerComponent * state.width; int bitPadding = neededBits % 8; for (int i = 0; i < bytes.length; i++) { int idx = (int) iis.readBits(bitsPerComponent); byte v; if (idx < transparencyTable.length) { // Inside the table, use the transparency value v = transparencyTable[idx]; } else { // Outside the table -> transparent value is 0xFF here. v = (byte) 0xFF; } bytes[i] = v; w++; if (w == state.width) { w = 0; iis.readBits(bitPadding); } } } return LosslessFactory .prepareImageXObject(doc, bytes, image.getWidth(), image.getHeight(), 8, PDDeviceGray.INSTANCE); } private static void setupIndexedColorSpace(PDDocument doc, Chunk lookupTable, PDImageXObject image, int highVal) throws IOException { COSArray indexedArray = new COSArray(); indexedArray.add(COSName.INDEXED); indexedArray.add(image.getColorSpace()); ((COSDictionary) image.getCOSObject().getItem(COSName.DECODE_PARMS)) .setItem(COSName.COLORS, COSInteger.ONE); indexedArray.add(COSInteger.get(highVal)); PDStream colorTable = new PDStream(doc); try (OutputStream colorTableStream = colorTable.createOutputStream(COSName.FLATE_DECODE)) { colorTableStream.write(lookupTable.bytes, lookupTable.start, lookupTable.length); } indexedArray.add(colorTable); PDIndexed indexed = new PDIndexed(indexedArray); image.setColorSpace(indexed); } /** * Build the base image object from the IDATs and profile information */ private static PDImageXObject buildImageObject(PDDocument document, PNGConverterState state) throws IOException { InputStream encodedByteStream = getIDATInputStream(state); PDColorSpace colorSpace = PDDeviceRGB.INSTANCE; PDImageXObject imageXObject = new PDImageXObject(document, encodedByteStream, COSName.FLATE_DECODE, state.width, state.height, state.bitsPerComponent, colorSpace); COSDictionary decodeParams = buildDecodeParams(state, colorSpace); imageXObject.getCOSObject().setItem(COSName.DECODE_PARMS, decodeParams); // We ignore gAMA and cHRM chunks if we have a ICC profile, as the ICC profile // takes preference boolean hasICCColorProfile = state.sRGB != null || state.iCCP != null; if (state.gAMA != null && !hasICCColorProfile) { if (state.gAMA.length != 4) { LOG.error("Invalid gAMA chunk length " + state.gAMA.length); return null; } float gamma = readPNGFloat(state.gAMA.bytes, state.gAMA.start); // If the gamma is 2.2 for sRGB everything is fine. Otherwise bail out. // The gamma is stored as 1 / gamma. if (Math.abs(gamma - (1 / 2.2f)) > 0.00001) { LOG.debug(String.format("We can't handle gamma of %f yet.", gamma)); return null; } } if (state.sRGB != null) { if (state.sRGB.length != 1) { LOG.error( String.format("sRGB chunk has an invalid length of %d", state.sRGB.length)); return null; } // Store the specified rendering intent int renderIntent = state.sRGB.bytes[state.sRGB.start]; COSName value = mapPNGRenderIntent(renderIntent); imageXObject.getCOSObject().setItem(COSName.INTENT, value); } if (state.cHRM != null && !hasICCColorProfile) { if (state.cHRM.length != 32) { LOG.error("Invalid cHRM chunk length " + state.cHRM.length); return null; } LOG.debug("We can not handle cHRM chunks yet."); return null; } // If possible we prefer a ICCBased color profile, just because its way faster // to decode ... if (state.iCCP != null || state.sRGB != null) { // We have got a color profile, which we must attach PDICCBased profile = new PDICCBased(document); COSStream cosStream = profile.getPDStream().getCOSObject(); cosStream.setInt(COSName.N, colorSpace.getNumberOfComponents()); cosStream.setItem(COSName.ALTERNATE, colorSpace.getNumberOfComponents() == 1 ? COSName.DEVICEGRAY : COSName.DEVICERGB); if (state.iCCP != null) { // We need to skip over the name int iccProfileDataStart = 0; while (iccProfileDataStart < 80 && iccProfileDataStart < state.iCCP.length) { if (state.iCCP.bytes[state.iCCP.start + iccProfileDataStart] == 0) break; iccProfileDataStart++; } iccProfileDataStart++; if (iccProfileDataStart >= state.iCCP.length) { LOG.error("Invalid iCCP chunk, to few bytes"); return null; } byte compressionMethod = state.iCCP.bytes[state.iCCP.start + iccProfileDataStart]; if (compressionMethod != 0) { LOG.error(String.format("iCCP chunk: invalid compression method %d", compressionMethod)); return null; } // Skip over the compression method iccProfileDataStart++; try (OutputStream rawOutputStream = cosStream.createRawOutputStream()) { rawOutputStream.write(state.iCCP.bytes, state.iCCP.start + iccProfileDataStart, state.iCCP.length - iccProfileDataStart); } } else { // We tag the image with the sRGB profile ICC_Profile rgbProfile = ICC_Profile.getInstance(ColorSpace.CS_sRGB); try (OutputStream outputStream = cosStream.createRawOutputStream()) { outputStream.write(rgbProfile.getData()); } } imageXObject.setColorSpace(profile); } return imageXObject; } private static COSDictionary buildDecodeParams(PNGConverterState state, PDColorSpace colorSpace) { COSDictionary decodeParms = new COSDictionary(); decodeParms.setItem(COSName.BITS_PER_COMPONENT, COSInteger.get(state.bitsPerComponent)); decodeParms.setItem(COSName.PREDICTOR, COSInteger.get(15)); decodeParms.setItem(COSName.COLUMNS, COSInteger.get(state.width)); decodeParms.setItem(COSName.COLORS, COSInteger.get(colorSpace.getNumberOfComponents())); return decodeParms; } /** * Build an input stream for the IDAT data. May need to concat multiple IDAT * chunks. * * @param state the converter state. * @return a input stream with the IDAT data. */ private static InputStream getIDATInputStream(PNGConverterState state) { MultipleInputStream inputStream = new MultipleInputStream(); for (Chunk idat : state.IDATs) { inputStream.inputStreams .add(new ByteArrayInputStream(idat.bytes, idat.start, idat.length)); } return inputStream; } private static class MultipleInputStream extends InputStream { List<InputStream> inputStreams = new ArrayList<>(); int currentStreamIdx; InputStream currentStream; private boolean ensureStream() { if (currentStream == null) { if (currentStreamIdx >= inputStreams.size()) { return false; } currentStream = inputStreams.get(currentStreamIdx++); } return true; } @Override public int read() throws IOException { if (!ensureStream()) { return -1; } int ret = currentStream.read(); if (ret == -1) { currentStream = null; return read(); } return ret; } @Override public int available() throws IOException { if (!ensureStream()) { return 0; } return 1; } @Override public int read(byte[] b, int off, int len) throws IOException { if (!ensureStream()) { return -1; } int ret = currentStream.read(b, off, len); if (ret == -1) { currentStream = null; return read(b, off, len); } return ret; } } /** * Map the renderIntent int to a PDF render intent. See also * https://www.w3.org/TR/2003/REC-PNG-20031110/#11sRGB * * @param renderIntent the PNG render intent * @return the matching PDF Render Intent or null */ static COSName mapPNGRenderIntent(int renderIntent) { COSName value; switch (renderIntent) { case 0: value = COSName.PERCEPTUAL; break; case 1: value = COSName.RELATIVE_COLORIMETRIC; break; case 2: value = COSName.SATURATION; break; case 3: value = COSName.ABSOLUTE_COLORIMETRIC; break; default: value = null; break; } return value; } /** * Check if the converter state is sane. * * @param state the parsed converter state * @return true if the state seems plausible */ static boolean checkConverterState(PNGConverterState state) { if (state == null) { return false; } if (state.IHDR == null || !checkChunkSane(state.IHDR)) { LOG.error("Invalid IHDR chunk."); return false; } if (!checkChunkSane(state.PLTE)) { LOG.error("Invalid PLTE chunk."); return false; } if (!checkChunkSane(state.iCCP)) { LOG.error("Invalid iCCP chunk."); return false; } if (!checkChunkSane(state.tRNS)) { LOG.error("Invalid tRNS chunk."); return false; } if (!checkChunkSane(state.sRGB)) { LOG.error("Invalid sRGB chunk."); return false; } if (!checkChunkSane(state.cHRM)) { LOG.error("Invalid cHRM chunk."); return false; } if (!checkChunkSane(state.gAMA)) { LOG.error("Invalid gAMA chunk."); return false; } // Check the IDATs if (state.IDATs.isEmpty()) { LOG.error("No IDAT chunks."); return false; } for (Chunk idat : state.IDATs) { if (!checkChunkSane(idat)) { LOG.error("Invalid IDAT chunk."); return false; } } return true; } /** * Check if the chunk is sane, i.e. CRC matches and offsets and lengths in the * byte array */ static boolean checkChunkSane(Chunk chunk) { if (chunk == null) { // If the chunk does not exist, it can not be wrong... return true; } if (chunk.start + chunk.length > chunk.bytes.length) { return false; } if (chunk.start < 4) { return false; } // We must include the chunk type in the CRC calculation int ourCRC = crc(chunk.bytes, chunk.start - 4, chunk.length + 4); if (ourCRC != chunk.crc) { LOG.error(String.format("Invalid CRC %08X on chunk %08X, expected %08X.", ourCRC, chunk.chunkType, chunk.crc)); return false; } return true; } /** * Holds the information about a chunks */ static final class Chunk { /** * This field holds the whole byte array; In that it's redundant, as all chunks * will have the same byte array. But have this byte array per chunk makes it * easier to validate and pass around. And we won't have that many chunks, so * those 8 bytes for the pointer (on 64-bit systems) don't matter. */ byte[] bytes; /** * The chunk type, see the CHUNK_??? constants. */ int chunkType; /** * The crc of the chunk data, as stored in the PNG stream. */ int crc; /** * The start index of the chunk data within bytes. */ int start; /** * The length of the data within the byte array. */ int length; /** * Get the data of this chunk as a byte array * * @return a byte-array with only the data of the chunk */ byte[] getData() { return Arrays.copyOfRange(bytes, start, start + length); } } /** * Holds all relevant chunks of the PNG */ static final class PNGConverterState { List<Chunk> IDATs = new ArrayList<>(); @SuppressWarnings("SpellCheckingInspection") Chunk IHDR; @SuppressWarnings("SpellCheckingInspection") Chunk PLTE; Chunk iCCP; Chunk tRNS; Chunk sRGB; Chunk gAMA; Chunk cHRM; // Parsed header fields int width; int height; int bitsPerComponent; } private static int readInt(byte[] data, int offset) { int b1 = (data[offset] & 0xFF) << 24; int b2 = (data[offset + 1] & 0xFF) << 16; int b3 = (data[offset + 2] & 0xFF) << 8; int b4 = (data[offset + 3] & 0xFF); return b1 | b2 | b3 | b4; } private static float readPNGFloat(byte[] bytes, int offset) { int v = readInt(bytes, offset); return v / 100000f; } /** * Parse the PNG structure into the PNGConverterState. If we can't handle * something, this method will return null. * * @param imageData the byte array with the PNG data * @return null or the converter state with all relevant chunks */ private static PNGConverterState parsePNGChunks(byte[] imageData) { if (imageData.length < 20) { LOG.error("ByteArray way to small: " + imageData.length); return null; } PNGConverterState state = new PNGConverterState(); int ptr = 8; int firstChunkType = readInt(imageData, ptr + 4); if (firstChunkType != CHUNK_IHDR) { LOG.error(String.format("First Chunktype was %08X, not IHDR", firstChunkType)); return null; } while (ptr + 12 <= imageData.length) { int chunkLength = readInt(imageData, ptr); int chunkType = readInt(imageData, ptr + 4); ptr += 8; if (ptr + chunkLength + 4 > imageData.length) { LOG.error("Not enough bytes. At offset " + ptr + " are " + chunkLength + " bytes expected. Overall length is " + imageData.length); return null; } Chunk chunk = new Chunk(); chunk.chunkType = chunkType; chunk.bytes = imageData; chunk.start = ptr; chunk.length = chunkLength; switch (chunkType) { case CHUNK_IHDR: if (state.IHDR != null) { LOG.error("Two IHDR chunks? There is something wrong."); return null; } state.IHDR = chunk; break; case CHUNK_IDAT: // The image data itself state.IDATs.add(chunk); break; case CHUNK_PLTE: // For indexed images the palette table if (state.PLTE != null) { LOG.error("Two PLTE chunks? There is something wrong."); return null; } state.PLTE = chunk; break; case CHUNK_IEND: // We are done, return the state return state; case CHUNK_TRNS: // For indexed images the alpha transparency table if (state.tRNS != null) { LOG.error("Two tRNS chunks? There is something wrong."); return null; } state.tRNS = chunk; break; case CHUNK_GAMA: // Gama state.gAMA = chunk; break; case CHUNK_CHRM: // Chroma state.cHRM = chunk; break; case CHUNK_ICCP: // ICC Profile state.iCCP = chunk; break; case CHUNK_SBIT: LOG.debug("Can't convert PNGs with sBIT chunk."); break; case CHUNK_SRGB: // We use the rendering intent from the chunk state.sRGB = chunk; break; case CHUNK_TEXT: case CHUNK_ZTXT: case CHUNK_ITXT: // We don't care about this text infos / metadata break; case CHUNK_KBKG: // As we can handle transparency we don't need the background color information. break; case CHUNK_HIST: // We don't need the color histogram break; case CHUNK_PHYS: // The PDImageXObject will be placed by the user however he wants, // so we can not enforce the physical dpi information stored here. // We just ignore it. break; case CHUNK_SPLT: // This palette stuff seems editor related, we don't need it. break; case CHUNK_TIME: // We don't need the last image change time either break; default: LOG.debug(String.format("Unknown chunk type %08X, skipping.", chunkType)); break; } ptr += chunkLength; // Read the CRC chunk.crc = readInt(imageData, ptr); ptr += 4; } LOG.error("No IEND chunk found."); return null; } /* Make the table for a fast CRC. */ private static void makeCrcTable() { int c; for (int n = 0; n < 256; n++) { c = n; for (int k = 0; k < 8; k++) { if ((c & 1) != 0) { c = 0xEDB88320 ^ (c >>> 1); } else { c = c >>> 1; } } CRC_TABLE[n] = c; } } /* * Update a running CRC with the bytes buf[0..len-1]--the CRC should be * initialized to all 1's, and the transmitted value is the 1's complement of * the final running CRC (see the crc() routine below). */ private static int updateCrc(byte[] buf, int offset, int len) { int c = -1; int end = offset + len; for (int n = offset; n < end; n++) { c = CRC_TABLE[(c ^ buf[n]) & 0xff] ^ (c >>> 8); } return c; } /* Return the CRC of the bytes buf[offset..(offset+len-1)]. */ static int crc(byte[] buf, int offset, int len) { return ~updateCrc(buf, offset, len); } }
PDFBOX-4847: fix bug that created unusable icc profile, by Emmeran Seehuber git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1878199 13f79535-47bb-0310-9956-ffa450edef68
pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/image/PNGConverter.java
PDFBOX-4847: fix bug that created unusable icc profile, by Emmeran Seehuber
<ide><path>dfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/image/PNGConverter.java <ide> == 1 ? COSName.DEVICEGRAY : COSName.DEVICERGB); <ide> if (state.iCCP != null) <ide> { <add> cosStream.setItem(COSName.FILTER, COSName.FLATE_DECODE); <ide> // We need to skip over the name <ide> int iccProfileDataStart = 0; <ide> while (iccProfileDataStart < 80 && iccProfileDataStart < state.iCCP.length)
Java
mit
9cbae4e7a7e6347cc35b10b26e23bedc5f662d25
0
jaquadro/StorageDrawers,bloodmc/StorageDrawers,jaquadro/StorageDrawers
package com.jaquadro.minecraft.storagedrawers.core; import com.jaquadro.minecraft.storagedrawers.StorageDrawers; import com.jaquadro.minecraft.storagedrawers.block.BlockDrawers; import com.jaquadro.minecraft.storagedrawers.config.ConfigManager; import com.jaquadro.minecraft.storagedrawers.core.recipe.FallbackShapedOreRecipe; import cpw.mods.fml.common.registry.GameRegistry; import minetweaker.mc1710.recipes.ShapedRecipeOre; import net.minecraft.block.BlockWood; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.RecipeSorter; import net.minecraftforge.oredict.ShapedOreRecipe; public class ModRecipes { public void init () { OreDictionary.registerOre("chestWood", new ItemStack(Blocks.chest)); // Remove when porting to 1.8 RecipeSorter.register("StorageDrawers:FallbackShapedOreRecipe", FallbackShapedOreRecipe.class, RecipeSorter.Category.SHAPED, "after:forge:shapedore"); ConfigManager config = StorageDrawers.config; for (int i = 0; i < BlockWood.field_150096_a.length; i++) { if (config.isBlockEnabled("fulldrawers1")) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.fullDrawers1, config.getBlockRecipeOutput("fulldrawers1"), i), "xxx", " y ", "xxx", 'x', new ItemStack(Blocks.planks, 1, i), 'y', "chestWood")); if (config.isBlockEnabled("fulldrawers2")) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.fullDrawers2, config.getBlockRecipeOutput("fulldrawers2"), i), "xyx", "xxx", "xyx", 'x', new ItemStack(Blocks.planks, 1, i), 'y', "chestWood")); if (config.isBlockEnabled("halfdrawers2")) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.halfDrawers2, config.getBlockRecipeOutput("halfdrawers2"), i), "xyx", "xxx", "xyx", 'x', new ItemStack(Blocks.wooden_slab, 1, i), 'y', "chestWood")); if (config.isBlockEnabled("fulldrawers4")) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.fullDrawers4, config.getBlockRecipeOutput("fulldrawers4"), i), "yxy", "xxx", "yxy", 'x', new ItemStack(Blocks.planks, 1, i), 'y', "chestWood")); if (config.isBlockEnabled("halfdrawers4")) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.halfDrawers4, config.getBlockRecipeOutput("halfdrawers4"), i), "yxy", "xxx", "yxy", 'x', new ItemStack(Blocks.wooden_slab, 1, i), 'y', "chestWood")); if (config.isBlockEnabled("trim")) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.trim, config.getBlockRecipeOutput("trim"), i), "xyx", "yyy", "xyx", 'x', "stickWood", 'y', new ItemStack(Blocks.planks, 1, i))); } } // Fallback recipes if (config.cache.enableFallbackRecipes) { if (config.isBlockEnabled("fulldrawers1")) GameRegistry.addRecipe(new FallbackShapedOreRecipe(new ItemStack(ModBlocks.fullDrawers1, config.getBlockRecipeOutput("fulldrawers1"), 0), "xxx", " y ", "xxx", 'x', "plankWood", 'y', "chestWood")); if (config.isBlockEnabled("fulldrawers2")) GameRegistry.addRecipe(new FallbackShapedOreRecipe(new ItemStack(ModBlocks.fullDrawers2, config.getBlockRecipeOutput("fulldrawers2"), 0), "xyx", "xxx", "xyx", 'x', "plankWood", 'y', "chestWood")); if (config.isBlockEnabled("halfdrawers2")) GameRegistry.addRecipe(new FallbackShapedOreRecipe(new ItemStack(ModBlocks.halfDrawers2, config.getBlockRecipeOutput("halfdrawers2"), 0), "xyx", "xxx", "xyx", 'x', "slabWood", 'y', "chestWood")); if (config.isBlockEnabled("fulldrawers4")) GameRegistry.addRecipe(new FallbackShapedOreRecipe(new ItemStack(ModBlocks.fullDrawers4, config.getBlockRecipeOutput("fulldrawers4"), 0), "yxy", "xxx", "yxy", 'x', "plankWood", 'y', "chestWood")); if (config.isBlockEnabled("halfdrawers4")) GameRegistry.addRecipe(new FallbackShapedOreRecipe(new ItemStack(ModBlocks.halfDrawers4, config.getBlockRecipeOutput("halfdrawers4"), 0), "yxy", "xxx", "yxy", 'x', "slabWood", 'y', "chestWood")); if (config.isBlockEnabled("trim")) GameRegistry.addRecipe(new FallbackShapedOreRecipe(new ItemStack(ModBlocks.trim, config.getBlockRecipeOutput("trim"), 0), "xyx", "yyy", "xyx", 'x', "stickWood", 'y', "plankWood")); } if (config.isBlockEnabled("compdrawers")) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.compDrawers, config.getBlockRecipeOutput("compdrawers")), "xxx", "zwz", "xyx", 'x', new ItemStack(Blocks.stone), 'y', "ingotIron", 'z', new ItemStack(Blocks.piston), 'w', "drawerBasic")); if (config.isBlockEnabled("controller")) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.controller), "xxx", "yzy", "xwx", 'x', new ItemStack(Blocks.stone), 'y', Items.comparator, 'z', "drawerBasic", 'w', "gemDiamond")); if (config.isBlockEnabled("controllerSlave")) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.controllerSlave), "xxx", "yzy", "xwx", 'x', new ItemStack(Blocks.stone), 'y', Items.comparator, 'z', "drawerBasic", 'w', "ingotGold")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.upgradeTemplate, 2), "xxx", "xyx", "xxx", 'x', "stickWood", 'y', "drawerBasic")); if (config.cache.enableStorageUpgrades) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.upgrade, 1, 2), "xyx", "yzy", "xyx", 'x', "ingotIron", 'y', "stickWood", 'z', ModItems.upgradeTemplate)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.upgrade, 1, 3), "xyx", "yzy", "xyx", 'x', "ingotGold", 'y', "stickWood", 'z', ModItems.upgradeTemplate)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.upgrade, 1, 4), "xyx", "yzy", "xyx", 'x', Blocks.obsidian, 'y', "stickWood", 'z', ModItems.upgradeTemplate)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.upgrade, 1, 5), "xyx", "yzy", "xyx", 'x', "gemDiamond", 'y', "stickWood", 'z', ModItems.upgradeTemplate)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.upgrade, 1, 6), "xyx", "yzy", "xyx", 'x', "gemEmerald", 'y', "stickWood", 'z', ModItems.upgradeTemplate)); } if (config.cache.enableIndicatorUpgrades) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.upgradeStatus, 1, 1), "wyw", "yzy", "xyx", 'w', new ItemStack(Blocks.redstone_torch), 'x', "dustRedstone", 'y', "stickWood", 'z', ModItems.upgradeTemplate)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.upgradeStatus, 1, 2), "wyw", "yzy", "xyx", 'w', Items.comparator, 'x', "dustRedstone", 'y', "stickWood", 'z', ModItems.upgradeTemplate)); } if (config.cache.enableLockUpgrades) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.upgradeLock), "xy ", " y ", " z ", 'x', "nuggetGold", 'y', "ingotGold", 'z', ModItems.upgradeTemplate)); } if (config.cache.enableVoidUpgrades) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.upgradeVoid), "yyy", "xzx", "yyy", 'x', Blocks.obsidian, 'y', "stickWood", 'z', ModItems.upgradeTemplate)); } if (config.cache.enableRedstoneUpgrades) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.upgradeRedstone, 1, 0), "xyx", "yzy", "xyx", 'x', "dustRedstone", 'y', "stickWood", 'z', ModItems.upgradeTemplate)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.upgradeRedstone, 1, 1), "xxx", "yzy", "yyy", 'x', "dustRedstone", 'y', "stickWood", 'z', ModItems.upgradeTemplate)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.upgradeRedstone, 1, 2), "yyy", "yzy", "xxx", 'x', "dustRedstone", 'y', "stickWood", 'z', ModItems.upgradeTemplate)); } if (config.cache.enableShroudUpgrades) { GameRegistry.addShapelessRecipe(new ItemStack(ModItems.shroudKey), ModItems.upgradeLock, Items.ender_eye); } if (config.cache.enablePersonalUpgrades) { GameRegistry.addShapelessRecipe(new ItemStack(ModItems.personalKey), ModItems.upgradeLock, Items.name_tag); } if (config.cache.enableTape) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.tape), " x ", "yyy", 'x', "slimeball", 'y', Items.paper)); } if (config.cache.enableFramedDrawers) { GameRegistry.addShapedRecipe(new ItemStack(ModBlocks.framingTable), "xxx", "x x", 'x', ModBlocks.trim); if (config.isBlockEnabled("fulldrawers1")) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.fullCustom1, config.getBlockRecipeOutput("fulldrawers1"), 0), "xxx", " y ", "xxx", 'x', "stickWood", 'y', "chestWood")); if (config.isBlockEnabled("fulldrawers2")) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.fullCustom2, config.getBlockRecipeOutput("fulldrawers2"), 0), "xyx", "xzx", "xyx", 'x', "stickWood", 'y', "chestWood", 'z', "plankWood")); if (config.isBlockEnabled("halfdrawers2")) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.halfCustom2, config.getBlockRecipeOutput("halfdrawers2"), 0), "xyx", "xzx", "xyx", 'x', "stickWood", 'y', "chestWood", 'z', "slabWood")); if (config.isBlockEnabled("fulldrawers4")) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.fullCustom4, config.getBlockRecipeOutput("fulldrawers4"), 0), "yxy", "xzx", "yxy", 'x', "stickWood", 'y', "chestWood", 'z', "plankWood")); if (config.isBlockEnabled("halfdrawers4")) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.halfCustom4, config.getBlockRecipeOutput("halfdrawers4"), 0), "yxy", "xzx", "yxy", 'x', "stickWood", 'y', "chestWood", 'z', "slabWood")); } } }
src/com/jaquadro/minecraft/storagedrawers/core/ModRecipes.java
package com.jaquadro.minecraft.storagedrawers.core; import com.jaquadro.minecraft.storagedrawers.StorageDrawers; import com.jaquadro.minecraft.storagedrawers.block.BlockDrawers; import com.jaquadro.minecraft.storagedrawers.config.ConfigManager; import com.jaquadro.minecraft.storagedrawers.core.recipe.FallbackShapedOreRecipe; import cpw.mods.fml.common.registry.GameRegistry; import minetweaker.mc1710.recipes.ShapedRecipeOre; import net.minecraft.block.BlockWood; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.RecipeSorter; import net.minecraftforge.oredict.ShapedOreRecipe; public class ModRecipes { public void init () { OreDictionary.registerOre("chestWood", new ItemStack(Blocks.chest)); // Remove when porting to 1.8 RecipeSorter.register("StorageDrawers:FallbackShapedOreRecipe", FallbackShapedOreRecipe.class, RecipeSorter.Category.SHAPED, "after:minecraft:shapedore"); ConfigManager config = StorageDrawers.config; for (int i = 0; i < BlockWood.field_150096_a.length; i++) { if (config.isBlockEnabled("fulldrawers1")) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.fullDrawers1, config.getBlockRecipeOutput("fulldrawers1"), i), "xxx", " y ", "xxx", 'x', new ItemStack(Blocks.planks, 1, i), 'y', "chestWood")); if (config.isBlockEnabled("fulldrawers2")) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.fullDrawers2, config.getBlockRecipeOutput("fulldrawers2"), i), "xyx", "xxx", "xyx", 'x', new ItemStack(Blocks.planks, 1, i), 'y', "chestWood")); if (config.isBlockEnabled("halfdrawers2")) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.halfDrawers2, config.getBlockRecipeOutput("halfdrawers2"), i), "xyx", "xxx", "xyx", 'x', new ItemStack(Blocks.wooden_slab, 1, i), 'y', "chestWood")); if (config.isBlockEnabled("fulldrawers4")) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.fullDrawers4, config.getBlockRecipeOutput("fulldrawers4"), i), "yxy", "xxx", "yxy", 'x', new ItemStack(Blocks.planks, 1, i), 'y', "chestWood")); if (config.isBlockEnabled("halfdrawers4")) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.halfDrawers4, config.getBlockRecipeOutput("halfdrawers4"), i), "yxy", "xxx", "yxy", 'x', new ItemStack(Blocks.wooden_slab, 1, i), 'y', "chestWood")); if (config.isBlockEnabled("trim")) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.trim, config.getBlockRecipeOutput("trim"), i), "xyx", "yyy", "xyx", 'x', "stickWood", 'y', new ItemStack(Blocks.planks, 1, i))); } } // Fallback recipes if (config.cache.enableFallbackRecipes) { if (config.isBlockEnabled("fulldrawers1")) GameRegistry.addRecipe(new FallbackShapedOreRecipe(new ItemStack(ModBlocks.fullDrawers1, config.getBlockRecipeOutput("fulldrawers1"), 0), "xxx", " y ", "xxx", 'x', "plankWood", 'y', "chestWood")); if (config.isBlockEnabled("fulldrawers2")) GameRegistry.addRecipe(new FallbackShapedOreRecipe(new ItemStack(ModBlocks.fullDrawers2, config.getBlockRecipeOutput("fulldrawers2"), 0), "xyx", "xxx", "xyx", 'x', "plankWood", 'y', "chestWood")); if (config.isBlockEnabled("halfdrawers2")) GameRegistry.addRecipe(new FallbackShapedOreRecipe(new ItemStack(ModBlocks.halfDrawers2, config.getBlockRecipeOutput("halfdrawers2"), 0), "xyx", "xxx", "xyx", 'x', "slabWood", 'y', "chestWood")); if (config.isBlockEnabled("fulldrawers4")) GameRegistry.addRecipe(new FallbackShapedOreRecipe(new ItemStack(ModBlocks.fullDrawers4, config.getBlockRecipeOutput("fulldrawers4"), 0), "yxy", "xxx", "yxy", 'x', "plankWood", 'y', "chestWood")); if (config.isBlockEnabled("halfdrawers4")) GameRegistry.addRecipe(new FallbackShapedOreRecipe(new ItemStack(ModBlocks.halfDrawers4, config.getBlockRecipeOutput("halfdrawers4"), 0), "yxy", "xxx", "yxy", 'x', "slabWood", 'y', "chestWood")); if (config.isBlockEnabled("trim")) GameRegistry.addRecipe(new FallbackShapedOreRecipe(new ItemStack(ModBlocks.trim, config.getBlockRecipeOutput("trim"), 0), "xyx", "yyy", "xyx", 'x', "stickWood", 'y', "plankWood")); } if (config.isBlockEnabled("compdrawers")) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.compDrawers, config.getBlockRecipeOutput("compdrawers")), "xxx", "zwz", "xyx", 'x', new ItemStack(Blocks.stone), 'y', "ingotIron", 'z', new ItemStack(Blocks.piston), 'w', "drawerBasic")); if (config.isBlockEnabled("controller")) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.controller), "xxx", "yzy", "xwx", 'x', new ItemStack(Blocks.stone), 'y', Items.comparator, 'z', "drawerBasic", 'w', "gemDiamond")); if (config.isBlockEnabled("controllerSlave")) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.controllerSlave), "xxx", "yzy", "xwx", 'x', new ItemStack(Blocks.stone), 'y', Items.comparator, 'z', "drawerBasic", 'w', "ingotGold")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.upgradeTemplate, 2), "xxx", "xyx", "xxx", 'x', "stickWood", 'y', "drawerBasic")); if (config.cache.enableStorageUpgrades) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.upgrade, 1, 2), "xyx", "yzy", "xyx", 'x', "ingotIron", 'y', "stickWood", 'z', ModItems.upgradeTemplate)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.upgrade, 1, 3), "xyx", "yzy", "xyx", 'x', "ingotGold", 'y', "stickWood", 'z', ModItems.upgradeTemplate)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.upgrade, 1, 4), "xyx", "yzy", "xyx", 'x', Blocks.obsidian, 'y', "stickWood", 'z', ModItems.upgradeTemplate)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.upgrade, 1, 5), "xyx", "yzy", "xyx", 'x', "gemDiamond", 'y', "stickWood", 'z', ModItems.upgradeTemplate)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.upgrade, 1, 6), "xyx", "yzy", "xyx", 'x', "gemEmerald", 'y', "stickWood", 'z', ModItems.upgradeTemplate)); } if (config.cache.enableIndicatorUpgrades) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.upgradeStatus, 1, 1), "wyw", "yzy", "xyx", 'w', new ItemStack(Blocks.redstone_torch), 'x', "dustRedstone", 'y', "stickWood", 'z', ModItems.upgradeTemplate)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.upgradeStatus, 1, 2), "wyw", "yzy", "xyx", 'w', Items.comparator, 'x', "dustRedstone", 'y', "stickWood", 'z', ModItems.upgradeTemplate)); } if (config.cache.enableLockUpgrades) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.upgradeLock), "xy ", " y ", " z ", 'x', "nuggetGold", 'y', "ingotGold", 'z', ModItems.upgradeTemplate)); } if (config.cache.enableVoidUpgrades) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.upgradeVoid), "yyy", "xzx", "yyy", 'x', Blocks.obsidian, 'y', "stickWood", 'z', ModItems.upgradeTemplate)); } if (config.cache.enableRedstoneUpgrades) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.upgradeRedstone, 1, 0), "xyx", "yzy", "xyx", 'x', "dustRedstone", 'y', "stickWood", 'z', ModItems.upgradeTemplate)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.upgradeRedstone, 1, 1), "xxx", "yzy", "yyy", 'x', "dustRedstone", 'y', "stickWood", 'z', ModItems.upgradeTemplate)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.upgradeRedstone, 1, 2), "yyy", "yzy", "xxx", 'x', "dustRedstone", 'y', "stickWood", 'z', ModItems.upgradeTemplate)); } if (config.cache.enableShroudUpgrades) { GameRegistry.addShapelessRecipe(new ItemStack(ModItems.shroudKey), ModItems.upgradeLock, Items.ender_eye); } if (config.cache.enablePersonalUpgrades) { GameRegistry.addShapelessRecipe(new ItemStack(ModItems.personalKey), ModItems.upgradeLock, Items.name_tag); } if (config.cache.enableTape) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.tape), " x ", "yyy", 'x', "slimeball", 'y', Items.paper)); } if (config.cache.enableFramedDrawers) { GameRegistry.addShapedRecipe(new ItemStack(ModBlocks.framingTable), "xxx", "x x", 'x', ModBlocks.trim); if (config.isBlockEnabled("fulldrawers1")) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.fullCustom1, config.getBlockRecipeOutput("fulldrawers1"), 0), "xxx", " y ", "xxx", 'x', "stickWood", 'y', "chestWood")); if (config.isBlockEnabled("fulldrawers2")) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.fullCustom2, config.getBlockRecipeOutput("fulldrawers2"), 0), "xyx", "xzx", "xyx", 'x', "stickWood", 'y', "chestWood", 'z', "plankWood")); if (config.isBlockEnabled("halfdrawers2")) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.halfCustom2, config.getBlockRecipeOutput("halfdrawers2"), 0), "xyx", "xzx", "xyx", 'x', "stickWood", 'y', "chestWood", 'z', "slabWood")); if (config.isBlockEnabled("fulldrawers4")) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.fullCustom4, config.getBlockRecipeOutput("fulldrawers4"), 0), "yxy", "xzx", "yxy", 'x', "stickWood", 'y', "chestWood", 'z', "plankWood")); if (config.isBlockEnabled("halfdrawers4")) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.halfCustom4, config.getBlockRecipeOutput("halfdrawers4"), 0), "yxy", "xzx", "yxy", 'x', "stickWood", 'y', "chestWood", 'z', "slabWood")); } } }
Fix fallback shaped ore recipe sorting priority Fixes #214
src/com/jaquadro/minecraft/storagedrawers/core/ModRecipes.java
Fix fallback shaped ore recipe sorting priority
<ide><path>rc/com/jaquadro/minecraft/storagedrawers/core/ModRecipes.java <ide> public void init () { <ide> OreDictionary.registerOre("chestWood", new ItemStack(Blocks.chest)); // Remove when porting to 1.8 <ide> <del> RecipeSorter.register("StorageDrawers:FallbackShapedOreRecipe", FallbackShapedOreRecipe.class, RecipeSorter.Category.SHAPED, "after:minecraft:shapedore"); <add> RecipeSorter.register("StorageDrawers:FallbackShapedOreRecipe", FallbackShapedOreRecipe.class, RecipeSorter.Category.SHAPED, "after:forge:shapedore"); <ide> <ide> ConfigManager config = StorageDrawers.config; <ide>
Java
apache-2.0
29fbff3ba63d05be97a87d18021864b24cde8d8b
0
AmeBel/relex,rodsol/relex-temp,virneo/relex,rodsol/relex-temp,rodsol/relex-temp,anitzkin/relex,virneo/relex,anitzkin/relex,anitzkin/relex,leungmanhin/relex,ainishdave/relex,rodsol/relex,ainishdave/relex,opencog/relex,ainishdave/relex,linas/relex,rodsol/relex,ainishdave/relex,williampma/relex,leungmanhin/relex,AmeBel/relex,williampma/relex,leungmanhin/relex,rodsol/relex,opencog/relex,virneo/relex,linas/relex,rodsol/relex-temp,linas/relex,anitzkin/relex,rodsol/relex-temp,AmeBel/relex,rodsol/relex,williampma/relex,virneo/relex,anitzkin/relex,williampma/relex,opencog/relex
/* * Copyright 2008 Novamente LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package relex.feature; import relex.stats.TruthValue; /** * An object that ever so vaguely resembles an OpenCog Atom. * * Copyright (C) 2008 Linas Vepstas <[email protected]> */ public class Atom { protected TruthValue truth_value; public Atom() { truth_value = null; } public TruthValue getTruthValue() { return truth_value; } public void setTruthValue(TruthValue tv) { truth_value = tv; } }
src/java/relex/feature/Atom.java
/* * Copyright 2008 Novamente LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package relex.feature; import relex.stats.TruthValue; /** * An object that ever so vaguely resembles an OpenCog Atom. * * Copyright (C) 2008 Linas Vepstas <[email protected]> */ public class Atom { protected TruthValue truth_value; public Atom() { truth_value = null; } public TruthValue getTruthValue() { return truth_value; } public void setTruthValue(TruthVale tv) { truth_value = tv; } }
wtf .. typo
src/java/relex/feature/Atom.java
wtf .. typo
<ide><path>rc/java/relex/feature/Atom.java <ide> { <ide> return truth_value; <ide> } <del> public void setTruthValue(TruthVale tv) <add> public void setTruthValue(TruthValue tv) <ide> { <ide> truth_value = tv; <ide> }
Java
epl-1.0
3c20b85de5760f8f95b16499e09a16ee035cd678
0
bendisposto/prob2-ui,bendisposto/prob2-ui,bendisposto/prob2-ui,bendisposto/prob2-ui
package de.prob2.ui.beditor; import java.io.IOException; import java.io.PushbackReader; import java.io.StringReader; import java.time.Duration; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.ResourceBundle; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import com.google.inject.Inject; import de.be4.classicalb.core.parser.BLexer; import de.be4.classicalb.core.parser.lexer.LexerException; import de.be4.classicalb.core.parser.node.EOF; import de.be4.classicalb.core.parser.node.TAbstractConstants; import de.be4.classicalb.core.parser.node.TAbstractVariables; import de.be4.classicalb.core.parser.node.TAny; import de.be4.classicalb.core.parser.node.TArity; import de.be4.classicalb.core.parser.node.TAssert; import de.be4.classicalb.core.parser.node.TAssertions; import de.be4.classicalb.core.parser.node.TAssign; import de.be4.classicalb.core.parser.node.TBe; import de.be4.classicalb.core.parser.node.TBegin; import de.be4.classicalb.core.parser.node.TBool; import de.be4.classicalb.core.parser.node.TBtree; import de.be4.classicalb.core.parser.node.TCase; import de.be4.classicalb.core.parser.node.TChoice; import de.be4.classicalb.core.parser.node.TClosure; import de.be4.classicalb.core.parser.node.TClosure1; import de.be4.classicalb.core.parser.node.TComment; import de.be4.classicalb.core.parser.node.TCommentBody; import de.be4.classicalb.core.parser.node.TCommentEnd; import de.be4.classicalb.core.parser.node.TConcreteConstants; import de.be4.classicalb.core.parser.node.TConcreteVariables; import de.be4.classicalb.core.parser.node.TConjunction; import de.be4.classicalb.core.parser.node.TConst; import de.be4.classicalb.core.parser.node.TConstants; import de.be4.classicalb.core.parser.node.TConstraints; import de.be4.classicalb.core.parser.node.TDefinitions; import de.be4.classicalb.core.parser.node.TDirectProduct; import de.be4.classicalb.core.parser.node.TDivision; import de.be4.classicalb.core.parser.node.TDo; import de.be4.classicalb.core.parser.node.TDoubleColon; import de.be4.classicalb.core.parser.node.TDoubleEqual; import de.be4.classicalb.core.parser.node.TDoubleVerticalBar; import de.be4.classicalb.core.parser.node.TEither; import de.be4.classicalb.core.parser.node.TElementOf; import de.be4.classicalb.core.parser.node.TElse; import de.be4.classicalb.core.parser.node.TElsif; import de.be4.classicalb.core.parser.node.TEmptySet; import de.be4.classicalb.core.parser.node.TEnd; import de.be4.classicalb.core.parser.node.TEqual; import de.be4.classicalb.core.parser.node.TEquivalence; import de.be4.classicalb.core.parser.node.TExists; import de.be4.classicalb.core.parser.node.TExtends; import de.be4.classicalb.core.parser.node.TFalse; import de.be4.classicalb.core.parser.node.TFather; import de.be4.classicalb.core.parser.node.TFin; import de.be4.classicalb.core.parser.node.TFin1; import de.be4.classicalb.core.parser.node.TForAny; import de.be4.classicalb.core.parser.node.TGreater; import de.be4.classicalb.core.parser.node.TGreaterEqual; import de.be4.classicalb.core.parser.node.TIdentifierLiteral; import de.be4.classicalb.core.parser.node.TIf; import de.be4.classicalb.core.parser.node.TImplementation; import de.be4.classicalb.core.parser.node.TImplies; import de.be4.classicalb.core.parser.node.TImports; import de.be4.classicalb.core.parser.node.TIn; import de.be4.classicalb.core.parser.node.TIncludes; import de.be4.classicalb.core.parser.node.TInfix; import de.be4.classicalb.core.parser.node.TInitialisation; import de.be4.classicalb.core.parser.node.TInt; import de.be4.classicalb.core.parser.node.TInteger; import de.be4.classicalb.core.parser.node.TInterval; import de.be4.classicalb.core.parser.node.TInvariant; import de.be4.classicalb.core.parser.node.TIseq; import de.be4.classicalb.core.parser.node.TIseq1; import de.be4.classicalb.core.parser.node.TLeft; import de.be4.classicalb.core.parser.node.TLess; import de.be4.classicalb.core.parser.node.TLessEqual; import de.be4.classicalb.core.parser.node.TLet; import de.be4.classicalb.core.parser.node.TLineComment; import de.be4.classicalb.core.parser.node.TLogicalOr; import de.be4.classicalb.core.parser.node.TMachine; import de.be4.classicalb.core.parser.node.TMirror; import de.be4.classicalb.core.parser.node.TModel; import de.be4.classicalb.core.parser.node.TNat; import de.be4.classicalb.core.parser.node.TNat1; import de.be4.classicalb.core.parser.node.TNatural; import de.be4.classicalb.core.parser.node.TNatural1; import de.be4.classicalb.core.parser.node.TNonInclusion; import de.be4.classicalb.core.parser.node.TNot; import de.be4.classicalb.core.parser.node.TNotEqual; import de.be4.classicalb.core.parser.node.TOf; import de.be4.classicalb.core.parser.node.TOperations; import de.be4.classicalb.core.parser.node.TOr; import de.be4.classicalb.core.parser.node.TOutputParameters; import de.be4.classicalb.core.parser.node.TPartialBijection; import de.be4.classicalb.core.parser.node.TPartialFunction; import de.be4.classicalb.core.parser.node.TPartialInjection; import de.be4.classicalb.core.parser.node.TPartialSurjection; import de.be4.classicalb.core.parser.node.TPerm; import de.be4.classicalb.core.parser.node.TPostfix; import de.be4.classicalb.core.parser.node.TPow; import de.be4.classicalb.core.parser.node.TPow1; import de.be4.classicalb.core.parser.node.TPre; import de.be4.classicalb.core.parser.node.TPrefix; import de.be4.classicalb.core.parser.node.TPromotes; import de.be4.classicalb.core.parser.node.TProperties; import de.be4.classicalb.core.parser.node.TRank; import de.be4.classicalb.core.parser.node.TRefinement; import de.be4.classicalb.core.parser.node.TRefines; import de.be4.classicalb.core.parser.node.TRight; import de.be4.classicalb.core.parser.node.TSees; import de.be4.classicalb.core.parser.node.TSelect; import de.be4.classicalb.core.parser.node.TSeq; import de.be4.classicalb.core.parser.node.TSeq1; import de.be4.classicalb.core.parser.node.TSetRelation; import de.be4.classicalb.core.parser.node.TSets; import de.be4.classicalb.core.parser.node.TSizet; import de.be4.classicalb.core.parser.node.TSkip; import de.be4.classicalb.core.parser.node.TSon; import de.be4.classicalb.core.parser.node.TSons; import de.be4.classicalb.core.parser.node.TString; import de.be4.classicalb.core.parser.node.TStringLiteral; import de.be4.classicalb.core.parser.node.TStruct; import de.be4.classicalb.core.parser.node.TSubtree; import de.be4.classicalb.core.parser.node.TSystem; import de.be4.classicalb.core.parser.node.TThen; import de.be4.classicalb.core.parser.node.TTop; import de.be4.classicalb.core.parser.node.TTotalBijection; import de.be4.classicalb.core.parser.node.TTotalFunction; import de.be4.classicalb.core.parser.node.TTotalInjection; import de.be4.classicalb.core.parser.node.TTotalRelation; import de.be4.classicalb.core.parser.node.TTotalSurjection; import de.be4.classicalb.core.parser.node.TTotalSurjectionRelation; import de.be4.classicalb.core.parser.node.TTree; import de.be4.classicalb.core.parser.node.TTrue; import de.be4.classicalb.core.parser.node.TUnion; import de.be4.classicalb.core.parser.node.TUses; import de.be4.classicalb.core.parser.node.TVar; import de.be4.classicalb.core.parser.node.TVariables; import de.be4.classicalb.core.parser.node.TVariant; import de.be4.classicalb.core.parser.node.TWhen; import de.be4.classicalb.core.parser.node.TWhere; import de.be4.classicalb.core.parser.node.TWhile; import de.be4.classicalb.core.parser.node.Token; import de.prob.animator.domainobjects.ErrorItem; import de.prob2.ui.internal.FXMLInjected; import de.prob2.ui.layout.FontSize; import de.prob2.ui.prob2fx.CurrentProject; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.concurrent.Task; import javafx.scene.control.ContextMenu; import javafx.scene.control.MenuItem; import org.fxmisc.richtext.CodeArea; import org.fxmisc.richtext.LineNumberFactory; import org.fxmisc.richtext.model.StyleSpans; import org.fxmisc.richtext.model.StyleSpansBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @FXMLInjected public class BEditor extends CodeArea { private static final Logger LOGGER = LoggerFactory.getLogger(BEditor.class); private ExecutorService executor; private static final Map<Class<? extends Token>, String> syntaxClasses = new HashMap<>(); static { addTokens("editor_identifier", TIdentifierLiteral.class); addTokens("editor_assignments", TAssign.class, TOutputParameters.class, TDoubleVerticalBar.class, TAssert.class, TClosure.class, TClosure1.class, TDirectProduct.class, TDivision.class, TEmptySet.class, TDoubleColon.class, TImplies.class, TLogicalOr.class, TInterval.class, TUnion.class, TOr.class, TNonInclusion.class, TTotalBijection.class, TTotalFunction.class, TTotalInjection.class, TTotalRelation.class, TTotalSurjection.class, TFalse.class, TTrue.class, TTotalSurjectionRelation.class, TPartialBijection.class, TPartialFunction.class, TPartialInjection.class, TPartialSurjection.class, TSetRelation.class, TFin.class, TFin1.class, TPerm.class, TSeq.class, TSeq1.class, TIseq.class, TIseq1.class, TNot.class); addTokens("editor_logical", TConjunction.class, TForAny.class, TExists.class); addTokens("editor_arithmetic", TDoubleEqual.class, TEqual.class, TElementOf.class, TEquivalence.class, TGreaterEqual.class, TLessEqual.class, TNotEqual.class, TGreater.class, TLess.class); addTokens("editor_types", TBool.class, TNat.class, TNat1.class, TNatural.class, TNatural1.class, TStruct.class, TInteger.class, TInt.class, TString.class); addTokens("editor_string", TStringLiteral.class); addTokens("editor_unsupported", TTree.class, TLeft.class, TRight.class, TInfix.class, TArity.class, TSubtree.class, TPow.class, TPow1.class, TSon.class, TFather.class, TRank.class, TMirror.class, TSizet.class, TPostfix.class, TPrefix.class, TSons.class, TTop.class, TConst.class, TBtree.class); addTokens("editor_ctrlkeyword", TSkip.class, TLet.class, TBe.class, TVar.class, TIn.class, TAny.class, TWhile.class, TDo.class, TVariant.class, TElsif.class, TIf.class, TThen.class, TElse.class, TEither.class, TCase.class, TSelect.class, TAssert.class, TAssertions.class, TWhen.class, TPre.class, TBegin.class, TChoice.class, TWhere.class, TOf.class, TEnd.class); addTokens("editor_keyword", TMachine.class, TOperations.class, TRefinement.class, TImplementation.class, TOperations.class, TAssertions.class, TInitialisation.class, TSees.class, TPromotes.class, TUses.class, TIncludes.class, TImports.class, TRefines.class, TExtends.class, TSystem.class, TModel.class, TInvariant.class, TConcreteVariables.class, TAbstractVariables.class, TVariables.class, TProperties.class, TConstants.class, TAbstractConstants.class, TConcreteConstants.class, TConstraints.class, TSets.class, TDefinitions.class); addTokens("editor_comment", TComment.class, TCommentBody.class, TCommentEnd.class, TLineComment.class); } private final FontSize fontSize; private final CurrentProject currentProject; private final ResourceBundle bundle; private final ObservableList<ErrorItem.Location> errorLocations; @Inject private BEditor(final FontSize fontSize, final ResourceBundle bundle, final CurrentProject currentProject) { this.fontSize = fontSize; this.currentProject = currentProject; this.bundle = bundle; this.errorLocations = FXCollections.observableArrayList(); initialize(); initializeContextMenu(); } private void initializeContextMenu() { final ContextMenu contextMenu = new ContextMenu(); final MenuItem undoItem = new MenuItem(bundle.getString("common.contextMenu.undo")); undoItem.setOnAction(e -> this.getUndoManager().undo()); contextMenu.getItems().add(undoItem); final MenuItem redoItem = new MenuItem(bundle.getString("common.contextMenu.redo")); redoItem.setOnAction(e -> this.getUndoManager().redo()); contextMenu.getItems().add(redoItem); final MenuItem cutItem = new MenuItem(bundle.getString("common.contextMenu.cut")); cutItem.setOnAction(e -> this.cut()); contextMenu.getItems().add(cutItem); final MenuItem copyItem = new MenuItem(bundle.getString("common.contextMenu.copy")); copyItem.setOnAction(e -> this.copy()); contextMenu.getItems().add(copyItem); final MenuItem pasteItem = new MenuItem(bundle.getString("common.contextMenu.paste")); pasteItem.setOnAction(e -> this.paste()); contextMenu.getItems().add(pasteItem); final MenuItem deleteItem = new MenuItem(bundle.getString("common.contextMenu.delete")); deleteItem.setOnAction(e -> this.deleteText(this.getSelection())); contextMenu.getItems().add(deleteItem); final MenuItem selectAllItem = new MenuItem(bundle.getString("common.contextMenu.selectAll")); selectAllItem.setOnAction(e -> this.selectAll()); contextMenu.getItems().add(selectAllItem); this.setContextMenu(contextMenu); } private void initialize() { currentProject.currentMachineProperty().addListener((observable, from, to) -> { this.clear(); this.appendText(bundle.getString("beditor.hint")); }); this.setParagraphGraphicFactory(LineNumberFactory.get(this)); this.richChanges() .filter(ch -> !ch.isPlainTextIdentity()) .successionEnds(Duration.ofMillis(100)) .supplyTask(this::computeHighlightingAsync) .awaitLatest(this.richChanges()) .filterMap(t -> { if (t.isSuccess()) { return Optional.of(t.get()); } else { LOGGER.info("Highlighting failed", t.getFailure()); return Optional.empty(); } }).subscribe(highlighting -> { this.getErrorLocations().clear(); // Remove error highlighting if editor text changes this.applyHighlighting(highlighting); }); this.errorLocations.addListener((ListChangeListener<ErrorItem.Location>)change -> this.applyHighlighting(computeHighlighting(this.getText())) ); fontSize.fontSizeProperty().addListener((observable, from, to) -> this.setStyle(String.format("-fx-font-size: %dpx;", to.intValue())) ); } public void startHighlighting() { if (this.executor == null) { this.executor = Executors.newSingleThreadExecutor(); } } public void stopHighlighting() { if(this.executor != null) { this.executor.shutdown(); this.executor = null; } } @SafeVarargs private static void addTokens(String syntaxclass, Class<? extends Token>... tokens) { for (Class<? extends Token> c : tokens) { syntaxClasses.put(c, syntaxclass); } } private void applyHighlighting(StyleSpans<Collection<String>> highlighting) { this.setStyleSpans(0, highlighting); final List<String> errorStyle = Collections.singletonList("error"); for (final ErrorItem.Location location : this.getErrorLocations()) { final int startParagraph = location.getStartLine() - 1; final int endParagraph = location.getEndLine() - 1; if (startParagraph == endParagraph) { final int displayedEndColumn = location.getStartColumn() == location.getEndColumn() ? location.getStartColumn() + 1 : location.getEndColumn(); this.setStyle(startParagraph, location.getStartColumn(), displayedEndColumn, errorStyle); } else { this.setStyle(startParagraph, location.getStartColumn(), this.getParagraphLength(startParagraph), errorStyle); for (int para = startParagraph + 1; para < endParagraph; para++) { this.setStyle(para, errorStyle); } this.setStyle(endParagraph, 0, location.getEndColumn(), errorStyle); } } } private Task<StyleSpans<Collection<String>>> computeHighlightingAsync() { final String text = this.getText(); if (executor == null) { // No executor - run and return a dummy task that does no highlighting final Task<StyleSpans<Collection<String>>> task = new Task<StyleSpans<Collection<String>>>() { @Override protected StyleSpans<Collection<String>> call() { return StyleSpans.singleton(Collections.singleton("default"), text.length()); } }; task.run(); return task; } else { // Executor exists - do proper highlighting final Task<StyleSpans<Collection<String>>> task = new Task<StyleSpans<Collection<String>>>() { @Override protected StyleSpans<Collection<String>> call() { return computeHighlighting(text); } }; executor.execute(task); return task; } } private static StyleSpans<Collection<String>> computeHighlighting(String text) { BLexer lexer = new BLexer(new PushbackReader(new StringReader(text), text.length())); StyleSpansBuilder<Collection<String>> spansBuilder = new StyleSpansBuilder<>(); try { Token t; do { t = lexer.next(); String string = syntaxClasses.get(t.getClass()); int length = t.getText().length(); if (t instanceof TStringLiteral) { length += 2; } spansBuilder.add(Collections.singleton(string == null ? "default" : string), length); } while (!(t instanceof EOF)); } catch (LexerException | IOException e) { LOGGER.info("Failed to lex", e); } return spansBuilder.create(); } public void clearHistory() { this.getUndoManager().forgetHistory(); } public ObservableList<ErrorItem.Location> getErrorLocations() { return this.errorLocations; } }
src/main/java/de/prob2/ui/beditor/BEditor.java
package de.prob2.ui.beditor; import java.io.IOException; import java.io.PushbackReader; import java.io.StringReader; import java.time.Duration; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.ResourceBundle; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import com.google.inject.Inject; import de.be4.classicalb.core.parser.BLexer; import de.be4.classicalb.core.parser.lexer.LexerException; import de.be4.classicalb.core.parser.node.EOF; import de.be4.classicalb.core.parser.node.TAbstractConstants; import de.be4.classicalb.core.parser.node.TAbstractVariables; import de.be4.classicalb.core.parser.node.TAny; import de.be4.classicalb.core.parser.node.TArity; import de.be4.classicalb.core.parser.node.TAssert; import de.be4.classicalb.core.parser.node.TAssertions; import de.be4.classicalb.core.parser.node.TAssign; import de.be4.classicalb.core.parser.node.TBe; import de.be4.classicalb.core.parser.node.TBegin; import de.be4.classicalb.core.parser.node.TBool; import de.be4.classicalb.core.parser.node.TBtree; import de.be4.classicalb.core.parser.node.TCase; import de.be4.classicalb.core.parser.node.TChoice; import de.be4.classicalb.core.parser.node.TClosure; import de.be4.classicalb.core.parser.node.TClosure1; import de.be4.classicalb.core.parser.node.TComment; import de.be4.classicalb.core.parser.node.TCommentBody; import de.be4.classicalb.core.parser.node.TCommentEnd; import de.be4.classicalb.core.parser.node.TConcreteConstants; import de.be4.classicalb.core.parser.node.TConcreteVariables; import de.be4.classicalb.core.parser.node.TConjunction; import de.be4.classicalb.core.parser.node.TConst; import de.be4.classicalb.core.parser.node.TConstants; import de.be4.classicalb.core.parser.node.TConstraints; import de.be4.classicalb.core.parser.node.TDefinitions; import de.be4.classicalb.core.parser.node.TDirectProduct; import de.be4.classicalb.core.parser.node.TDivision; import de.be4.classicalb.core.parser.node.TDo; import de.be4.classicalb.core.parser.node.TDoubleColon; import de.be4.classicalb.core.parser.node.TDoubleEqual; import de.be4.classicalb.core.parser.node.TDoubleVerticalBar; import de.be4.classicalb.core.parser.node.TEither; import de.be4.classicalb.core.parser.node.TElementOf; import de.be4.classicalb.core.parser.node.TElse; import de.be4.classicalb.core.parser.node.TElsif; import de.be4.classicalb.core.parser.node.TEmptySet; import de.be4.classicalb.core.parser.node.TEnd; import de.be4.classicalb.core.parser.node.TEqual; import de.be4.classicalb.core.parser.node.TEquivalence; import de.be4.classicalb.core.parser.node.TExists; import de.be4.classicalb.core.parser.node.TExtends; import de.be4.classicalb.core.parser.node.TFalse; import de.be4.classicalb.core.parser.node.TFather; import de.be4.classicalb.core.parser.node.TFin; import de.be4.classicalb.core.parser.node.TFin1; import de.be4.classicalb.core.parser.node.TForAny; import de.be4.classicalb.core.parser.node.TGreater; import de.be4.classicalb.core.parser.node.TGreaterEqual; import de.be4.classicalb.core.parser.node.TIdentifierLiteral; import de.be4.classicalb.core.parser.node.TIf; import de.be4.classicalb.core.parser.node.TImplementation; import de.be4.classicalb.core.parser.node.TImplies; import de.be4.classicalb.core.parser.node.TImports; import de.be4.classicalb.core.parser.node.TIn; import de.be4.classicalb.core.parser.node.TIncludes; import de.be4.classicalb.core.parser.node.TInfix; import de.be4.classicalb.core.parser.node.TInitialisation; import de.be4.classicalb.core.parser.node.TInt; import de.be4.classicalb.core.parser.node.TInteger; import de.be4.classicalb.core.parser.node.TInterval; import de.be4.classicalb.core.parser.node.TInvariant; import de.be4.classicalb.core.parser.node.TIseq; import de.be4.classicalb.core.parser.node.TIseq1; import de.be4.classicalb.core.parser.node.TLeft; import de.be4.classicalb.core.parser.node.TLess; import de.be4.classicalb.core.parser.node.TLessEqual; import de.be4.classicalb.core.parser.node.TLet; import de.be4.classicalb.core.parser.node.TLineComment; import de.be4.classicalb.core.parser.node.TLogicalOr; import de.be4.classicalb.core.parser.node.TMachine; import de.be4.classicalb.core.parser.node.TMirror; import de.be4.classicalb.core.parser.node.TModel; import de.be4.classicalb.core.parser.node.TNat; import de.be4.classicalb.core.parser.node.TNat1; import de.be4.classicalb.core.parser.node.TNatural; import de.be4.classicalb.core.parser.node.TNatural1; import de.be4.classicalb.core.parser.node.TNonInclusion; import de.be4.classicalb.core.parser.node.TNot; import de.be4.classicalb.core.parser.node.TNotEqual; import de.be4.classicalb.core.parser.node.TOf; import de.be4.classicalb.core.parser.node.TOperations; import de.be4.classicalb.core.parser.node.TOr; import de.be4.classicalb.core.parser.node.TOutputParameters; import de.be4.classicalb.core.parser.node.TPartialBijection; import de.be4.classicalb.core.parser.node.TPartialFunction; import de.be4.classicalb.core.parser.node.TPartialInjection; import de.be4.classicalb.core.parser.node.TPartialSurjection; import de.be4.classicalb.core.parser.node.TPerm; import de.be4.classicalb.core.parser.node.TPostfix; import de.be4.classicalb.core.parser.node.TPow; import de.be4.classicalb.core.parser.node.TPow1; import de.be4.classicalb.core.parser.node.TPre; import de.be4.classicalb.core.parser.node.TPrefix; import de.be4.classicalb.core.parser.node.TPromotes; import de.be4.classicalb.core.parser.node.TProperties; import de.be4.classicalb.core.parser.node.TRank; import de.be4.classicalb.core.parser.node.TRefinement; import de.be4.classicalb.core.parser.node.TRefines; import de.be4.classicalb.core.parser.node.TRight; import de.be4.classicalb.core.parser.node.TSees; import de.be4.classicalb.core.parser.node.TSelect; import de.be4.classicalb.core.parser.node.TSeq; import de.be4.classicalb.core.parser.node.TSeq1; import de.be4.classicalb.core.parser.node.TSetRelation; import de.be4.classicalb.core.parser.node.TSets; import de.be4.classicalb.core.parser.node.TSizet; import de.be4.classicalb.core.parser.node.TSkip; import de.be4.classicalb.core.parser.node.TSon; import de.be4.classicalb.core.parser.node.TSons; import de.be4.classicalb.core.parser.node.TString; import de.be4.classicalb.core.parser.node.TStringLiteral; import de.be4.classicalb.core.parser.node.TStruct; import de.be4.classicalb.core.parser.node.TSubtree; import de.be4.classicalb.core.parser.node.TSystem; import de.be4.classicalb.core.parser.node.TThen; import de.be4.classicalb.core.parser.node.TTop; import de.be4.classicalb.core.parser.node.TTotalBijection; import de.be4.classicalb.core.parser.node.TTotalFunction; import de.be4.classicalb.core.parser.node.TTotalInjection; import de.be4.classicalb.core.parser.node.TTotalRelation; import de.be4.classicalb.core.parser.node.TTotalSurjection; import de.be4.classicalb.core.parser.node.TTotalSurjectionRelation; import de.be4.classicalb.core.parser.node.TTree; import de.be4.classicalb.core.parser.node.TTrue; import de.be4.classicalb.core.parser.node.TUnion; import de.be4.classicalb.core.parser.node.TUses; import de.be4.classicalb.core.parser.node.TVar; import de.be4.classicalb.core.parser.node.TVariables; import de.be4.classicalb.core.parser.node.TVariant; import de.be4.classicalb.core.parser.node.TWhen; import de.be4.classicalb.core.parser.node.TWhere; import de.be4.classicalb.core.parser.node.TWhile; import de.be4.classicalb.core.parser.node.Token; import de.prob.animator.domainobjects.ErrorItem; import de.prob2.ui.internal.FXMLInjected; import de.prob2.ui.layout.FontSize; import de.prob2.ui.prob2fx.CurrentProject; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.concurrent.Task; import javafx.scene.control.ContextMenu; import javafx.scene.control.MenuItem; import org.fxmisc.richtext.CodeArea; import org.fxmisc.richtext.LineNumberFactory; import org.fxmisc.richtext.model.StyleSpans; import org.fxmisc.richtext.model.StyleSpansBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @FXMLInjected public class BEditor extends CodeArea { private static final Logger LOGGER = LoggerFactory.getLogger(BEditor.class); private ExecutorService executor; private static final Map<Class<? extends Token>, String> syntaxClasses = new HashMap<>(); static { addTokens("editor_identifier", TIdentifierLiteral.class); addTokens("editor_assignments", TAssign.class, TOutputParameters.class, TDoubleVerticalBar.class, TAssert.class, TClosure.class, TClosure1.class, TDirectProduct.class, TDivision.class, TEmptySet.class, TDoubleColon.class, TImplies.class, TLogicalOr.class, TInterval.class, TUnion.class, TOr.class, TNonInclusion.class, TTotalBijection.class, TTotalFunction.class, TTotalInjection.class, TTotalRelation.class, TTotalSurjection.class, TFalse.class, TTrue.class, TTotalSurjectionRelation.class, TPartialBijection.class, TPartialFunction.class, TPartialInjection.class, TPartialSurjection.class, TSetRelation.class, TFin.class, TFin1.class, TPerm.class, TSeq.class, TSeq1.class, TIseq.class, TIseq1.class, TNot.class); addTokens("editor_logical", TConjunction.class, TForAny.class, TExists.class); addTokens("editor_arithmetic", TDoubleEqual.class, TEqual.class, TElementOf.class, TEquivalence.class, TGreaterEqual.class, TLessEqual.class, TNotEqual.class, TGreater.class, TLess.class); addTokens("editor_types", TBool.class, TNat.class, TNat1.class, TNatural.class, TNatural1.class, TStruct.class, TInteger.class, TInt.class, TString.class); addTokens("editor_string", TStringLiteral.class); addTokens("editor_unsupported", TTree.class, TLeft.class, TRight.class, TInfix.class, TArity.class, TSubtree.class, TPow.class, TPow1.class, TSon.class, TFather.class, TRank.class, TMirror.class, TSizet.class, TPostfix.class, TPrefix.class, TSons.class, TTop.class, TConst.class, TBtree.class); addTokens("editor_ctrlkeyword", TSkip.class, TLet.class, TBe.class, TVar.class, TIn.class, TAny.class, TWhile.class, TDo.class, TVariant.class, TElsif.class, TIf.class, TThen.class, TElse.class, TEither.class, TCase.class, TSelect.class, TAssert.class, TAssertions.class, TWhen.class, TPre.class, TBegin.class, TChoice.class, TWhere.class, TOf.class, TEnd.class); addTokens("editor_keyword", TMachine.class, TOperations.class, TRefinement.class, TImplementation.class, TOperations.class, TAssertions.class, TInitialisation.class, TSees.class, TPromotes.class, TUses.class, TIncludes.class, TImports.class, TRefines.class, TExtends.class, TSystem.class, TModel.class, TInvariant.class, TConcreteVariables.class, TAbstractVariables.class, TVariables.class, TProperties.class, TConstants.class, TAbstractConstants.class, TConcreteConstants.class, TConstraints.class, TSets.class, TDefinitions.class); addTokens("editor_comment", TComment.class, TCommentBody.class, TCommentEnd.class, TLineComment.class); } private final FontSize fontSize; private final CurrentProject currentProject; private final ResourceBundle bundle; private final ObservableList<ErrorItem.Location> errorLocations; @Inject private BEditor(final FontSize fontSize, final ResourceBundle bundle, final CurrentProject currentProject) { this.fontSize = fontSize; this.currentProject = currentProject; this.bundle = bundle; this.errorLocations = FXCollections.observableArrayList(); initialize(); initializeContextMenu(); } private void initializeContextMenu() { final ContextMenu contextMenu = new ContextMenu(); final MenuItem undoItem = new MenuItem(bundle.getString("common.contextMenu.undo")); undoItem.setOnAction(e -> this.getUndoManager().undo()); contextMenu.getItems().add(undoItem); final MenuItem redoItem = new MenuItem(bundle.getString("common.contextMenu.redo")); redoItem.setOnAction(e -> this.getUndoManager().redo()); contextMenu.getItems().add(redoItem); final MenuItem cutItem = new MenuItem(bundle.getString("common.contextMenu.cut")); cutItem.setOnAction(e -> this.cut()); contextMenu.getItems().add(cutItem); final MenuItem copyItem = new MenuItem(bundle.getString("common.contextMenu.copy")); copyItem.setOnAction(e -> this.copy()); contextMenu.getItems().add(copyItem); final MenuItem pasteItem = new MenuItem(bundle.getString("common.contextMenu.paste")); pasteItem.setOnAction(e -> this.paste()); contextMenu.getItems().add(pasteItem); final MenuItem deleteItem = new MenuItem(bundle.getString("common.contextMenu.delete")); deleteItem.setOnAction(e -> this.deleteText(this.getSelection())); contextMenu.getItems().add(deleteItem); final MenuItem selectAllItem = new MenuItem(bundle.getString("common.contextMenu.selectAll")); selectAllItem.setOnAction(e -> this.selectAll()); contextMenu.getItems().add(selectAllItem); this.setContextMenu(contextMenu); } private void initialize() { currentProject.currentMachineProperty().addListener((observable, from, to) -> { this.clear(); this.appendText(bundle.getString("beditor.hint")); }); this.setParagraphGraphicFactory(LineNumberFactory.get(this)); this.richChanges() .filter(ch -> !ch.isPlainTextIdentity()) .successionEnds(Duration.ofMillis(100)) .supplyTask(this::computeHighlightingAsync) .awaitLatest(this.richChanges()) .filterMap(t -> { if (t.isSuccess()) { return Optional.of(t.get()); } else { LOGGER.info("Highlighting failed", t.getFailure()); return Optional.empty(); } }).subscribe(highlighting -> { this.getErrorLocations().clear(); // Remove error highlighting if editor text changes this.applyHighlighting(highlighting); }); this.errorLocations.addListener((ListChangeListener<ErrorItem.Location>)change -> this.applyHighlighting(computeHighlighting(this.getText())) ); fontSize.fontSizeProperty().addListener((observable, from, to) -> this.setStyle(String.format("-fx-font-size: %dpx;", to.intValue())) ); } public void startHighlighting() { if (this.executor == null) { this.executor = Executors.newSingleThreadExecutor(); } } public void stopHighlighting() { if(this.executor != null) { this.executor.shutdown(); this.executor = null; } } @SafeVarargs private static void addTokens(String syntaxclass, Class<? extends Token>... tokens) { for (Class<? extends Token> c : tokens) { syntaxClasses.put(c, syntaxclass); } } private void applyHighlighting(StyleSpans<Collection<String>> highlighting) { this.setStyleSpans(0, highlighting); for (final ErrorItem.Location location : this.getErrorLocations()) { assert location.getStartLine() == location.getEndLine() : "TODO multiline errors"; this.setStyle(location.getStartLine()-1, location.getStartColumn(), location.getEndColumn(), Collections.singletonList("error")); } } private Task<StyleSpans<Collection<String>>> computeHighlightingAsync() { final String text = this.getText(); if (executor == null) { // No executor - run and return a dummy task that does no highlighting final Task<StyleSpans<Collection<String>>> task = new Task<StyleSpans<Collection<String>>>() { @Override protected StyleSpans<Collection<String>> call() { return StyleSpans.singleton(Collections.singleton("default"), text.length()); } }; task.run(); return task; } else { // Executor exists - do proper highlighting final Task<StyleSpans<Collection<String>>> task = new Task<StyleSpans<Collection<String>>>() { @Override protected StyleSpans<Collection<String>> call() { return computeHighlighting(text); } }; executor.execute(task); return task; } } private static StyleSpans<Collection<String>> computeHighlighting(String text) { BLexer lexer = new BLexer(new PushbackReader(new StringReader(text), text.length())); StyleSpansBuilder<Collection<String>> spansBuilder = new StyleSpansBuilder<>(); try { Token t; do { t = lexer.next(); String string = syntaxClasses.get(t.getClass()); int length = t.getText().length(); if (t instanceof TStringLiteral) { length += 2; } spansBuilder.add(Collections.singleton(string == null ? "default" : string), length); } while (!(t instanceof EOF)); } catch (LexerException | IOException e) { LOGGER.info("Failed to lex", e); } return spansBuilder.create(); } public void clearHistory() { this.getUndoManager().forgetHistory(); } public ObservableList<ErrorItem.Location> getErrorLocations() { return this.errorLocations; } }
Implement highlighting for multiline and zero-length error ranges
src/main/java/de/prob2/ui/beditor/BEditor.java
Implement highlighting for multiline and zero-length error ranges
<ide><path>rc/main/java/de/prob2/ui/beditor/BEditor.java <ide> import java.util.Collection; <ide> import java.util.Collections; <ide> import java.util.HashMap; <add>import java.util.List; <ide> import java.util.Map; <ide> import java.util.Optional; <ide> import java.util.ResourceBundle; <ide> <ide> private void applyHighlighting(StyleSpans<Collection<String>> highlighting) { <ide> this.setStyleSpans(0, highlighting); <add> final List<String> errorStyle = Collections.singletonList("error"); <ide> for (final ErrorItem.Location location : this.getErrorLocations()) { <del> assert location.getStartLine() == location.getEndLine() : "TODO multiline errors"; <del> this.setStyle(location.getStartLine()-1, location.getStartColumn(), location.getEndColumn(), Collections.singletonList("error")); <add> final int startParagraph = location.getStartLine() - 1; <add> final int endParagraph = location.getEndLine() - 1; <add> if (startParagraph == endParagraph) { <add> final int displayedEndColumn = location.getStartColumn() == location.getEndColumn() ? location.getStartColumn() + 1 : location.getEndColumn(); <add> this.setStyle(startParagraph, location.getStartColumn(), displayedEndColumn, errorStyle); <add> } else { <add> this.setStyle(startParagraph, location.getStartColumn(), this.getParagraphLength(startParagraph), errorStyle); <add> for (int para = startParagraph + 1; para < endParagraph; para++) { <add> this.setStyle(para, errorStyle); <add> } <add> this.setStyle(endParagraph, 0, location.getEndColumn(), errorStyle); <add> } <ide> } <ide> } <ide>
Java
bsd-3-clause
9973db592d6bd34a9ef92ebee25baefce0fd85de
0
picocontainer/PicoContainer1,picocontainer/PicoContainer1
/***************************************************************************** * Copyright (c) PicoContainer Organization. All rights reserved. * * ------------------------------------------------------------------------- * * The software in this package is published under the terms of the BSD * * style license a copy of which has been included with this distribution in * * the license.html file. * * * * Idea by Rachel Davies, Original code by Aslak Hellesoy and Paul Hammant * *****************************************************************************/ package org.picocontainer.defaults; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import junit.framework.Assert; import junit.framework.TestCase; import org.picocontainer.MutablePicoContainer; import org.picocontainer.PicoContainer; import org.picocontainer.Startable; import org.picocontainer.testmodel.RecordingLifecycle.FiveTriesToBeMalicious; import org.picocontainer.testmodel.RecordingLifecycle.Four; import org.picocontainer.testmodel.RecordingLifecycle.One; import org.picocontainer.testmodel.RecordingLifecycle.Three; import org.picocontainer.testmodel.RecordingLifecycle.Two; /** * This class tests the lifecycle aspects of DefaultPicoContainer. * * @author Aslak Helles&oslash;y * @author Paul Hammant * @author Ward Cunningham * @version $Revision$ */ public class DefaultPicoContainerLifecycleTestCase extends TestCase { public void testOrderOfInstantiationShouldBeDependencyOrder() throws Exception { DefaultPicoContainer pico = new DefaultPicoContainer(); pico.registerComponentImplementation("recording", StringBuffer.class); pico.registerComponentImplementation(Four.class); pico.registerComponentImplementation(Two.class); pico.registerComponentImplementation(One.class); pico.registerComponentImplementation(Three.class); final List componentInstances = pico.getComponentInstances(); // instantiation - would be difficult to do these in the wrong order!! assertEquals("Incorrect Order of Instantiation", One.class, componentInstances.get(1).getClass()); assertEquals("Incorrect Order of Instantiation", Two.class, componentInstances.get(2).getClass()); assertEquals("Incorrect Order of Instantiation", Three.class, componentInstances.get(3).getClass()); assertEquals("Incorrect Order of Instantiation", Four.class, componentInstances.get(4).getClass()); } public void testOrderOfStartShouldBeDependencyOrderAndStopAndDisposeTheOpposite() throws Exception { DefaultPicoContainer parent = new DefaultPicoContainer(); MutablePicoContainer child = parent.makeChildContainer(); parent.registerComponentImplementation("recording", StringBuffer.class); child.registerComponentImplementation(Four.class); parent.registerComponentImplementation(Two.class); parent.registerComponentImplementation(One.class); child.registerComponentImplementation(Three.class); parent.start(); parent.stop(); parent.dispose(); assertEquals("<One<Two<Three<FourFour>Three>Two>One>!Four!Three!Two!One", parent.getComponentInstance("recording").toString()); } public void testStartStartShouldFail() throws Exception { DefaultPicoContainer pico = new DefaultPicoContainer(); pico.start(); try { pico.start(); fail("Should have failed"); } catch (IllegalStateException e) { // expected; } } public void testStartStopStopShouldFail() throws Exception { DefaultPicoContainer pico = new DefaultPicoContainer(); pico.start(); pico.stop(); try { pico.stop(); fail("Should have failed"); } catch (IllegalStateException e) { // expected; } } public void testStartStopDisposeDisposeShouldFail() throws Exception { DefaultPicoContainer pico = new DefaultPicoContainer(); pico.start(); pico.stop(); pico.dispose(); try { pico.dispose(); fail("Should have barfed"); } catch (IllegalStateException e) { // expected; } } public static class FooRunnable implements Runnable, Startable { private int runCount; private Thread thread = new Thread(); private boolean interrupted; public FooRunnable() { } public int runCount() { return runCount; } public boolean isInterrupted() { return interrupted; } public void start() { thread = new Thread(this); thread.start(); } public void stop() { thread.interrupt(); } // this would do something a bit more concrete // than counting in real life ! public void run() { runCount++; try { Thread.sleep(10000); } catch (InterruptedException e) { interrupted = true; } } } public void testStartStopOfDaemonizedThread() throws Exception { DefaultPicoContainer pico = new DefaultPicoContainer(); pico.registerComponentImplementation(FooRunnable.class); pico.getComponentInstances(); pico.start(); Thread.sleep(100); pico.stop(); FooRunnable foo = (FooRunnable) pico.getComponentInstance(FooRunnable.class); assertEquals(1, foo.runCount()); pico.start(); Thread.sleep(100); pico.stop(); assertEquals(2, foo.runCount()); } public void testGetComponentInstancesOnParentContainerHostedChildContainerDoesntReturnParentAdapter() { MutablePicoContainer parent = new DefaultPicoContainer(); MutablePicoContainer child = parent.makeChildContainer(); assertEquals(0, child.getComponentInstances().size()); } public void testComponentsAreStartedBreadthFirstAndStoppedAndDisposedDepthFirst() { MutablePicoContainer parent = new DefaultPicoContainer(); parent.registerComponentImplementation(Two.class); parent.registerComponentImplementation("recording", StringBuffer.class); parent.registerComponentImplementation(One.class); MutablePicoContainer child = parent.makeChildContainer(); child.registerComponentImplementation(Three.class); parent.start(); parent.stop(); parent.dispose(); assertEquals("<One<Two<ThreeThree>Two>One>!Three!Two!One", parent.getComponentInstance("recording").toString()); } public void testMaliciousComponentCannotExistInAChildContainerAndSeeAnyElementOfContainerHierarchy() { MutablePicoContainer parent = new DefaultPicoContainer(); parent.registerComponentImplementation(Two.class); parent.registerComponentImplementation("recording", StringBuffer.class); parent.registerComponentImplementation(One.class); MutablePicoContainer child = parent.makeChildContainer(); child.registerComponentImplementation(Three.class); child.registerComponentImplementation(FiveTriesToBeMalicious.class); parent.start(); String recording = parent.getComponentInstance("recording").toString(); assertEquals("<One<Two<Three", recording); Object five = child.getComponentInstanceOfType(FiveTriesToBeMalicious.class); assertNull(five); // can't get instantiated as there is no PicoContainer in any component set. recording = parent.getComponentInstance("recording").toString(); assertEquals("<One<Two<Three", recording); // still the same } public static class NotStartable { public NotStartable() { Assert.fail("Shouldn't be instantiated"); } } public void testOnlyStartableComponentsAreInstantiatedOnStart() { MutablePicoContainer pico = new DefaultPicoContainer(); pico.registerComponentImplementation("recording", StringBuffer.class); pico.registerComponentImplementation(One.class); pico.registerComponentImplementation(NotStartable.class); pico.start(); pico.stop(); pico.dispose(); assertEquals("<OneOne>!One", pico.getComponentInstance("recording").toString()); } public void testShouldFailOnStartAfterDispose() { MutablePicoContainer pico = new DefaultPicoContainer(); pico.dispose(); try { pico.start(); fail(); } catch (IllegalStateException expected) { } } public void testShouldFailOnStopAfterDispose() { MutablePicoContainer pico = new DefaultPicoContainer(); pico.dispose(); try { pico.stop(); fail(); } catch (IllegalStateException expected) { } } public void testShouldStackContainersLast() { // this is merely a code coverage test - but it doesn't seem to cover the StackContainersAtEndComparator // fully. oh well. MutablePicoContainer pico = new DefaultPicoContainer(); pico.registerComponentImplementation(ArrayList.class); pico.registerComponentImplementation(DefaultPicoContainer.class); pico.registerComponentImplementation(HashMap.class); pico.start(); PicoContainer childContainer = (PicoContainer) pico.getComponentInstance(DefaultPicoContainer.class); // it should be started too try { childContainer.start(); fail(); } catch (IllegalStateException e) { } } }
container/src/test/org/picocontainer/defaults/DefaultPicoContainerLifecycleTestCase.java
/***************************************************************************** * Copyright (c) PicoContainer Organization. All rights reserved. * * ------------------------------------------------------------------------- * * The software in this package is published under the terms of the BSD * * style license a copy of which has been included with this distribution in * * the license.html file. * * * * Idea by Rachel Davies, Original code by Aslak Hellesoy and Paul Hammant * *****************************************************************************/ package org.picocontainer.defaults; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import junit.framework.Assert; import junit.framework.TestCase; import org.picocontainer.MutablePicoContainer; import org.picocontainer.PicoContainer; import org.picocontainer.Startable; import org.picocontainer.testmodel.RecordingLifecycle.FiveTriesToBeMalicious; import org.picocontainer.testmodel.RecordingLifecycle.Four; import org.picocontainer.testmodel.RecordingLifecycle.One; import org.picocontainer.testmodel.RecordingLifecycle.Three; import org.picocontainer.testmodel.RecordingLifecycle.Two; /** * This class tests the lifecycle aspects of DefaultPicoContainer. * * @author Aslak Helles&oslash;y * @author Paul Hammant * @author Ward Cunningham * @version $Revision$ */ public class DefaultPicoContainerLifecycleTestCase extends TestCase { public void testOrderOfInstantiationShouldBeDependencyOrder() throws Exception { DefaultPicoContainer pico = new DefaultPicoContainer(); pico.registerComponentImplementation("recording", StringBuffer.class); pico.registerComponentImplementation(Four.class); pico.registerComponentImplementation(Two.class); pico.registerComponentImplementation(One.class); pico.registerComponentImplementation(Three.class); final List componentInstances = pico.getComponentInstances(); // instantiation - would be difficult to do these in the wrong order!! assertEquals("Incorrect Order of Instantiation", One.class, componentInstances.get(1).getClass()); assertEquals("Incorrect Order of Instantiation", Two.class, componentInstances.get(2).getClass()); assertEquals("Incorrect Order of Instantiation", Three.class, componentInstances.get(3).getClass()); assertEquals("Incorrect Order of Instantiation", Four.class, componentInstances.get(4).getClass()); } public void testOrderOfStartShouldBeDependencyOrderAndStopAndDisposeTheOpposite() throws Exception { DefaultPicoContainer parent = new DefaultPicoContainer(); MutablePicoContainer child = parent.makeChildContainer(); parent.registerComponentImplementation("recording", StringBuffer.class); child.registerComponentImplementation(Four.class); parent.registerComponentImplementation(Two.class); parent.registerComponentImplementation(One.class); child.registerComponentImplementation(Three.class); parent.start(); parent.stop(); parent.dispose(); assertEquals("<One<Two<Three<FourFour>Three>Two>One>!Four!Three!Two!One", parent.getComponentInstance("recording").toString()); } public void testStartStartShouldFail() throws Exception { DefaultPicoContainer pico = new DefaultPicoContainer(); pico.start(); try { pico.start(); fail("Should have failed"); } catch (IllegalStateException e) { // expected; } } public void testStartStopStopShouldFail() throws Exception { DefaultPicoContainer pico = new DefaultPicoContainer(); pico.start(); pico.stop(); try { pico.stop(); fail("Should have failed"); } catch (IllegalStateException e) { // expected; } } public void testStartStopDisposeDisposeShouldFail() throws Exception { DefaultPicoContainer pico = new DefaultPicoContainer(); pico.start(); pico.stop(); pico.dispose(); try { pico.dispose(); fail("Should have barfed"); } catch (IllegalStateException e) { // expected; } } public static class FooRunnable implements Runnable, Startable { private int runCount; private Thread thread = new Thread(); private boolean interrupted; public FooRunnable() { } public int runCount() { return runCount; } public boolean isInterrupted() { return interrupted; } public void start() { thread = new Thread(this); thread.start(); } public void stop() { thread.interrupt(); } // this would do something a bit more concrete // than counting in real life ! public void run() { runCount++; try { Thread.sleep(10000); } catch (InterruptedException e) { interrupted = true; } } } public void testStartStopOfDaemonizedThread() throws Exception { DefaultPicoContainer pico = new DefaultPicoContainer(); pico.registerComponentImplementation(FooRunnable.class); pico.getComponentInstances(); pico.start(); Thread.sleep(100); pico.stop(); FooRunnable foo = (FooRunnable) pico.getComponentInstance(FooRunnable.class); assertEquals(1, foo.runCount()); pico.start(); Thread.sleep(100); pico.stop(); assertEquals(2, foo.runCount()); } public void testGetComponentInstancesOnParentContainerHostedChildContainerDoesntReturnParentAdapter() { MutablePicoContainer parent = new DefaultPicoContainer(); MutablePicoContainer child = parent.makeChildContainer(); assertEquals(0, child.getComponentInstances().size()); } public void testComponentsAreStartedBreadthFirstAndStoppedAndDisposedDepthFirst() { MutablePicoContainer parent = new DefaultPicoContainer(); parent.registerComponentImplementation(Two.class); parent.registerComponentImplementation("recording", StringBuffer.class); parent.registerComponentImplementation(One.class); MutablePicoContainer child = parent.makeChildContainer(); child.registerComponentImplementation(Three.class); parent.start(); parent.stop(); parent.dispose(); assertEquals("<One<Two<ThreeThree>Two>One>!Three!Two!One", parent.getComponentInstance("recording").toString()); } public void testMaliciousComponentCannotExistInAChildContainerAndSeeAnyElementOfContainerHierarchy() { MutablePicoContainer parent = new DefaultPicoContainer(); parent.registerComponentImplementation(Two.class); parent.registerComponentImplementation("recording", StringBuffer.class); parent.registerComponentImplementation(One.class); MutablePicoContainer child = parent.makeChildContainer(); child.registerComponentImplementation(Three.class); child.registerComponentImplementation(FiveTriesToBeMalicious.class); try { parent.start(); fail(); } catch (UnsatisfiableDependenciesException expected) { } } public static class NotStartable { public NotStartable() { Assert.fail("Shouldn't be instantiated"); } } public void testOnlyStartableComponentsAreInstantiatedOnStart() { MutablePicoContainer pico = new DefaultPicoContainer(); pico.registerComponentImplementation("recording", StringBuffer.class); pico.registerComponentImplementation(One.class); pico.registerComponentImplementation(NotStartable.class); pico.start(); pico.stop(); pico.dispose(); assertEquals("<OneOne>!One", pico.getComponentInstance("recording").toString()); } public void testShouldFailOnStartAfterDispose() { MutablePicoContainer pico = new DefaultPicoContainer(); pico.dispose(); try { pico.start(); fail(); } catch (IllegalStateException expected) { } } public void testShouldFailOnStopAfterDispose() { MutablePicoContainer pico = new DefaultPicoContainer(); pico.dispose(); try { pico.stop(); fail(); } catch (IllegalStateException expected) { } } public void testShouldStackContainersLast() { // this is merely a code coverage test - but it doesn't seem to cover the StackContainersAtEndComparator // fully. oh well. MutablePicoContainer pico = new DefaultPicoContainer(); pico.registerComponentImplementation(ArrayList.class); pico.registerComponentImplementation(DefaultPicoContainer.class); pico.registerComponentImplementation(HashMap.class); pico.start(); PicoContainer childContainer = (PicoContainer) pico.getComponentInstance(DefaultPicoContainer.class); // it should be started too try { childContainer.start(); fail(); } catch (IllegalStateException e) { } } }
fixed git-svn-id: 39c93fb42c3fce26a4768237af3b74bd47e2a670@2310 ac66bb80-72f5-0310-8d68-9f556cfffb23
container/src/test/org/picocontainer/defaults/DefaultPicoContainerLifecycleTestCase.java
fixed
<ide><path>ontainer/src/test/org/picocontainer/defaults/DefaultPicoContainerLifecycleTestCase.java <ide> MutablePicoContainer child = parent.makeChildContainer(); <ide> child.registerComponentImplementation(Three.class); <ide> child.registerComponentImplementation(FiveTriesToBeMalicious.class); <del> try { <del> parent.start(); <del> fail(); <del> } catch (UnsatisfiableDependenciesException expected) { <del> } <del> } <add> parent.start(); <add> String recording = parent.getComponentInstance("recording").toString(); <add> assertEquals("<One<Two<Three", recording); <add> Object five = child.getComponentInstanceOfType(FiveTriesToBeMalicious.class); <add> assertNull(five); // can't get instantiated as there is no PicoContainer in any component set. <add> recording = parent.getComponentInstance("recording").toString(); <add> assertEquals("<One<Two<Three", recording); // still the same <add> <add> } <add> <ide> <ide> public static class NotStartable { <ide> public NotStartable() {
Java
apache-2.0
ee8b925606f12d195d9a95c118d53bef577dd9e8
0
mikegr/mmc,kvolstorf/FCMonitor
package at.elfkw.mmc; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.lang.reflect.Method; import java.util.StringTokenizer; import android.app.Activity; import android.app.AlertDialog; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.graphics.Color; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.CompoundButton; import android.widget.TextView; import android.widget.Toast; import android.widget.ToggleButton; public class TestActivity extends Activity { private static final String TAG = TestActivity.class.getName(); private static final int CENTER_HORIZONTAL = 1; private static final int CENTER_VERTICAL = 16; private TextView speedTextView; private TextView consumeTextView; private TextView voltageTextView; private TextView currentTextView; private TextView battTextView; private TextView reserveTextView; private ToggleButton onOffButton; private Button monitorButton; private ToggleButton lightButton; //private ProgressBar batteryBar; private TextView mTitle; SharedPreferences prefs = null; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); prefs = PreferenceManager.getDefaultSharedPreferences(this); requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); setContentView(R.layout.main_screen); getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title); mTitle = (TextView) findViewById(R.id.title_left_text); mTitle.setText(R.string.title_elfkw); mTitle = (TextView) findViewById(R.id.title_right_text); speedTextView = (TextView) findViewById(R.id.speedTextView); speedTextView.setTextColor(Color.BLACK); speedTextView.setGravity(CENTER_HORIZONTAL + CENTER_VERTICAL); speedTextView.setText("0.0km/h"); consumeTextView = (TextView) findViewById(R.id.consumeTextView); consumeTextView.setTextColor(Color.BLACK); consumeTextView.setGravity(CENTER_HORIZONTAL + CENTER_VERTICAL); consumeTextView.setText("0.0Wh/km"); voltageTextView = (TextView) findViewById(R.id.voltageTextView); voltageTextView.setTextColor(Color.BLACK); voltageTextView.setGravity(CENTER_HORIZONTAL + CENTER_VERTICAL); voltageTextView.setText("0.0V"); currentTextView = (TextView) findViewById(R.id.currentTextView); currentTextView.setTextColor(Color.BLACK); currentTextView.setGravity(CENTER_HORIZONTAL + CENTER_VERTICAL); currentTextView.setText("0.0A"); battTextView = (TextView) findViewById(R.id.battTextView); battTextView.setTextColor(Color.BLACK); battTextView.setGravity(CENTER_HORIZONTAL + CENTER_VERTICAL); battTextView.setText("0.0Ah"); reserveTextView = (TextView) findViewById(R.id.reserveTextView); reserveTextView.setTextColor(Color.BLACK); reserveTextView.setGravity(CENTER_HORIZONTAL + CENTER_VERTICAL); reserveTextView.setText("0.0km"); monitorButton = (Button) findViewById(R.id.monitorButton); monitorButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent i = new Intent(TestActivity.this, BluetoothChat.class); startActivity(i); } }); //reserveTextView.setHeight(30); onOffButton = (ToggleButton) findViewById(R.id.onOffButton); onOffButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { } }); lightButton = (ToggleButton) findViewById(R.id.lightButton); lightButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { try { Log.v(TAG, "changing light status"); mmOutStream.write("at-push=0\r".getBytes()); if (isChecked) { mmOutStream.write("at-light=0\r".getBytes()); } else { mmOutStream.write("at-light=1\r".getBytes()); } mmOutStream.write("at-push=1\r".getBytes()); } catch (Exception e) { Log.v(TAG, "changing light status failed" ,e); } } }); //batteryBar = (ProgressBar) findViewById(R.id.batteryBar); //batteryBar.setBackgroundColor(Color.GRAY); //batteryBar.setAnimation(null); //batteryBar.setEnabled(true); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); } @Override protected void onResume() { super.onResume(); } protected void onStop() { logout(); super.onStop(); }; // Intent request codes private static final int REQUEST_CONNECT_DEVICE = 1; private static final int REQUEST_ENABLE_BT = 2; BluetoothAdapter mBluetoothAdapter = null; BluetoothSocket socket = null; InputStream mmInStream = null; OutputStream mmOutStream = null; @Override public void onStart() { super.onStart(); Log.e(TAG, "++ ON START ++"); // If BT is not on, request that it be enabled. // setupChat() will then be called during onActivityResult if (mBluetoothAdapter != null) { if (!mBluetoothAdapter.isEnabled()) { Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableIntent, REQUEST_ENABLE_BT); } else { login(); } } } public void login() { Log.v(TAG, "starting login"); try { Log.v(TAG, "got adapter"); String deviceId = prefs.getString("device_id",""); if ("".equals(deviceId)) { Intent serverIntent = new Intent(this, DeviceListActivity.class); startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE); return; } if (socket != null) { try { socket.close(); } catch (Exception e2) { e2.printStackTrace(); } } BluetoothDevice mmDevice = mBluetoothAdapter .getRemoteDevice(deviceId); Log.v(TAG, "got device"); Method m = mmDevice.getClass().getMethod("createRfcommSocket", new Class[] { int.class }); socket = (BluetoothSocket) m.invoke(mmDevice, Integer.valueOf(1)); socket.connect(); Log.v(TAG, "socket connected"); mmInStream = socket.getInputStream(); mmOutStream = socket.getOutputStream(); final InputStream inStream = mmInStream; final BufferedReader reader = new BufferedReader(new InputStreamReader(inStream)); new Thread(new Runnable() { public void run() { try { String line = null; while( (line = reader.readLine()) != null) { Log.v(TAG, line); try { StringTokenizer t = new StringTokenizer(line, "\t"); if (t.countTokens() >= 4) { final float fVoltage = (float)Integer.parseInt(t.nextToken())/10; final String sVoltage = Float.toString(fVoltage); final float fCurrent = (float)(Math.round((float)Integer.parseInt(t.nextToken())/1000*100.0)/100.0); final String sCurrent = Float.toString(fCurrent); final float fSpeed = (float)Integer.parseInt(t.nextToken())/10; final String sSpeed = Float.toString(fSpeed); float fConsume = (float)0.0; String sConsume = Float.toString(fConsume); if (fSpeed < 1) { sConsume = "--.-"; } else { fConsume = (float)(Math.round(fVoltage*fCurrent/fSpeed*10.0)/10.0); sConsume = Float.toString(fConsume); } final String fsConsume = sConsume; final float fUsedCapa = Math.round(((float)Integer.parseInt(t.nextToken())/3600000)*100.0/100.0); final String sCapa = prefs.getString("capacity_id",""); float fCapa = (float)Integer.parseInt(sCapa); final float fRestCapa = (float)(fCapa-fUsedCapa)/1000f; final String sRestCapa = Float.toString(fRestCapa); float fRestKm = (float)0.0; String sRestKm = Float.toString(fRestKm); if (fCurrent < 0.01) { sRestKm = "--.-"; } else { fRestKm = (float)(Math.round(fRestCapa/fCurrent*fSpeed*10.0)/10.0); sRestKm = Float.toString(fRestKm); } final String fsRestKm = sRestKm; TestActivity.this.runOnUiThread(new Runnable() { public void run() { voltageTextView.setText(sVoltage + "V"); currentTextView.setText(sCurrent + "A"); speedTextView.setText(sSpeed + "km/h"); consumeTextView.setText(fsConsume + "Wh/km"); battTextView.setText(sRestCapa + "Ah"); reserveTextView.setText(fsRestKm + "km"); } }); } } catch (Exception e) { Log.e(TAG, "Processing line failed",e); } } } catch (Exception e) { Log.v(TAG, "Reading thread throwed exception", e); } finally { /* TestActivity.this.runOnUiThread(new Runnable() { public void run() { mTitle.setText(R.string.title_not_connected); } }); try { socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } */ } } }).start(); Thread.sleep(500); // password_id? String password = prefs.getString("password_id", ""); Log.v(TAG, "password read:" + password); mmOutStream.write((password + "\r").getBytes()); //mmOutStream.write(("a\r").getBytes()); //byte[] buffer = new byte[1024]; //int len = mmInStream.read(buffer); //Log.v(TAG, "Read:" + new String(buffer, 0, len)); Log.v(TAG, "password sent"); mTitle.setText(R.string.title_connected_to); // MK mmOutStream.write("at-push=1\r".getBytes()); //mmOutStream.write("at-logout\r".getBytes()); Log.v(TAG, "at-push=1 sent"); new Thread(new Runnable() { public void run() { while (true) { try { Thread.sleep(60000); Log.v(TAG, "Writing at-0"); mmOutStream.write("at-0\r".getBytes()); } catch (Exception e) { Log.v(TAG, "Writing at-0 thread throwed exception", e); } } } }); } catch (Exception e) { AlertDialog dlg = new AlertDialog.Builder(this) .setTitle("Login failed") .setMessage(e.getMessage()).create(); dlg.show(); // TODO Auto-generated catch block Log.w(TAG, "login failed", e); } finally { } } private void logout() { Log.v(TAG, "start logout"); try { if (mmOutStream != null) { mmOutStream.write("at-push=0\r".getBytes()); mmOutStream.write("at-logout\r".getBytes()); } close(); } catch (Exception e) { close(); } finally { mTitle.setText(R.string.title_not_connected); } } private void close() { Log.v(TAG, "Closing streams and socket"); try { if (socket != null) socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.mmc_options, menu); return super.onCreateOptionsMenu(menu); } public void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(TAG, "onActivityResult " + resultCode); switch (requestCode) { case REQUEST_CONNECT_DEVICE: // When DeviceListActivity returns with a device to connect if (resultCode == Activity.RESULT_OK) { // Get the device MAC address String address = data.getExtras() .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS); // Get the BLuetoothDevice object Editor editor = prefs.edit(); editor.putString("device_id", address); editor.commit(); // Attempt to connect to the device login(); } break; case REQUEST_ENABLE_BT: // When the request to enable Bluetooth returns if (resultCode == Activity.RESULT_OK) { login(); } else { // User did not enable Bluetooth or an error occured Log.d(TAG, "BT not enabled"); Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show(); finish(); } } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.settings) { Intent i = new Intent(this, MmcPreferences.class); startActivity(i); return true; } if (item.getItemId() == R.id.logout) { logout(); } if (item.getItemId() == R.id.login) { login(); } return super.onOptionsItemSelected(item); } }
src/at/elfkw/mmc/TestActivity.java
package at.elfkw.mmc; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.lang.reflect.Method; import java.util.StringTokenizer; import android.app.Activity; import android.app.AlertDialog; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.graphics.Color; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.CompoundButton; import android.widget.TextView; import android.widget.Toast; import android.widget.ToggleButton; public class TestActivity extends Activity { private static final String TAG = TestActivity.class.getName(); private static final int CENTER_HORIZONTAL = 1; private static final int CENTER_VERTICAL = 16; private TextView speedTextView; private TextView consumeTextView; private TextView voltageTextView; private TextView currentTextView; private TextView battTextView; private TextView reserveTextView; private ToggleButton onOffButton; private Button monitorButton; private ToggleButton lightButton; //private ProgressBar batteryBar; private TextView mTitle; SharedPreferences prefs = null; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); prefs = PreferenceManager.getDefaultSharedPreferences(this); requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); setContentView(R.layout.main_screen); getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title); mTitle = (TextView) findViewById(R.id.title_left_text); mTitle.setText(R.string.title_elfkw); mTitle = (TextView) findViewById(R.id.title_right_text); speedTextView = (TextView) findViewById(R.id.speedTextView); speedTextView.setTextColor(Color.BLACK); speedTextView.setGravity(CENTER_HORIZONTAL + CENTER_VERTICAL); speedTextView.setText("28.7km/h"); consumeTextView = (TextView) findViewById(R.id.consumeTextView); consumeTextView.setTextColor(Color.BLACK); consumeTextView.setGravity(CENTER_HORIZONTAL + CENTER_VERTICAL); consumeTextView.setText("10.6Wh/km"); voltageTextView = (TextView) findViewById(R.id.voltageTextView); voltageTextView.setTextColor(Color.BLACK); voltageTextView.setGravity(CENTER_HORIZONTAL + CENTER_VERTICAL); voltageTextView.setText("38.4V"); currentTextView = (TextView) findViewById(R.id.currentTextView); currentTextView.setTextColor(Color.BLACK); currentTextView.setGravity(CENTER_HORIZONTAL + CENTER_VERTICAL); currentTextView.setText("8.1A"); battTextView = (TextView) findViewById(R.id.battTextView); battTextView.setTextColor(Color.BLACK); battTextView.setGravity(CENTER_HORIZONTAL + CENTER_VERTICAL); battTextView.setText("11.6Ah"); reserveTextView = (TextView) findViewById(R.id.reserveTextView); reserveTextView.setTextColor(Color.BLACK); reserveTextView.setGravity(CENTER_HORIZONTAL + CENTER_VERTICAL); reserveTextView.setText("23.0km"); monitorButton = (Button) findViewById(R.id.monitorButton); monitorButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent i = new Intent(TestActivity.this, BluetoothChat.class); startActivity(i); } }); //reserveTextView.setHeight(30); onOffButton = (ToggleButton) findViewById(R.id.onOffButton); onOffButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // } }); lightButton = (ToggleButton) findViewById(R.id.lightButton); lightButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // } }); //batteryBar = (ProgressBar) findViewById(R.id.batteryBar); //batteryBar.setBackgroundColor(Color.GRAY); //batteryBar.setAnimation(null); //batteryBar.setEnabled(true); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); } @Override protected void onResume() { super.onResume(); } protected void onStop() { logout(); super.onStop(); }; // Intent request codes private static final int REQUEST_CONNECT_DEVICE = 1; private static final int REQUEST_ENABLE_BT = 2; BluetoothAdapter mBluetoothAdapter = null; BluetoothSocket socket = null; InputStream mmInStream = null; OutputStream mmOutStream = null; @Override public void onStart() { super.onStart(); Log.e(TAG, "++ ON START ++"); // If BT is not on, request that it be enabled. // setupChat() will then be called during onActivityResult if (mBluetoothAdapter != null) { if (!mBluetoothAdapter.isEnabled()) { Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableIntent, REQUEST_ENABLE_BT); } else { login(); } } } public void login() { Log.v(TAG, "starting login"); try { Log.v(TAG, "got adapter"); String deviceId = prefs.getString("device_id",""); if ("".equals(deviceId)) { Intent serverIntent = new Intent(this, DeviceListActivity.class); startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE); return; } if (socket != null) { try { socket.close(); } catch (Exception e2) { e2.printStackTrace(); } } BluetoothDevice mmDevice = mBluetoothAdapter .getRemoteDevice(deviceId); Log.v(TAG, "got device"); Method m = mmDevice.getClass().getMethod("createRfcommSocket", new Class[] { int.class }); socket = (BluetoothSocket) m.invoke(mmDevice, Integer.valueOf(1)); socket.connect(); Log.v(TAG, "socket connected"); mmInStream = socket.getInputStream(); mmOutStream = socket.getOutputStream(); final InputStream inStream = mmInStream; final BufferedReader reader = new BufferedReader(new InputStreamReader(inStream)); new Thread(new Runnable() { public void run() { try { String line = null; while( (line = reader.readLine()) != null) { Log.v(TAG, line); try { StringTokenizer t = new StringTokenizer(line, "\t"); if (t.countTokens() >= 4) { final float fVoltage = (float)Integer.parseInt(t.nextToken())/10; final String sVoltage = Float.toString(fVoltage); final float fCurrent = (float)(Math.round((float)Integer.parseInt(t.nextToken())/1000*100.0)/100.0); final String sCurrent = Float.toString(fCurrent); final float fSpeed = (float)Integer.parseInt(t.nextToken())/10; final String sSpeed = Float.toString(fSpeed); float fConsume = (float)0.0; String sConsume = Float.toString(fConsume); if (fSpeed < 1) { sConsume = "--.-"; } else { fConsume = (float)(Math.round(fVoltage*fCurrent/fSpeed*10.0)/10.0); sConsume = Float.toString(fConsume); } final String fsConsume = sConsume; final float fUsedCapa = Math.round(((float)Integer.parseInt(t.nextToken())/3600000)*100.0/100.0); final String sCapa = prefs.getString("capacity_id",""); //NOGO final float fCapa = (float)Integer.parseInt(sCapa)/1000; final float fRestCapa = (float)(9300-fUsedCapa)/1000; final String sRestCapa = Float.toString(fRestCapa); float fRestKm = (float)0.0; String sRestKm = Float.toString(fRestKm); if (fCurrent < 0.01) { sRestKm = "--.-"; } else { fRestKm = (float)(Math.round(fRestCapa/fCurrent*fSpeed*10.0)/10.0); sRestKm = Float.toString(fRestKm); } final String fsRestKm = sRestKm; TestActivity.this.runOnUiThread(new Runnable() { public void run() { voltageTextView.setText(sVoltage + "V"); currentTextView.setText(sCurrent + "A"); speedTextView.setText(sSpeed + "km/h"); consumeTextView.setText(fsConsume + "Wh/km"); battTextView.setText(sRestCapa + "Ah"); reserveTextView.setText(fsRestKm + "km"); } }); } } catch (Exception e) { Log.e(TAG, "Processing line failed",e); } } } catch (Exception e) { Log.v(TAG, "Reading thread throwed exception", e); } finally { /* TestActivity.this.runOnUiThread(new Runnable() { public void run() { mTitle.setText(R.string.title_not_connected); } }); try { socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } */ } } }).start(); Thread.sleep(500); // password_id? String password = prefs.getString("password_id", ""); Log.v(TAG, "password read:" + password); mmOutStream.write((password + "\r").getBytes()); //mmOutStream.write(("a\r").getBytes()); //byte[] buffer = new byte[1024]; //int len = mmInStream.read(buffer); //Log.v(TAG, "Read:" + new String(buffer, 0, len)); Log.v(TAG, "password sent"); mTitle.setText(R.string.title_connected_to); // MK mmOutStream.write("at-push=1\r".getBytes()); //mmOutStream.write("at-logout\r".getBytes()); Log.v(TAG, "at-push=1 sent"); new Thread(new Runnable() { public void run() { while (true) { try { Thread.sleep(60000); Log.v(TAG, "Writing at-0"); mmOutStream.write("at-0\r".getBytes()); } catch (Exception e) { Log.v(TAG, "Writing at-0 thread throwed exception", e); } } } }); } catch (Exception e) { AlertDialog dlg = new AlertDialog.Builder(this) .setTitle("Login failed") .setMessage(e.getMessage()).create(); dlg.show(); // TODO Auto-generated catch block Log.w(TAG, "login failed", e); } finally { } } private void logout() { Log.v(TAG, "start logout"); try { if (mmOutStream != null) { mmOutStream.write("at-push=0\r".getBytes()); mmOutStream.write("at-logout\r".getBytes()); } close(); } catch (Exception e) { close(); } finally { mTitle.setText(R.string.title_not_connected); } } private void close() { Log.v(TAG, "Closing streams and socket"); try { if (socket != null) socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.mmc_options, menu); return super.onCreateOptionsMenu(menu); } public void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(TAG, "onActivityResult " + resultCode); switch (requestCode) { case REQUEST_CONNECT_DEVICE: // When DeviceListActivity returns with a device to connect if (resultCode == Activity.RESULT_OK) { // Get the device MAC address String address = data.getExtras() .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS); // Get the BLuetoothDevice object Editor editor = prefs.edit(); editor.putString("device_id", address); editor.commit(); // Attempt to connect to the device login(); } break; case REQUEST_ENABLE_BT: // When the request to enable Bluetooth returns if (resultCode == Activity.RESULT_OK) { login(); } else { // User did not enable Bluetooth or an error occured Log.d(TAG, "BT not enabled"); Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show(); finish(); } } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.settings) { Intent i = new Intent(this, MmcPreferences.class); startActivity(i); return true; } if (item.getItemId() == R.id.logout) { logout(); } if (item.getItemId() == R.id.login) { login(); } return super.onOptionsItemSelected(item); } }
light on/off
src/at/elfkw/mmc/TestActivity.java
light on/off
<ide><path>rc/at/elfkw/mmc/TestActivity.java <ide> <ide> speedTextView.setTextColor(Color.BLACK); <ide> speedTextView.setGravity(CENTER_HORIZONTAL + CENTER_VERTICAL); <del> speedTextView.setText("28.7km/h"); <add> speedTextView.setText("0.0km/h"); <ide> <ide> consumeTextView = (TextView) findViewById(R.id.consumeTextView); <ide> consumeTextView.setTextColor(Color.BLACK); <ide> consumeTextView.setGravity(CENTER_HORIZONTAL + CENTER_VERTICAL); <del> consumeTextView.setText("10.6Wh/km"); <add> consumeTextView.setText("0.0Wh/km"); <ide> <ide> voltageTextView = (TextView) findViewById(R.id.voltageTextView); <ide> voltageTextView.setTextColor(Color.BLACK); <ide> voltageTextView.setGravity(CENTER_HORIZONTAL + CENTER_VERTICAL); <del> voltageTextView.setText("38.4V"); <add> voltageTextView.setText("0.0V"); <ide> <ide> currentTextView = (TextView) findViewById(R.id.currentTextView); <ide> currentTextView.setTextColor(Color.BLACK); <ide> currentTextView.setGravity(CENTER_HORIZONTAL + CENTER_VERTICAL); <del> currentTextView.setText("8.1A"); <add> currentTextView.setText("0.0A"); <ide> <ide> battTextView = (TextView) findViewById(R.id.battTextView); <ide> battTextView.setTextColor(Color.BLACK); <ide> battTextView.setGravity(CENTER_HORIZONTAL + CENTER_VERTICAL); <del> battTextView.setText("11.6Ah"); <add> battTextView.setText("0.0Ah"); <ide> <ide> reserveTextView = (TextView) findViewById(R.id.reserveTextView); <ide> reserveTextView.setTextColor(Color.BLACK); <ide> reserveTextView.setGravity(CENTER_HORIZONTAL + CENTER_VERTICAL); <del> reserveTextView.setText("23.0km"); <add> reserveTextView.setText("0.0km"); <ide> <ide> monitorButton = (Button) findViewById(R.id.monitorButton); <ide> monitorButton.setOnClickListener(new View.OnClickListener() { <ide> onOffButton = (ToggleButton) findViewById(R.id.onOffButton); <ide> onOffButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { <ide> public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { <del> // <ide> } <ide> }); <ide> <ide> lightButton = (ToggleButton) findViewById(R.id.lightButton); <ide> lightButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { <ide> public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { <del> // <add> try { <add> Log.v(TAG, "changing light status"); <add> mmOutStream.write("at-push=0\r".getBytes()); <add> if (isChecked) { <add> <add> mmOutStream.write("at-light=0\r".getBytes()); <add> } <add> else { <add> mmOutStream.write("at-light=1\r".getBytes()); <add> } <add> mmOutStream.write("at-push=1\r".getBytes()); <add> } catch (Exception e) { <add> Log.v(TAG, "changing light status failed" ,e); <add> } <ide> } <ide> }); <ide> <ide> <ide> final float fUsedCapa = Math.round(((float)Integer.parseInt(t.nextToken())/3600000)*100.0/100.0); <ide> final String sCapa = prefs.getString("capacity_id",""); <del> //NOGO final float fCapa = (float)Integer.parseInt(sCapa)/1000; <del> final float fRestCapa = (float)(9300-fUsedCapa)/1000; <add> float fCapa = (float)Integer.parseInt(sCapa); <add> final float fRestCapa = (float)(fCapa-fUsedCapa)/1000f; <ide> final String sRestCapa = Float.toString(fRestCapa); <ide> <ide> float fRestKm = (float)0.0;
Java
agpl-3.0
803152b4ced59e1d9076d365cd1259e697e28ffb
0
UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,bhutchinson/kfs,kuali/kfs,quikkian-ua-devops/kfs,ua-eas/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs-devops-automation-fork,kkronenb/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs,kkronenb/kfs,ua-eas/kfs-devops-automation-fork,ua-eas/kfs-devops-automation-fork,UniversityOfHawaii/kfs,bhutchinson/kfs,ua-eas/kfs,UniversityOfHawaii/kfs,kuali/kfs,kkronenb/kfs,smith750/kfs,smith750/kfs,quikkian-ua-devops/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials,kuali/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/kfs,UniversityOfHawaii/kfs,smith750/kfs,smith750/kfs,quikkian-ua-devops/will-financials,bhutchinson/kfs,bhutchinson/kfs,ua-eas/kfs,kuali/kfs,ua-eas/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/will-financials,kuali/kfs,kkronenb/kfs,ua-eas/kfs
/* * Copyright 2008 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kfs.module.cam.document.web.struts; import static org.kuali.kfs.module.cam.CamsPropertyConstants.Asset.CAPITAL_ASSET_NUMBER; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.kuali.kfs.module.cam.CamsKeyConstants; import org.kuali.kfs.module.cam.CamsPropertyConstants; import org.kuali.kfs.module.cam.businessobject.Asset; import org.kuali.kfs.module.cam.businessobject.AssetPayment; import org.kuali.kfs.module.cam.document.AssetTransferDocument; import org.kuali.kfs.module.cam.document.service.AssetLocationService; import org.kuali.kfs.module.cam.document.service.AssetPaymentService; import org.kuali.kfs.module.cam.document.service.PaymentSummaryService; import org.kuali.kfs.sys.context.SpringContext; import org.kuali.kfs.sys.document.web.struts.FinancialSystemTransactionalDocumentActionBase; import org.kuali.rice.kew.util.KEWConstants; import org.kuali.rice.kim.bo.Person; import org.kuali.rice.kns.util.ErrorMessage; import org.kuali.rice.kns.util.GlobalVariables; import org.kuali.rice.kns.util.MessageMap; import org.kuali.rice.kns.web.struts.form.KualiDocumentFormBase; public class AssetTransferAction extends FinancialSystemTransactionalDocumentActionBase { protected static final Logger LOG = Logger.getLogger(AssetTransferAction.class); /** * This method had to override because asset information has to be refreshed before display * * @see org.kuali.rice.kns.web.struts.action.KualiDocumentActionBase#docHandler(org.apache.struts.action.ActionMapping, * org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override public ActionForward docHandler(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward docHandlerForward = super.docHandler(mapping, form, request, response); // refresh asset information AssetTransferForm assetTransferForm = (AssetTransferForm) form; AssetTransferDocument assetTransferDocument = (AssetTransferDocument) assetTransferForm.getDocument(); handleRequestFromLookup(request, assetTransferForm, assetTransferDocument); handleRequestFromWorkflow(assetTransferForm, assetTransferDocument); Asset asset = assetTransferDocument.getAsset(); asset.refreshReferenceObject(CamsPropertyConstants.Asset.ASSET_LOCATIONS); asset.refreshReferenceObject(CamsPropertyConstants.Asset.ASSET_PAYMENTS); SpringContext.getBean(AssetLocationService.class).setOffCampusLocation(asset); SpringContext.getBean(PaymentSummaryService.class).calculateAndSetPaymentSummary(asset); // populate old asset fields for historic retaining on document String command = assetTransferForm.getCommand(); if (KEWConstants.INITIATE_COMMAND.equals(command)) { assetTransferDocument.setOldOrganizationOwnerChartOfAccountsCode(asset.getOrganizationOwnerChartOfAccountsCode()); assetTransferDocument.setOldOrganizationOwnerAccountNumber(asset.getOrganizationOwnerAccountNumber()); } this.refresh(mapping, form, request, response); return docHandlerForward; } /** * This method handles when request is from a work flow document search * * @param assetTransferForm Form * @param assetTransferDocument Document * @param service BusinessObjectService * @return Asset */ protected void handleRequestFromWorkflow(AssetTransferForm assetTransferForm, AssetTransferDocument assetTransferDocument) { LOG.debug("Start- Handle request from workflow"); if (assetTransferForm.getDocId() != null) { assetTransferDocument.refreshReferenceObject(CamsPropertyConstants.AssetTransferDocument.ASSET); org.kuali.rice.kim.service.PersonService personService = SpringContext.getBean(org.kuali.rice.kim.service.PersonService.class); Person person = personService.getPerson(assetTransferDocument.getRepresentativeUniversalIdentifier()); if (person != null) { assetTransferDocument.setAssetRepresentative(person); } else { LOG.error("org.kuali.rice.kim.service.PersonService returned null for uuid " + assetTransferDocument.getRepresentativeUniversalIdentifier()); } } } /** * This method handles the request coming from asset lookup screen * * @param request Request * @param assetTransferForm Current form * @param assetTransferDocument Document * @param service Business Object Service * @param asset Asset * @return Asset */ protected void handleRequestFromLookup(HttpServletRequest request, AssetTransferForm assetTransferForm, AssetTransferDocument assetTransferDocument) { LOG.debug("Start - Handle request from asset lookup screen"); if (assetTransferForm.getDocId() == null) { String capitalAssetNumber = request.getParameter(CAPITAL_ASSET_NUMBER); assetTransferDocument.setCapitalAssetNumber(Long.valueOf(capitalAssetNumber)); assetTransferDocument.refreshReferenceObject(CamsPropertyConstants.AssetTransferDocument.ASSET); } } /** * Since the organization fields are view only we need to make sure they are in sync with the data entry fields. * * @see org.kuali.rice.kns.web.struts.action.KualiDocumentActionBase#refresh(org.apache.struts.action.ActionMapping, * org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override public ActionForward refresh(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ((KualiDocumentFormBase) form).setMessageMapFromPreviousRequest(new MessageMap()); ActionForward actionForward = super.refresh(mapping, form, request, response); AssetTransferDocument assetTransferDocument = ((AssetTransferForm) form).getAssetTransferDocument(); assetTransferDocument.refreshReferenceObject(CamsPropertyConstants.AssetTransferDocument.ORGANIZATION_OWNER_ACCOUNT); assetTransferDocument.refreshReferenceObject(CamsPropertyConstants.AssetTransferDocument.OLD_ORGANIZATION_OWNER_ACCOUNT); return actionForward; } /** * Route the document */ @Override public ActionForward route(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward actionForward = super.route(mapping, form, request, response); allPaymentsFederalOwnedMessage(form); return actionForward; } protected void allPaymentsFederalOwnedMessage(ActionForm form) { boolean allPaymentsFederalOwned = true; AssetTransferDocument assetTransferDocument = ((AssetTransferForm) form).getAssetTransferDocument(); for (AssetPayment assetPayment : assetTransferDocument.getAsset().getAssetPayments()) { if (!getAssetPaymentService().isPaymentFederalOwned(assetPayment)) { allPaymentsFederalOwned = false; } } // display a message for asset not generating ledger entries when it is federally owned if (allPaymentsFederalOwned) { GlobalVariables.getMessageList().add(0, new ErrorMessage(CamsKeyConstants.Transfer.MESSAGE_NO_LEDGER_ENTRY_REQUIRED_TRANSFER)); } } protected AssetPaymentService getAssetPaymentService() { return SpringContext.getBean(AssetPaymentService.class); } }
work/src/org/kuali/kfs/module/cam/document/web/struts/AssetTransferAction.java
/* * Copyright 2008 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kfs.module.cam.document.web.struts; import static org.kuali.kfs.module.cam.CamsPropertyConstants.Asset.CAPITAL_ASSET_NUMBER; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.kuali.kfs.module.cam.CamsKeyConstants; import org.kuali.kfs.module.cam.CamsPropertyConstants; import org.kuali.kfs.module.cam.businessobject.Asset; import org.kuali.kfs.module.cam.businessobject.AssetPayment; import org.kuali.kfs.module.cam.document.AssetTransferDocument; import org.kuali.kfs.module.cam.document.service.AssetLocationService; import org.kuali.kfs.module.cam.document.service.AssetPaymentService; import org.kuali.kfs.module.cam.document.service.PaymentSummaryService; import org.kuali.kfs.sys.context.SpringContext; import org.kuali.kfs.sys.document.web.struts.FinancialSystemTransactionalDocumentActionBase; import org.kuali.rice.kew.util.KEWConstants; import org.kuali.rice.kim.bo.Person; import org.kuali.rice.kns.util.ErrorMap; import org.kuali.rice.kns.util.ErrorMessage; import org.kuali.rice.kns.util.GlobalVariables; import org.kuali.rice.kns.util.WebUtils; import org.kuali.rice.kns.web.struts.form.KualiDocumentFormBase; public class AssetTransferAction extends FinancialSystemTransactionalDocumentActionBase { protected static final Logger LOG = Logger.getLogger(AssetTransferAction.class); /** * This method had to override because asset information has to be refreshed before display * * @see org.kuali.rice.kns.web.struts.action.KualiDocumentActionBase#docHandler(org.apache.struts.action.ActionMapping, * org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override public ActionForward docHandler(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward docHandlerForward = super.docHandler(mapping, form, request, response); // refresh asset information AssetTransferForm assetTransferForm = (AssetTransferForm) form; AssetTransferDocument assetTransferDocument = (AssetTransferDocument) assetTransferForm.getDocument(); handleRequestFromLookup(request, assetTransferForm, assetTransferDocument); handleRequestFromWorkflow(assetTransferForm, assetTransferDocument); Asset asset = assetTransferDocument.getAsset(); asset.refreshReferenceObject(CamsPropertyConstants.Asset.ASSET_LOCATIONS); asset.refreshReferenceObject(CamsPropertyConstants.Asset.ASSET_PAYMENTS); SpringContext.getBean(AssetLocationService.class).setOffCampusLocation(asset); SpringContext.getBean(PaymentSummaryService.class).calculateAndSetPaymentSummary(asset); // populate old asset fields for historic retaining on document String command = assetTransferForm.getCommand(); if (KEWConstants.INITIATE_COMMAND.equals(command)) { assetTransferDocument.setOldOrganizationOwnerChartOfAccountsCode(asset.getOrganizationOwnerChartOfAccountsCode()); assetTransferDocument.setOldOrganizationOwnerAccountNumber(asset.getOrganizationOwnerAccountNumber()); } this.refresh(mapping, form, request, response); return docHandlerForward; } /** * This method handles when request is from a work flow document search * * @param assetTransferForm Form * @param assetTransferDocument Document * @param service BusinessObjectService * @return Asset */ protected void handleRequestFromWorkflow(AssetTransferForm assetTransferForm, AssetTransferDocument assetTransferDocument) { LOG.debug("Start- Handle request from workflow"); if (assetTransferForm.getDocId() != null) { assetTransferDocument.refreshReferenceObject(CamsPropertyConstants.AssetTransferDocument.ASSET); org.kuali.rice.kim.service.PersonService personService = SpringContext.getBean(org.kuali.rice.kim.service.PersonService.class); Person person = personService.getPerson(assetTransferDocument.getRepresentativeUniversalIdentifier()); if (person != null) { assetTransferDocument.setAssetRepresentative(person); } else { LOG.error("org.kuali.rice.kim.service.PersonService returned null for uuid " + assetTransferDocument.getRepresentativeUniversalIdentifier()); } } } /** * This method handles the request coming from asset lookup screen * * @param request Request * @param assetTransferForm Current form * @param assetTransferDocument Document * @param service Business Object Service * @param asset Asset * @return Asset */ protected void handleRequestFromLookup(HttpServletRequest request, AssetTransferForm assetTransferForm, AssetTransferDocument assetTransferDocument) { LOG.debug("Start - Handle request from asset lookup screen"); if (assetTransferForm.getDocId() == null) { String capitalAssetNumber = request.getParameter(CAPITAL_ASSET_NUMBER); assetTransferDocument.setCapitalAssetNumber(Long.valueOf(capitalAssetNumber)); assetTransferDocument.refreshReferenceObject(CamsPropertyConstants.AssetTransferDocument.ASSET); } } /** * Since the organization fields are view only we need to make sure they are in sync with the data entry fields. * * @see org.kuali.rice.kns.web.struts.action.KualiDocumentActionBase#refresh(org.apache.struts.action.ActionMapping, * org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override public ActionForward refresh(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ((KualiDocumentFormBase) form).setErrorMapFromPreviousRequest(new ErrorMap()); ActionForward actionForward = super.refresh(mapping, form, request, response); AssetTransferDocument assetTransferDocument = ((AssetTransferForm) form).getAssetTransferDocument(); assetTransferDocument.refreshReferenceObject(CamsPropertyConstants.AssetTransferDocument.ORGANIZATION_OWNER_ACCOUNT); assetTransferDocument.refreshReferenceObject(CamsPropertyConstants.AssetTransferDocument.OLD_ORGANIZATION_OWNER_ACCOUNT); return actionForward; } /** * Route the document */ @Override public ActionForward route(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward actionForward = super.route(mapping, form, request, response); allPaymentsFederalOwnedMessage(form); return actionForward; } protected void allPaymentsFederalOwnedMessage(ActionForm form) { boolean allPaymentsFederalOwned = true; AssetTransferDocument assetTransferDocument = ((AssetTransferForm) form).getAssetTransferDocument(); for (AssetPayment assetPayment : assetTransferDocument.getAsset().getAssetPayments()) { if (!getAssetPaymentService().isPaymentFederalOwned(assetPayment)) { allPaymentsFederalOwned = false; } } // display a message for asset not generating ledger entries when it is federally owned if (allPaymentsFederalOwned) { GlobalVariables.getMessageList().add(0, new ErrorMessage(CamsKeyConstants.Transfer.MESSAGE_NO_LEDGER_ENTRY_REQUIRED_TRANSFER)); } } protected AssetPaymentService getAssetPaymentService() { return SpringContext.getBean(AssetPaymentService.class); } }
KFSMI-6446 : Removing reference to ErrorMap API method
work/src/org/kuali/kfs/module/cam/document/web/struts/AssetTransferAction.java
KFSMI-6446 : Removing reference to ErrorMap API method
<ide><path>ork/src/org/kuali/kfs/module/cam/document/web/struts/AssetTransferAction.java <ide> import org.kuali.kfs.sys.document.web.struts.FinancialSystemTransactionalDocumentActionBase; <ide> import org.kuali.rice.kew.util.KEWConstants; <ide> import org.kuali.rice.kim.bo.Person; <del>import org.kuali.rice.kns.util.ErrorMap; <ide> import org.kuali.rice.kns.util.ErrorMessage; <ide> import org.kuali.rice.kns.util.GlobalVariables; <del>import org.kuali.rice.kns.util.WebUtils; <add>import org.kuali.rice.kns.util.MessageMap; <ide> import org.kuali.rice.kns.web.struts.form.KualiDocumentFormBase; <ide> <ide> public class AssetTransferAction extends FinancialSystemTransactionalDocumentActionBase { <ide> */ <ide> @Override <ide> public ActionForward refresh(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { <del> ((KualiDocumentFormBase) form).setErrorMapFromPreviousRequest(new ErrorMap()); <add> ((KualiDocumentFormBase) form).setMessageMapFromPreviousRequest(new MessageMap()); <ide> ActionForward actionForward = super.refresh(mapping, form, request, response); <ide> <ide> AssetTransferDocument assetTransferDocument = ((AssetTransferForm) form).getAssetTransferDocument();
Java
apache-2.0
fb63f8c3a5a79713a803d6e8328bd11de805943a
0
svn2github/commons-scxml2,svn2github/commons-scxml2,svn2github/commons-scxml2
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.scxml2.io; import java.io.StringReader; import org.apache.commons.scxml2.SCXMLExecutor; import org.apache.commons.scxml2.SCXMLTestHelper; import org.apache.commons.scxml2.env.jexl.JexlContext; import org.apache.commons.scxml2.env.jexl.JexlEvaluator; import org.apache.commons.scxml2.model.ModelException; import org.apache.commons.scxml2.model.SCXML; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Test enforcement of required SCXML element attributes, spec http://www.w3.org/TR/2013/WD-scxml-20130801 * <p> * TODO required attributes for elements: * <ul> * <li>&lt;raise&gt; required attribute: 'id'</li> * </ul> * </p> */ public class SCXMLRequiredAttributesTest { private static final String VALID_SCXML = "<scxml xmlns=\"http://www.w3.org/2005/07/scxml\" version=\"1.0\">\n" + " <state id=\"s1\">\n" + " <transition target=\"fine\">\n" + " <if cond=\"true\"><log expr=\"'hello'\"/></if>\n" + " </transition>\n" + " </state>\n" + " <final id=\"fine\"/>\n" + "</scxml>"; private static final String SCXML_WITH_MISSING_VERSION = "<scxml xmlns=\"http://www.w3.org/2005/07/scxml\">\n" + " <final id=\"fine\"/>\n" + "</scxml>"; private static final String SCXML_WITH_INVALID_VERSION = "<scxml xmlns=\"http://www.w3.org/2005/07/scxml\" version=\"2.0\">\n" + " <final id=\"fine\"/>\n" + "</scxml>"; private static final String SCXML_WITH_MISSING_IF_COND = "<scxml xmlns=\"http://www.w3.org/2005/07/scxml\" version=\"1.0\">\n" + " <state id=\"s1\">\n" + " <transition target=\"fine\">\n" + " <if><log expr=\"'hello'\"/></if>\n" + " </transition>\n" + " </state>\n" + " <final id=\"fine\"/>\n" + "</scxml>"; private static final String SCXML_WITH_MISSING_ELSEIF_COND = "<scxml xmlns=\"http://www.w3.org/2005/07/scxml\" version=\"1.0\">\n" + " <state id=\"s1\">\n" + " <transition target=\"fine\">\n" + " <if cond=\"false\"><elseif/><log expr=\"'hello'\"/></if>\n" + " </transition>\n" + " </state>\n" + " <final id=\"fine\"/>\n" + "</scxml>"; private static final String SCXML_WITH_MISSING_DATA_ID = "<scxml xmlns=\"http://www.w3.org/2005/07/scxml\" version=\"1.0\">\n" + " <datamodel><data></data></datamodel>\n" + " <final id=\"fine\"/>\n" + "</scxml>"; private static final String SCXML_WITH_MISSING_ASSIGN_LOCATION = "<scxml xmlns=\"http://www.w3.org/2005/07/scxml\" version=\"1.0\">\n" + " <state id=\"s1\">\n" + " <transition target=\"fine\">\n" + " <assign expr=\"1\"/>\n" + " </transition>\n" + " </state>\n" + " <final id=\"fine\"/>\n" + "</scxml>"; private static final String SCXML_WITH_ASSIGN_WITHOUT_LOCATION = "<scxml xmlns=\"http://www.w3.org/2005/07/scxml\" version=\"1.0\">\n" + " <datamodel><data id=\"x\"></data></datamodel>\n" + " <state id=\"s1\">\n" + " <transition target=\"fine\">\n" + " <assign name=\"x\" expr=\"1\"/>\n" + " </transition>\n" + " </state>\n" + " <final id=\"fine\"/>\n" + "</scxml>"; private static final String SCXML_WITH_MISSING_PARAM_NAME = "<scxml xmlns=\"http://www.w3.org/2005/07/scxml\" version=\"1.0\">\n" + " <state id=\"s1\">\n" + " <invoke type=\"scxml\" src=\"foo\">\n" + // Note: invalid src, but not executed during test " <param expr=\"1\"/>\n" + " </invoke>\n" + " </state>\n" + " <final id=\"fine\"/>\n" + "</scxml>"; private static final String SCXML_WITH_PARAM_AND_NAME = "<scxml xmlns=\"http://www.w3.org/2005/07/scxml\" version=\"1.0\">\n" + " <state id=\"s1\">\n" + " <invoke type=\"scxml\" src=\"foo\">\n" + // Note: invalid src, but not executed during test " <param name=\"bar\" expr=\"1\"/>\n" + " </invoke>\n" + " </state>\n" + " <final id=\"fine\"/>\n" + "</scxml>"; private static final String SCXML_WITH_MISSING_FOREACH_ARRAY = "<scxml xmlns=\"http://www.w3.org/2005/07/scxml\" version=\"1.0\">\n" + " <state id=\"s1\">\n" + " <transition target=\"fine\">\n" + " <foreach item=\"y\"></foreach>\n" + " </transition>\n" + " </state>\n" + " <final id=\"fine\"/>\n" + "</scxml>"; private static final String SCXML_WITH_MISSING_FOREACH_ITEM = "<scxml xmlns=\"http://www.w3.org/2005/07/scxml\" version=\"1.0\">\n" + " <state id=\"s1\">\n" + " <transition target=\"fine\">\n" + " <foreach array=\"[1,2]\"></foreach>\n" + " </transition>\n" + " </state>\n" + " <final id=\"fine\"/>\n" + "</scxml>"; private static final String SCXML_WITH_FOREACH = "<scxml xmlns=\"http://www.w3.org/2005/07/scxml\" version=\"1.0\">\n" + " <state id=\"s1\">\n" + " <transition target=\"fine\">\n" + " <foreach array=\"[1,2]\" item=\"x\"></foreach>\n" + " </transition>\n" + " </state>\n" + " <final id=\"fine\"/>\n" + "</scxml>"; @Test public void testValidSCXML() throws Exception { SCXML scxml = SCXMLTestHelper.parse(new StringReader(VALID_SCXML), null); assertNotNull(scxml); SCXMLExecutor exec = executeSCXML(scxml); assertTrue(exec.getCurrentStatus().isFinal()); } @Test public void testSCXMLMissingVersion() throws Exception { try { SCXMLTestHelper.parse(new StringReader(SCXML_WITH_MISSING_VERSION), null); fail("SCXML reading should have failed due to missing version in SCXML"); } catch (ModelException e) { assertTrue(e.getMessage().startsWith("<scxml> is missing required attribute \"version\" value")); } } @Test public void testSCXMLInvalidVersion() throws Exception { try { SCXMLTestHelper.parse(new StringReader(SCXML_WITH_INVALID_VERSION), null); fail("SCXML reading should have failed due to missing version in SCXML"); } catch (ModelException e) { assertEquals("The <scxml> element defines an unsupported version \"2.0\", only version \"1.0\" is supported.", e.getMessage()); } } @Test public void testSCXMLMissingIfCond() throws Exception { try { SCXMLTestHelper.parse(new StringReader(SCXML_WITH_MISSING_IF_COND), null); fail("SCXML reading should have failed due to missing if condition in SCXML"); } catch (ModelException e) { assertTrue(e.getMessage().startsWith("<if> is missing required attribute \"cond\" value")); } } @Test public void testSCXMLMissingElseIfCond() throws Exception { try { SCXMLTestHelper.parse(new StringReader(SCXML_WITH_MISSING_ELSEIF_COND), null); fail("SCXML reading should have failed due to missing elseif condition in SCXML"); } catch (ModelException e) { assertTrue(e.getMessage().startsWith("<elseif> is missing required attribute \"cond\" value")); } } @Test public void testSCXMLMissingDataId() throws Exception { try { SCXMLTestHelper.parse(new StringReader(SCXML_WITH_MISSING_DATA_ID), null); fail("SCXML reading should have failed due to missing data id in SCXML"); } catch (ModelException e) { assertTrue(e.getMessage().startsWith("<data> is missing required attribute \"id\" value")); } } @Test public void testSCXMLMissingAssignLocation() throws Exception { try { SCXMLTestHelper.parse(new StringReader(SCXML_WITH_MISSING_ASSIGN_LOCATION), null); fail("SCXML reading should have failed due to missing assign location in SCXML"); } catch (ModelException e) { assertTrue(e.getMessage().startsWith("<assign> is missing required attribute \"location\" value")); } } @Test public void testSCXMLWithAssignWithoutLocation() throws Exception { SCXML scxml = SCXMLTestHelper.parse(new StringReader(SCXML_WITH_ASSIGN_WITHOUT_LOCATION), null); assertNotNull(scxml); SCXMLExecutor exec = executeSCXML(scxml); assertTrue(exec.getCurrentStatus().isFinal()); } @Test public void testSCXMLMissingParamName() throws Exception { try { SCXMLTestHelper.parse(new StringReader(SCXML_WITH_MISSING_PARAM_NAME), null); fail("SCXML reading should have failed due to missing param name in SCXML"); } catch (ModelException e) { assertTrue(e.getMessage().startsWith("<param> is missing required attribute \"name\" value")); } } @Test public void testSCXMLParamWithName() throws Exception { SCXML scxml = SCXMLTestHelper.parse(new StringReader(SCXML_WITH_PARAM_AND_NAME), null); assertNotNull(scxml); // Note: cannot execute this instance without providing proper <invoke> src attribute } @Test public void testSCXMLMissingForeachArray() throws Exception { try { SCXMLTestHelper.parse(new StringReader(SCXML_WITH_MISSING_FOREACH_ARRAY), null); fail("SCXML reading should have failed due to missing foreach array in SCXML"); } catch (ModelException e) { assertTrue(e.getMessage().startsWith("<foreach> is missing required attribute \"array\" value")); } } @Test public void testSCXMLMissingForeachItem() throws Exception { try { SCXMLTestHelper.parse(new StringReader(SCXML_WITH_MISSING_FOREACH_ITEM), null); fail("SCXML reading should have failed due to missing foreach item in SCXML"); } catch (ModelException e) { assertTrue(e.getMessage().startsWith("<foreach> is missing required attribute \"item\" value")); } } @Test public void testSCXMLWithForEach() throws Exception { SCXML scxml = SCXMLTestHelper.parse(new StringReader(SCXML_WITH_FOREACH), null); assertNotNull(scxml); SCXMLExecutor exec = executeSCXML(scxml); assertTrue(exec.getCurrentStatus().isFinal()); } private SCXMLExecutor executeSCXML(SCXML scxml) throws Exception { SCXMLExecutor exec = SCXMLTestHelper.getExecutor(scxml, new JexlContext(), new JexlEvaluator()); exec.go(); return exec; } }
src/test/java/org/apache/commons/scxml2/io/SCXMLRequiredAttributesTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.scxml2.io; import java.io.StringReader; import org.apache.commons.scxml2.SCXMLExecutor; import org.apache.commons.scxml2.SCXMLTestHelper; import org.apache.commons.scxml2.env.jexl.JexlContext; import org.apache.commons.scxml2.env.jexl.JexlEvaluator; import org.apache.commons.scxml2.model.ModelException; import org.apache.commons.scxml2.model.SCXML; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Test enforcement of required SCXML element attributes, spec http://www.w3.org/TR/2013/WD-scxml-20130801 * <p> * TODO required attributes for elements: * <ul> * <li>&lt;raise&gt; required attribute: 'id'</li> * <li>&lt;foreach&gt; required attributes: 'array' and 'item'</li> * </ul> * </p> */ public class SCXMLRequiredAttributesTest { private static final String VALID_SCXML = "<scxml xmlns=\"http://www.w3.org/2005/07/scxml\" version=\"1.0\">\n" + " <state id=\"s1\">\n" + " <transition target=\"fine\">\n" + " <if cond=\"true\"><log expr=\"'hello'\"/></if>\n" + " </transition>\n" + " </state>\n" + " <final id=\"fine\"/>\n" + "</scxml>"; private static final String SCXML_WITH_MISSING_VERSION = "<scxml xmlns=\"http://www.w3.org/2005/07/scxml\">\n" + " <final id=\"fine\"/>\n" + "</scxml>"; private static final String SCXML_WITH_INVALID_VERSION = "<scxml xmlns=\"http://www.w3.org/2005/07/scxml\" version=\"2.0\">\n" + " <final id=\"fine\"/>\n" + "</scxml>"; private static final String SCXML_WITH_MISSING_IF_COND = "<scxml xmlns=\"http://www.w3.org/2005/07/scxml\" version=\"1.0\">\n" + " <state id=\"s1\">\n" + " <transition target=\"fine\">\n" + " <if><log expr=\"'hello'\"/></if>\n" + " </transition>\n" + " </state>\n" + " <final id=\"fine\"/>\n" + "</scxml>"; private static final String SCXML_WITH_MISSING_ELSEIF_COND = "<scxml xmlns=\"http://www.w3.org/2005/07/scxml\" version=\"1.0\">\n" + " <state id=\"s1\">\n" + " <transition target=\"fine\">\n" + " <if cond=\"false\"><elseif/><log expr=\"'hello'\"/></if>\n" + " </transition>\n" + " </state>\n" + " <final id=\"fine\"/>\n" + "</scxml>"; private static final String SCXML_WITH_MISSING_DATA_ID = "<scxml xmlns=\"http://www.w3.org/2005/07/scxml\" version=\"1.0\">\n" + " <datamodel><data></data></datamodel>\n" + " <final id=\"fine\"/>\n" + "</scxml>"; private static final String SCXML_WITH_MISSING_ASSIGN_LOCATION = "<scxml xmlns=\"http://www.w3.org/2005/07/scxml\" version=\"1.0\">\n" + " <state id=\"s1\">\n" + " <transition target=\"fine\">\n" + " <assign expr=\"1\"/>\n" + " </transition>\n" + " </state>\n" + " <final id=\"fine\"/>\n" + "</scxml>"; private static final String SCXML_WITH_ASSIGN_WITHOUT_LOCATION = "<scxml xmlns=\"http://www.w3.org/2005/07/scxml\" version=\"1.0\">\n" + " <datamodel><data id=\"x\"></data></datamodel>\n" + " <state id=\"s1\">\n" + " <transition target=\"fine\">\n" + " <assign name=\"x\" expr=\"1\"/>\n" + " </transition>\n" + " </state>\n" + " <final id=\"fine\"/>\n" + "</scxml>"; private static final String SCXML_WITH_MISSING_PARAM_NAME = "<scxml xmlns=\"http://www.w3.org/2005/07/scxml\" version=\"1.0\">\n" + " <state id=\"s1\">\n" + " <invoke type=\"scxml\" src=\"foo\">\n" + // Note: invalid src, but not executed during test " <param expr=\"1\"/>\n" + " </invoke>\n" + " </state>\n" + " <final id=\"fine\"/>\n" + "</scxml>"; private static final String SCXML_WITH_PARAM_AND_NAME = "<scxml xmlns=\"http://www.w3.org/2005/07/scxml\" version=\"1.0\">\n" + " <state id=\"s1\">\n" + " <invoke type=\"scxml\" src=\"foo\">\n" + // Note: invalid src, but not executed during test " <param name=\"bar\" expr=\"1\"/>\n" + " </invoke>\n" + " </state>\n" + " <final id=\"fine\"/>\n" + "</scxml>"; private static final String SCXML_WITH_MISSING_FOREACH_ARRAY = "<scxml xmlns=\"http://www.w3.org/2005/07/scxml\" version=\"1.0\">\n" + " <state id=\"s1\">\n" + " <transition target=\"fine\">\n" + " <foreach item=\"y\"></foreach>\n" + " </transition>\n" + " </state>\n" + " <final id=\"fine\"/>\n" + "</scxml>"; private static final String SCXML_WITH_MISSING_FOREACH_ITEM = "<scxml xmlns=\"http://www.w3.org/2005/07/scxml\" version=\"1.0\">\n" + " <state id=\"s1\">\n" + " <transition target=\"fine\">\n" + " <foreach array=\"[1,2]\"></foreach>\n" + " </transition>\n" + " </state>\n" + " <final id=\"fine\"/>\n" + "</scxml>"; private static final String SCXML_WITH_FOREACH = "<scxml xmlns=\"http://www.w3.org/2005/07/scxml\" version=\"1.0\">\n" + " <state id=\"s1\">\n" + " <transition target=\"fine\">\n" + " <foreach array=\"[1,2]\" item=\"x\"></foreach>\n" + " </transition>\n" + " </state>\n" + " <final id=\"fine\"/>\n" + "</scxml>"; @Test public void testValidSCXML() throws Exception { SCXML scxml = SCXMLTestHelper.parse(new StringReader(VALID_SCXML), null); assertNotNull(scxml); SCXMLExecutor exec = executeSCXML(scxml); assertTrue(exec.getCurrentStatus().isFinal()); } @Test public void testSCXMLMissingVersion() throws Exception { try { SCXMLTestHelper.parse(new StringReader(SCXML_WITH_MISSING_VERSION), null); fail("SCXML reading should have failed due to missing version in SCXML"); } catch (ModelException e) { assertTrue(e.getMessage().startsWith("<scxml> is missing required attribute \"version\" value")); } } @Test public void testSCXMLInvalidVersion() throws Exception { try { SCXMLTestHelper.parse(new StringReader(SCXML_WITH_INVALID_VERSION), null); fail("SCXML reading should have failed due to missing version in SCXML"); } catch (ModelException e) { assertEquals("The <scxml> element defines an unsupported version \"2.0\", only version \"1.0\" is supported.", e.getMessage()); } } @Test public void testSCXMLMissingIfCond() throws Exception { try { SCXMLTestHelper.parse(new StringReader(SCXML_WITH_MISSING_IF_COND), null); fail("SCXML reading should have failed due to missing if condition in SCXML"); } catch (ModelException e) { assertTrue(e.getMessage().startsWith("<if> is missing required attribute \"cond\" value")); } } @Test public void testSCXMLMissingElseIfCond() throws Exception { try { SCXMLTestHelper.parse(new StringReader(SCXML_WITH_MISSING_ELSEIF_COND), null); fail("SCXML reading should have failed due to missing elseif condition in SCXML"); } catch (ModelException e) { assertTrue(e.getMessage().startsWith("<elseif> is missing required attribute \"cond\" value")); } } @Test public void testSCXMLMissingDataId() throws Exception { try { SCXMLTestHelper.parse(new StringReader(SCXML_WITH_MISSING_DATA_ID), null); fail("SCXML reading should have failed due to missing data id in SCXML"); } catch (ModelException e) { assertTrue(e.getMessage().startsWith("<data> is missing required attribute \"id\" value")); } } @Test public void testSCXMLMissingAssignLocation() throws Exception { try { SCXMLTestHelper.parse(new StringReader(SCXML_WITH_MISSING_ASSIGN_LOCATION), null); fail("SCXML reading should have failed due to missing assign location in SCXML"); } catch (ModelException e) { assertTrue(e.getMessage().startsWith("<assign> is missing required attribute \"location\" value")); } } @Test public void testSCXMLWithAssignWithoutLocation() throws Exception { SCXML scxml = SCXMLTestHelper.parse(new StringReader(SCXML_WITH_ASSIGN_WITHOUT_LOCATION), null); assertNotNull(scxml); SCXMLExecutor exec = executeSCXML(scxml); assertTrue(exec.getCurrentStatus().isFinal()); } @Test public void testSCXMLMissingParamName() throws Exception { try { SCXMLTestHelper.parse(new StringReader(SCXML_WITH_MISSING_PARAM_NAME), null); fail("SCXML reading should have failed due to missing param name in SCXML"); } catch (ModelException e) { assertTrue(e.getMessage().startsWith("<param> is missing required attribute \"name\" value")); } } @Test public void testSCXMLParamWithName() throws Exception { SCXML scxml = SCXMLTestHelper.parse(new StringReader(SCXML_WITH_PARAM_AND_NAME), null); assertNotNull(scxml); // Note: cannot execute this instance without providing proper <invoke> src attribute } @Test public void testSCXMLMissingForeachArray() throws Exception { try { SCXMLTestHelper.parse(new StringReader(SCXML_WITH_MISSING_FOREACH_ARRAY), null); fail("SCXML reading should have failed due to missing foreach array in SCXML"); } catch (ModelException e) { assertTrue(e.getMessage().startsWith("<foreach> is missing required attribute \"array\" value")); } } @Test public void testSCXMLMissingForeachItem() throws Exception { try { SCXMLTestHelper.parse(new StringReader(SCXML_WITH_MISSING_FOREACH_ITEM), null); fail("SCXML reading should have failed due to missing foreach item in SCXML"); } catch (ModelException e) { assertTrue(e.getMessage().startsWith("<foreach> is missing required attribute \"item\" value")); } } @Test public void testSCXMLWithForEach() throws Exception { SCXML scxml = SCXMLTestHelper.parse(new StringReader(SCXML_WITH_FOREACH), null); assertNotNull(scxml); SCXMLExecutor exec = executeSCXML(scxml); assertTrue(exec.getCurrentStatus().isFinal()); } private SCXMLExecutor executeSCXML(SCXML scxml) throws Exception { SCXMLExecutor exec = SCXMLTestHelper.getExecutor(scxml, new JexlContext(), new JexlEvaluator()); exec.go(); return exec; } }
SCXML-190: Check and enforce required scxml element attributes as defined by the spec, http://www.w3.org/TR/2013/WD-scxml-20130801 - checks for <foreach> element added TODO: when support for <<raise> is added, also add checks for its required attributes (id) git-svn-id: 5d8fe9a566db79829532a6a4175371ceef757e7a@1561916 13f79535-47bb-0310-9956-ffa450edef68
src/test/java/org/apache/commons/scxml2/io/SCXMLRequiredAttributesTest.java
SCXML-190: Check and enforce required scxml element attributes as defined by the spec, http://www.w3.org/TR/2013/WD-scxml-20130801 - checks for <foreach> element added TODO: when support for <<raise> is added, also add checks for its required attributes (id)
<ide><path>rc/test/java/org/apache/commons/scxml2/io/SCXMLRequiredAttributesTest.java <ide> * TODO required attributes for elements: <ide> * <ul> <ide> * <li>&lt;raise&gt; required attribute: 'id'</li> <del> * <li>&lt;foreach&gt; required attributes: 'array' and 'item'</li> <ide> * </ul> <ide> * </p> <ide> */
JavaScript
apache-2.0
27d63e7e7157bcc72658533709633afd826ebbde
0
rogerpueyo/luci,openwrt/luci,rogerpueyo/luci,hnyman/luci,tobiaswaldvogel/luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,openwrt/luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,openwrt/luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,openwrt/luci,rogerpueyo/luci,openwrt/luci,hnyman/luci,tobiaswaldvogel/luci,tobiaswaldvogel/luci,openwrt/luci,tobiaswaldvogel/luci,hnyman/luci,rogerpueyo/luci,rogerpueyo/luci,rogerpueyo/luci,rogerpueyo/luci,hnyman/luci,lbthomsen/openwrt-luci,hnyman/luci,rogerpueyo/luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,hnyman/luci,hnyman/luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,openwrt/luci,openwrt/luci,hnyman/luci
'use strict'; 'require fs'; 'require uci'; 'require form'; return L.Class.extend({ title: _('Iptables Plugin Configuration'), description: _('The iptables plugin will monitor selected firewall rules and collect information about processed bytes and packets per rule.'), addFormOptions: function(s) { var o, ss; o = s.option(form.Flag, 'enable', _('Enable this plugin')); o.default = '0'; for (var family = 4; family <= 6; family += 2) { var suffix = (family == 4 ? '' : '6'); o = s.option(form.SectionValue, '__match' + suffix, form.TableSection, 'collectd_iptables_match' + suffix, suffix ? _('Match IPv6 iptables rules') : _('Match IPv4 iptables rules'), _('Here you can define various criteria by which the monitored iptables rules are selected.')); o.depends('enable', '1'); o.load = L.bind(function(suffix, section_id) { return L.resolveDefault(fs.exec_direct('/usr/sbin/ip' + suffix + 'tables-save', []), '').then(L.bind(function(res) { var lines = res.split(/\n/), table, chain, count, iptables = {}; for (var i = 0; i < lines.length; i++) { var m; if ((m = lines[i].match(/^\*(\S+)$/)) != null) { table = m[1]; count = {}; } else if ((m = lines[i].match(/^-A (.+?) ([!-].+)$/)) != null) { count[m[1]] = (count[m[1]] || 0) + 1; iptables[table] = iptables[table] || {}; iptables[table][m[1]] = iptables[table][m[1]] || {}; iptables[table][m[1]][count[m[1]]] = E('span', { 'style': 'overflow:hidden; text-overflow:ellipsis; max-width:200px', 'data-tooltip': m[2] }, [ '#%d: '.format(count[m[1]]), m[2].replace(/-m comment --comment "(.+?)" /, '') ]); /* * collectd currently does not support comments with spaces: * https://github.com/collectd/collectd/issues/2766 */ var c = m[2].match(/-m comment --comment "(.+)" -/); if (c && c[1] != '!fw3' && !c[1].match(/[ \t\n]/)) iptables[table][m[1]][c[1]] = E('span', {}, [ c[1] ]); } } this.subsection.iptables = iptables; return form.SectionValue.prototype.load.apply(this, [section_id]); }, this)); }, o, suffix); ss = o.subsection; ss.anonymous = true; ss.addremove = true; ss.addbtntitle = suffix ? _('Add IPv6 rule selector') : _('Add IPv4 rule selector'); o = ss.option(form.Value, 'name', _('Instance name')); o.datatype = 'maxlength(63)'; o.validate = function(section_id, v) { var table_opt = this.section.children.filter(function(o) { return o.option == 'table' })[0], table_elem = table_opt.getUIElement(section_id); table_elem.clearChoices(); table_elem.addChoices(Object.keys(this.section.iptables).sort()); if (v != '' && v.match(/[ \t\n]/)) return _('The instance name must not contain spaces'); return true; }; o = ss.option(form.Value, 'table', _('Table')); o.default = 'filter'; o.optional = true; o.rmempty = true; o.transformChoices = function() { return this.super('transformChoices', []) || {} }; o.validate = function(section_id, table) { var chain_opt = this.section.children.filter(function(o) { return o.option == 'chain' })[0], chain_elem = chain_opt.getUIElement(section_id); chain_elem.clearChoices(); chain_elem.addChoices(Object.keys(this.section.iptables[table]).sort()); return true; }; o = ss.option(form.Value, 'chain', _('Chain')); o.optional = true; o.rmempty = true; o.transformChoices = function() { return this.super('transformChoices', []) || {} }; o.validate = function(section_id, chain) { var table_opt = this.section.children.filter(function(o) { return o.option == 'table' })[0], rule_opt = this.section.children.filter(function(o) { return o.option == 'rule' })[0], rule_elem = rule_opt.getUIElement(section_id), table = table_opt.formvalue(section_id); rule_elem.clearChoices(); if (this.section.iptables[table][chain]) { var keys = Object.keys(this.section.iptables[table][chain]).sort(function(a, b) { var x = a.match(/^(\d+)/), y = b.match(/^(\d+)/); if (x && y) return +x[1] > +y[1]; else if (x || y) return +!!x > +!!y; else return a > b; }); var labels = {}; for (var i = 0; i < keys.length; i++) labels[keys[i]] = this.section.iptables[table][chain][keys[i]].cloneNode(true); rule_elem.addChoices(keys, labels); } if (chain != '' && chain.match(/[ \t\n]/)) return _('The chain name must not contain spaces'); return true; }; o = ss.option(form.Value, 'rule', _('Comment / Rule Number')); o.optional = true; o.rmempty = true; o.transformChoices = function() { return this.super('transformChoices', []) || {} }; o.load = function(section_id) { var table = uci.get('luci_statistics', section_id, 'table'), chain = uci.get('luci_statistics', section_id, 'chain'), rule = uci.get('luci_statistics', section_id, 'rule'), ipt = this.section.iptables; if (ipt[table] && ipt[table][chain] && ipt[table][chain][rule]) this.value(rule, ipt[table][chain][rule].cloneNode(true)); return rule; }; o.validate = function(section_id, rule) { if (rule != '' && rule.match(/[ \t\n]/)) return _('The comment to match must not contain spaces'); return true; }; } }, configSummary: function(section) { return _('Rule monitoring enabled'); } });
applications/luci-app-statistics/htdocs/luci-static/resources/view/statistics/plugins/iptables.js
'use strict'; 'require fs'; 'require uci'; 'require form'; return L.Class.extend({ title: _('Iptables Plugin Configuration'), description: _('The iptables plugin will monitor selected firewall rules and collect information about processed bytes and packets per rule.'), addFormOptions: function(s) { var o, ss; o = s.option(form.Flag, 'enable', _('Enable this plugin')); o.default = '0'; for (var family = 4; family <= 6; family += 2) { var suffix = (family == 4 ? '' : '6'); o = s.option(form.SectionValue, '__match' + suffix, form.TableSection, 'collectd_iptables_match' + suffix, suffix ? _('Match IPv6 iptables rules') : _('Match IPv4 iptables rules'), _('Here you can define various criteria by which the monitored iptables rules are selected.')); o.depends('enable', '1'); o.load = L.bind(function(suffix, section_id) { return L.resolveDefault(fs.exec_direct('/usr/sbin/ip' + suffix + 'tables-save', []), '').then(L.bind(function(res) { var lines = res.split(/\n/), table, chain, count, iptables = {}; for (var i = 0; i < lines.length; i++) { var m; if ((m = lines[i].match(/^\*(\S+)$/)) != null) { table = m[1]; count = {}; } else if ((m = lines[i].match(/^-A (.+?) (-.+)$/)) != null) { count[m[1]] = (count[m[1]] || 0) + 1; iptables[table] = iptables[table] || {}; iptables[table][m[1]] = iptables[table][m[1]] || {}; iptables[table][m[1]][count[m[1]]] = E('span', { 'style': 'overflow:hidden; text-overflow:ellipsis; max-width:200px', 'data-tooltip': m[2] }, [ '#%d: '.format(count[m[1]]), m[2].replace(/-m comment --comment "(.+?)" /, '') ]); /* * collectd currently does not support comments with spaces: * https://github.com/collectd/collectd/issues/2766 */ var c = m[2].match(/-m comment --comment "(.+)" -/); if (c && c[1] != '!fw3' && !c[1].match(/[ \t\n]/)) iptables[table][m[1]][c[1]] = E('span', {}, [ c[1] ]); } } this.subsection.iptables = iptables; return form.SectionValue.prototype.load.apply(this, [section_id]); }, this)); }, o, suffix); ss = o.subsection; ss.anonymous = true; ss.addremove = true; ss.addbtntitle = suffix ? _('Add IPv6 rule selector') : _('Add IPv4 rule selector'); o = ss.option(form.Value, 'name', _('Instance name')); o.datatype = 'maxlength(63)'; o.validate = function(section_id, v) { var table_opt = this.section.children.filter(function(o) { return o.option == 'table' })[0], table_elem = table_opt.getUIElement(section_id); table_elem.clearChoices(); table_elem.addChoices(Object.keys(this.section.iptables).sort()); if (v != '' && v.match(/[ \t\n]/)) return _('The instance name must not contain spaces'); return true; }; o = ss.option(form.Value, 'table', _('Table')); o.default = 'filter'; o.optional = true; o.rmempty = true; o.transformChoices = function() { return this.super('transformChoices', []) || {} }; o.validate = function(section_id, table) { var chain_opt = this.section.children.filter(function(o) { return o.option == 'chain' })[0], chain_elem = chain_opt.getUIElement(section_id); chain_elem.clearChoices(); chain_elem.addChoices(Object.keys(this.section.iptables[table]).sort()); return true; }; o = ss.option(form.Value, 'chain', _('Chain')); o.optional = true; o.rmempty = true; o.transformChoices = function() { return this.super('transformChoices', []) || {} }; o.validate = function(section_id, chain) { var table_opt = this.section.children.filter(function(o) { return o.option == 'table' })[0], rule_opt = this.section.children.filter(function(o) { return o.option == 'rule' })[0], rule_elem = rule_opt.getUIElement(section_id), table = table_opt.formvalue(section_id); rule_elem.clearChoices(); if (this.section.iptables[table][chain]) { var keys = Object.keys(this.section.iptables[table][chain]).sort(function(a, b) { var x = a.match(/^(\d+)/), y = b.match(/^(\d+)/); if (x && y) return +x[1] > +y[1]; else if (x || y) return +!!x > +!!y; else return a > b; }); var labels = {}; for (var i = 0; i < keys.length; i++) labels[keys[i]] = this.section.iptables[table][chain][keys[i]].cloneNode(true); rule_elem.addChoices(keys, labels); } if (chain != '' && chain.match(/[ \t\n]/)) return _('The chain name must not contain spaces'); return true; }; o = ss.option(form.Value, 'rule', _('Comment / Rule Number')); o.optional = true; o.rmempty = true; o.transformChoices = function() { return this.super('transformChoices', []) || {} }; o.load = function(section_id) { var table = uci.get('luci_statistics', section_id, 'table'), chain = uci.get('luci_statistics', section_id, 'chain'), rule = uci.get('luci_statistics', section_id, 'rule'), ipt = this.section.iptables; if (ipt[table] && ipt[table][chain] && ipt[table][chain][rule]) this.value(rule, ipt[table][chain][rule].cloneNode(true)); return rule; }; o.validate = function(section_id, rule) { if (rule != '' && rule.match(/[ \t\n]/)) return _('The comment to match must not contain spaces'); return true; }; } }, configSummary: function(section) { return _('Rule monitoring enabled'); } });
luci-app-statistics: iptables.js: fix rule match expression Fixes: #3658 Signed-off-by: Jo-Philipp Wich <[email protected]>
applications/luci-app-statistics/htdocs/luci-static/resources/view/statistics/plugins/iptables.js
luci-app-statistics: iptables.js: fix rule match expression
<ide><path>pplications/luci-app-statistics/htdocs/luci-static/resources/view/statistics/plugins/iptables.js <ide> table = m[1]; <ide> count = {}; <ide> } <del> else if ((m = lines[i].match(/^-A (.+?) (-.+)$/)) != null) { <add> else if ((m = lines[i].match(/^-A (.+?) ([!-].+)$/)) != null) { <ide> count[m[1]] = (count[m[1]] || 0) + 1; <ide> <ide> iptables[table] = iptables[table] || {};
Java
mpl-2.0
0bfdf2cce23415e4aad782924dc0031d244ba672
0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
/************************************************************************* * * $RCSfile: EnhancedComplexTestCase.java,v $ * * $Revision: 1.3 $ * * last change: $Date: 2005-02-24 17:20:07 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ package convwatch; import complexlib.ComplexTestCase; import helper.ProcessHandler; import java.io.File; import convwatch.GraphicalTestArguments; /** * Some Helperfunctions which are nice in ReferenceBuilder and ConvWatchTest */ public abstract class EnhancedComplexTestCase extends ComplexTestCase { // public void before() // { // // System.out.println("before()"); // } // // public void after() // { // // System.out.println("after()"); // } void checkExistance(String _sScriptFile, String _sName) { boolean bBackValue = false; // Process testshl = Runtime.getRuntime().exec(scriptFile); ProcessHandler aHandler = new ProcessHandler(_sScriptFile); bBackValue = aHandler.executeSynchronously(); StringBuffer aBuffer = new StringBuffer(); aBuffer.append(aHandler.getErrorText()).append(aHandler.getOutputText()); String sText = aBuffer.toString(); if (sText.length() == 0) { String sError = "Must quit. " + _sName + " may be not accessable."; assure(sError, false); // System.exit(1); } else { // System.out.println("Output from script:"); // System.out.println(sText); } } // ----------------------------------------------------------------------------- protected void checkEnvironment(Object[] _aList) { // checks if some packages already installed, // this function will not return if packages are not installed, // it will call System.exit(1)! for (int i=0;i<_aList.length;i++) { String sCommand = (String)_aList[i]; // TODO: nice to have, a pair object checkExistance(sCommand, sCommand); } } // ----------------------------------------------------------------------------- protected abstract Object[] mustInstalledSoftware(); // ----------------------------------------------------------------------------- public GraphicalTestArguments getGraphicalTestArguments() { GraphicalTestArguments aGTA = new GraphicalTestArguments(param); if (aGTA.getImportFilterName() != null && aGTA.getImportFilterName().toLowerCase().equals("help")) { aGTA = null; } if (aGTA.getExportFilterName() != null && aGTA.getExportFilterName().toLowerCase().equals("help")) { aGTA = null; } return aGTA; } }
qadevOOo/runner/convwatch/EnhancedComplexTestCase.java
/************************************************************************* * * $RCSfile: EnhancedComplexTestCase.java,v $ * * $Revision: 1.2 $ * * last change: $Date: 2004-11-02 11:09:05 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ package convwatch; import complexlib.ComplexTestCase; import helper.ProcessHandler; import java.io.File; import convwatch.GraphicalTestArguments; /** * Some Helperfunctions which are nice in ReferenceBuilder and ConvWatchTest */ public abstract class EnhancedComplexTestCase extends ComplexTestCase { // public void before() // { // // System.out.println("before()"); // } // // public void after() // { // // System.out.println("after()"); // } void checkExistance(String _sScriptFile, String _sName) { boolean bBackValue = false; // Process testshl = Runtime.getRuntime().exec(scriptFile); ProcessHandler aHandler = new ProcessHandler(_sScriptFile); bBackValue = aHandler.executeSynchronously(); StringBuffer aBuffer = new StringBuffer(); aBuffer.append(aHandler.getErrorText()).append(aHandler.getOutputText()); String sText = aBuffer.toString(); if (sText.length() == 0) { String sError = "Must quit. " + _sName + " may be not accessable."; assure(sError, false); // System.exit(1); } else { // System.out.println("Output from script:"); // System.out.println(sText); } } // ----------------------------------------------------------------------------- protected void checkEnvironment(Object[] _aList) { // checks if some packages already installed, // this function will not return if packages are not installed, // it will call System.exit(1)! for (int i=0;i<_aList.length;i++) { String sCommand = (String)_aList[i]; // TODO: nice to have, a pair object checkExistance(sCommand, sCommand); } } // ----------------------------------------------------------------------------- protected abstract Object[] mustInstalledSoftware(); // ----------------------------------------------------------------------------- public GraphicalTestArguments getGraphicalTestArguments() { return new GraphicalTestArguments(param); } }
INTEGRATION: CWS qadev21 (1.2.14); FILE MERGED 2005/01/06 09:16:05 lla 1.2.14.1: #i31243# handle help in IMPORT/EXPORT filter
qadevOOo/runner/convwatch/EnhancedComplexTestCase.java
INTEGRATION: CWS qadev21 (1.2.14); FILE MERGED 2005/01/06 09:16:05 lla 1.2.14.1: #i31243# handle help in IMPORT/EXPORT filter
<ide><path>adevOOo/runner/convwatch/EnhancedComplexTestCase.java <ide> * <ide> * $RCSfile: EnhancedComplexTestCase.java,v $ <ide> * <del> * $Revision: 1.2 $ <add> * $Revision: 1.3 $ <ide> * <del> * last change: $Date: 2004-11-02 11:09:05 $ <add> * last change: $Date: 2005-02-24 17:20:07 $ <ide> * <ide> * The Contents of this file are made available subject to the terms of <ide> * either of the following licenses <ide> <ide> public GraphicalTestArguments getGraphicalTestArguments() <ide> { <del> return new GraphicalTestArguments(param); <add> GraphicalTestArguments aGTA = new GraphicalTestArguments(param); <add> if (aGTA.getImportFilterName() != null && aGTA.getImportFilterName().toLowerCase().equals("help")) <add> { <add> aGTA = null; <add> } <add> if (aGTA.getExportFilterName() != null && aGTA.getExportFilterName().toLowerCase().equals("help")) <add> { <add> aGTA = null; <add> } <add> return aGTA; <ide> } <ide> <ide>
Java
apache-2.0
e52f20e59643b79b23b98f79fa255a4880472ce1
0
googleapis/java-dialogflow-cx,googleapis/java-dialogflow-cx,googleapis/java-dialogflow-cx
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.dialogflow.cx.v3beta1.it; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import com.google.api.gax.longrunning.OperationFuture; import com.google.cloud.ServiceOptions; import com.google.cloud.dialogflow.cx.v3beta1.Agent; import com.google.cloud.dialogflow.cx.v3beta1.AgentsClient; import com.google.cloud.dialogflow.cx.v3beta1.CreateEntityTypeRequest; import com.google.cloud.dialogflow.cx.v3beta1.CreateFlowRequest; import com.google.cloud.dialogflow.cx.v3beta1.CreateIntentRequest; import com.google.cloud.dialogflow.cx.v3beta1.CreatePageRequest; import com.google.cloud.dialogflow.cx.v3beta1.CreateTransitionRouteGroupRequest; import com.google.cloud.dialogflow.cx.v3beta1.CreateVersionRequest; import com.google.cloud.dialogflow.cx.v3beta1.DeleteAgentRequest; import com.google.cloud.dialogflow.cx.v3beta1.DeleteEntityTypeRequest; import com.google.cloud.dialogflow.cx.v3beta1.DeleteFlowRequest; import com.google.cloud.dialogflow.cx.v3beta1.DeleteIntentRequest; import com.google.cloud.dialogflow.cx.v3beta1.DeletePageRequest; import com.google.cloud.dialogflow.cx.v3beta1.DeleteTransitionRouteGroupRequest; import com.google.cloud.dialogflow.cx.v3beta1.DeleteVersionRequest; import com.google.cloud.dialogflow.cx.v3beta1.DetectIntentRequest; import com.google.cloud.dialogflow.cx.v3beta1.DetectIntentResponse; import com.google.cloud.dialogflow.cx.v3beta1.EntityType; import com.google.cloud.dialogflow.cx.v3beta1.EntityTypesClient; import com.google.cloud.dialogflow.cx.v3beta1.ExportAgentRequest; import com.google.cloud.dialogflow.cx.v3beta1.ExportAgentResponse; import com.google.cloud.dialogflow.cx.v3beta1.Flow; import com.google.cloud.dialogflow.cx.v3beta1.FlowsClient; import com.google.cloud.dialogflow.cx.v3beta1.Form; import com.google.cloud.dialogflow.cx.v3beta1.GetAgentRequest; import com.google.cloud.dialogflow.cx.v3beta1.GetEntityTypeRequest; import com.google.cloud.dialogflow.cx.v3beta1.GetFlowRequest; import com.google.cloud.dialogflow.cx.v3beta1.GetIntentRequest; import com.google.cloud.dialogflow.cx.v3beta1.GetPageRequest; import com.google.cloud.dialogflow.cx.v3beta1.GetTransitionRouteGroupRequest; import com.google.cloud.dialogflow.cx.v3beta1.GetVersionRequest; import com.google.cloud.dialogflow.cx.v3beta1.Intent; import com.google.cloud.dialogflow.cx.v3beta1.IntentsClient; import com.google.cloud.dialogflow.cx.v3beta1.ListAgentsRequest; import com.google.cloud.dialogflow.cx.v3beta1.ListEntityTypesRequest; import com.google.cloud.dialogflow.cx.v3beta1.ListFlowsRequest; import com.google.cloud.dialogflow.cx.v3beta1.ListIntentsRequest; import com.google.cloud.dialogflow.cx.v3beta1.ListPagesRequest; import com.google.cloud.dialogflow.cx.v3beta1.ListTransitionRouteGroupsRequest; import com.google.cloud.dialogflow.cx.v3beta1.ListVersionsRequest; import com.google.cloud.dialogflow.cx.v3beta1.LocationName; import com.google.cloud.dialogflow.cx.v3beta1.MatchIntentRequest; import com.google.cloud.dialogflow.cx.v3beta1.MatchIntentResponse; import com.google.cloud.dialogflow.cx.v3beta1.NluSettings; import com.google.cloud.dialogflow.cx.v3beta1.Page; import com.google.cloud.dialogflow.cx.v3beta1.PagesClient; import com.google.cloud.dialogflow.cx.v3beta1.QueryInput; import com.google.cloud.dialogflow.cx.v3beta1.RestoreAgentRequest; import com.google.cloud.dialogflow.cx.v3beta1.SessionsClient; import com.google.cloud.dialogflow.cx.v3beta1.TextInput; import com.google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup; import com.google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroupsClient; import com.google.cloud.dialogflow.cx.v3beta1.UpdateEntityTypeRequest; import com.google.cloud.dialogflow.cx.v3beta1.UpdateTransitionRouteGroupRequest; import com.google.cloud.dialogflow.cx.v3beta1.UpdateVersionRequest; import com.google.cloud.dialogflow.cx.v3beta1.Version; import com.google.cloud.dialogflow.cx.v3beta1.VersionsClient; import com.google.common.collect.Lists; import com.google.protobuf.Empty; import com.google.protobuf.FieldMask; import com.google.protobuf.Struct; import java.io.IOException; import java.util.List; import java.util.UUID; import java.util.concurrent.ExecutionException; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; public class ITSystemTest { private static AgentsClient agentsClient; private static EntityTypesClient entityTypesClient; private static FlowsClient flowsClient; private static IntentsClient intentsClient; private static PagesClient pagesClient; private static SessionsClient sessionsClient; private static TransitionRouteGroupsClient transitionRouteGroupsClient; private static VersionsClient versionsClient; private static String agentName; private static String entityTypesName; private static String flowName; private static String trainFlowName; private static String intentsName; private static String pageName; private static String transitionRouteGroupName; private static String versionName; private static final String PROJECT = ServiceOptions.getDefaultProjectId(); private static final String ID = UUID.randomUUID().toString(); private static final String LOCATION = "global"; private static final String DISPLAY_NAME = "test-" + ID.substring(0, 8); private static final String AGENT_TIME_ZONE = "America/Los_Angeles"; private static final String DEFAULT_LANGUAGE_CODE = "en"; private static final String DESCRIPTION = "description-test-" + ID; private static final String TEXT = "hello"; private static final QueryInput QUERY_INPUT = QueryInput.newBuilder() .setText(TextInput.newBuilder().setText(TEXT).build()) .setLanguageCode(DEFAULT_LANGUAGE_CODE) .build(); private static final LocationName PARENT = LocationName.of(PROJECT, LOCATION); private static NluSettings NLUSETTINGS = NluSettings.newBuilder() .setModelType(NluSettings.ModelType.MODEL_TYPE_STANDARD) .setClassificationThreshold(0.3f) .setModelTrainingModeValue(1) .build(); @BeforeClass public static void setUp() throws IOException, ExecutionException, InterruptedException { /* create agents */ agentsClient = AgentsClient.create(); Agent agent = Agent.newBuilder() .setDisplayName(DISPLAY_NAME) .setDescription(DESCRIPTION) .setTimeZone(AGENT_TIME_ZONE) .setDefaultLanguageCode(DEFAULT_LANGUAGE_CODE) .setStartFlow(ID) .setEnableStackdriverLogging(true) .build(); Agent response = agentsClient.createAgent(PARENT, agent); agentName = response.getName(); /* create entity types */ entityTypesClient = EntityTypesClient.create(); EntityType entityType = EntityType.newBuilder() .setAutoExpansionMode(EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT) .setAutoExpansionModeValue(1) .setDisplayName(DISPLAY_NAME) .setEnableFuzzyExtraction(true) .setKind(EntityType.Kind.KIND_LIST) .build(); CreateEntityTypeRequest request = CreateEntityTypeRequest.newBuilder().setParent(agentName).setEntityType(entityType).build(); EntityType entityTypeResponse = entityTypesClient.createEntityType(request); entityTypesName = entityTypeResponse.getName(); /* create flows */ flowsClient = FlowsClient.create(); Flow flow = Flow.newBuilder() .setNluSettings(NLUSETTINGS) .setDisplayName(DISPLAY_NAME) .setDescription(DESCRIPTION) .build(); CreateFlowRequest createFlowRequest = CreateFlowRequest.newBuilder().setParent(agentName).setFlow(flow).build(); Flow flowResponse = flowsClient.createFlow(createFlowRequest); flowName = flowResponse.getName(); Flow trainFlow = Flow.newBuilder() .setNluSettings(NLUSETTINGS) .setDisplayName(DISPLAY_NAME) .setDescription(DESCRIPTION) .build(); CreateFlowRequest createTrainFlowRequest = CreateFlowRequest.newBuilder().setParent(agentName).setFlow(trainFlow).build(); Flow trainFlowResponse = flowsClient.createFlow(createTrainFlowRequest); trainFlowName = trainFlowResponse.getName(); /* create intents */ intentsClient = IntentsClient.create(); Intent intent = Intent.newBuilder().setDisplayName(DISPLAY_NAME).setPriority(1).build(); CreateIntentRequest createIntentRequest = CreateIntentRequest.newBuilder().setIntent(intent).setParent(agentName).build(); Intent intentResponse = intentsClient.createIntent(createIntentRequest); intentsName = intentResponse.getName(); /* create pages */ pagesClient = PagesClient.create(); Page page = Page.newBuilder().setDisplayName(DISPLAY_NAME).build(); CreatePageRequest createPageRequest = CreatePageRequest.newBuilder().setPage(page).setParent(flowName).build(); Page pageResponse = pagesClient.createPage(createPageRequest); pageName = pageResponse.getName(); /* create session */ sessionsClient = SessionsClient.create(); /* create transition route groups */ transitionRouteGroupsClient = TransitionRouteGroupsClient.create(); TransitionRouteGroup transitionRouteGroup = TransitionRouteGroup.newBuilder().setDisplayName(DISPLAY_NAME).build(); CreateTransitionRouteGroupRequest transitionRouteGroupRequest = CreateTransitionRouteGroupRequest.newBuilder() .setParent(flowName) .setTransitionRouteGroup(transitionRouteGroup) .build(); TransitionRouteGroup transitionRouteGroupResponse = transitionRouteGroupsClient.createTransitionRouteGroup(transitionRouteGroupRequest); transitionRouteGroupName = transitionRouteGroupResponse.getName(); /* create version */ versionsClient = VersionsClient.create(); Version version = Version.newBuilder().setStateValue(2).setDisplayName(DISPLAY_NAME).build(); CreateVersionRequest createVersionRequest = CreateVersionRequest.newBuilder().setParent(flowName).setVersion(version).build(); Version versionResponse = versionsClient.createVersionAsync(createVersionRequest).get(); versionName = versionResponse.getName(); } @AfterClass public static void tearDown() { /* delete version */ DeleteVersionRequest deleteVersionRequest = DeleteVersionRequest.newBuilder().setName(versionName).build(); versionsClient.deleteVersion(deleteVersionRequest); versionsClient.close(); /* delete transition route groups */ DeleteTransitionRouteGroupRequest deleteTransitionRouteGroupRequest = DeleteTransitionRouteGroupRequest.newBuilder().setName(transitionRouteGroupName).build(); transitionRouteGroupsClient.deleteTransitionRouteGroup(deleteTransitionRouteGroupRequest); transitionRouteGroupsClient.close(); /* delete session */ sessionsClient.close(); /* delete pages */ DeletePageRequest deletePageRequest = DeletePageRequest.newBuilder().setName(pageName).build(); pagesClient.deletePage(deletePageRequest); pagesClient.close(); /* delete intents */ DeleteIntentRequest deleteIntentRequest = DeleteIntentRequest.newBuilder().setName(intentsName).build(); intentsClient.deleteIntent(deleteIntentRequest); intentsClient.close(); /* delete flows */ DeleteFlowRequest deleteFlowRequest = DeleteFlowRequest.newBuilder().setName(flowName).build(); flowsClient.deleteFlow(deleteFlowRequest); DeleteFlowRequest deleteTrainFlowRequest = DeleteFlowRequest.newBuilder().setName(trainFlowName).build(); flowsClient.deleteFlow(deleteTrainFlowRequest); flowsClient.close(); /* delete entity types */ DeleteEntityTypeRequest deleteEntityTypeRequest = DeleteEntityTypeRequest.newBuilder().setName(entityTypesName).build(); entityTypesClient.deleteEntityType(deleteEntityTypeRequest); entityTypesClient.close(); /* delete agents */ DeleteAgentRequest deleteAgentRequest = DeleteAgentRequest.newBuilder().setName(agentName).build(); agentsClient.deleteAgent(deleteAgentRequest); agentsClient.close(); } @Test public void getAgentTest() { GetAgentRequest request = GetAgentRequest.newBuilder().setName(agentName).build(); Agent agent = agentsClient.getAgent(request); assertAgentDetails(agent); } @Test public void listAgentsTest() { ListAgentsRequest request = ListAgentsRequest.newBuilder().setParent(PARENT.toString()).build(); Iterable<Agent> agents = agentsClient.listAgents(request).iterateAll(); boolean isAgentExists = false; for (Agent agent : agents) { if (agentName.equals(agent.getName())) { assertAgentDetails(agent); isAgentExists = true; } } assertTrue(isAgentExists); } @Test public void exportAgentTest() throws ExecutionException, InterruptedException { ExportAgentRequest request = ExportAgentRequest.newBuilder().setName(agentName).build(); ExportAgentResponse exportAgentResponse = agentsClient.exportAgentAsync(request).get(); assertNotNull(exportAgentResponse.getAgentContent()); assertTrue(exportAgentResponse.getAgentContent().toStringUtf8().contains(agentName)); } @Test public void restoreAgentTest() throws ExecutionException, InterruptedException { Agent agent = Agent.newBuilder() .setDisplayName("test_agent_" + UUID.randomUUID().toString()) .setDescription(DESCRIPTION) .setTimeZone(AGENT_TIME_ZONE) .setDefaultLanguageCode(DEFAULT_LANGUAGE_CODE) .setEnableStackdriverLogging(true) .setEnableSpellCorrection(true) .build(); Agent response = agentsClient.createAgent(PARENT, agent); String agentName = response.getName(); try { /* Replaces the current agent with a new one. Note that all existing resources in agent (e.g. * intents, entity types, flows) will be removed */ RestoreAgentRequest restoreAgentRequest = RestoreAgentRequest.newBuilder().setName(agentName).build(); OperationFuture<Empty, Struct> operationFuture = agentsClient.restoreAgentAsync(restoreAgentRequest); assertNotEquals(agentName, operationFuture.getName()); } finally { DeleteAgentRequest deleteAgentRequest = DeleteAgentRequest.newBuilder().setName(agentName).build(); agentsClient.deleteAgent(deleteAgentRequest); } } @Test public void getEntityTypeTest() { GetEntityTypeRequest request = GetEntityTypeRequest.newBuilder().setName(entityTypesName).build(); EntityType entityType = entityTypesClient.getEntityType(request); assertEntityTypesDetails(entityType); } @Test public void listEntityTypesTest() { ListEntityTypesRequest request = ListEntityTypesRequest.newBuilder().setParent(agentName).build(); Iterable<EntityType> entityTypes = entityTypesClient.listEntityTypes(request).iterateAll(); boolean isEntityTypeExists = false; for (EntityType entityType : entityTypes) { if (entityTypesName.equals(entityType.getName())) { assertEntityTypesDetails(entityType); isEntityTypeExists = true; } } assertTrue(isEntityTypeExists); } @Test public void updateEntityTypeTest() { EntityType entityType = EntityType.newBuilder() .setName(entityTypesName) .setKind(EntityType.Kind.KIND_LIST) .setDisplayName(DISPLAY_NAME) .setKindValue(2) .build(); UpdateEntityTypeRequest updateEntityTypeRequest = UpdateEntityTypeRequest.newBuilder().setEntityType(entityType).build(); EntityType response = entityTypesClient.updateEntityType(updateEntityTypeRequest); assertEquals(2, response.getKindValue()); } @Test public void getFlowTest() { GetFlowRequest request = GetFlowRequest.newBuilder().setName(flowName).build(); Flow flow = flowsClient.getFlow(request); assertFlowDetails(flow); } @Test public void listFlowsTest() { ListFlowsRequest request = ListFlowsRequest.newBuilder().setParent(agentName).build(); FlowsClient.ListFlowsPagedResponse pagedListResponse = flowsClient.listFlows(request); List<Flow> flows = Lists.newArrayList(pagedListResponse.iterateAll()); boolean isFlowExists = false; for (Flow flow : flows) { if (flow.getName().equals(flowName)) { assertFlowDetails(flow); isFlowExists = true; } } assertTrue(isFlowExists); } @Test @Ignore("https://github.com/googleapis/java-dialogflow-cx/issues/230") public void trainFlowTest() throws ExecutionException, InterruptedException { Empty expectedResponse = Empty.newBuilder().build(); Empty response = flowsClient.trainFlowAsync(trainFlowName).get(); assertEquals(expectedResponse, response); } @Test public void getIntentsTest() { GetIntentRequest request = GetIntentRequest.newBuilder().setName(intentsName).build(); Intent intent = intentsClient.getIntent(request); assertIntentDetails(intent); } @Test public void listIntentsTest() { ListIntentsRequest request = ListIntentsRequest.newBuilder().setParent(agentName).build(); IntentsClient.ListIntentsPagedResponse pagedListResponse = intentsClient.listIntents(request); List<Intent> intents = Lists.newArrayList(pagedListResponse.iterateAll()); boolean isIntentExists = false; for (Intent intent : intents) { if (intent.getName().equals(intentsName)) { assertIntentDetails(intent); isIntentExists = true; } } assertTrue(isIntentExists); } @Test public void updateIntentTest() { Intent intent = Intent.newBuilder() .setName(intentsName) .setDisplayName(DISPLAY_NAME) .setPriority(50) .build(); FieldMask updateMask = FieldMask.newBuilder().build(); Intent intentResponse = intentsClient.updateIntent(intent, updateMask); assertEquals(50, intentResponse.getPriority()); } @Test public void getPageTest() { GetPageRequest request = GetPageRequest.newBuilder().setName(pageName).build(); Page page = pagesClient.getPage(request); assertPageDetails(page); } @Test public void listPagesTest() { ListPagesRequest request = ListPagesRequest.newBuilder().setParent(flowName).build(); PagesClient.ListPagesPagedResponse pagedListResponse = pagesClient.listPages(request); List<Page> pages = Lists.newArrayList(pagedListResponse.iterateAll()); boolean isPageExists = false; for (Page page : pages) { if (page.getName().equals(pageName)) { assertPageDetails(page); isPageExists = true; } } assertTrue(isPageExists); } @Test public void updatePageTest() { Page page = Page.newBuilder() .setName(pageName) .setForm(Form.getDefaultInstance()) .setDisplayName(DISPLAY_NAME) .build(); FieldMask updateMask = FieldMask.newBuilder().build(); Page updatedPage = pagesClient.updatePage(page, updateMask); assertPageDetails(updatedPage); } @Test public void detectIntentTest() { String session = String.format("%s/sessions/%s", agentName, ID); DetectIntentRequest request = DetectIntentRequest.newBuilder().setSession(session).setQueryInput(QUERY_INPUT).build(); DetectIntentResponse detectIntent = sessionsClient.detectIntent(request); assertTrue(detectIntent.getQueryResult().getText().contains(TEXT)); } @Test public void matchIntentTest() { String session = String.format("%s/sessions/%s", agentName, ID); MatchIntentRequest request = MatchIntentRequest.newBuilder().setSession(session).setQueryInput(QUERY_INPUT).build(); MatchIntentResponse matchIntentResponse = sessionsClient.matchIntent(request); assertTrue(matchIntentResponse.getMatchesList().size() > 0); assertEquals(TEXT, matchIntentResponse.getText()); } @Test public void getTransitionRouteGroupTest() { GetTransitionRouteGroupRequest routeGroupRequest = GetTransitionRouteGroupRequest.newBuilder().setName(transitionRouteGroupName).build(); TransitionRouteGroup transitionRouteGroup = transitionRouteGroupsClient.getTransitionRouteGroup(routeGroupRequest); assertTransitionRouteGroupsDetails(transitionRouteGroup); } @Test public void listTransitionRouteGroupsTest() { ListTransitionRouteGroupsRequest routeGroupsRequest = ListTransitionRouteGroupsRequest.newBuilder().setParent(flowName).build(); TransitionRouteGroupsClient.ListTransitionRouteGroupsPagedResponse pagedListResponse = transitionRouteGroupsClient.listTransitionRouteGroups(routeGroupsRequest); List<TransitionRouteGroup> routeGroups = Lists.newArrayList(pagedListResponse.iterateAll()); boolean isTransitionRouteGroupNameExists = false; for (TransitionRouteGroup routeGroup : routeGroups) { if (routeGroup.getName().equals(transitionRouteGroupName)) { assertTransitionRouteGroupsDetails(routeGroup); isTransitionRouteGroupNameExists = true; } } assertTrue(isTransitionRouteGroupNameExists); } @Test public void updateTransitionRouteGroupTest() { String updatedDisplayName = DISPLAY_NAME + "-" + ID; TransitionRouteGroup transitionRouteGroup = TransitionRouteGroup.newBuilder() .setName(transitionRouteGroupName) .setDisplayName(updatedDisplayName) .build(); FieldMask updateMask = FieldMask.newBuilder().build(); UpdateTransitionRouteGroupRequest routeGroupRequest = UpdateTransitionRouteGroupRequest.newBuilder() .setTransitionRouteGroup(transitionRouteGroup) .setUpdateMask(updateMask) .build(); TransitionRouteGroup updatedTransitionRouteGroup = transitionRouteGroupsClient.updateTransitionRouteGroup(routeGroupRequest); assertEquals(updatedDisplayName, updatedTransitionRouteGroup.getDisplayName()); } @Test public void getVersionTest() { GetVersionRequest versionRequest = GetVersionRequest.newBuilder().setName(versionName).build(); Version version = versionsClient.getVersion(versionRequest); assertVersionDetails(version); } @Test public void listVersionsTest() { ListVersionsRequest versionsRequest = ListVersionsRequest.newBuilder().setParent(flowName).build(); VersionsClient.ListVersionsPagedResponse pagedListResponse = versionsClient.listVersions(versionsRequest); List<Version> versions = Lists.newArrayList(pagedListResponse.iterateAll()); boolean isVersionNameExists = false; for (Version version : versions) { if (version.getName().equals(versionName)) { assertVersionDetails(version); isVersionNameExists = true; } } assertTrue(isVersionNameExists); } @Test public void updateVersionTest() { Version version = Version.newBuilder() .setName(versionName) .setDisplayName(DISPLAY_NAME) .setState(Version.State.SUCCEEDED) .build(); FieldMask updateMask = FieldMask.newBuilder().build(); UpdateVersionRequest versionRequest = UpdateVersionRequest.newBuilder().setVersion(version).setUpdateMask(updateMask).build(); Version updatedVersion = versionsClient.updateVersion(versionRequest); assertEquals(Version.State.SUCCEEDED, updatedVersion.getState()); } @Test public void loadVersionTest() throws Exception { Empty expectedResponse = Empty.newBuilder().build(); Empty actualResponse = versionsClient.loadVersionAsync(versionName).get(); assertEquals(expectedResponse, actualResponse); } private void assertAgentDetails(Agent agent) { assertEquals(agentName, agent.getName()); assertEquals(DISPLAY_NAME, agent.getDisplayName()); assertEquals(DEFAULT_LANGUAGE_CODE, agent.getDefaultLanguageCode()); assertEquals(AGENT_TIME_ZONE, agent.getTimeZone()); assertEquals(DESCRIPTION, agent.getDescription()); assertTrue(agent.getEnableStackdriverLogging()); } private void assertEntityTypesDetails(EntityType entityType) { assertEquals(entityTypesName, entityType.getName()); assertEquals( EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, entityType.getAutoExpansionMode()); assertEquals(1, entityType.getAutoExpansionModeValue()); assertEquals(DISPLAY_NAME, entityType.getDisplayName()); assertEquals(EntityType.Kind.KIND_LIST, entityType.getKind()); assertTrue(entityType.getEnableFuzzyExtraction()); } private void assertFlowDetails(Flow flow) { assertEquals(flowName, flow.getName()); assertEquals(DISPLAY_NAME, flow.getDisplayName()); assertEquals(DESCRIPTION, flow.getDescription()); assertEquals(NLUSETTINGS.getModelType(), flow.getNluSettings().getModelType()); assertEquals( NLUSETTINGS.getClassificationThreshold(), flow.getNluSettings().getClassificationThreshold(), 0); assertEquals(NLUSETTINGS.getModelTrainingMode(), flow.getNluSettings().getModelTrainingMode()); } private void assertIntentDetails(Intent intent) { assertEquals(intentsName, intent.getName()); assertEquals(DISPLAY_NAME, intent.getDisplayName()); assertEquals(1, intent.getPriority()); } private void assertPageDetails(Page page) { assertEquals(pageName, page.getName()); assertEquals(DISPLAY_NAME, page.getDisplayName()); } private void assertTransitionRouteGroupsDetails(TransitionRouteGroup transitionRouteGroup) { assertEquals(transitionRouteGroupName, transitionRouteGroup.getName()); assertTrue(transitionRouteGroup.getDisplayName().contains(DISPLAY_NAME)); } private void assertVersionDetails(Version version) { assertEquals(versionName, version.getName()); assertEquals(DISPLAY_NAME, version.getDisplayName()); assertEquals(NLUSETTINGS.getModelType(), version.getNluSettings().getModelType()); assertEquals( NLUSETTINGS.getClassificationThreshold(), version.getNluSettings().getClassificationThreshold(), 0); assertEquals( NLUSETTINGS.getModelTrainingMode(), version.getNluSettings().getModelTrainingMode()); assertEquals(2, version.getStateValue()); } }
google-cloud-dialogflow-cx/src/test/java/com/google/cloud/dialogflow/cx/v3beta1/it/ITSystemTest.java
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.dialogflow.cx.v3beta1.it; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import com.google.api.gax.longrunning.OperationFuture; import com.google.cloud.ServiceOptions; import com.google.cloud.dialogflow.cx.v3beta1.Agent; import com.google.cloud.dialogflow.cx.v3beta1.AgentsClient; import com.google.cloud.dialogflow.cx.v3beta1.CreateEntityTypeRequest; import com.google.cloud.dialogflow.cx.v3beta1.CreateFlowRequest; import com.google.cloud.dialogflow.cx.v3beta1.CreateIntentRequest; import com.google.cloud.dialogflow.cx.v3beta1.CreatePageRequest; import com.google.cloud.dialogflow.cx.v3beta1.CreateTransitionRouteGroupRequest; import com.google.cloud.dialogflow.cx.v3beta1.CreateVersionRequest; import com.google.cloud.dialogflow.cx.v3beta1.DeleteAgentRequest; import com.google.cloud.dialogflow.cx.v3beta1.DeleteEntityTypeRequest; import com.google.cloud.dialogflow.cx.v3beta1.DeleteFlowRequest; import com.google.cloud.dialogflow.cx.v3beta1.DeleteIntentRequest; import com.google.cloud.dialogflow.cx.v3beta1.DeletePageRequest; import com.google.cloud.dialogflow.cx.v3beta1.DeleteTransitionRouteGroupRequest; import com.google.cloud.dialogflow.cx.v3beta1.DeleteVersionRequest; import com.google.cloud.dialogflow.cx.v3beta1.DetectIntentRequest; import com.google.cloud.dialogflow.cx.v3beta1.DetectIntentResponse; import com.google.cloud.dialogflow.cx.v3beta1.EntityType; import com.google.cloud.dialogflow.cx.v3beta1.EntityTypesClient; import com.google.cloud.dialogflow.cx.v3beta1.ExportAgentRequest; import com.google.cloud.dialogflow.cx.v3beta1.ExportAgentResponse; import com.google.cloud.dialogflow.cx.v3beta1.Flow; import com.google.cloud.dialogflow.cx.v3beta1.FlowsClient; import com.google.cloud.dialogflow.cx.v3beta1.Form; import com.google.cloud.dialogflow.cx.v3beta1.GetAgentRequest; import com.google.cloud.dialogflow.cx.v3beta1.GetEntityTypeRequest; import com.google.cloud.dialogflow.cx.v3beta1.GetFlowRequest; import com.google.cloud.dialogflow.cx.v3beta1.GetIntentRequest; import com.google.cloud.dialogflow.cx.v3beta1.GetPageRequest; import com.google.cloud.dialogflow.cx.v3beta1.GetTransitionRouteGroupRequest; import com.google.cloud.dialogflow.cx.v3beta1.GetVersionRequest; import com.google.cloud.dialogflow.cx.v3beta1.Intent; import com.google.cloud.dialogflow.cx.v3beta1.IntentsClient; import com.google.cloud.dialogflow.cx.v3beta1.ListAgentsRequest; import com.google.cloud.dialogflow.cx.v3beta1.ListEntityTypesRequest; import com.google.cloud.dialogflow.cx.v3beta1.ListFlowsRequest; import com.google.cloud.dialogflow.cx.v3beta1.ListIntentsRequest; import com.google.cloud.dialogflow.cx.v3beta1.ListPagesRequest; import com.google.cloud.dialogflow.cx.v3beta1.ListTransitionRouteGroupsRequest; import com.google.cloud.dialogflow.cx.v3beta1.ListVersionsRequest; import com.google.cloud.dialogflow.cx.v3beta1.LocationName; import com.google.cloud.dialogflow.cx.v3beta1.MatchIntentRequest; import com.google.cloud.dialogflow.cx.v3beta1.MatchIntentResponse; import com.google.cloud.dialogflow.cx.v3beta1.NluSettings; import com.google.cloud.dialogflow.cx.v3beta1.Page; import com.google.cloud.dialogflow.cx.v3beta1.PagesClient; import com.google.cloud.dialogflow.cx.v3beta1.QueryInput; import com.google.cloud.dialogflow.cx.v3beta1.RestoreAgentRequest; import com.google.cloud.dialogflow.cx.v3beta1.SessionsClient; import com.google.cloud.dialogflow.cx.v3beta1.TextInput; import com.google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup; import com.google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroupsClient; import com.google.cloud.dialogflow.cx.v3beta1.UpdateEntityTypeRequest; import com.google.cloud.dialogflow.cx.v3beta1.UpdateTransitionRouteGroupRequest; import com.google.cloud.dialogflow.cx.v3beta1.UpdateVersionRequest; import com.google.cloud.dialogflow.cx.v3beta1.Version; import com.google.cloud.dialogflow.cx.v3beta1.VersionsClient; import com.google.common.collect.Lists; import com.google.protobuf.Empty; import com.google.protobuf.FieldMask; import com.google.protobuf.Struct; import java.io.IOException; import java.util.List; import java.util.UUID; import java.util.concurrent.ExecutionException; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class ITSystemTest { private static AgentsClient agentsClient; private static EntityTypesClient entityTypesClient; private static FlowsClient flowsClient; private static IntentsClient intentsClient; private static PagesClient pagesClient; private static SessionsClient sessionsClient; private static TransitionRouteGroupsClient transitionRouteGroupsClient; private static VersionsClient versionsClient; private static String agentName; private static String entityTypesName; private static String flowName; private static String trainFlowName; private static String intentsName; private static String pageName; private static String transitionRouteGroupName; private static String versionName; private static final String PROJECT = ServiceOptions.getDefaultProjectId(); private static final String ID = UUID.randomUUID().toString(); private static final String LOCATION = "global"; private static final String DISPLAY_NAME = "test-" + ID.substring(0, 8); private static final String AGENT_TIME_ZONE = "America/Los_Angeles"; private static final String DEFAULT_LANGUAGE_CODE = "en"; private static final String DESCRIPTION = "description-test-" + ID; private static final String TEXT = "hello"; private static final QueryInput QUERY_INPUT = QueryInput.newBuilder() .setText(TextInput.newBuilder().setText(TEXT).build()) .setLanguageCode(DEFAULT_LANGUAGE_CODE) .build(); private static final LocationName PARENT = LocationName.of(PROJECT, LOCATION); private static NluSettings NLUSETTINGS = NluSettings.newBuilder() .setModelType(NluSettings.ModelType.MODEL_TYPE_STANDARD) .setClassificationThreshold(0.3f) .setModelTrainingModeValue(1) .build(); @BeforeClass public static void setUp() throws IOException, ExecutionException, InterruptedException { /* create agents */ agentsClient = AgentsClient.create(); Agent agent = Agent.newBuilder() .setDisplayName(DISPLAY_NAME) .setDescription(DESCRIPTION) .setTimeZone(AGENT_TIME_ZONE) .setDefaultLanguageCode(DEFAULT_LANGUAGE_CODE) .setStartFlow(ID) .setEnableStackdriverLogging(true) .build(); Agent response = agentsClient.createAgent(PARENT, agent); agentName = response.getName(); /* create entity types */ entityTypesClient = EntityTypesClient.create(); EntityType entityType = EntityType.newBuilder() .setAutoExpansionMode(EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT) .setAutoExpansionModeValue(1) .setDisplayName(DISPLAY_NAME) .setEnableFuzzyExtraction(true) .setKind(EntityType.Kind.KIND_LIST) .build(); CreateEntityTypeRequest request = CreateEntityTypeRequest.newBuilder().setParent(agentName).setEntityType(entityType).build(); EntityType entityTypeResponse = entityTypesClient.createEntityType(request); entityTypesName = entityTypeResponse.getName(); /* create flows */ flowsClient = FlowsClient.create(); Flow flow = Flow.newBuilder() .setNluSettings(NLUSETTINGS) .setDisplayName(DISPLAY_NAME) .setDescription(DESCRIPTION) .build(); CreateFlowRequest createFlowRequest = CreateFlowRequest.newBuilder().setParent(agentName).setFlow(flow).build(); Flow flowResponse = flowsClient.createFlow(createFlowRequest); flowName = flowResponse.getName(); Flow trainFlow = Flow.newBuilder() .setNluSettings(NLUSETTINGS) .setDisplayName(DISPLAY_NAME) .setDescription(DESCRIPTION) .build(); CreateFlowRequest createTrainFlowRequest = CreateFlowRequest.newBuilder().setParent(agentName).setFlow(trainFlow).build(); Flow trainFlowResponse = flowsClient.createFlow(createTrainFlowRequest); trainFlowName = trainFlowResponse.getName(); /* create intents */ intentsClient = IntentsClient.create(); Intent intent = Intent.newBuilder().setDisplayName(DISPLAY_NAME).setPriority(1).build(); CreateIntentRequest createIntentRequest = CreateIntentRequest.newBuilder().setIntent(intent).setParent(agentName).build(); Intent intentResponse = intentsClient.createIntent(createIntentRequest); intentsName = intentResponse.getName(); /* create pages */ pagesClient = PagesClient.create(); Page page = Page.newBuilder().setDisplayName(DISPLAY_NAME).build(); CreatePageRequest createPageRequest = CreatePageRequest.newBuilder().setPage(page).setParent(flowName).build(); Page pageResponse = pagesClient.createPage(createPageRequest); pageName = pageResponse.getName(); /* create session */ sessionsClient = SessionsClient.create(); /* create transition route groups */ transitionRouteGroupsClient = TransitionRouteGroupsClient.create(); TransitionRouteGroup transitionRouteGroup = TransitionRouteGroup.newBuilder().setDisplayName(DISPLAY_NAME).build(); CreateTransitionRouteGroupRequest transitionRouteGroupRequest = CreateTransitionRouteGroupRequest.newBuilder() .setParent(flowName) .setTransitionRouteGroup(transitionRouteGroup) .build(); TransitionRouteGroup transitionRouteGroupResponse = transitionRouteGroupsClient.createTransitionRouteGroup(transitionRouteGroupRequest); transitionRouteGroupName = transitionRouteGroupResponse.getName(); /* create version */ versionsClient = VersionsClient.create(); Version version = Version.newBuilder().setStateValue(2).setDisplayName(DISPLAY_NAME).build(); CreateVersionRequest createVersionRequest = CreateVersionRequest.newBuilder().setParent(flowName).setVersion(version).build(); Version versionResponse = versionsClient.createVersionAsync(createVersionRequest).get(); versionName = versionResponse.getName(); } @AfterClass public static void tearDown() { /* delete version */ DeleteVersionRequest deleteVersionRequest = DeleteVersionRequest.newBuilder().setName(versionName).build(); versionsClient.deleteVersion(deleteVersionRequest); versionsClient.close(); /* delete transition route groups */ DeleteTransitionRouteGroupRequest deleteTransitionRouteGroupRequest = DeleteTransitionRouteGroupRequest.newBuilder().setName(transitionRouteGroupName).build(); transitionRouteGroupsClient.deleteTransitionRouteGroup(deleteTransitionRouteGroupRequest); transitionRouteGroupsClient.close(); /* delete session */ sessionsClient.close(); /* delete pages */ DeletePageRequest deletePageRequest = DeletePageRequest.newBuilder().setName(pageName).build(); pagesClient.deletePage(deletePageRequest); pagesClient.close(); /* delete intents */ DeleteIntentRequest deleteIntentRequest = DeleteIntentRequest.newBuilder().setName(intentsName).build(); intentsClient.deleteIntent(deleteIntentRequest); intentsClient.close(); /* delete flows */ DeleteFlowRequest deleteFlowRequest = DeleteFlowRequest.newBuilder().setName(flowName).build(); flowsClient.deleteFlow(deleteFlowRequest); DeleteFlowRequest deleteTrainFlowRequest = DeleteFlowRequest.newBuilder().setName(trainFlowName).build(); flowsClient.deleteFlow(deleteTrainFlowRequest); flowsClient.close(); /* delete entity types */ DeleteEntityTypeRequest deleteEntityTypeRequest = DeleteEntityTypeRequest.newBuilder().setName(entityTypesName).build(); entityTypesClient.deleteEntityType(deleteEntityTypeRequest); entityTypesClient.close(); /* delete agents */ DeleteAgentRequest deleteAgentRequest = DeleteAgentRequest.newBuilder().setName(agentName).build(); agentsClient.deleteAgent(deleteAgentRequest); agentsClient.close(); } @Test public void getAgentTest() { GetAgentRequest request = GetAgentRequest.newBuilder().setName(agentName).build(); Agent agent = agentsClient.getAgent(request); assertAgentDetails(agent); } @Test public void listAgentsTest() { ListAgentsRequest request = ListAgentsRequest.newBuilder().setParent(PARENT.toString()).build(); Iterable<Agent> agents = agentsClient.listAgents(request).iterateAll(); boolean isAgentExists = false; for (Agent agent : agents) { if (agentName.equals(agent.getName())) { assertAgentDetails(agent); isAgentExists = true; } } assertTrue(isAgentExists); } @Test public void exportAgentTest() throws ExecutionException, InterruptedException { ExportAgentRequest request = ExportAgentRequest.newBuilder().setName(agentName).build(); ExportAgentResponse exportAgentResponse = agentsClient.exportAgentAsync(request).get(); assertNotNull(exportAgentResponse.getAgentContent()); assertTrue(exportAgentResponse.getAgentContent().toStringUtf8().contains(agentName)); } @Test public void restoreAgentTest() throws ExecutionException, InterruptedException { Agent agent = Agent.newBuilder() .setDisplayName("test_agent_" + UUID.randomUUID().toString()) .setDescription(DESCRIPTION) .setTimeZone(AGENT_TIME_ZONE) .setDefaultLanguageCode(DEFAULT_LANGUAGE_CODE) .setEnableStackdriverLogging(true) .setEnableSpellCorrection(true) .build(); Agent response = agentsClient.createAgent(PARENT, agent); String agentName = response.getName(); try { /* Replaces the current agent with a new one. Note that all existing resources in agent (e.g. * intents, entity types, flows) will be removed */ RestoreAgentRequest restoreAgentRequest = RestoreAgentRequest.newBuilder().setName(agentName).build(); OperationFuture<Empty, Struct> operationFuture = agentsClient.restoreAgentAsync(restoreAgentRequest); assertNotEquals(agentName, operationFuture.getName()); } finally { DeleteAgentRequest deleteAgentRequest = DeleteAgentRequest.newBuilder().setName(agentName).build(); agentsClient.deleteAgent(deleteAgentRequest); } } @Test public void getEntityTypeTest() { GetEntityTypeRequest request = GetEntityTypeRequest.newBuilder().setName(entityTypesName).build(); EntityType entityType = entityTypesClient.getEntityType(request); assertEntityTypesDetails(entityType); } @Test public void listEntityTypesTest() { ListEntityTypesRequest request = ListEntityTypesRequest.newBuilder().setParent(agentName).build(); Iterable<EntityType> entityTypes = entityTypesClient.listEntityTypes(request).iterateAll(); boolean isEntityTypeExists = false; for (EntityType entityType : entityTypes) { if (entityTypesName.equals(entityType.getName())) { assertEntityTypesDetails(entityType); isEntityTypeExists = true; } } assertTrue(isEntityTypeExists); } @Test public void updateEntityTypeTest() { EntityType entityType = EntityType.newBuilder() .setName(entityTypesName) .setKind(EntityType.Kind.KIND_LIST) .setDisplayName(DISPLAY_NAME) .setKindValue(2) .build(); UpdateEntityTypeRequest updateEntityTypeRequest = UpdateEntityTypeRequest.newBuilder().setEntityType(entityType).build(); EntityType response = entityTypesClient.updateEntityType(updateEntityTypeRequest); assertEquals(2, response.getKindValue()); } @Test public void getFlowTest() { GetFlowRequest request = GetFlowRequest.newBuilder().setName(flowName).build(); Flow flow = flowsClient.getFlow(request); assertFlowDetails(flow); } @Test public void listFlowsTest() { ListFlowsRequest request = ListFlowsRequest.newBuilder().setParent(agentName).build(); FlowsClient.ListFlowsPagedResponse pagedListResponse = flowsClient.listFlows(request); List<Flow> flows = Lists.newArrayList(pagedListResponse.iterateAll()); boolean isFlowExists = false; for (Flow flow : flows) { if (flow.getName().equals(flowName)) { assertFlowDetails(flow); isFlowExists = true; } } assertTrue(isFlowExists); } @Test public void trainFlowTest() throws ExecutionException, InterruptedException { Empty expectedResponse = Empty.newBuilder().build(); Empty response = flowsClient.trainFlowAsync(trainFlowName).get(); assertEquals(expectedResponse, response); } @Test public void getIntentsTest() { GetIntentRequest request = GetIntentRequest.newBuilder().setName(intentsName).build(); Intent intent = intentsClient.getIntent(request); assertIntentDetails(intent); } @Test public void listIntentsTest() { ListIntentsRequest request = ListIntentsRequest.newBuilder().setParent(agentName).build(); IntentsClient.ListIntentsPagedResponse pagedListResponse = intentsClient.listIntents(request); List<Intent> intents = Lists.newArrayList(pagedListResponse.iterateAll()); boolean isIntentExists = false; for (Intent intent : intents) { if (intent.getName().equals(intentsName)) { assertIntentDetails(intent); isIntentExists = true; } } assertTrue(isIntentExists); } @Test public void updateIntentTest() { Intent intent = Intent.newBuilder() .setName(intentsName) .setDisplayName(DISPLAY_NAME) .setPriority(50) .build(); FieldMask updateMask = FieldMask.newBuilder().build(); Intent intentResponse = intentsClient.updateIntent(intent, updateMask); assertEquals(50, intentResponse.getPriority()); } @Test public void getPageTest() { GetPageRequest request = GetPageRequest.newBuilder().setName(pageName).build(); Page page = pagesClient.getPage(request); assertPageDetails(page); } @Test public void listPagesTest() { ListPagesRequest request = ListPagesRequest.newBuilder().setParent(flowName).build(); PagesClient.ListPagesPagedResponse pagedListResponse = pagesClient.listPages(request); List<Page> pages = Lists.newArrayList(pagedListResponse.iterateAll()); boolean isPageExists = false; for (Page page : pages) { if (page.getName().equals(pageName)) { assertPageDetails(page); isPageExists = true; } } assertTrue(isPageExists); } @Test public void updatePageTest() { Page page = Page.newBuilder() .setName(pageName) .setForm(Form.getDefaultInstance()) .setDisplayName(DISPLAY_NAME) .build(); FieldMask updateMask = FieldMask.newBuilder().build(); Page updatedPage = pagesClient.updatePage(page, updateMask); assertPageDetails(updatedPage); } @Test public void detectIntentTest() { String session = String.format("%s/sessions/%s", agentName, ID); DetectIntentRequest request = DetectIntentRequest.newBuilder().setSession(session).setQueryInput(QUERY_INPUT).build(); DetectIntentResponse detectIntent = sessionsClient.detectIntent(request); assertTrue(detectIntent.getQueryResult().getText().contains(TEXT)); } @Test public void matchIntentTest() { String session = String.format("%s/sessions/%s", agentName, ID); MatchIntentRequest request = MatchIntentRequest.newBuilder().setSession(session).setQueryInput(QUERY_INPUT).build(); MatchIntentResponse matchIntentResponse = sessionsClient.matchIntent(request); assertTrue(matchIntentResponse.getMatchesList().size() > 0); assertEquals(TEXT, matchIntentResponse.getText()); } @Test public void getTransitionRouteGroupTest() { GetTransitionRouteGroupRequest routeGroupRequest = GetTransitionRouteGroupRequest.newBuilder().setName(transitionRouteGroupName).build(); TransitionRouteGroup transitionRouteGroup = transitionRouteGroupsClient.getTransitionRouteGroup(routeGroupRequest); assertTransitionRouteGroupsDetails(transitionRouteGroup); } @Test public void listTransitionRouteGroupsTest() { ListTransitionRouteGroupsRequest routeGroupsRequest = ListTransitionRouteGroupsRequest.newBuilder().setParent(flowName).build(); TransitionRouteGroupsClient.ListTransitionRouteGroupsPagedResponse pagedListResponse = transitionRouteGroupsClient.listTransitionRouteGroups(routeGroupsRequest); List<TransitionRouteGroup> routeGroups = Lists.newArrayList(pagedListResponse.iterateAll()); boolean isTransitionRouteGroupNameExists = false; for (TransitionRouteGroup routeGroup : routeGroups) { if (routeGroup.getName().equals(transitionRouteGroupName)) { assertTransitionRouteGroupsDetails(routeGroup); isTransitionRouteGroupNameExists = true; } } assertTrue(isTransitionRouteGroupNameExists); } @Test public void updateTransitionRouteGroupTest() { String updatedDisplayName = DISPLAY_NAME + "-" + ID; TransitionRouteGroup transitionRouteGroup = TransitionRouteGroup.newBuilder() .setName(transitionRouteGroupName) .setDisplayName(updatedDisplayName) .build(); FieldMask updateMask = FieldMask.newBuilder().build(); UpdateTransitionRouteGroupRequest routeGroupRequest = UpdateTransitionRouteGroupRequest.newBuilder() .setTransitionRouteGroup(transitionRouteGroup) .setUpdateMask(updateMask) .build(); TransitionRouteGroup updatedTransitionRouteGroup = transitionRouteGroupsClient.updateTransitionRouteGroup(routeGroupRequest); assertEquals(updatedDisplayName, updatedTransitionRouteGroup.getDisplayName()); } @Test public void getVersionTest() { GetVersionRequest versionRequest = GetVersionRequest.newBuilder().setName(versionName).build(); Version version = versionsClient.getVersion(versionRequest); assertVersionDetails(version); } @Test public void listVersionsTest() { ListVersionsRequest versionsRequest = ListVersionsRequest.newBuilder().setParent(flowName).build(); VersionsClient.ListVersionsPagedResponse pagedListResponse = versionsClient.listVersions(versionsRequest); List<Version> versions = Lists.newArrayList(pagedListResponse.iterateAll()); boolean isVersionNameExists = false; for (Version version : versions) { if (version.getName().equals(versionName)) { assertVersionDetails(version); isVersionNameExists = true; } } assertTrue(isVersionNameExists); } @Test public void updateVersionTest() { Version version = Version.newBuilder() .setName(versionName) .setDisplayName(DISPLAY_NAME) .setState(Version.State.SUCCEEDED) .build(); FieldMask updateMask = FieldMask.newBuilder().build(); UpdateVersionRequest versionRequest = UpdateVersionRequest.newBuilder().setVersion(version).setUpdateMask(updateMask).build(); Version updatedVersion = versionsClient.updateVersion(versionRequest); assertEquals(Version.State.SUCCEEDED, updatedVersion.getState()); } @Test public void loadVersionTest() throws Exception { Empty expectedResponse = Empty.newBuilder().build(); Empty actualResponse = versionsClient.loadVersionAsync(versionName).get(); assertEquals(expectedResponse, actualResponse); } private void assertAgentDetails(Agent agent) { assertEquals(agentName, agent.getName()); assertEquals(DISPLAY_NAME, agent.getDisplayName()); assertEquals(DEFAULT_LANGUAGE_CODE, agent.getDefaultLanguageCode()); assertEquals(AGENT_TIME_ZONE, agent.getTimeZone()); assertEquals(DESCRIPTION, agent.getDescription()); assertTrue(agent.getEnableStackdriverLogging()); } private void assertEntityTypesDetails(EntityType entityType) { assertEquals(entityTypesName, entityType.getName()); assertEquals( EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, entityType.getAutoExpansionMode()); assertEquals(1, entityType.getAutoExpansionModeValue()); assertEquals(DISPLAY_NAME, entityType.getDisplayName()); assertEquals(EntityType.Kind.KIND_LIST, entityType.getKind()); assertTrue(entityType.getEnableFuzzyExtraction()); } private void assertFlowDetails(Flow flow) { assertEquals(flowName, flow.getName()); assertEquals(DISPLAY_NAME, flow.getDisplayName()); assertEquals(DESCRIPTION, flow.getDescription()); assertEquals(NLUSETTINGS.getModelType(), flow.getNluSettings().getModelType()); assertEquals( NLUSETTINGS.getClassificationThreshold(), flow.getNluSettings().getClassificationThreshold(), 0); assertEquals(NLUSETTINGS.getModelTrainingMode(), flow.getNluSettings().getModelTrainingMode()); } private void assertIntentDetails(Intent intent) { assertEquals(intentsName, intent.getName()); assertEquals(DISPLAY_NAME, intent.getDisplayName()); assertEquals(1, intent.getPriority()); } private void assertPageDetails(Page page) { assertEquals(pageName, page.getName()); assertEquals(DISPLAY_NAME, page.getDisplayName()); } private void assertTransitionRouteGroupsDetails(TransitionRouteGroup transitionRouteGroup) { assertEquals(transitionRouteGroupName, transitionRouteGroup.getName()); assertTrue(transitionRouteGroup.getDisplayName().contains(DISPLAY_NAME)); } private void assertVersionDetails(Version version) { assertEquals(versionName, version.getName()); assertEquals(DISPLAY_NAME, version.getDisplayName()); assertEquals(NLUSETTINGS.getModelType(), version.getNluSettings().getModelType()); assertEquals( NLUSETTINGS.getClassificationThreshold(), version.getNluSettings().getClassificationThreshold(), 0); assertEquals( NLUSETTINGS.getModelTrainingMode(), version.getNluSettings().getModelTrainingMode()); assertEquals(2, version.getStateValue()); } }
chore: skip TrainFlow IT for now (#231)
google-cloud-dialogflow-cx/src/test/java/com/google/cloud/dialogflow/cx/v3beta1/it/ITSystemTest.java
chore: skip TrainFlow IT for now (#231)
<ide><path>oogle-cloud-dialogflow-cx/src/test/java/com/google/cloud/dialogflow/cx/v3beta1/it/ITSystemTest.java <ide> import java.util.concurrent.ExecutionException; <ide> import org.junit.AfterClass; <ide> import org.junit.BeforeClass; <add>import org.junit.Ignore; <ide> import org.junit.Test; <ide> <ide> public class ITSystemTest { <ide> } <ide> <ide> @Test <add> @Ignore("https://github.com/googleapis/java-dialogflow-cx/issues/230") <ide> public void trainFlowTest() throws ExecutionException, InterruptedException { <ide> Empty expectedResponse = Empty.newBuilder().build(); <ide> Empty response = flowsClient.trainFlowAsync(trainFlowName).get();
Java
apache-2.0
a87bea71d488b7ffff91dfe3f803d00f51fb005b
0
esaunders/autopsy,rcordovano/autopsy,rcordovano/autopsy,esaunders/autopsy,esaunders/autopsy,esaunders/autopsy,rcordovano/autopsy,rcordovano/autopsy,rcordovano/autopsy,esaunders/autopsy,rcordovano/autopsy
/* * Autopsy Forensic Browser * * Copyright 2012-2020 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sleuthkit.autopsy.casemodule; import org.sleuthkit.autopsy.featureaccess.FeatureAccessUtils; import com.google.common.annotations.Beta; import com.google.common.eventbus.Subscribe; import org.sleuthkit.autopsy.casemodule.multiusercases.CaseNodeData; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.File; import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.nio.file.Paths; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TimeZone; import java.util.UUID; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.ThreadSafe; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import org.openide.util.Exceptions; import org.openide.util.Lookup; import org.openide.util.NbBundle; import org.openide.util.NbBundle.Messages; import org.openide.util.actions.CallableSystemAction; import org.openide.windows.WindowManager; import org.sleuthkit.autopsy.actions.OpenOutputFolderAction; import org.sleuthkit.autopsy.appservices.AutopsyService; import org.sleuthkit.autopsy.appservices.AutopsyService.CaseContext; import org.sleuthkit.autopsy.casemodule.CaseMetadata.CaseMetadataException; import org.sleuthkit.autopsy.casemodule.datasourcesummary.DataSourceSummaryAction; import org.sleuthkit.autopsy.casemodule.events.AddingDataSourceEvent; import org.sleuthkit.autopsy.casemodule.events.AddingDataSourceFailedEvent; import org.sleuthkit.autopsy.casemodule.events.BlackBoardArtifactTagAddedEvent; import org.sleuthkit.autopsy.casemodule.events.BlackBoardArtifactTagDeletedEvent; import org.sleuthkit.autopsy.casemodule.events.CommentChangedEvent; import org.sleuthkit.autopsy.casemodule.events.ContentTagAddedEvent; import org.sleuthkit.autopsy.casemodule.events.ContentTagDeletedEvent; import org.sleuthkit.autopsy.casemodule.events.DataSourceAddedEvent; import org.sleuthkit.autopsy.casemodule.events.DataSourceDeletedEvent; import org.sleuthkit.autopsy.casemodule.events.DataSourceNameChangedEvent; import org.sleuthkit.autopsy.casemodule.events.ReportAddedEvent; import org.sleuthkit.autopsy.casemodule.multiusercases.CaseNodeData.CaseNodeDataException; import org.sleuthkit.autopsy.casemodule.multiusercases.CoordinationServiceUtils; import org.sleuthkit.autopsy.casemodule.services.Services; import org.sleuthkit.autopsy.commonpropertiessearch.CommonAttributeSearchAction; import org.sleuthkit.autopsy.communications.OpenCommVisualizationToolAction; import org.sleuthkit.autopsy.coordinationservice.CoordinationService; import org.sleuthkit.autopsy.coordinationservice.CoordinationService.CategoryNode; import org.sleuthkit.autopsy.coordinationservice.CoordinationService.CoordinationServiceException; import org.sleuthkit.autopsy.coordinationservice.CoordinationService.Lock; import org.sleuthkit.autopsy.core.RuntimeProperties; import org.sleuthkit.autopsy.core.UserPreferences; import org.sleuthkit.autopsy.core.UserPreferencesException; import org.sleuthkit.autopsy.corecomponentinterfaces.CoreComponentControl; import org.sleuthkit.autopsy.coreutils.DriveUtils; import org.sleuthkit.autopsy.coreutils.FileUtil; import org.sleuthkit.autopsy.coreutils.Logger; import org.sleuthkit.autopsy.coreutils.MessageNotifyUtil; import org.sleuthkit.autopsy.coreutils.NetworkUtils; import org.sleuthkit.autopsy.coreutils.PlatformUtil; import org.sleuthkit.autopsy.coreutils.ThreadUtils; import org.sleuthkit.autopsy.coreutils.TimeZoneUtils; import org.sleuthkit.autopsy.coreutils.Version; import org.sleuthkit.autopsy.events.AutopsyEvent; import org.sleuthkit.autopsy.events.AutopsyEventException; import org.sleuthkit.autopsy.events.AutopsyEventPublisher; import org.sleuthkit.autopsy.filequery.OpenFileDiscoveryAction; import org.sleuthkit.autopsy.ingest.IngestJob; import org.sleuthkit.autopsy.ingest.IngestManager; import org.sleuthkit.autopsy.ingest.IngestServices; import org.sleuthkit.autopsy.ingest.ModuleDataEvent; import org.sleuthkit.autopsy.keywordsearchservice.KeywordSearchService; import org.sleuthkit.autopsy.keywordsearchservice.KeywordSearchServiceException; import org.sleuthkit.autopsy.progress.LoggingProgressIndicator; import org.sleuthkit.autopsy.progress.ModalDialogProgressIndicator; import org.sleuthkit.autopsy.progress.ProgressIndicator; import org.sleuthkit.autopsy.timeline.OpenTimelineAction; import org.sleuthkit.autopsy.timeline.events.TimelineEventAddedEvent; import org.sleuthkit.datamodel.Blackboard; import org.sleuthkit.datamodel.BlackboardArtifact; import org.sleuthkit.datamodel.BlackboardArtifactTag; import org.sleuthkit.datamodel.CaseDbConnectionInfo; import org.sleuthkit.datamodel.Content; import org.sleuthkit.datamodel.ContentTag; import org.sleuthkit.datamodel.DataSource; import org.sleuthkit.datamodel.FileSystem; import org.sleuthkit.datamodel.Image; import org.sleuthkit.datamodel.Report; import org.sleuthkit.datamodel.SleuthkitCase; import org.sleuthkit.datamodel.TimelineManager; import org.sleuthkit.datamodel.SleuthkitCaseAdminUtil; import org.sleuthkit.datamodel.TskCoreException; import org.sleuthkit.datamodel.TskDataException; import org.sleuthkit.datamodel.TskUnsupportedSchemaVersionException; /** * An Autopsy case. Currently, only one case at a time may be open. */ public class Case { private static final int CASE_LOCK_TIMEOUT_MINS = 1; private static final int CASE_RESOURCES_LOCK_TIMEOUT_HOURS = 1; private static final String SINGLE_USER_CASE_DB_NAME = "autopsy.db"; private static final String EVENT_CHANNEL_NAME = "%s-Case-Events"; //NON-NLS private static final String CACHE_FOLDER = "Cache"; //NON-NLS private static final String EXPORT_FOLDER = "Export"; //NON-NLS private static final String LOG_FOLDER = "Log"; //NON-NLS private static final String REPORTS_FOLDER = "Reports"; //NON-NLS private static final String CONFIG_FOLDER = "Config"; // NON-NLS private static final String TEMP_FOLDER = "Temp"; //NON-NLS private static final String MODULE_FOLDER = "ModuleOutput"; //NON-NLS private static final String CASE_ACTION_THREAD_NAME = "%s-case-action"; private static final String CASE_RESOURCES_THREAD_NAME = "%s-manage-case-resources"; private static final String NO_NODE_ERROR_MSG_FRAGMENT = "KeeperErrorCode = NoNode"; private static final Logger logger = Logger.getLogger(Case.class.getName()); private static final AutopsyEventPublisher eventPublisher = new AutopsyEventPublisher(); private static final Object caseActionSerializationLock = new Object(); private static volatile Frame mainFrame; private static volatile Case currentCase; private final CaseMetadata metadata; private volatile ExecutorService caseActionExecutor; private CoordinationService.Lock caseLock; private SleuthkitCase caseDb; private final SleuthkitEventListener sleuthkitEventListener; private CollaborationMonitor collaborationMonitor; private Services caseServices; /* * Get a reference to the main window of the desktop application to use to * parent pop up dialogs and initialize the application name for use in * changing the main window title. */ static { WindowManager.getDefault().invokeWhenUIReady(() -> { mainFrame = WindowManager.getDefault().getMainWindow(); }); } /** * An enumeration of case types. */ public enum CaseType { SINGLE_USER_CASE("Single-user case"), //NON-NLS MULTI_USER_CASE("Multi-user case"); //NON-NLS private final String typeName; /** * Gets a case type from a case type name string. * * @param typeName The case type name string. * * @return */ public static CaseType fromString(String typeName) { if (typeName != null) { for (CaseType c : CaseType.values()) { if (typeName.equalsIgnoreCase(c.toString())) { return c; } } } return null; } /** * Gets the string representation of this case type. * * @return */ @Override public String toString() { return typeName; } /** * Gets the localized display name for this case type. * * @return The display name. */ @Messages({ "Case_caseType_singleUser=Single-user case", "Case_caseType_multiUser=Multi-user case" }) String getLocalizedDisplayName() { if (fromString(typeName) == SINGLE_USER_CASE) { return Bundle.Case_caseType_singleUser(); } else { return Bundle.Case_caseType_multiUser(); } } /** * Constructs a case type. * * @param typeName The type name. */ private CaseType(String typeName) { this.typeName = typeName; } /** * Tests the equality of the type name of this case type with another * case type name. * * @param otherTypeName A case type name, * * @return True or false, * * @deprecated Do not use. */ @Deprecated public boolean equalsName(String otherTypeName) { return (otherTypeName == null) ? false : typeName.equals(otherTypeName); } }; /** * An enumeration of the case events (property change events) a case may * publish (fire). */ public enum Events { /** * The name of the current case has changed. The old value of the * PropertyChangeEvent is the old case name (type: String), the new * value is the new case name (type: String). * * @deprecated CASE_DETAILS event should be used instead */ @Deprecated NAME, /** * The number of the current case has changed. The old value of the * PropertyChangeEvent is the old case number (type: String), the new * value is the new case number (type: String). * * @deprecated CASE_DETAILS event should be used instead */ @Deprecated NUMBER, /** * The examiner associated with the current case has changed. The old * value of the PropertyChangeEvent is the old examiner (type: String), * the new value is the new examiner (type: String). * * @deprecated CASE_DETAILS event should be used instead */ @Deprecated EXAMINER, /** * An attempt to add a new data source to the current case is being * made. The old and new values of the PropertyChangeEvent are null. * Cast the PropertyChangeEvent to * org.sleuthkit.autopsy.casemodule.events.AddingDataSourceEvent to * access additional event data. */ ADDING_DATA_SOURCE, /** * A failure to add a new data source to the current case has occurred. * The old and new values of the PropertyChangeEvent are null. Cast the * PropertyChangeEvent to * org.sleuthkit.autopsy.casemodule.events.AddingDataSourceFailedEvent * to access additional event data. */ ADDING_DATA_SOURCE_FAILED, /** * A new data source or series of data sources have been added to the * current case. The old value of the PropertyChangeEvent is null, the * new value is the newly-added data source (type: Content). Cast the * PropertyChangeEvent to * org.sleuthkit.autopsy.casemodule.events.DataSourceAddedEvent to * access additional event data. */ DATA_SOURCE_ADDED, /** * A data source has been deleted from the current case. The old value * of the PropertyChangeEvent is the object id of the data source that * was deleted (type: Long), the new value is null. */ DATA_SOURCE_DELETED, /** * A data source's name has changed. The new value of the property * change event is the new name. */ DATA_SOURCE_NAME_CHANGED, /** * The current case has changed. * * If a new case has been opened as the current case, the old value of * the PropertyChangeEvent is null, and the new value is the new case * (type: Case). * * If the current case has been closed, the old value of the * PropertyChangeEvent is the closed case (type: Case), and the new * value is null. IMPORTANT: Subscribers to this event should not call * isCaseOpen or getCurrentCase in the interval between a case closed * event and a case opened event. If there is any need for upon closing * interaction with a closed case, the case in the old value should be * used, and it should be done synchronously in the CURRENT_CASE event * handler. */ CURRENT_CASE, /** * A report has been added to the current case. The old value of the * PropertyChangeEvent is null, the new value is the report (type: * Report). */ REPORT_ADDED, /** * A report has been deleted from the current case. The old value of the * PropertyChangeEvent is the report (type: Report), the new value is * null. */ REPORT_DELETED, /** * An artifact associated with the current case has been tagged. The old * value of the PropertyChangeEvent is null, the new value is the tag * (type: BlackBoardArtifactTag). */ BLACKBOARD_ARTIFACT_TAG_ADDED, /** * A tag has been removed from an artifact associated with the current * case. The old value of the PropertyChangeEvent is the tag info (type: * BlackBoardArtifactTagDeletedEvent.DeletedBlackboardArtifactTagInfo), * the new value is null. */ BLACKBOARD_ARTIFACT_TAG_DELETED, /** * Content associated with the current case has been tagged. The old * value of the PropertyChangeEvent is null, the new value is the tag * (type: ContentTag). */ CONTENT_TAG_ADDED, /** * A tag has been removed from content associated with the current case. * The old value of the PropertyChangeEvent is is the tag info (type: * ContentTagDeletedEvent.DeletedContentTagInfo), the new value is null. */ CONTENT_TAG_DELETED, /** * The case display name or an optional detail which can be provided * regarding a case has been changed. The optional details include the * case number, the examiner name, examiner phone, examiner email, and * the case notes. */ CASE_DETAILS, /** * A tag definition has changed (e.g., description, known status). The * old value of the PropertyChangeEvent is the display name of the tag * definition that has changed. */ TAG_DEFINITION_CHANGED, /** * An timeline event, such mac time or web activity was added to the * current case. The old value is null and the new value is the * TimelineEvent that was added. */ TIMELINE_EVENT_ADDED, /* * An item in the central repository has had its comment modified. The * old value is null, the new value is string for current comment. */ CR_COMMENT_CHANGED; }; /** * An instance of this class is registered as a listener on the event bus * associated with the case database so that selected SleuthKit layer * application events can be published as Autopsy application events. */ private final class SleuthkitEventListener { @Subscribe public void publishTimelineEventAddedEvent(TimelineManager.TimelineEventAddedEvent event) { eventPublisher.publish(new TimelineEventAddedEvent(event)); } @SuppressWarnings("deprecation") @Subscribe public void publishArtifactsPostedEvent(Blackboard.ArtifactsPostedEvent event) { for (BlackboardArtifact.Type artifactType : event.getArtifactTypes()) { /* * IngestServices.fireModuleDataEvent is deprecated to * discourage ingest module writers from using it (they should * use org.sleuthkit.datamodel.Blackboard.postArtifact(s) * instead), but a way to publish * Blackboard.ArtifactsPostedEvents from the SleuthKit layer as * Autopsy ModuleDataEvents is still needed. */ IngestServices.getInstance().fireModuleDataEvent(new ModuleDataEvent( event.getModuleName(), artifactType, event.getArtifacts(artifactType))); } } } /** * Adds a subscriber to all case events. To subscribe to only specific * events, use one of the overloads of addEventSubscriber. * * @param listener The subscriber (PropertyChangeListener) to add. */ public static void addPropertyChangeListener(PropertyChangeListener listener) { addEventSubscriber(Stream.of(Events.values()) .map(Events::toString) .collect(Collectors.toSet()), listener); } /** * Removes a subscriber to all case events. To remove a subscription to only * specific events, use one of the overloads of removeEventSubscriber. * * @param listener The subscriber (PropertyChangeListener) to remove. */ public static void removePropertyChangeListener(PropertyChangeListener listener) { removeEventSubscriber(Stream.of(Events.values()) .map(Events::toString) .collect(Collectors.toSet()), listener); } /** * Adds a subscriber to specific case events. * * @param eventNames The events the subscriber is interested in. * @param subscriber The subscriber (PropertyChangeListener) to add. * * @deprecated Use addEventTypeSubscriber instead. */ @Deprecated public static void addEventSubscriber(Set<String> eventNames, PropertyChangeListener subscriber) { eventPublisher.addSubscriber(eventNames, subscriber); } /** * Adds a subscriber to specific case events. * * @param eventTypes The events the subscriber is interested in. * @param subscriber The subscriber (PropertyChangeListener) to add. */ public static void addEventTypeSubscriber(Set<Events> eventTypes, PropertyChangeListener subscriber) { eventTypes.forEach((Events event) -> { eventPublisher.addSubscriber(event.toString(), subscriber); }); } /** * Adds a subscriber to specific case events. * * @param eventName The event the subscriber is interested in. * @param subscriber The subscriber (PropertyChangeListener) to add. * * @deprecated Use addEventTypeSubscriber instead. */ @Deprecated public static void addEventSubscriber(String eventName, PropertyChangeListener subscriber) { eventPublisher.addSubscriber(eventName, subscriber); } /** * Removes a subscriber to specific case events. * * @param eventName The event the subscriber is no longer interested in. * @param subscriber The subscriber (PropertyChangeListener) to remove. */ public static void removeEventSubscriber(String eventName, PropertyChangeListener subscriber) { eventPublisher.removeSubscriber(eventName, subscriber); } /** * Removes a subscriber to specific case events. * * @param eventNames The event the subscriber is no longer interested in. * @param subscriber The subscriber (PropertyChangeListener) to remove. */ public static void removeEventSubscriber(Set<String> eventNames, PropertyChangeListener subscriber) { eventPublisher.removeSubscriber(eventNames, subscriber); } /** * Removes a subscriber to specific case events. * * @param eventTypes The events the subscriber is no longer interested in. * @param subscriber The subscriber (PropertyChangeListener) to remove. */ public static void removeEventTypeSubscriber(Set<Events> eventTypes, PropertyChangeListener subscriber) { eventTypes.forEach((Events event) -> { eventPublisher.removeSubscriber(event.toString(), subscriber); }); } /** * Checks if a case display name is valid, i.e., does not include any * characters that cannot be used in file names. * * @param caseName The candidate case name. * * @return True or false. */ public static boolean isValidName(String caseName) { return !(caseName.contains("\\") || caseName.contains("/") || caseName.contains(":") || caseName.contains("*") || caseName.contains("?") || caseName.contains("\"") || caseName.contains("<") || caseName.contains(">") || caseName.contains("|")); } /** * Creates a new case and makes it the current case. * * IMPORTANT: This method should not be called in the event dispatch thread * (EDT). * * @param caseDir The full path of the case directory. The directory * will be created if it doesn't already exist; if it * exists, it is ASSUMED it was created by calling * createCaseDirectory. * @param caseDisplayName The display name of case, which may be changed * later by the user. * @param caseNumber The case number, can be the empty string. * @param examiner The examiner to associate with the case, can be * the empty string. * @param caseType The type of case (single-user or multi-user). * * @throws CaseActionException If there is a problem creating the * case. * @throws CaseActionCancelledException If creating the case is cancelled. * * @deprecated use createAsCurrentCase(CaseType caseType, String caseDir, * CaseDetails caseDetails) instead */ @Deprecated public static void createAsCurrentCase(String caseDir, String caseDisplayName, String caseNumber, String examiner, CaseType caseType) throws CaseActionException, CaseActionCancelledException { createAsCurrentCase(caseType, caseDir, new CaseDetails(caseDisplayName, caseNumber, examiner, "", "", "")); } /** * Creates a new case and makes it the current case. * * IMPORTANT: This method should not be called in the event dispatch thread * (EDT). * * @param caseDir The full path of the case directory. The directory * will be created if it doesn't already exist; if it * exists, it is ASSUMED it was created by calling * createCaseDirectory. * @param caseType The type of case (single-user or multi-user). * @param caseDetails Contains the modifiable details of the case such as * the case display name, the case number, and the * examiner related data. * * @throws CaseActionException If there is a problem creating the * case. * @throws CaseActionCancelledException If creating the case is cancelled. */ @Messages({ "Case.exceptionMessage.emptyCaseName=Must specify a case name.", "Case.exceptionMessage.emptyCaseDir=Must specify a case directory path." }) public static void createAsCurrentCase(CaseType caseType, String caseDir, CaseDetails caseDetails) throws CaseActionException, CaseActionCancelledException { if (caseDetails.getCaseDisplayName().isEmpty()) { throw new CaseActionException(Bundle.Case_exceptionMessage_emptyCaseName()); } if (caseDir.isEmpty()) { throw new CaseActionException(Bundle.Case_exceptionMessage_emptyCaseDir()); } openAsCurrentCase(new Case(caseType, caseDir, caseDetails), true); } /** * Opens an existing case and makes it the current case. * * IMPORTANT: This method should not be called in the event dispatch thread * (EDT). * * @param caseMetadataFilePath The path of the case metadata (.aut) file. * * @throws CaseActionException If there is a problem opening the case. The * exception will have a user-friendly message * and may be a wrapper for a lower-level * exception. */ @Messages({ "# {0} - exception message", "Case.exceptionMessage.failedToReadMetadata=Failed to read case metadata:\n{0}.", "Case.exceptionMessage.cannotOpenMultiUserCaseNoSettings=Multi-user settings are missing (see Tools, Options, Multi-user tab), cannot open a multi-user case." }) public static void openAsCurrentCase(String caseMetadataFilePath) throws CaseActionException { CaseMetadata metadata; try { metadata = new CaseMetadata(Paths.get(caseMetadataFilePath)); } catch (CaseMetadataException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_failedToReadMetadata(ex.getLocalizedMessage()), ex); } if (CaseType.MULTI_USER_CASE == metadata.getCaseType() && !UserPreferences.getIsMultiUserModeEnabled()) { throw new CaseActionException(Bundle.Case_exceptionMessage_cannotOpenMultiUserCaseNoSettings()); } openAsCurrentCase(new Case(metadata), false); } /** * Checks if a case, the current case, is open at the time it is called. * * @return True or false. */ public static boolean isCaseOpen() { return currentCase != null; } /** * Gets the current case. This method should only be called by clients that * can be sure a case is currently open. Some examples of suitable clients * are data source processors, ingest modules, and report modules. * * @return The current case. */ public static Case getCurrentCase() { try { return getCurrentCaseThrows(); } catch (NoCurrentCaseException ex) { /* * Throw a runtime exception, since this is a programming error. */ throw new IllegalStateException(NbBundle.getMessage(Case.class, "Case.getCurCase.exception.noneOpen"), ex); } } /** * Gets the current case, if there is one, or throws an exception if there * is no current case. This method should only be called by methods known to * run in threads where it is possible that another thread has closed the * current case. The exception provides some protection from the * consequences of the race condition between the calling thread and a case * closing thread, but it is not fool-proof. Background threads calling this * method should put all operations in an exception firewall with a try and * catch-all block to handle the possibility of bad timing. * * @return The current case. * * @throws NoCurrentCaseException if there is no current case. */ public static Case getCurrentCaseThrows() throws NoCurrentCaseException { /* * TODO (JIRA-3825): Introduce a reference counting scheme for this get * case method. */ Case openCase = currentCase; if (openCase == null) { throw new NoCurrentCaseException(NbBundle.getMessage(Case.class, "Case.getCurCase.exception.noneOpen")); } else { return openCase; } } /** * Closes the current case. * * @throws CaseActionException If there is a problem closing the case. The * exception will have a user-friendly message * and may be a wrapper for a lower-level * exception. */ @Messages({ "# {0} - exception message", "Case.closeException.couldNotCloseCase=Error closing case: {0}", "Case.progressIndicatorTitle.closingCase=Closing Case" }) public static void closeCurrentCase() throws CaseActionException { synchronized (caseActionSerializationLock) { if (null == currentCase) { return; } Case closedCase = currentCase; try { eventPublisher.publishLocally(new AutopsyEvent(Events.CURRENT_CASE.toString(), closedCase, null)); logger.log(Level.INFO, "Closing current case {0} ({1}) in {2}", new Object[]{closedCase.getDisplayName(), closedCase.getName(), closedCase.getCaseDirectory()}); //NON-NLS currentCase = null; closedCase.doCloseCaseAction(); logger.log(Level.INFO, "Closed current case {0} ({1}) in {2}", new Object[]{closedCase.getDisplayName(), closedCase.getName(), closedCase.getCaseDirectory()}); //NON-NLS } catch (CaseActionException ex) { logger.log(Level.SEVERE, String.format("Error closing current case %s (%s) in %s", closedCase.getDisplayName(), closedCase.getName(), closedCase.getCaseDirectory()), ex); //NON-NLS throw ex; } finally { if (RuntimeProperties.runningWithGUI()) { updateGUIForCaseClosed(); } } } } /** * Deletes the current case. * * @throws CaseActionException If there is a problem deleting the case. The * exception will have a user-friendly message * and may be a wrapper for a lower-level * exception. */ public static void deleteCurrentCase() throws CaseActionException { synchronized (caseActionSerializationLock) { if (null == currentCase) { return; } CaseMetadata metadata = currentCase.getMetadata(); closeCurrentCase(); deleteCase(metadata); } } /** * Deletes a data source from the current case. * * @param dataSourceObjectID The object ID of the data source to delete. * * @throws CaseActionException If there is a problem deleting the case. The * exception will have a user-friendly message * and may be a wrapper for a lower-level * exception. */ @Messages({ "Case.progressIndicatorTitle.deletingDataSource=Removing Data Source" }) static void deleteDataSourceFromCurrentCase(Long dataSourceObjectID) throws CaseActionException { synchronized (caseActionSerializationLock) { if (null == currentCase) { return; } /* * Close the current case to release the shared case lock. */ CaseMetadata caseMetadata = currentCase.getMetadata(); closeCurrentCase(); /* * Re-open the case with an exclusive case lock, delete the data * source, and close the case again, releasing the exclusive case * lock. */ Case theCase = new Case(caseMetadata); theCase.doOpenCaseAction(Bundle.Case_progressIndicatorTitle_deletingDataSource(), theCase::deleteDataSource, CaseLockType.EXCLUSIVE, false, dataSourceObjectID); /* * Re-open the case with a shared case lock. */ openAsCurrentCase(new Case(caseMetadata), false); } } /** * Deletes a case. The case to be deleted must not be the "current case." * Deleting the current case must be done by calling Case.deleteCurrentCase. * * @param metadata The case metadata. * * @throws CaseActionException If there were one or more errors deleting the * case. The exception will have a user-friendly * message and may be a wrapper for a * lower-level exception. */ @Messages({ "Case.progressIndicatorTitle.deletingCase=Deleting Case", "Case.exceptionMessage.cannotDeleteCurrentCase=Cannot delete current case, it must be closed first.", "# {0} - case display name", "Case.exceptionMessage.deletionInterrupted=Deletion of the case {0} was cancelled." }) public static void deleteCase(CaseMetadata metadata) throws CaseActionException { synchronized (caseActionSerializationLock) { if (null != currentCase) { throw new CaseActionException(Bundle.Case_exceptionMessage_cannotDeleteCurrentCase()); } } ProgressIndicator progressIndicator; if (RuntimeProperties.runningWithGUI()) { progressIndicator = new ModalDialogProgressIndicator(mainFrame, Bundle.Case_progressIndicatorTitle_deletingCase()); } else { progressIndicator = new LoggingProgressIndicator(); } progressIndicator.start(Bundle.Case_progressMessage_preparing()); try { if (CaseType.SINGLE_USER_CASE == metadata.getCaseType()) { deleteSingleUserCase(metadata, progressIndicator); } else { try { deleteMultiUserCase(metadata, progressIndicator); } catch (InterruptedException ex) { /* * Note that task cancellation is not currently supported * for this code path, so this catch block is not expected * to be executed. */ throw new CaseActionException(Bundle.Case_exceptionMessage_deletionInterrupted(metadata.getCaseDisplayName()), ex); } } } finally { progressIndicator.finish(); } } /** * Opens a new or existing case as the current case. * * @param newCurrentCase The case. * @param isNewCase True for a new case, false otherwise. * * @throws CaseActionException If there is a problem creating the * case. * @throws CaseActionCancelledException If creating the case is cancelled. */ @Messages({ "Case.progressIndicatorTitle.creatingCase=Creating Case", "Case.progressIndicatorTitle.openingCase=Opening Case", "Case.exceptionMessage.cannotLocateMainWindow=Cannot locate main application window" }) private static void openAsCurrentCase(Case newCurrentCase, boolean isNewCase) throws CaseActionException, CaseActionCancelledException { synchronized (caseActionSerializationLock) { if (null != currentCase) { try { closeCurrentCase(); } catch (CaseActionException ex) { /* * Notify the user and continue (the error has already been * logged in closeCurrentCase. */ MessageNotifyUtil.Message.error(ex.getLocalizedMessage()); } } try { logger.log(Level.INFO, "Opening {0} ({1}) in {2} as the current case", new Object[]{newCurrentCase.getDisplayName(), newCurrentCase.getName(), newCurrentCase.getCaseDirectory()}); //NON-NLS String progressIndicatorTitle; CaseAction<ProgressIndicator, Object, Void> openCaseAction; if (isNewCase) { progressIndicatorTitle = Bundle.Case_progressIndicatorTitle_creatingCase(); openCaseAction = newCurrentCase::create; } else { progressIndicatorTitle = Bundle.Case_progressIndicatorTitle_openingCase(); openCaseAction = newCurrentCase::open; } newCurrentCase.doOpenCaseAction(progressIndicatorTitle, openCaseAction, CaseLockType.SHARED, true, null); currentCase = newCurrentCase; logger.log(Level.INFO, "Opened {0} ({1}) in {2} as the current case", new Object[]{newCurrentCase.getDisplayName(), newCurrentCase.getName(), newCurrentCase.getCaseDirectory()}); //NON-NLS if (RuntimeProperties.runningWithGUI()) { updateGUIForCaseOpened(newCurrentCase); } eventPublisher.publishLocally(new AutopsyEvent(Events.CURRENT_CASE.toString(), null, currentCase)); } catch (CaseActionCancelledException ex) { logger.log(Level.INFO, String.format("Cancelled opening %s (%s) in %s as the current case", newCurrentCase.getDisplayName(), newCurrentCase.getName(), newCurrentCase.getCaseDirectory())); //NON-NLS throw ex; } catch (CaseActionException ex) { logger.log(Level.SEVERE, String.format("Error opening %s (%s) in %s as the current case", newCurrentCase.getDisplayName(), newCurrentCase.getName(), newCurrentCase.getCaseDirectory()), ex); //NON-NLS throw ex; } } } /** * Transforms a case display name into a unique case name that can be used * to identify the case even if the display name is changed. * * @param caseDisplayName A case display name. * * @return The unique case name. */ private static String displayNameToUniqueName(String caseDisplayName) { /* * Replace all non-ASCII characters. */ String uniqueCaseName = caseDisplayName.replaceAll("[^\\p{ASCII}]", "_"); //NON-NLS /* * Replace all control characters. */ uniqueCaseName = uniqueCaseName.replaceAll("[\\p{Cntrl}]", "_"); //NON-NLS /* * Replace /, \, :, ?, space, ' ". */ uniqueCaseName = uniqueCaseName.replaceAll("[ /?:'\"\\\\]", "_"); //NON-NLS /* * Make it all lowercase. */ uniqueCaseName = uniqueCaseName.toLowerCase(); /* * Add a time stamp for uniqueness. */ SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss"); Date date = new Date(); uniqueCaseName = uniqueCaseName + "_" + dateFormat.format(date); return uniqueCaseName; } /** * Creates a case directory and its subdirectories. * * @param caseDirPath Path to the case directory (typically base + case * name). * @param caseType The type of case, single-user or multi-user. * * @throws CaseActionException throw if could not create the case dir */ public static void createCaseDirectory(String caseDirPath, CaseType caseType) throws CaseActionException { /* * Check the case directory path and permissions. The case directory may * already exist. */ File caseDir = new File(caseDirPath); if (caseDir.exists()) { if (caseDir.isFile()) { throw new CaseActionException(NbBundle.getMessage(Case.class, "Case.createCaseDir.exception.existNotDir", caseDirPath)); } else if (!caseDir.canRead() || !caseDir.canWrite()) { throw new CaseActionException(NbBundle.getMessage(Case.class, "Case.createCaseDir.exception.existCantRW", caseDirPath)); } } /* * Create the case directory, if it does not already exist. */ if (!caseDir.mkdirs()) { throw new CaseActionException(NbBundle.getMessage(Case.class, "Case.createCaseDir.exception.cantCreate", caseDirPath)); } /* * Create the subdirectories of the case directory, if they do not * already exist. Note that multi-user cases get an extra layer of * subdirectories, one subdirectory per application host machine. */ String hostPathComponent = ""; if (caseType == CaseType.MULTI_USER_CASE) { hostPathComponent = File.separator + NetworkUtils.getLocalHostName(); } Path exportDir = Paths.get(caseDirPath, hostPathComponent, EXPORT_FOLDER); if (!exportDir.toFile().mkdirs()) { throw new CaseActionException(NbBundle.getMessage(Case.class, "Case.createCaseDir.exception.cantCreateCaseDir", exportDir)); } Path logsDir = Paths.get(caseDirPath, hostPathComponent, LOG_FOLDER); if (!logsDir.toFile().mkdirs()) { throw new CaseActionException(NbBundle.getMessage(Case.class, "Case.createCaseDir.exception.cantCreateCaseDir", logsDir)); } Path tempDir = Paths.get(caseDirPath, hostPathComponent, TEMP_FOLDER); if (!tempDir.toFile().mkdirs()) { throw new CaseActionException(NbBundle.getMessage(Case.class, "Case.createCaseDir.exception.cantCreateCaseDir", tempDir)); } Path cacheDir = Paths.get(caseDirPath, hostPathComponent, CACHE_FOLDER); if (!cacheDir.toFile().mkdirs()) { throw new CaseActionException(NbBundle.getMessage(Case.class, "Case.createCaseDir.exception.cantCreateCaseDir", cacheDir)); } Path moduleOutputDir = Paths.get(caseDirPath, hostPathComponent, MODULE_FOLDER); if (!moduleOutputDir.toFile().mkdirs()) { throw new CaseActionException(NbBundle.getMessage(Case.class, "Case.createCaseDir.exception.cantCreateModDir", moduleOutputDir)); } Path reportsDir = Paths.get(caseDirPath, hostPathComponent, REPORTS_FOLDER); if (!reportsDir.toFile().mkdirs()) { throw new CaseActionException(NbBundle.getMessage(Case.class, "Case.createCaseDir.exception.cantCreateReportsDir", reportsDir)); } } /** * Gets the paths of data sources that are images. * * @param db A case database. * * @return A mapping of object ids to image paths. */ static Map<Long, String> getImagePaths(SleuthkitCase db) { Map<Long, String> imgPaths = new HashMap<>(); try { Map<Long, List<String>> imgPathsList = db.getImagePaths(); for (Map.Entry<Long, List<String>> entry : imgPathsList.entrySet()) { if (entry.getValue().size() > 0) { imgPaths.put(entry.getKey(), entry.getValue().get(0)); } } } catch (TskCoreException ex) { logger.log(Level.SEVERE, "Error getting image paths", ex); //NON-NLS } return imgPaths; } /** * Acquires an exclusive case resources lock. * * @param caseDir The full path of the case directory. * * @return The lock or null if the lock could not be acquired. * * @throws CaseActionException with a user-friendly message if the lock * cannot be acquired due to an exception. */ @Messages({ "Case.creationException.couldNotAcquireResourcesLock=Failed to get lock on case resources" }) private static CoordinationService.Lock acquireCaseResourcesLock(String caseDir) throws CaseActionException { try { Path caseDirPath = Paths.get(caseDir); String resourcesNodeName = CoordinationServiceUtils.getCaseResourcesNodePath(caseDirPath); Lock lock = CoordinationService.getInstance().tryGetExclusiveLock(CategoryNode.CASES, resourcesNodeName, CASE_RESOURCES_LOCK_TIMEOUT_HOURS, TimeUnit.HOURS); return lock; } catch (InterruptedException ex) { throw new CaseActionCancelledException(Bundle.Case_exceptionMessage_cancelled()); } catch (CoordinationServiceException ex) { throw new CaseActionException(Bundle.Case_creationException_couldNotAcquireResourcesLock(), ex); } } private static String getNameForTitle() { //Method should become unnecessary once technical debt story 3334 is done. if (UserPreferences.getAppName().equals(Version.getName())) { //Available version number is version number for this application return String.format("%s %s", UserPreferences.getAppName(), Version.getVersion()); } else { return UserPreferences.getAppName(); } } /** * Update the GUI to to reflect the current case. */ private static void updateGUIForCaseOpened(Case newCurrentCase) { if (RuntimeProperties.runningWithGUI()) { SwingUtilities.invokeLater(() -> { /* * If the case database was upgraded for a new schema and a * backup database was created, notify the user. */ SleuthkitCase caseDb = newCurrentCase.getSleuthkitCase(); String backupDbPath = caseDb.getBackupDatabasePath(); if (null != backupDbPath) { JOptionPane.showMessageDialog( mainFrame, NbBundle.getMessage(Case.class, "Case.open.msgDlg.updated.msg", backupDbPath), NbBundle.getMessage(Case.class, "Case.open.msgDlg.updated.title"), JOptionPane.INFORMATION_MESSAGE); } /* * Look for the files for the data sources listed in the case * database and give the user the opportunity to locate any that * are missing. */ Map<Long, String> imgPaths = getImagePaths(caseDb); for (Map.Entry<Long, String> entry : imgPaths.entrySet()) { long obj_id = entry.getKey(); String path = entry.getValue(); boolean fileExists = (new File(path).isFile() || DriveUtils.driveExists(path)); if (!fileExists) { int response = JOptionPane.showConfirmDialog( mainFrame, NbBundle.getMessage(Case.class, "Case.checkImgExist.confDlg.doesntExist.msg", path), NbBundle.getMessage(Case.class, "Case.checkImgExist.confDlg.doesntExist.title"), JOptionPane.YES_NO_OPTION); if (response == JOptionPane.YES_OPTION) { MissingImageDialog.makeDialog(obj_id, caseDb); } else { logger.log(Level.SEVERE, "User proceeding with missing image files"); //NON-NLS } } } /* * Enable the case-specific actions. */ CallableSystemAction.get(AddImageAction.class).setEnabled(FeatureAccessUtils.canAddDataSources()); CallableSystemAction.get(CaseCloseAction.class).setEnabled(true); CallableSystemAction.get(CaseDetailsAction.class).setEnabled(true); CallableSystemAction.get(DataSourceSummaryAction.class).setEnabled(true); CallableSystemAction.get(CaseDeleteAction.class).setEnabled(FeatureAccessUtils.canDeleteCurrentCase()); CallableSystemAction.get(OpenTimelineAction.class).setEnabled(true); CallableSystemAction.get(OpenCommVisualizationToolAction.class).setEnabled(true); CallableSystemAction.get(CommonAttributeSearchAction.class).setEnabled(true); CallableSystemAction.get(OpenOutputFolderAction.class).setEnabled(false); CallableSystemAction.get(OpenFileDiscoveryAction.class).setEnabled(true); /* * Add the case to the recent cases tracker that supplies a list * of recent cases to the recent cases menu item and the * open/create case dialog. */ RecentCases.getInstance().addRecentCase(newCurrentCase.getDisplayName(), newCurrentCase.getMetadata().getFilePath().toString()); /* * Open the top components (windows within the main application * window). * * Note: If the core windows are not opened here, they will be * opened via the DirectoryTreeTopComponent 'propertyChange()' * method on a DATA_SOURCE_ADDED event. */ if (newCurrentCase.hasData()) { CoreComponentControl.openCoreWindows(); } /* * Reset the main window title to: * * [curent case display name] - [application name]. */ mainFrame.setTitle(newCurrentCase.getDisplayName() + " - " + getNameForTitle()); }); } } /* * Update the GUI to to reflect the lack of a current case. */ private static void updateGUIForCaseClosed() { if (RuntimeProperties.runningWithGUI()) { SwingUtilities.invokeLater(() -> { /* * Close the top components (windows within the main application * window). */ CoreComponentControl.closeCoreWindows(); /* * Disable the case-specific menu items. */ CallableSystemAction.get(AddImageAction.class).setEnabled(false); CallableSystemAction.get(CaseCloseAction.class).setEnabled(false); CallableSystemAction.get(CaseDetailsAction.class).setEnabled(false); CallableSystemAction.get(DataSourceSummaryAction.class).setEnabled(false); CallableSystemAction.get(CaseDeleteAction.class).setEnabled(false); CallableSystemAction.get(OpenTimelineAction.class).setEnabled(false); CallableSystemAction.get(OpenCommVisualizationToolAction.class).setEnabled(false); CallableSystemAction.get(OpenOutputFolderAction.class).setEnabled(false); CallableSystemAction.get(CommonAttributeSearchAction.class).setEnabled(false); CallableSystemAction.get(OpenFileDiscoveryAction.class).setEnabled(false); /* * Clear the notifications in the notfier component in the lower * right hand corner of the main application window. */ MessageNotifyUtil.Notify.clear(); /* * Reset the main window title to be just the application name, * instead of [curent case display name] - [application name]. */ mainFrame.setTitle(getNameForTitle()); }); } } /** * Empties the temp subdirectory for the current case. */ private static void clearTempSubDir(String tempSubDirPath) { File tempFolder = new File(tempSubDirPath); if (tempFolder.isDirectory()) { File[] files = tempFolder.listFiles(); if (files.length > 0) { for (File file : files) { if (file.isDirectory()) { FileUtil.deleteDir(file); } else { file.delete(); } } } } } /** * Gets the case database. * * @return The case database. */ public SleuthkitCase getSleuthkitCase() { return this.caseDb; } /** * Gets the case services manager. * * @return The case services manager. */ public Services getServices() { return caseServices; } /** * Gets the case type. * * @return The case type. */ public CaseType getCaseType() { return metadata.getCaseType(); } /** * Gets the case create date. * * @return case The case create date. */ public String getCreatedDate() { return metadata.getCreatedDate(); } /** * Gets the unique and immutable case name. * * @return The case name. */ public String getName() { return metadata.getCaseName(); } /** * Gets the case name that can be changed by the user. * * @return The case display name. */ public String getDisplayName() { return metadata.getCaseDisplayName(); } /** * Gets the case number. * * @return The case number */ public String getNumber() { return metadata.getCaseNumber(); } /** * Gets the examiner name. * * @return The examiner name. */ public String getExaminer() { return metadata.getExaminer(); } /** * Gets the examiner phone number. * * @return The examiner phone number. */ public String getExaminerPhone() { return metadata.getExaminerPhone(); } /** * Gets the examiner email address. * * @return The examiner email address. */ public String getExaminerEmail() { return metadata.getExaminerEmail(); } /** * Gets the case notes. * * @return The case notes. */ public String getCaseNotes() { return metadata.getCaseNotes(); } /** * Gets the path to the top-level case directory. * * @return The top-level case directory path. */ public String getCaseDirectory() { return metadata.getCaseDirectory(); } /** * Gets the root case output directory for this case, creating it if it does * not exist. If the case is a single-user case, this is the case directory. * If the case is a multi-user case, this is a subdirectory of the case * directory specific to the host machine. * * @return the path to the host output directory. */ public String getOutputDirectory() { String caseDirectory = getCaseDirectory(); Path hostPath; if (CaseType.MULTI_USER_CASE == metadata.getCaseType()) { hostPath = Paths.get(caseDirectory, NetworkUtils.getLocalHostName()); } else { hostPath = Paths.get(caseDirectory); } if (!hostPath.toFile().exists()) { hostPath.toFile().mkdirs(); } return hostPath.toString(); } /** * Gets the full path to the temp directory for this case, creating it if it * does not exist. * * @return The temp subdirectory path. */ public String getTempDirectory() { return getOrCreateSubdirectory(TEMP_FOLDER); } /** * Gets the full path to the cache directory for this case, creating it if * it does not exist. * * @return The cache directory path. */ public String getCacheDirectory() { return getOrCreateSubdirectory(CACHE_FOLDER); } /** * Gets the full path to the export directory for this case, creating it if * it does not exist. * * @return The export directory path. */ public String getExportDirectory() { return getOrCreateSubdirectory(EXPORT_FOLDER); } /** * Gets the full path to the log directory for this case, creating it if it * does not exist. * * @return The log directory path. */ public String getLogDirectoryPath() { return getOrCreateSubdirectory(LOG_FOLDER); } /** * Gets the full path to the reports directory for this case, creating it if * it does not exist. * * @return The report directory path. */ public String getReportDirectory() { return getOrCreateSubdirectory(REPORTS_FOLDER); } /** * Gets the full path to the config directory for this case, creating it if * it does not exist. * * @return The config directory path. */ public String getConfigDirectory() { return getOrCreateSubdirectory(CONFIG_FOLDER); } /** * Gets the full path to the module output directory for this case, creating * it if it does not exist. * * @return The module output directory path. */ public String getModuleDirectory() { return getOrCreateSubdirectory(MODULE_FOLDER); } /** * Gets the path of the module output directory for this case, relative to * the case directory, creating it if it does not exist. * * @return The path to the module output directory, relative to the case * directory. */ public String getModuleOutputDirectoryRelativePath() { Path path = Paths.get(getModuleDirectory()); if (getCaseType() == CaseType.MULTI_USER_CASE) { return path.subpath(path.getNameCount() - 2, path.getNameCount()).toString(); } else { return path.subpath(path.getNameCount() - 1, path.getNameCount()).toString(); } } /** * Gets the data sources for the case. * * @return A list of data sources, possibly empty. * * @throws org.sleuthkit.datamodel.TskCoreException if there is a problem * querying the case * database. */ public List<Content> getDataSources() throws TskCoreException { return caseDb.getRootObjects(); } /** * Gets the time zone(s) of the image data source(s) in this case. * * @return The set of time zones in use. */ public Set<TimeZone> getTimeZones() { Set<TimeZone> timezones = new HashSet<>(); try { for (Content c : getDataSources()) { final Content dataSource = c.getDataSource(); if ((dataSource != null) && (dataSource instanceof Image)) { Image image = (Image) dataSource; timezones.add(TimeZone.getTimeZone(image.getTimeZone())); } } } catch (TskCoreException ex) { logger.log(Level.SEVERE, "Error getting data source time zones", ex); //NON-NLS } return timezones; } /** * Gets the name of the legacy keyword search index for the case. Not for * general use. * * @return The index name. */ public String getTextIndexName() { return getMetadata().getTextIndexName(); } /** * Queries whether or not the case has data, i.e., whether or not at least * one data source has been added to the case. * * @return True or false. */ public boolean hasData() { boolean hasDataSources = false; try { hasDataSources = (getDataSources().size() > 0); } catch (TskCoreException ex) { logger.log(Level.SEVERE, "Error accessing case database", ex); //NON-NLS } return hasDataSources; } /** * Notifies case event subscribers that a data source is being added to the * case. * * This should not be called from the event dispatch thread (EDT) * * @param eventId A unique identifier for the event. This UUID must be used * to call notifyFailedAddingDataSource or * notifyNewDataSource after the data source is added. */ public void notifyAddingDataSource(UUID eventId) { eventPublisher.publish(new AddingDataSourceEvent(eventId)); } /** * Notifies case event subscribers that a data source failed to be added to * the case. * * This should not be called from the event dispatch thread (EDT) * * @param addingDataSourceEventId The unique identifier for the * corresponding adding data source event * (see notifyAddingDataSource). */ public void notifyFailedAddingDataSource(UUID addingDataSourceEventId) { eventPublisher.publish(new AddingDataSourceFailedEvent(addingDataSourceEventId)); } /** * Notifies case event subscribers that a data source has been added to the * case database. * * This should not be called from the event dispatch thread (EDT) * * @param dataSource The data source. * @param addingDataSourceEventId The unique identifier for the * corresponding adding data source event * (see notifyAddingDataSource). */ public void notifyDataSourceAdded(Content dataSource, UUID addingDataSourceEventId) { eventPublisher.publish(new DataSourceAddedEvent(dataSource, addingDataSourceEventId)); } /** * Notifies case event subscribers that a data source has been added to the * case database. * * This should not be called from the event dispatch thread (EDT) * * @param dataSource The data source. * @param newName The new name for the data source */ public void notifyDataSourceNameChanged(Content dataSource, String newName) { eventPublisher.publish(new DataSourceNameChangedEvent(dataSource, newName)); } /** * Notifies case event subscribers that a content tag has been added. * * This should not be called from the event dispatch thread (EDT) * * @param newTag new ContentTag added */ public void notifyContentTagAdded(ContentTag newTag) { eventPublisher.publish(new ContentTagAddedEvent(newTag)); } /** * Notifies case event subscribers that a content tag has been deleted. * * This should not be called from the event dispatch thread (EDT) * * @param deletedTag ContentTag deleted */ public void notifyContentTagDeleted(ContentTag deletedTag) { eventPublisher.publish(new ContentTagDeletedEvent(deletedTag)); } /** * Notifies case event subscribers that a tag definition has changed. * * This should not be called from the event dispatch thread (EDT) * * @param changedTagName the name of the tag definition which was changed */ public void notifyTagDefinitionChanged(String changedTagName) { //leaving new value of changedTagName as null, because we do not currently support changing the display name of a tag. eventPublisher.publish(new AutopsyEvent(Events.TAG_DEFINITION_CHANGED.toString(), changedTagName, null)); } /** * Notifies case event subscribers that a central repository comment has * been changed. * * This should not be called from the event dispatch thread (EDT) * * @param contentId the objectId for the Content which has had its central * repo comment changed * @param newComment the new value of the comment */ public void notifyCentralRepoCommentChanged(long contentId, String newComment) { try { eventPublisher.publish(new CommentChangedEvent(contentId, newComment)); } catch (NoCurrentCaseException ex) { logger.log(Level.WARNING, "Unable to send notifcation regarding comment change due to no current case being open", ex); } } /** * Notifies case event subscribers that an artifact tag has been added. * * This should not be called from the event dispatch thread (EDT) * * @param newTag new BlackboardArtifactTag added */ public void notifyBlackBoardArtifactTagAdded(BlackboardArtifactTag newTag) { eventPublisher.publish(new BlackBoardArtifactTagAddedEvent(newTag)); } /** * Notifies case event subscribers that an artifact tag has been deleted. * * This should not be called from the event dispatch thread (EDT) * * @param deletedTag BlackboardArtifactTag deleted */ public void notifyBlackBoardArtifactTagDeleted(BlackboardArtifactTag deletedTag) { eventPublisher.publish(new BlackBoardArtifactTagDeletedEvent(deletedTag)); } /** * Adds a report to the case. * * @param localPath The path of the report file, must be in the case * directory or one of its subdirectories. * @param srcModuleName The name of the module that created the report. * @param reportName The report name, may be empty. * * @throws TskCoreException if there is a problem adding the report to the * case database. */ public void addReport(String localPath, String srcModuleName, String reportName) throws TskCoreException { addReport(localPath, srcModuleName, reportName, null); } /** * Adds a report to the case. * * @param localPath The path of the report file, must be in the case * directory or one of its subdirectories. * @param srcModuleName The name of the module that created the report. * @param reportName The report name, may be empty. * @param parent The Content used to create the report, if available. * * @return The new Report instance. * * @throws TskCoreException if there is a problem adding the report to the * case database. */ public Report addReport(String localPath, String srcModuleName, String reportName, Content parent) throws TskCoreException { String normalizedLocalPath; try { if (localPath.toLowerCase().contains("http:")) { normalizedLocalPath = localPath; } else { normalizedLocalPath = Paths.get(localPath).normalize().toString(); } } catch (InvalidPathException ex) { String errorMsg = "Invalid local path provided: " + localPath; // NON-NLS throw new TskCoreException(errorMsg, ex); } Report report = this.caseDb.addReport(normalizedLocalPath, srcModuleName, reportName, parent); eventPublisher.publish(new ReportAddedEvent(report)); return report; } /** * Gets the reports that have been added to the case. * * @return A collection of report objects. * * @throws TskCoreException if there is a problem querying the case * database. */ public List<Report> getAllReports() throws TskCoreException { return this.caseDb.getAllReports(); } /** * Deletes one or more reports from the case database. Does not delete the * report files. * * @param reports The report(s) to be deleted from the case. * * @throws TskCoreException if there is an error deleting the report(s). */ public void deleteReports(Collection<? extends Report> reports) throws TskCoreException { for (Report report : reports) { this.caseDb.deleteReport(report); eventPublisher.publish(new AutopsyEvent(Events.REPORT_DELETED.toString(), report, null)); } } /** * Gets the case metadata. * * @return A CaseMetaData object. */ CaseMetadata getMetadata() { return metadata; } /** * Updates the case details. * * @param newDisplayName the new display name for the case * * @throws org.sleuthkit.autopsy.casemodule.CaseActionException */ @Messages({ "Case.exceptionMessage.metadataUpdateError=Failed to update case metadata" }) void updateCaseDetails(CaseDetails caseDetails) throws CaseActionException { CaseDetails oldCaseDetails = metadata.getCaseDetails(); try { metadata.setCaseDetails(caseDetails); } catch (CaseMetadataException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_metadataUpdateError(), ex); } if (getCaseType() == CaseType.MULTI_USER_CASE && !oldCaseDetails.getCaseDisplayName().equals(caseDetails.getCaseDisplayName())) { try { CaseNodeData nodeData = CaseNodeData.readCaseNodeData(metadata.getCaseDirectory()); nodeData.setDisplayName(caseDetails.getCaseDisplayName()); CaseNodeData.writeCaseNodeData(nodeData); } catch (CaseNodeDataException | InterruptedException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_couldNotUpdateCaseNodeData(ex.getLocalizedMessage()), ex); } } if (!oldCaseDetails.getCaseNumber().equals(caseDetails.getCaseNumber())) { eventPublisher.publish(new AutopsyEvent(Events.NUMBER.toString(), oldCaseDetails.getCaseNumber(), caseDetails.getCaseNumber())); } if (!oldCaseDetails.getExaminerName().equals(caseDetails.getExaminerName())) { eventPublisher.publish(new AutopsyEvent(Events.NUMBER.toString(), oldCaseDetails.getExaminerName(), caseDetails.getExaminerName())); } if (!oldCaseDetails.getCaseDisplayName().equals(caseDetails.getCaseDisplayName())) { eventPublisher.publish(new AutopsyEvent(Events.NAME.toString(), oldCaseDetails.getCaseDisplayName(), caseDetails.getCaseDisplayName())); } eventPublisher.publish(new AutopsyEvent(Events.CASE_DETAILS.toString(), oldCaseDetails, caseDetails)); if (RuntimeProperties.runningWithGUI()) { SwingUtilities.invokeLater(() -> { mainFrame.setTitle(caseDetails.getCaseDisplayName() + " - " + getNameForTitle()); try { RecentCases.getInstance().updateRecentCase(oldCaseDetails.getCaseDisplayName(), metadata.getFilePath().toString(), caseDetails.getCaseDisplayName(), metadata.getFilePath().toString()); } catch (Exception ex) { logger.log(Level.SEVERE, "Error updating case name in UI", ex); //NON-NLS } }); } } /** * Constructs a Case object for a new Autopsy case. * * @param caseType The type of case (single-user or multi-user). * @param caseDir The full path of the case directory. The directory * will be created if it doesn't already exist; if it * exists, it is ASSUMED it was created by calling * createCaseDirectory. * @param caseDetails Contains details of the case, such as examiner, * display name, etc * */ private Case(CaseType caseType, String caseDir, CaseDetails caseDetails) { this(new CaseMetadata(caseType, caseDir, displayNameToUniqueName(caseDetails.getCaseDisplayName()), caseDetails)); } /** * Constructs a Case object for an existing Autopsy case. * * @param caseMetaData The metadata for the case. */ private Case(CaseMetadata caseMetaData) { metadata = caseMetaData; sleuthkitEventListener = new SleuthkitEventListener(); } /** * Performs a case action that involves creating or opening a case. If the * case is a multi-user case, the action is done after acquiring a * coordination service case lock. This case lock must be released in the * same thread in which it was acquired, as required by the coordination * service. A single-threaded executor is therefore created to do the case * opening action, and is saved for an eventual case closing action. * * IMPORTANT: If an open case action for a multi-user case is terminated * because an exception is thrown or the action is cancelled, the action is * responsible for releasing the case lock while still running in the case * action executor's thread. This method assumes this has been done and * performs an orderly shut down of the case action executor. * * @param progressIndicatorTitle A title for the progress indicator for the * case action. * @param caseAction The case action method. * @param caseLockType The type of case lock required for the case * action. * @param allowCancellation Whether or not to allow the action to be * cancelled. * @param additionalParams An Object that holds any additional * parameters for a case action. * * @throws CaseActionException If there is a problem completing the action. * The exception will have a user-friendly * message and may be a wrapper for a * lower-level exception. */ @Messages({ "Case.progressIndicatorCancelButton.label=Cancel", "Case.progressMessage.preparing=Preparing...", "Case.progressMessage.cancelling=Cancelling...", "Case.exceptionMessage.cancelled=Cancelled.", "# {0} - exception message", "Case.exceptionMessage.execExceptionWrapperMessage={0}" }) private void doOpenCaseAction(String progressIndicatorTitle, CaseAction<ProgressIndicator, Object, Void> caseAction, CaseLockType caseLockType, boolean allowCancellation, Object additionalParams) throws CaseActionException { /* * Create and start either a GUI progress indicator (with or without a * cancel button) or a logging progress indicator. */ CancelButtonListener cancelButtonListener = null; ProgressIndicator progressIndicator; if (RuntimeProperties.runningWithGUI()) { if (allowCancellation) { cancelButtonListener = new CancelButtonListener(Bundle.Case_progressMessage_cancelling()); progressIndicator = new ModalDialogProgressIndicator( mainFrame, progressIndicatorTitle, new String[]{Bundle.Case_progressIndicatorCancelButton_label()}, Bundle.Case_progressIndicatorCancelButton_label(), cancelButtonListener); } else { progressIndicator = new ModalDialogProgressIndicator( mainFrame, progressIndicatorTitle); } } else { progressIndicator = new LoggingProgressIndicator(); } progressIndicator.start(Bundle.Case_progressMessage_preparing()); /* * Do the case action in the single thread in the case action executor. * If the case is a multi-user case, a case lock is acquired and held * until explictly released and an exclusive case resources lock is * aquired and held for the duration of the action. */ TaskThreadFactory threadFactory = new TaskThreadFactory(String.format(CASE_ACTION_THREAD_NAME, metadata.getCaseName())); caseActionExecutor = Executors.newSingleThreadExecutor(threadFactory); Future<Void> future = caseActionExecutor.submit(() -> { if (CaseType.SINGLE_USER_CASE == metadata.getCaseType()) { caseAction.execute(progressIndicator, additionalParams); } else { acquireCaseLock(caseLockType); try (CoordinationService.Lock resourcesLock = acquireCaseResourcesLock(metadata.getCaseDirectory())) { if (null == resourcesLock) { throw new CaseActionException(Bundle.Case_creationException_couldNotAcquireResourcesLock()); } caseAction.execute(progressIndicator, additionalParams); } catch (CaseActionException ex) { releaseCaseLock(); throw ex; } } return null; }); if (null != cancelButtonListener) { cancelButtonListener.setCaseActionFuture(future); } /* * Wait for the case action task to finish. */ try { future.get(); } catch (InterruptedException discarded) { /* * The thread this method is running in has been interrupted. */ if (null != cancelButtonListener) { cancelButtonListener.actionPerformed(null); } else { future.cancel(true); } ThreadUtils.shutDownTaskExecutor(caseActionExecutor); } catch (CancellationException discarded) { /* * The case action has been cancelled. */ ThreadUtils.shutDownTaskExecutor(caseActionExecutor); throw new CaseActionCancelledException(Bundle.Case_exceptionMessage_cancelled()); } catch (ExecutionException ex) { /* * The case action has thrown an exception. */ ThreadUtils.shutDownTaskExecutor(caseActionExecutor); throw new CaseActionException(Bundle.Case_exceptionMessage_execExceptionWrapperMessage(ex.getCause().getLocalizedMessage()), ex); } finally { progressIndicator.finish(); } } /** * A case action (interface CaseAction<T, V, R>) that creates the case * directory and case database and opens the application services for this * case. * * @param progressIndicator A progress indicator. * @param additionalParams An Object that holds any additional parameters * for a case action. For this action, this is * null. * * @throws CaseActionException If there is a problem completing the action. * The exception will have a user-friendly * message and may be a wrapper for a * lower-level exception. */ private Void create(ProgressIndicator progressIndicator, Object additionalParams) throws CaseActionException { assert (additionalParams == null); try { checkForCancellation(); createCaseDirectoryIfDoesNotExist(progressIndicator); checkForCancellation(); switchLoggingToCaseLogsDirectory(progressIndicator); checkForCancellation(); saveCaseMetadataToFile(progressIndicator); checkForCancellation(); createCaseNodeData(progressIndicator); checkForCancellation(); checkForCancellation(); createCaseDatabase(progressIndicator); checkForCancellation(); openCaseLevelServices(progressIndicator); checkForCancellation(); openAppServiceCaseResources(progressIndicator); checkForCancellation(); openCommunicationChannels(progressIndicator); return null; } catch (CaseActionException ex) { /* * Cancellation or failure. The sleep is a little hack to clear the * interrupted flag for this thread if this is a cancellation * scenario, so that the clean up can run to completion in the * current thread. */ try { Thread.sleep(1); } catch (InterruptedException discarded) { } close(progressIndicator); throw ex; } } /** * A case action (interface CaseAction<T, V, R>) that opens the case * database and application services for this case. * * @param progressIndicator A progress indicator. * @param additionalParams An Object that holds any additional parameters * for a case action. For this action, this is * null. * * @throws CaseActionException If there is a problem completing the action. * The exception will have a user-friendly * message and may be a wrapper for a * lower-level exception. */ private Void open(ProgressIndicator progressIndicator, Object additionalParams) throws CaseActionException { assert (additionalParams == null); try { checkForCancellation(); switchLoggingToCaseLogsDirectory(progressIndicator); checkForCancellation(); updateCaseNodeData(progressIndicator); checkForCancellation(); deleteTempfilesFromCaseDirectory(progressIndicator); checkForCancellation(); openCaseDataBase(progressIndicator); checkForCancellation(); openCaseLevelServices(progressIndicator); checkForCancellation(); openAppServiceCaseResources(progressIndicator); checkForCancellation(); openCommunicationChannels(progressIndicator); checkForCancellation(); openFileSystems(progressIndicator); return null; } catch (CaseActionException ex) { /* * Cancellation or failure. The sleep is a little hack to clear the * interrupted flag for this thread if this is a cancellation * scenario, so that the clean up can run to completion in the * current thread. */ try { Thread.sleep(1); } catch (InterruptedException discarded) { } close(progressIndicator); throw ex; } } /** * Reads a sector from each file system of each image of a case to do an eager open of the filesystems in case. * @param progressIndicator The progress indicator for the operation. * @throws CaseActionCancelledException Exception thrown if task is cancelled. */ @Messages({ "# {0} - case", "Case.openFileSystems.retrievingImages=Retrieving images for case: {0}...", "# {0} - image", "Case.openFileSystems.openingImage=Opening all filesystems for image: {0}..." }) private void openFileSystems(ProgressIndicator progressIndicator) throws CaseActionCancelledException { String caseName = (this.caseDb != null) ? this.caseDb.getDatabaseName() : ""; progressIndicator.progress(Bundle.Case_openFileSystems_retrievingImages(caseName)); List<Image> images = null; try { images = this.caseDb.getImages(); } catch (TskCoreException ex) { logger.log( Level.SEVERE, String.format("Could not obtain images while opening case: %s.", caseName), ex); return; } checkForCancellation(); byte[] tempBuff = new byte[512]; for (Image image : images) { String imageStr = image.getName(); progressIndicator.progress(Bundle.Case_openFileSystems_openingImage(imageStr)); Collection<FileSystem> fileSystems = this.caseDb.getFileSystems(image); checkForCancellation(); for (FileSystem fileSystem : fileSystems) { try { fileSystem.read(tempBuff, 0, 512); } catch (TskCoreException ex) { String fileSysStr = fileSystem.getName(); logger.log( Level.WARNING, String.format("Could not open filesystem: %s in image: %s for case: %s.", fileSysStr, imageStr, caseName), ex); } checkForCancellation(); } } } /** * A case action (interface CaseAction<T, V, R>) that opens a case, deletes * a data source from the case, and closes the case. * * @param progressIndicator A progress indicator. * @param additionalParams An Object that holds any additional parameters * for a case action. For this action, this the * object ID of the data source to be deleted. * * @throws CaseActionException If there is a problem completing the action. * The exception will have a user-friendly * message and may be a wrapper for a * lower-level exception. */ @Messages({ "Case.progressMessage.deletingDataSource=Removing the data source from the case...", "Case.exceptionMessage.dataSourceNotFound=The data source was not found.", "Case.exceptionMessage.errorDeletingDataSourceFromCaseDb=An error occurred while removing the data source from the case database.", "Case.exceptionMessage.errorDeletingDataSourceFromTextIndex=An error occurred while removing the data source from the text index.",}) Void deleteDataSource(ProgressIndicator progressIndicator, Object additionalParams) throws CaseActionException { assert (additionalParams instanceof Long); open(progressIndicator, null); try { progressIndicator.progress(Bundle.Case_progressMessage_deletingDataSource()); Long dataSourceObjectID = (Long) additionalParams; try { DataSource dataSource = this.caseDb.getDataSource(dataSourceObjectID); if (dataSource == null) { throw new CaseActionException(Bundle.Case_exceptionMessage_dataSourceNotFound()); } SleuthkitCaseAdminUtil.deleteDataSource(this.caseDb, dataSourceObjectID); } catch (TskDataException | TskCoreException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_errorDeletingDataSourceFromCaseDb(), ex); } try { this.caseServices.getKeywordSearchService().deleteDataSource(dataSourceObjectID); } catch (KeywordSearchServiceException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_errorDeletingDataSourceFromTextIndex(), ex); } eventPublisher.publish(new DataSourceDeletedEvent(dataSourceObjectID)); return null; } finally { close(progressIndicator); releaseCaseLock(); } } /** * Create an empty portable case from the current case * * @param caseName Case name * @param portableCaseFolder Case folder - must not exist * * @return The portable case database * * @throws TskCoreException */ public SleuthkitCase createPortableCase(String caseName, File portableCaseFolder) throws TskCoreException { if (portableCaseFolder.exists()) { throw new TskCoreException("Portable case folder " + portableCaseFolder.toString() + " already exists"); } if (!portableCaseFolder.mkdirs()) { throw new TskCoreException("Error creating portable case folder " + portableCaseFolder.toString()); } CaseDetails details = new CaseDetails(caseName, getNumber(), getExaminer(), getExaminerPhone(), getExaminerEmail(), getCaseNotes()); try { CaseMetadata portableCaseMetadata = new CaseMetadata(Case.CaseType.SINGLE_USER_CASE, portableCaseFolder.toString(), caseName, details, metadata); portableCaseMetadata.setCaseDatabaseName(SINGLE_USER_CASE_DB_NAME); } catch (CaseMetadataException ex) { throw new TskCoreException("Error creating case metadata", ex); } // Create the Sleuthkit case SleuthkitCase portableSleuthkitCase; String dbFilePath = Paths.get(portableCaseFolder.toString(), SINGLE_USER_CASE_DB_NAME).toString(); portableSleuthkitCase = SleuthkitCase.newCase(dbFilePath); return portableSleuthkitCase; } /** * Checks current thread for an interrupt. Usage: checking for user * cancellation of a case creation/opening operation, as reflected in the * exception message. * * @throws CaseActionCancelledException If the current thread is * interrupted, assumes interrupt was * due to a user action. */ private static void checkForCancellation() throws CaseActionCancelledException { if (Thread.currentThread().isInterrupted()) { throw new CaseActionCancelledException(Bundle.Case_exceptionMessage_cancelled()); } } /** * Creates the case directory, if it does not already exist. * * @param progressIndicator A progress indicator. * * @throws CaseActionException If there is a problem completing the * operation. The exception will have a * user-friendly message and may be a wrapper * for a lower-level exception. */ @Messages({ "Case.progressMessage.creatingCaseDirectory=Creating case directory..." }) private void createCaseDirectoryIfDoesNotExist(ProgressIndicator progressIndicator) throws CaseActionException { /* * TODO (JIRA-2180): Always create the case directory as part of the * case creation process. */ progressIndicator.progress(Bundle.Case_progressMessage_creatingCaseDirectory()); if (new File(metadata.getCaseDirectory()).exists() == false) { progressIndicator.progress(Bundle.Case_progressMessage_creatingCaseDirectory()); Case.createCaseDirectory(metadata.getCaseDirectory(), metadata.getCaseType()); } } /** * Switches from writing log messages to the application logs to the logs * subdirectory of the case directory. * * @param progressIndicator A progress indicator. */ @Messages({ "Case.progressMessage.switchingLogDirectory=Switching log directory..." }) private void switchLoggingToCaseLogsDirectory(ProgressIndicator progressIndicator) { progressIndicator.progress(Bundle.Case_progressMessage_switchingLogDirectory()); Logger.setLogDirectory(getLogDirectoryPath()); } /** * Saves teh case metadata to a file.SHould not be called until the case * directory has been created. * * @param progressIndicator A progress indicator. * * @throws CaseActionException If there is a problem completing the * operation. The exception will have a * user-friendly message and may be a wrapper * for a lower-level exception. */ @Messages({ "Case.progressMessage.savingCaseMetadata=Saving case metadata to file...", "# {0} - exception message", "Case.exceptionMessage.couldNotSaveCaseMetadata=Failed to save case metadata:\n{0}." }) private void saveCaseMetadataToFile(ProgressIndicator progressIndicator) throws CaseActionException { progressIndicator.progress(Bundle.Case_progressMessage_savingCaseMetadata()); try { this.metadata.writeToFile(); } catch (CaseMetadataException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_couldNotSaveCaseMetadata(ex.getLocalizedMessage()), ex); } } /** * Creates the node data for the case directory lock coordination service * node. * * @param progressIndicator A progress indicator. * * @throws CaseActionException If there is a problem completing the * operation. The exception will have a * user-friendly message and may be a wrapper * for a lower-level exception. */ @Messages({ "Case.progressMessage.creatingCaseNodeData=Creating coordination service node data...", "# {0} - exception message", "Case.exceptionMessage.couldNotCreateCaseNodeData=Failed to create coordination service node data:\n{0}." }) private void createCaseNodeData(ProgressIndicator progressIndicator) throws CaseActionException { if (getCaseType() == CaseType.MULTI_USER_CASE) { progressIndicator.progress(Bundle.Case_progressMessage_creatingCaseNodeData()); try { CaseNodeData.createCaseNodeData(metadata); } catch (CaseNodeDataException | InterruptedException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_couldNotCreateCaseNodeData(ex.getLocalizedMessage()), ex); } } } /** * Updates the node data for the case directory lock coordination service * node. * * @param progressIndicator A progress indicator. * * @throws CaseActionException If there is a problem completing the * operation. The exception will have a * user-friendly message and may be a wrapper * for a lower-level exception. */ @Messages({ "Case.progressMessage.updatingCaseNodeData=Updating coordination service node data...", "# {0} - exception message", "Case.exceptionMessage.couldNotUpdateCaseNodeData=Failed to update coordination service node data:\n{0}." }) private void updateCaseNodeData(ProgressIndicator progressIndicator) throws CaseActionException { if (getCaseType() == CaseType.MULTI_USER_CASE) { progressIndicator.progress(Bundle.Case_progressMessage_updatingCaseNodeData()); try { CaseNodeData nodeData = CaseNodeData.readCaseNodeData(metadata.getCaseDirectory()); nodeData.setLastAccessDate(new Date()); CaseNodeData.writeCaseNodeData(nodeData); } catch (CaseNodeDataException | InterruptedException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_couldNotUpdateCaseNodeData(ex.getLocalizedMessage()), ex); } } } /** * Deletes any files in the temp subdirectory of the case directory. * * @param progressIndicator A progress indicator. */ @Messages({ "Case.progressMessage.clearingTempDirectory=Clearing case temp directory..." }) private void deleteTempfilesFromCaseDirectory(ProgressIndicator progressIndicator) { /* * Clear the temp subdirectory of the case directory. */ progressIndicator.progress(Bundle.Case_progressMessage_clearingTempDirectory()); Case.clearTempSubDir(this.getTempDirectory()); } /** * Creates the node data for the case directory lock coordination service * node, the case directory, the case database and the case metadata file. * * @param progressIndicator A progress indicator. * * @throws CaseActionException If there is a problem completing the * operation. The exception will have a * user-friendly message and may be a wrapper * for a lower-level exception. */ @Messages({ "Case.progressMessage.creatingCaseDatabase=Creating case database...", "# {0} - exception message", "Case.exceptionMessage.couldNotGetDbServerConnectionInfo=Failed to get case database server conneciton info:\n{0}.", "# {0} - exception message", "Case.exceptionMessage.couldNotCreateCaseDatabase=Failed to create case database:\n{0}.", "# {0} - exception message", "Case.exceptionMessage.couldNotSaveDbNameToMetadataFile=Failed to save case database name to case metadata file:\n{0}." }) private void createCaseDatabase(ProgressIndicator progressIndicator) throws CaseActionException { progressIndicator.progress(Bundle.Case_progressMessage_creatingCaseDatabase()); try { if (CaseType.SINGLE_USER_CASE == metadata.getCaseType()) { /* * For single-user cases, the case database is a SQLite database * with a standard name, physically located in the case * directory. */ caseDb = SleuthkitCase.newCase(Paths.get(metadata.getCaseDirectory(), SINGLE_USER_CASE_DB_NAME).toString()); metadata.setCaseDatabaseName(SINGLE_USER_CASE_DB_NAME); } else { /* * For multi-user cases, the case database is a PostgreSQL * database with a name derived from the case display name, * physically located on the PostgreSQL database server. */ caseDb = SleuthkitCase.newCase(metadata.getCaseDisplayName(), UserPreferences.getDatabaseConnectionInfo(), metadata.getCaseDirectory()); metadata.setCaseDatabaseName(caseDb.getDatabaseName()); } } catch (TskCoreException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_couldNotCreateCaseDatabase(ex.getLocalizedMessage()), ex); } catch (UserPreferencesException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_couldNotGetDbServerConnectionInfo(ex.getLocalizedMessage()), ex); } catch (CaseMetadataException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_couldNotSaveDbNameToMetadataFile(ex.getLocalizedMessage()), ex); } } /** * Updates the node data for an existing case directory lock coordination * service node and opens an existing case database. * * @param progressIndicator A progress indicator. * * @throws CaseActionException If there is a problem completing the * operation. The exception will have a * user-friendly message and may be a wrapper * for a lower-level exception. */ @Messages({ "Case.progressMessage.openingCaseDatabase=Opening case database...", "# {0} - exception message", "Case.exceptionMessage.couldNotOpenCaseDatabase=Failed to open case database:\n{0}.", "# {0} - exception message", "Case.exceptionMessage.unsupportedSchemaVersionMessage=Unsupported case database schema version:\n{0}.", "Case.open.exception.multiUserCaseNotEnabled=Cannot open a multi-user case if multi-user cases are not enabled. See Tools, Options, Multi-User." }) private void openCaseDataBase(ProgressIndicator progressIndicator) throws CaseActionException { progressIndicator.progress(Bundle.Case_progressMessage_openingCaseDatabase()); try { String databaseName = metadata.getCaseDatabaseName(); if (CaseType.SINGLE_USER_CASE == metadata.getCaseType()) { caseDb = SleuthkitCase.openCase(Paths.get(metadata.getCaseDirectory(), databaseName).toString()); } else if (UserPreferences.getIsMultiUserModeEnabled()) { caseDb = SleuthkitCase.openCase(databaseName, UserPreferences.getDatabaseConnectionInfo(), metadata.getCaseDirectory()); } else { throw new CaseActionException(Bundle.Case_open_exception_multiUserCaseNotEnabled()); } } catch (TskUnsupportedSchemaVersionException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_unsupportedSchemaVersionMessage(ex.getLocalizedMessage()), ex); } catch (UserPreferencesException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_couldNotGetDbServerConnectionInfo(ex.getLocalizedMessage()), ex); } catch (TskCoreException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_couldNotOpenCaseDatabase(ex.getLocalizedMessage()), ex); } } /** * Opens the case-level services: the files manager, tags manager and * blackboard. * * @param progressIndicator A progress indicator. */ @Messages({ "Case.progressMessage.openingCaseLevelServices=Opening case-level services...",}) private void openCaseLevelServices(ProgressIndicator progressIndicator) { progressIndicator.progress(Bundle.Case_progressMessage_openingCaseLevelServices()); this.caseServices = new Services(caseDb); /* * RC Note: JM put this initialization here. I'm not sure why. However, * my attempt to put it in the openCaseDatabase method seems to lead to * intermittent unchecked exceptions concerning a missing subscriber. */ caseDb.registerForEvents(sleuthkitEventListener); } /** * Allows any registered application-level services to open resources * specific to this case. * * @param progressIndicator A progress indicator. * * @throws CaseActionException If there is a problem completing the * operation. The exception will have a * user-friendly message and may be a wrapper * for a lower-level exception. */ @NbBundle.Messages({ "Case.progressMessage.openingApplicationServiceResources=Opening application service case resources...", "# {0} - service name", "Case.serviceOpenCaseResourcesProgressIndicator.title={0} Opening Case Resources", "# {0} - service name", "Case.serviceOpenCaseResourcesProgressIndicator.cancellingMessage=Cancelling opening case resources by {0}...", "# {0} - service name", "Case.servicesException.notificationTitle={0} Error" }) private void openAppServiceCaseResources(ProgressIndicator progressIndicator) throws CaseActionException { /* * Each service gets its own independently cancellable/interruptible * task, running in a named thread managed by an executor service, with * its own progress indicator. This allows for cancellation of the * opening of case resources for individual services. It also makes it * possible to ensure that each service task completes before the next * one starts by awaiting termination of the executor service. */ progressIndicator.progress(Bundle.Case_progressMessage_openingApplicationServiceResources()); for (AutopsyService service : Lookup.getDefault().lookupAll(AutopsyService.class )) { /* * Create a progress indicator for the task and start the task. If * running with a GUI, the progress indicator will be a dialog box * with a Cancel button. */ CancelButtonListener cancelButtonListener = null; ProgressIndicator appServiceProgressIndicator; if (RuntimeProperties.runningWithGUI()) { cancelButtonListener = new CancelButtonListener(Bundle.Case_serviceOpenCaseResourcesProgressIndicator_cancellingMessage(service.getServiceName())); appServiceProgressIndicator = new ModalDialogProgressIndicator( mainFrame, Bundle.Case_serviceOpenCaseResourcesProgressIndicator_title(service.getServiceName()), new String[]{Bundle.Case_progressIndicatorCancelButton_label()}, Bundle.Case_progressIndicatorCancelButton_label(), cancelButtonListener); } else { appServiceProgressIndicator = new LoggingProgressIndicator(); } appServiceProgressIndicator.start(Bundle.Case_progressMessage_preparing()); AutopsyService.CaseContext context = new AutopsyService.CaseContext(this, appServiceProgressIndicator); String threadNameSuffix = service.getServiceName().replaceAll("[ ]", "-"); //NON-NLS threadNameSuffix = threadNameSuffix.toLowerCase(); TaskThreadFactory threadFactory = new TaskThreadFactory(String.format(CASE_RESOURCES_THREAD_NAME, threadNameSuffix)); ExecutorService executor = Executors.newSingleThreadExecutor(threadFactory); Future<Void> future = executor.submit(() -> { service.openCaseResources(context); return null; }); if (null != cancelButtonListener) { cancelButtonListener.setCaseContext(context); cancelButtonListener.setCaseActionFuture(future); } /* * Wait for the task to either be completed or * cancelled/interrupted, or for the opening of the case to be * cancelled. */ try { future.get(); } catch (InterruptedException discarded) { /* * The parent create/open case task has been cancelled. */ Case.logger.log(Level.WARNING, String.format("Opening of %s (%s) in %s cancelled during opening of case resources by %s", getDisplayName(), getName(), getCaseDirectory(), service.getServiceName())); future.cancel(true); } catch (CancellationException discarded) { /* * The opening of case resources by the application service has * been cancelled, so the executor service has thrown. Note that * there is no guarantee the task itself has responded to the * cancellation request yet. */ Case.logger.log(Level.WARNING, String.format("Opening of case resources by %s for %s (%s) in %s cancelled", service.getServiceName(), getDisplayName(), getName(), getCaseDirectory(), service.getServiceName())); } catch (ExecutionException ex) { /* * An exception was thrown while executing the task. The * case-specific application service resources are not * essential. Log an error and notify the user if running the * desktop GUI, but do not throw. */ Case.logger.log(Level.SEVERE, String.format("%s failed to open case resources for %s", service.getServiceName(), this.getDisplayName()), ex); if (RuntimeProperties.runningWithGUI()) { SwingUtilities.invokeLater(() -> { MessageNotifyUtil.Notify.error(Bundle.Case_servicesException_notificationTitle(service.getServiceName()), ex.getLocalizedMessage()); }); } } finally { /* * Shut down the executor service and wait for it to finish. * This ensures that the task has finished. Without this, it * would be possible to start the next task before the current * task responded to a cancellation request. */ ThreadUtils.shutDownTaskExecutor(executor); appServiceProgressIndicator.finish(); } checkForCancellation(); } } /** * If this case is a multi-user case, sets up for communication with other * application nodes. * * @param progressIndicator A progress indicator. * * @throws CaseActionException If there is a problem completing the * operation. The exception will have a * user-friendly message and may be a wrapper * for a lower-level exception. */ @Messages({ "Case.progressMessage.settingUpNetworkCommunications=Setting up network communications...", "# {0} - exception message", "Case.exceptionMessage.couldNotOpenRemoteEventChannel=Failed to open remote events channel:\n{0}.", "# {0} - exception message", "Case.exceptionMessage.couldNotCreatCollaborationMonitor=Failed to create collaboration monitor:\n{0}." }) private void openCommunicationChannels(ProgressIndicator progressIndicator) throws CaseActionException { if (CaseType.MULTI_USER_CASE == metadata.getCaseType()) { progressIndicator.progress(Bundle.Case_progressMessage_settingUpNetworkCommunications()); try { eventPublisher.openRemoteEventChannel(String.format(EVENT_CHANNEL_NAME, metadata.getCaseName())); checkForCancellation(); collaborationMonitor = new CollaborationMonitor(metadata.getCaseName()); } catch (AutopsyEventException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_couldNotOpenRemoteEventChannel(ex.getLocalizedMessage()), ex); } catch (CollaborationMonitor.CollaborationMonitorException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_couldNotCreatCollaborationMonitor(ex.getLocalizedMessage()), ex); } } } /** * Performs a case action that involves closing a case opened by calling * doOpenCaseAction. If the case is a multi-user case, the coordination * service case lock acquired by the call to doOpenCaseAction is released. * This case lock must be released in the same thread in which it was * acquired, as required by the coordination service. The single-threaded * executor saved during the case opening action is therefore used to do the * case closing action. * * @throws CaseActionException If there is a problem completing the action. * The exception will have a user-friendly * message and may be a wrapper for a * lower-level exception. */ private void doCloseCaseAction() throws CaseActionException { /* * Set up either a GUI progress indicator without a Cancel button or a * logging progress indicator. */ ProgressIndicator progressIndicator; if (RuntimeProperties.runningWithGUI()) { progressIndicator = new ModalDialogProgressIndicator( mainFrame, Bundle.Case_progressIndicatorTitle_closingCase()); } else { progressIndicator = new LoggingProgressIndicator(); } progressIndicator.start(Bundle.Case_progressMessage_preparing()); /* * Closing a case is always done in the same non-UI thread that * opened/created the case. If the case is a multi-user case, this * ensures that case lock that is held as long as the case is open is * released in the same thread in which it was acquired, as is required * by the coordination service. */ Future<Void> future = caseActionExecutor.submit(() -> { if (CaseType.SINGLE_USER_CASE == metadata.getCaseType()) { close(progressIndicator); } else { /* * Acquire an exclusive case resources lock to ensure only one * node at a time can create/open/upgrade/close the case * resources. */ progressIndicator.progress(Bundle.Case_progressMessage_preparing()); try (CoordinationService.Lock resourcesLock = acquireCaseResourcesLock(metadata.getCaseDirectory())) { if (null == resourcesLock) { throw new CaseActionException(Bundle.Case_creationException_couldNotAcquireResourcesLock()); } close(progressIndicator); } finally { /* * Always release the case directory lock that was acquired * when the case was opened. */ releaseCaseLock(); } } return null; }); try { future.get(); } catch (InterruptedException | CancellationException unused) { /* * The wait has been interrupted by interrupting the thread running * this method. Not allowing cancellation of case closing, so ignore * the interrupt. Likewise, cancellation of the case closing task is * not supported. */ } catch (ExecutionException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_execExceptionWrapperMessage(ex.getCause().getMessage()), ex); } finally { ThreadUtils.shutDownTaskExecutor(caseActionExecutor); progressIndicator.finish(); } } /** * Closes the case. * * @param progressIndicator A progress indicator. */ @Messages({ "Case.progressMessage.shuttingDownNetworkCommunications=Shutting down network communications...", "Case.progressMessage.closingApplicationServiceResources=Closing case-specific application service resources...", "Case.progressMessage.closingCaseDatabase=Closing case database..." }) private void close(ProgressIndicator progressIndicator) { IngestManager.getInstance().cancelAllIngestJobs(IngestJob.CancellationReason.CASE_CLOSED); /* * Stop sending/receiving case events to and from other nodes if this is * a multi-user case. */ if (CaseType.MULTI_USER_CASE == metadata.getCaseType()) { progressIndicator.progress(Bundle.Case_progressMessage_shuttingDownNetworkCommunications()); if (null != collaborationMonitor) { collaborationMonitor.shutdown(); } eventPublisher.closeRemoteEventChannel(); } /* * Allow all registered application services providers to close * resources related to the case. */ progressIndicator.progress(Bundle.Case_progressMessage_closingApplicationServiceResources()); closeAppServiceCaseResources(); /* * Close the case database. */ if (null != caseDb) { progressIndicator.progress(Bundle.Case_progressMessage_closingCaseDatabase()); caseDb.unregisterForEvents(sleuthkitEventListener); caseDb.close(); } /* * Switch the log directory. */ progressIndicator.progress(Bundle.Case_progressMessage_switchingLogDirectory()); Logger.setLogDirectory(PlatformUtil.getLogDirectory()); } /** * Allows any registered application-level services to close any resources * specific to this case. */ @Messages({ "# {0} - serviceName", "Case.serviceCloseResourcesProgressIndicator.title={0} Closing Case Resources", "# {0} - service name", "# {1} - exception message", "Case.servicesException.serviceResourcesCloseError=Could not close case resources for {0} service: {1}" }) private void closeAppServiceCaseResources() { /* * Each service gets its own independently cancellable task, and thus * its own task progress indicator. */ for (AutopsyService service : Lookup.getDefault().lookupAll(AutopsyService.class )) { ProgressIndicator progressIndicator; if (RuntimeProperties.runningWithGUI()) { progressIndicator = new ModalDialogProgressIndicator( mainFrame, Bundle.Case_serviceCloseResourcesProgressIndicator_title(service.getServiceName())); } else { progressIndicator = new LoggingProgressIndicator(); } progressIndicator.start(Bundle.Case_progressMessage_preparing()); AutopsyService.CaseContext context = new AutopsyService.CaseContext(this, progressIndicator); String threadNameSuffix = service.getServiceName().replaceAll("[ ]", "-"); //NON-NLS threadNameSuffix = threadNameSuffix.toLowerCase(); TaskThreadFactory threadFactory = new TaskThreadFactory(String.format(CASE_RESOURCES_THREAD_NAME, threadNameSuffix)); ExecutorService executor = Executors.newSingleThreadExecutor(threadFactory); Future<Void> future = executor.submit(() -> { service.closeCaseResources(context); return null; }); try { future.get(); } catch (InterruptedException ex) { Case.logger.log(Level.SEVERE, String.format("Unexpected interrupt while waiting on %s service to close case resources", service.getServiceName()), ex); } catch (CancellationException ex) { Case.logger.log(Level.SEVERE, String.format("Unexpected cancellation while waiting on %s service to close case resources", service.getServiceName()), ex); } catch (ExecutionException ex) { Case.logger.log(Level.SEVERE, String.format("%s service failed to open case resources", service.getServiceName()), ex); if (RuntimeProperties.runningWithGUI()) { SwingUtilities.invokeLater(() -> MessageNotifyUtil.Notify.error( Bundle.Case_servicesException_notificationTitle(service.getServiceName()), Bundle.Case_servicesException_serviceResourcesCloseError(service.getServiceName(), ex.getLocalizedMessage()))); } } finally { ThreadUtils.shutDownTaskExecutor(executor); progressIndicator.finish(); } } } /** * Acquires a case (case directory) lock for the current case. * * @throws CaseActionException If the lock cannot be acquired. */ @Messages({ "Case.lockingException.couldNotAcquireSharedLock=Failed to get an shared lock on the case.", "Case.lockingException.couldNotAcquireExclusiveLock=Failed to get a exclusive lock on the case." }) private void acquireCaseLock(CaseLockType lockType) throws CaseActionException { String caseDir = metadata.getCaseDirectory(); try { CoordinationService coordinationService = CoordinationService.getInstance(); caseLock = lockType == CaseLockType.SHARED ? coordinationService.tryGetSharedLock(CategoryNode.CASES, caseDir, CASE_LOCK_TIMEOUT_MINS, TimeUnit.MINUTES) : coordinationService.tryGetExclusiveLock(CategoryNode.CASES, caseDir, CASE_LOCK_TIMEOUT_MINS, TimeUnit.MINUTES); if (caseLock == null) { if (lockType == CaseLockType.SHARED) { throw new CaseActionException(Bundle.Case_lockingException_couldNotAcquireSharedLock()); } else { throw new CaseActionException(Bundle.Case_lockingException_couldNotAcquireExclusiveLock()); } } } catch (InterruptedException | CoordinationServiceException ex) { if (lockType == CaseLockType.SHARED) { throw new CaseActionException(Bundle.Case_lockingException_couldNotAcquireSharedLock(), ex); } else { throw new CaseActionException(Bundle.Case_lockingException_couldNotAcquireExclusiveLock(), ex); } } } /** * Releases a case (case directory) lock for the current case. */ private void releaseCaseLock() { if (caseLock != null) { try { caseLock.release(); caseLock = null; } catch (CoordinationService.CoordinationServiceException ex) { logger.log(Level.SEVERE, String.format("Failed to release shared case directory lock for %s", getMetadata().getCaseDirectory()), ex); } } } /** * Gets the path to the specified subdirectory of the case directory, * creating it if it does not already exist. * * @return The absolute path to the specified subdirectory. */ private String getOrCreateSubdirectory(String subDirectoryName) { File subDirectory = Paths.get(getOutputDirectory(), subDirectoryName).toFile(); if (!subDirectory.exists()) { subDirectory.mkdirs(); } return subDirectory.toString(); } /** * Deletes a single-user case. * * @param metadata The case metadata. * @param progressIndicator A progress indicator. * * @throws CaseActionException If there were one or more errors deleting the * case. The exception will have a user-friendly * message and may be a wrapper for a * lower-level exception. */ @Messages({ "Case.exceptionMessage.errorsDeletingCase=Errors occured while deleting the case. See the application log for details." }) private static void deleteSingleUserCase(CaseMetadata metadata, ProgressIndicator progressIndicator) throws CaseActionException { boolean errorsOccurred = false; try { deleteTextIndex(metadata, progressIndicator); } catch (KeywordSearchServiceException ex) { errorsOccurred = true; logger.log(Level.WARNING, String.format("Failed to delete text index for %s (%s) in %s", metadata.getCaseDisplayName(), metadata.getCaseName(), metadata.getCaseDirectory()), ex); //NON-NLS } try { deleteCaseDirectory(metadata, progressIndicator); } catch (CaseActionException ex) { errorsOccurred = true; logger.log(Level.WARNING, String.format("Failed to delete case directory for %s (%s) in %s", metadata.getCaseDisplayName(), metadata.getCaseName(), metadata.getCaseDirectory()), ex); //NON-NLS } deleteFromRecentCases(metadata, progressIndicator); if (errorsOccurred) { throw new CaseActionException(Bundle.Case_exceptionMessage_errorsDeletingCase()); } } /** * Deletes a multi-user case. This method does so after acquiring the case * directory coordination service lock and is intended to be used for * deleting simple multi-user cases without auto ingest input. Note that the * case directory coordination service node for the case is only deleted if * no errors occurred. * * @param metadata The case metadata. * @param progressIndicator A progress indicator. * * @throws CaseActionException If there were one or more errors deleting * the case. The exception will have a * user-friendly message and may be a wrapper * for a lower-level exception. * @throws InterruptedException If the thread this code is running in is * interrupted while blocked, i.e., if * cancellation of the operation is detected * during a wait. */ @Messages({ "Case.progressMessage.connectingToCoordSvc=Connecting to coordination service...", "# {0} - exception message", "Case.exceptionMessage.failedToConnectToCoordSvc=Failed to connect to coordination service:\n{0}.", "Case.exceptionMessage.cannotGetLockToDeleteCase=Cannot delete case because it is open for another user or host.", "# {0} - exception message", "Case.exceptionMessage.failedToLockCaseForDeletion=Failed to exclusively lock case for deletion:\n{0}.", "Case.progressMessage.fetchingCoordSvcNodeData=Fetching coordination service node data for the case...", "# {0} - exception message", "Case.exceptionMessage.failedToFetchCoordSvcNodeData=Failed to fetch coordination service node data:\n{0}.", "Case.progressMessage.deletingResourcesCoordSvcNode=Deleting case resources coordination service node...", "Case.progressMessage.deletingCaseDirCoordSvcNode=Deleting case directory coordination service node..." }) private static void deleteMultiUserCase(CaseMetadata metadata, ProgressIndicator progressIndicator) throws CaseActionException, InterruptedException { progressIndicator.progress(Bundle.Case_progressMessage_connectingToCoordSvc()); CoordinationService coordinationService; try { coordinationService = CoordinationService.getInstance(); } catch (CoordinationServiceException ex) { logger.log(Level.SEVERE, String.format("Failed to connect to coordination service when attempting to delete %s (%s) in %s", metadata.getCaseDisplayName(), metadata.getCaseName(), metadata.getCaseDirectory()), ex); //NON-NLS throw new CaseActionException(Bundle.Case_exceptionMessage_failedToConnectToCoordSvc(ex.getLocalizedMessage())); } CaseNodeData caseNodeData; boolean errorsOccurred = false; try (CoordinationService.Lock dirLock = coordinationService.tryGetExclusiveLock(CategoryNode.CASES, metadata.getCaseDirectory())) { if (dirLock == null) { logger.log(Level.INFO, String.format("Could not delete %s (%s) in %s because a case directory lock was held by another host", metadata.getCaseDisplayName(), metadata.getCaseName(), metadata.getCaseDirectory())); //NON-NLS throw new CaseActionException(Bundle.Case_exceptionMessage_cannotGetLockToDeleteCase()); } progressIndicator.progress(Bundle.Case_progressMessage_fetchingCoordSvcNodeData()); try { caseNodeData = CaseNodeData.readCaseNodeData(metadata.getCaseDirectory()); } catch (CaseNodeDataException | InterruptedException ex) { logger.log(Level.SEVERE, String.format("Failed to get coordination service node data %s (%s) in %s", metadata.getCaseDisplayName(), metadata.getCaseName(), metadata.getCaseDirectory()), ex); //NON-NLS throw new CaseActionException(Bundle.Case_exceptionMessage_failedToFetchCoordSvcNodeData(ex.getLocalizedMessage())); } errorsOccurred = deleteMultiUserCase(caseNodeData, metadata, progressIndicator, logger); progressIndicator.progress(Bundle.Case_progressMessage_deletingResourcesCoordSvcNode()); try { String resourcesLockNodePath = CoordinationServiceUtils.getCaseResourcesNodePath(caseNodeData.getDirectory()); coordinationService.deleteNode(CategoryNode.CASES, resourcesLockNodePath); } catch (CoordinationServiceException ex) { if (!isNoNodeException(ex)) { errorsOccurred = true; logger.log(Level.WARNING, String.format("Error deleting the case resources coordination service node for the case at %s (%s) in %s", metadata.getCaseDisplayName(), metadata.getCaseName(), metadata.getCaseDirectory()), ex); //NON-NLS } } catch (InterruptedException ex) { logger.log(Level.WARNING, String.format("Error deleting the case resources coordination service node for the case at %s (%s) in %s", metadata.getCaseDisplayName(), metadata.getCaseName(), metadata.getCaseDirectory()), ex); //NON-NLS } } catch (CoordinationServiceException ex) { logger.log(Level.SEVERE, String.format("Error exclusively locking the case directory for %s (%s) in %s", metadata.getCaseDisplayName(), metadata.getCaseName(), metadata.getCaseDirectory()), ex); //NON-NLS throw new CaseActionException(Bundle.Case_exceptionMessage_failedToLockCaseForDeletion(ex.getLocalizedMessage())); } if (!errorsOccurred) { progressIndicator.progress(Bundle.Case_progressMessage_deletingCaseDirCoordSvcNode()); try { String casDirNodePath = CoordinationServiceUtils.getCaseDirectoryNodePath(caseNodeData.getDirectory()); coordinationService.deleteNode(CategoryNode.CASES, casDirNodePath); } catch (CoordinationServiceException | InterruptedException ex) { logger.log(Level.SEVERE, String.format("Error deleting the case directory lock node for %s (%s) in %s", metadata.getCaseDisplayName(), metadata.getCaseName(), metadata.getCaseDirectory()), ex); //NON-NLS errorsOccurred = true; } } if (errorsOccurred) { throw new CaseActionException(Bundle.Case_exceptionMessage_errorsDeletingCase()); } } /** * IMPORTANT: This is a "beta" method and is subject to change or removal * without notice! * * Deletes a mulit-user case by attempting to delete the case database, the * text index, the case directory, and the case resources coordination * service node for a case, and removes the case from the recent cases menu * of the main application window. Callers of this method MUST acquire and * release the case directory lock for the case and are responsible for * deleting the corresponding coordination service nodes, if desired. * * @param caseNodeData The coordination service node data for the case. * @param metadata The case metadata. * @param progressIndicator A progress indicator. * @param logger A logger. * * @return True if one or more errors occurred (see log for details), false * otherwise. * * @throws InterruptedException If the thread this code is running in is * interrupted while blocked, i.e., if * cancellation of the operation is detected * during a wait. */ @Beta public static boolean deleteMultiUserCase(CaseNodeData caseNodeData, CaseMetadata metadata, ProgressIndicator progressIndicator, Logger logger) throws InterruptedException { boolean errorsOccurred = false; try { deleteMultiUserCaseDatabase(caseNodeData, metadata, progressIndicator, logger); deleteMultiUserCaseTextIndex(caseNodeData, metadata, progressIndicator, logger); deleteMultiUserCaseDirectory(caseNodeData, metadata, progressIndicator, logger); deleteFromRecentCases(metadata, progressIndicator); } catch (UserPreferencesException | ClassNotFoundException | SQLException ex) { errorsOccurred = true; logger.log(Level.WARNING, String.format("Failed to delete the case database for %s (%s) in %s", metadata.getCaseDisplayName(), metadata.getCaseName(), metadata.getCaseDirectory()), ex); //NON-NLS } catch (KeywordSearchServiceException ex) { errorsOccurred = true; logger.log(Level.WARNING, String.format("Failed to delete the text index for %s (%s) in %s", metadata.getCaseDisplayName(), metadata.getCaseName(), metadata.getCaseDirectory()), ex); //NON-NLS } catch (CaseActionException ex) { errorsOccurred = true; logger.log(Level.WARNING, String.format("Failed to delete the case directory for %s (%s) in %s", metadata.getCaseDisplayName(), metadata.getCaseName(), metadata.getCaseDirectory()), ex); //NON-NLS } return errorsOccurred; } /** * Attempts to delete the case database for a multi-user case. * * @param caseNodeData The coordination service node data for the case. * @param metadata The case metadata. * @param progressIndicator A progress indicator. * @param logger A logger. * * @throws UserPreferencesException if there is an error getting the * database server connection info. * @throws ClassNotFoundException if there is an error gettting the * required JDBC driver. * @throws SQLException if there is an error executing the SQL * to drop the database from the database * server. * @throws InterruptedException If interrupted while blocked waiting for * coordination service data to be written * to the coordination service node * database. */ @Messages({ "Case.progressMessage.deletingCaseDatabase=Deleting case database..." }) private static void deleteMultiUserCaseDatabase(CaseNodeData caseNodeData, CaseMetadata metadata, ProgressIndicator progressIndicator, Logger logger) throws UserPreferencesException, ClassNotFoundException, SQLException, InterruptedException { if (!caseNodeData.isDeletedFlagSet(CaseNodeData.DeletedFlags.CASE_DB)) { progressIndicator.progress(Bundle.Case_progressMessage_deletingCaseDatabase()); logger.log(Level.INFO, String.format("Deleting case database for %s (%s) in %s", caseNodeData.getDisplayName(), caseNodeData.getName(), caseNodeData.getDirectory())); //NON-NLS CaseDbConnectionInfo info = UserPreferences.getDatabaseConnectionInfo(); String url = "jdbc:postgresql://" + info.getHost() + ":" + info.getPort() + "/postgres"; //NON-NLS Class.forName("org.postgresql.Driver"); //NON-NLS try (Connection connection = DriverManager.getConnection(url, info.getUserName(), info.getPassword()); Statement statement = connection.createStatement()) { String dbExistsQuery = "SELECT 1 from pg_database WHERE datname = '" + metadata.getCaseDatabaseName() + "'"; //NON-NLS try (ResultSet queryResult = statement.executeQuery(dbExistsQuery)) { if (queryResult.next()) { String deleteCommand = "DROP DATABASE \"" + metadata.getCaseDatabaseName() + "\""; //NON-NLS statement.execute(deleteCommand); } } } setDeletedItemFlag(caseNodeData, CaseNodeData.DeletedFlags.CASE_DB); } } /** * Attempts to delete the text index for a multi-user case. * * @param caseNodeData The coordination service node data for the case. * @param metadata The case metadata. * @param progressIndicator A progress indicator. * @param logger A logger. * * @throws KeywordSearchServiceException If there is an error deleting the * text index. * @throws InterruptedException If interrupted while blocked * waiting for coordination service * data to be written to the * coordination service node database. */ private static void deleteMultiUserCaseTextIndex(CaseNodeData caseNodeData, CaseMetadata metadata, ProgressIndicator progressIndicator, Logger logger) throws KeywordSearchServiceException, InterruptedException { if (!caseNodeData.isDeletedFlagSet(CaseNodeData.DeletedFlags.TEXT_INDEX)) { logger.log(Level.INFO, String.format("Deleting text index for %s", caseNodeData.getDisplayName(), caseNodeData.getName(), caseNodeData.getDirectory())); //NON-NLS deleteTextIndex(metadata, progressIndicator); setDeletedItemFlag(caseNodeData, CaseNodeData.DeletedFlags.TEXT_INDEX); } } /** * Attempts to delete the text index for a case. * * @param metadata The case metadata. * @param progressIndicator A progress indicator. * * @throws KeywordSearchServiceException If there is an error deleting the * text index. */ @Messages({ "Case.progressMessage.deletingTextIndex=Deleting text index..." }) private static void deleteTextIndex(CaseMetadata metadata, ProgressIndicator progressIndicator) throws KeywordSearchServiceException { progressIndicator.progress(Bundle.Case_progressMessage_deletingTextIndex()); for (KeywordSearchService searchService : Lookup.getDefault().lookupAll(KeywordSearchService.class )) { searchService.deleteTextIndex(metadata); } } /** * Attempts to delete the case directory for a multi-user case. * * @param caseNodeData The coordination service node data for the case. * @param metadata The case metadata. * @param progressIndicator A progress indicator. * @param logger A logger. * * @throws CaseActionException if there is an error deleting the case * directory. * @throws InterruptedException If interrupted while blocked waiting for * coordination service data to be written to * the coordination service node database. */ private static void deleteMultiUserCaseDirectory(CaseNodeData caseNodeData, CaseMetadata metadata, ProgressIndicator progressIndicator, Logger logger) throws CaseActionException, InterruptedException { if (!caseNodeData.isDeletedFlagSet(CaseNodeData.DeletedFlags.CASE_DIR)) { logger.log(Level.INFO, String.format("Deleting case directory for %s", caseNodeData.getDisplayName(), caseNodeData.getName(), caseNodeData.getDirectory())); //NON-NLS deleteCaseDirectory(metadata, progressIndicator); setDeletedItemFlag(caseNodeData, CaseNodeData.DeletedFlags.CASE_DIR); } } /** * Attempts to delete the case directory for a case. * * @param metadata The case metadata. * @param progressIndicator A progress indicator. * * @throws CaseActionException If there is an error deleting the case * directory. */ @Messages({ "Case.progressMessage.deletingCaseDirectory=Deleting case directory..." }) private static void deleteCaseDirectory(CaseMetadata metadata, ProgressIndicator progressIndicator) throws CaseActionException { progressIndicator.progress(Bundle.Case_progressMessage_deletingCaseDirectory()); if (!FileUtil.deleteDir(new File(metadata.getCaseDirectory()))) { throw new CaseActionException(String.format("Failed to delete %s", metadata.getCaseDirectory())); //NON-NLS } } /** * Attempts to remove a case from the recent cases menu if the main * application window is present. * * @param metadata The case metadata. * @param progressIndicator A progress indicator. */ @Messages({ "Case.progressMessage.removingCaseFromRecentCases=Removing case from Recent Cases menu..." }) private static void deleteFromRecentCases(CaseMetadata metadata, ProgressIndicator progressIndicator) { if (RuntimeProperties.runningWithGUI()) { progressIndicator.progress(Bundle.Case_progressMessage_removingCaseFromRecentCases()); SwingUtilities.invokeLater(() -> { RecentCases.getInstance().removeRecentCase(metadata.getCaseDisplayName(), metadata.getFilePath().toString()); }); } } /** * Examines a coordination service exception to try to determine if it is a * "no node" exception, i.e., an operation was attempted on a node that does * not exist. * * @param ex A coordination service exception. * * @return True or false. */ private static boolean isNoNodeException(CoordinationServiceException ex) { boolean isNodeNodeEx = false; Throwable cause = ex.getCause(); if (cause != null) { String causeMessage = cause.getMessage(); isNodeNodeEx = causeMessage.contains(NO_NODE_ERROR_MSG_FRAGMENT); } return isNodeNodeEx; } /** * Sets a deleted item flag in the coordination service node data for a * multi-user case. * * @param caseNodeData The coordination service node data for the case. * @param flag The flag to set. * * @throws InterruptedException If interrupted while blocked waiting for * coordination service data to be written to * the coordination service node database. */ private static void setDeletedItemFlag(CaseNodeData caseNodeData, CaseNodeData.DeletedFlags flag) throws InterruptedException { try { caseNodeData.setDeletedFlag(flag); CaseNodeData.writeCaseNodeData(caseNodeData); } catch (CaseNodeDataException ex) { logger.log(Level.SEVERE, String.format("Error updating deleted item flag %s for %s (%s) in %s", flag.name(), caseNodeData.getDisplayName(), caseNodeData.getName(), caseNodeData.getDirectory()), ex); } } /** * Defines the signature for case action methods that can be passed as * arguments to the doCaseAction method. * * @param <T> A ProgressIndicator * @param <V> The optional parameters stored in an Object. * @param <R> The return type of Void. */ private interface CaseAction<T, V, R> { /** * The signature for a case action method. * * @param progressIndicator A ProgressIndicator. * @param additionalParams The optional parameters stored in an Object. * * @return A Void object (null). * * @throws CaseActionException */ R execute(T progressIndicator, V additionalParams) throws CaseActionException; } /** * The choices for the case (case directory) coordination service lock used * for multi-user cases. */ private enum CaseLockType { SHARED, EXCLUSIVE; } /** * A case operation Cancel button listener for use with a * ModalDialogProgressIndicator when running with a GUI. */ @ThreadSafe private final static class CancelButtonListener implements ActionListener { private final String cancellationMessage; @GuardedBy("this") private boolean cancelRequested; @GuardedBy("this") private CaseContext caseContext; @GuardedBy("this") private Future<?> caseActionFuture; /** * Constructs a case operation Cancel button listener for use with a * ModalDialogProgressIndicator when running with a GUI. * * @param cancellationMessage The message to display in the * ModalDialogProgressIndicator when the * cancel button is pressed. */ private CancelButtonListener(String cancellationMessage) { this.cancellationMessage = cancellationMessage; } /** * Sets a case context for this listener. * * @param caseContext A case context object. */ private synchronized void setCaseContext(CaseContext caseContext) { this.caseContext = caseContext; /* * If the cancel button has already been pressed, pass the * cancellation on to the case context. */ if (cancelRequested) { cancel(); } } /** * Sets a Future object for a task associated with this listener. * * @param caseActionFuture A task Future object. */ private synchronized void setCaseActionFuture(Future<?> caseActionFuture) { this.caseActionFuture = caseActionFuture; /* * If the cancel button has already been pressed, cancel the Future * of the task. */ if (cancelRequested) { cancel(); } } /** * The event handler for Cancel button pushes. * * @param event The button event, ignored, can be null. */ @Override public synchronized void actionPerformed(ActionEvent event) { cancel(); } /** * Handles a cancellation request. */ private void cancel() { /* * At a minimum, set the cancellation requested flag of this * listener. */ this.cancelRequested = true; if (null != this.caseContext) { /* * Set the cancellation request flag and display the * cancellation message in the progress indicator for the case * context associated with this listener. */ if (RuntimeProperties.runningWithGUI()) { ProgressIndicator progressIndicator = this.caseContext.getProgressIndicator(); if (progressIndicator instanceof ModalDialogProgressIndicator) { ((ModalDialogProgressIndicator) progressIndicator).setCancelling(cancellationMessage); } } this.caseContext.requestCancel(); } if (null != this.caseActionFuture) { /* * Cancel the Future of the task associated with this listener. * Note that the task thread will be interrupted if the task is * blocked. */ this.caseActionFuture.cancel(true); } } } /** * A thread factory that provides named threads. */ private static class TaskThreadFactory implements ThreadFactory { private final String threadName; private TaskThreadFactory(String threadName) { this.threadName = threadName; } @Override public Thread newThread(Runnable task) { return new Thread(task, threadName); } } /** * Gets the application name. * * @return The application name. * * @deprecated */ @Deprecated public static String getAppName() { return UserPreferences.getAppName(); } /** * Creates a new, single-user Autopsy case. * * @param caseDir The full path of the case directory. The directory * will be created if it doesn't already exist; if it * exists, it is ASSUMED it was created by calling * createCaseDirectory. * @param caseDisplayName The display name of case, which may be changed * later by the user. * @param caseNumber The case number, can be the empty string. * @param examiner The examiner to associate with the case, can be * the empty string. * * @throws CaseActionException if there is a problem creating the case. The * exception will have a user-friendly message * and may be a wrapper for a lower-level * exception. * @deprecated Use createAsCurrentCase instead. */ @Deprecated public static void create(String caseDir, String caseDisplayName, String caseNumber, String examiner) throws CaseActionException { createAsCurrentCase(caseDir, caseDisplayName, caseNumber, examiner, CaseType.SINGLE_USER_CASE); } /** * Creates a new Autopsy case and makes it the current case. * * @param caseDir The full path of the case directory. The directory * will be created if it doesn't already exist; if it * exists, it is ASSUMED it was created by calling * createCaseDirectory. * @param caseDisplayName The display name of case, which may be changed * later by the user. * @param caseNumber The case number, can be the empty string. * @param examiner The examiner to associate with the case, can be * the empty string. * @param caseType The type of case (single-user or multi-user). * * @throws CaseActionException if there is a problem creating the case. The * exception will have a user-friendly message * and may be a wrapper for a lower-level * exception. * @deprecated Use createAsCurrentCase instead. */ @Deprecated public static void create(String caseDir, String caseDisplayName, String caseNumber, String examiner, CaseType caseType) throws CaseActionException { createAsCurrentCase(caseDir, caseDisplayName, caseNumber, examiner, caseType); } /** * Opens an existing Autopsy case and makes it the current case. * * @param caseMetadataFilePath The path of the case metadata (.aut) file. * * @throws CaseActionException if there is a problem opening the case. The * exception will have a user-friendly message * and may be a wrapper for a lower-level * exception. * @deprecated Use openAsCurrentCase instead. */ @Deprecated public static void open(String caseMetadataFilePath) throws CaseActionException { openAsCurrentCase(caseMetadataFilePath); } /** * Closes this Autopsy case. * * @throws CaseActionException if there is a problem closing the case. The * exception will have a user-friendly message * and may be a wrapper for a lower-level * exception. * @deprecated Use closeCurrentCase instead. */ @Deprecated public void closeCase() throws CaseActionException { closeCurrentCase(); } /** * Invokes the startup dialog window. * * @deprecated Use StartupWindowProvider.getInstance().open() instead. */ @Deprecated public static void invokeStartupDialog() { StartupWindowProvider.getInstance().open(); } /** * Converts a Java timezone id to a coded string with only alphanumeric * characters. Example: "America/New_York" is converted to "EST5EDT" by this * method. * * @param timeZoneId The time zone id. * * @return The converted time zone string. * * @deprecated Use * org.sleuthkit.autopsy.coreutils.TimeZoneUtils.convertToAlphaNumericFormat * instead. */ @Deprecated public static String convertTimeZone(String timeZoneId) { return TimeZoneUtils.convertToAlphaNumericFormat(timeZoneId); } /** * Check if file exists and is a normal file. * * @param filePath The file path. * * @return True or false. * * @deprecated Use java.io.File.exists or java.io.File.isFile instead */ @Deprecated public static boolean pathExists(String filePath) { return new File(filePath).isFile(); } /** * Gets the Autopsy version. * * @return The Autopsy version. * * @deprecated Use org.sleuthkit.autopsy.coreutils.Version.getVersion * instead */ @Deprecated public static String getAutopsyVersion() { return Version.getVersion(); } /** * Check if case is currently open. * * @return True if a case is open. * * @deprecated Use isCaseOpen instead. */ @Deprecated public static boolean existsCurrentCase() { return isCaseOpen(); } /** * Get relative (with respect to case dir) module output directory path * where modules should save their permanent data. The directory is a * subdirectory of this case dir. * * @return relative path to the module output dir * * @deprecated Use getModuleOutputDirectoryRelativePath() instead */ @Deprecated public static String getModulesOutputDirRelPath() { return "ModuleOutput"; //NON-NLS } /** * Gets a PropertyChangeSupport object. The PropertyChangeSupport object * returned is not used by instances of this class and does not have any * PropertyChangeListeners. * * @return A new PropertyChangeSupport object. * * @deprecated Do not use. */ @Deprecated public static PropertyChangeSupport getPropertyChangeSupport() { return new PropertyChangeSupport(Case.class ); } /** * Get module output directory path where modules should save their * permanent data. * * @return absolute path to the module output directory * * @deprecated Use getModuleDirectory() instead. */ @Deprecated public String getModulesOutputDirAbsPath() { return getModuleDirectory(); } /** * Adds an image to the current case after it has been added to the DB. * Sends out event and reopens windows if needed. * * @param imgPath The path of the image file. * @param imgId The ID of the image. * @param timeZone The time zone of the image. * * @return * * @throws org.sleuthkit.autopsy.casemodule.CaseActionException * * @deprecated As of release 4.0 */ @Deprecated public Image addImage(String imgPath, long imgId, String timeZone) throws CaseActionException { try { Image newDataSource = caseDb.getImageById(imgId); notifyDataSourceAdded(newDataSource, UUID.randomUUID()); return newDataSource; } catch (TskCoreException ex) { throw new CaseActionException(NbBundle.getMessage(this.getClass(), "Case.addImg.exception.msg"), ex); } } /** * Gets the time zone(s) of the image data source(s) in this case. * * @return The set of time zones in use. * * @deprecated Use getTimeZones instead. */ @Deprecated public Set<TimeZone> getTimeZone() { return getTimeZones(); } /** * Deletes reports from the case. * * @param reports Collection of Report to be deleted from the case. * @param deleteFromDisk No longer supported - ignored. * * @throws TskCoreException * @deprecated Use deleteReports(Collection<? extends Report> reports) * instead. */ @Deprecated public void deleteReports(Collection<? extends Report> reports, boolean deleteFromDisk) throws TskCoreException { deleteReports(reports); } }
Core/src/org/sleuthkit/autopsy/casemodule/Case.java
/* * Autopsy Forensic Browser * * Copyright 2012-2020 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sleuthkit.autopsy.casemodule; import org.sleuthkit.autopsy.featureaccess.FeatureAccessUtils; import com.google.common.annotations.Beta; import com.google.common.eventbus.Subscribe; import org.sleuthkit.autopsy.casemodule.multiusercases.CaseNodeData; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.File; import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.nio.file.Paths; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TimeZone; import java.util.UUID; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.ThreadSafe; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import org.openide.util.Exceptions; import org.openide.util.Lookup; import org.openide.util.NbBundle; import org.openide.util.NbBundle.Messages; import org.openide.util.actions.CallableSystemAction; import org.openide.windows.WindowManager; import org.sleuthkit.autopsy.actions.OpenOutputFolderAction; import org.sleuthkit.autopsy.appservices.AutopsyService; import org.sleuthkit.autopsy.appservices.AutopsyService.CaseContext; import org.sleuthkit.autopsy.casemodule.CaseMetadata.CaseMetadataException; import org.sleuthkit.autopsy.casemodule.datasourcesummary.DataSourceSummaryAction; import org.sleuthkit.autopsy.casemodule.events.AddingDataSourceEvent; import org.sleuthkit.autopsy.casemodule.events.AddingDataSourceFailedEvent; import org.sleuthkit.autopsy.casemodule.events.BlackBoardArtifactTagAddedEvent; import org.sleuthkit.autopsy.casemodule.events.BlackBoardArtifactTagDeletedEvent; import org.sleuthkit.autopsy.casemodule.events.CommentChangedEvent; import org.sleuthkit.autopsy.casemodule.events.ContentTagAddedEvent; import org.sleuthkit.autopsy.casemodule.events.ContentTagDeletedEvent; import org.sleuthkit.autopsy.casemodule.events.DataSourceAddedEvent; import org.sleuthkit.autopsy.casemodule.events.DataSourceDeletedEvent; import org.sleuthkit.autopsy.casemodule.events.DataSourceNameChangedEvent; import org.sleuthkit.autopsy.casemodule.events.ReportAddedEvent; import org.sleuthkit.autopsy.casemodule.multiusercases.CaseNodeData.CaseNodeDataException; import org.sleuthkit.autopsy.casemodule.multiusercases.CoordinationServiceUtils; import org.sleuthkit.autopsy.casemodule.services.Services; import org.sleuthkit.autopsy.commonpropertiessearch.CommonAttributeSearchAction; import org.sleuthkit.autopsy.communications.OpenCommVisualizationToolAction; import org.sleuthkit.autopsy.coordinationservice.CoordinationService; import org.sleuthkit.autopsy.coordinationservice.CoordinationService.CategoryNode; import org.sleuthkit.autopsy.coordinationservice.CoordinationService.CoordinationServiceException; import org.sleuthkit.autopsy.coordinationservice.CoordinationService.Lock; import org.sleuthkit.autopsy.core.RuntimeProperties; import org.sleuthkit.autopsy.core.UserPreferences; import org.sleuthkit.autopsy.core.UserPreferencesException; import org.sleuthkit.autopsy.corecomponentinterfaces.CoreComponentControl; import org.sleuthkit.autopsy.coreutils.DriveUtils; import org.sleuthkit.autopsy.coreutils.FileUtil; import org.sleuthkit.autopsy.coreutils.Logger; import org.sleuthkit.autopsy.coreutils.MessageNotifyUtil; import org.sleuthkit.autopsy.coreutils.NetworkUtils; import org.sleuthkit.autopsy.coreutils.PlatformUtil; import org.sleuthkit.autopsy.coreutils.ThreadUtils; import org.sleuthkit.autopsy.coreutils.TimeZoneUtils; import org.sleuthkit.autopsy.coreutils.Version; import org.sleuthkit.autopsy.events.AutopsyEvent; import org.sleuthkit.autopsy.events.AutopsyEventException; import org.sleuthkit.autopsy.events.AutopsyEventPublisher; import org.sleuthkit.autopsy.filequery.OpenFileDiscoveryAction; import org.sleuthkit.autopsy.ingest.IngestJob; import org.sleuthkit.autopsy.ingest.IngestManager; import org.sleuthkit.autopsy.ingest.IngestServices; import org.sleuthkit.autopsy.ingest.ModuleDataEvent; import org.sleuthkit.autopsy.keywordsearchservice.KeywordSearchService; import org.sleuthkit.autopsy.keywordsearchservice.KeywordSearchServiceException; import org.sleuthkit.autopsy.progress.LoggingProgressIndicator; import org.sleuthkit.autopsy.progress.ModalDialogProgressIndicator; import org.sleuthkit.autopsy.progress.ProgressIndicator; import org.sleuthkit.autopsy.timeline.OpenTimelineAction; import org.sleuthkit.autopsy.timeline.events.TimelineEventAddedEvent; import org.sleuthkit.datamodel.Blackboard; import org.sleuthkit.datamodel.BlackboardArtifact; import org.sleuthkit.datamodel.BlackboardArtifactTag; import org.sleuthkit.datamodel.CaseDbConnectionInfo; import org.sleuthkit.datamodel.Content; import org.sleuthkit.datamodel.ContentTag; import org.sleuthkit.datamodel.DataSource; import org.sleuthkit.datamodel.FileSystem; import org.sleuthkit.datamodel.Image; import org.sleuthkit.datamodel.Report; import org.sleuthkit.datamodel.SleuthkitCase; import org.sleuthkit.datamodel.TimelineManager; import org.sleuthkit.datamodel.SleuthkitCaseAdminUtil; import org.sleuthkit.datamodel.TskCoreException; import org.sleuthkit.datamodel.TskDataException; import org.sleuthkit.datamodel.TskUnsupportedSchemaVersionException; /** * An Autopsy case. Currently, only one case at a time may be open. */ public class Case { private static final int CASE_LOCK_TIMEOUT_MINS = 1; private static final int CASE_RESOURCES_LOCK_TIMEOUT_HOURS = 1; private static final String SINGLE_USER_CASE_DB_NAME = "autopsy.db"; private static final String EVENT_CHANNEL_NAME = "%s-Case-Events"; //NON-NLS private static final String CACHE_FOLDER = "Cache"; //NON-NLS private static final String EXPORT_FOLDER = "Export"; //NON-NLS private static final String LOG_FOLDER = "Log"; //NON-NLS private static final String REPORTS_FOLDER = "Reports"; //NON-NLS private static final String CONFIG_FOLDER = "Config"; // NON-NLS private static final String TEMP_FOLDER = "Temp"; //NON-NLS private static final String MODULE_FOLDER = "ModuleOutput"; //NON-NLS private static final String CASE_ACTION_THREAD_NAME = "%s-case-action"; private static final String CASE_RESOURCES_THREAD_NAME = "%s-manage-case-resources"; private static final String NO_NODE_ERROR_MSG_FRAGMENT = "KeeperErrorCode = NoNode"; private static final Logger logger = Logger.getLogger(Case.class.getName()); private static final AutopsyEventPublisher eventPublisher = new AutopsyEventPublisher(); private static final Object caseActionSerializationLock = new Object(); private static volatile Frame mainFrame; private static volatile Case currentCase; private final CaseMetadata metadata; private volatile ExecutorService caseActionExecutor; private CoordinationService.Lock caseLock; private SleuthkitCase caseDb; private final SleuthkitEventListener sleuthkitEventListener; private CollaborationMonitor collaborationMonitor; private Services caseServices; /* * Get a reference to the main window of the desktop application to use to * parent pop up dialogs and initialize the application name for use in * changing the main window title. */ static { WindowManager.getDefault().invokeWhenUIReady(() -> { mainFrame = WindowManager.getDefault().getMainWindow(); }); } /** * An enumeration of case types. */ public enum CaseType { SINGLE_USER_CASE("Single-user case"), //NON-NLS MULTI_USER_CASE("Multi-user case"); //NON-NLS private final String typeName; /** * Gets a case type from a case type name string. * * @param typeName The case type name string. * * @return */ public static CaseType fromString(String typeName) { if (typeName != null) { for (CaseType c : CaseType.values()) { if (typeName.equalsIgnoreCase(c.toString())) { return c; } } } return null; } /** * Gets the string representation of this case type. * * @return */ @Override public String toString() { return typeName; } /** * Gets the localized display name for this case type. * * @return The display name. */ @Messages({ "Case_caseType_singleUser=Single-user case", "Case_caseType_multiUser=Multi-user case" }) String getLocalizedDisplayName() { if (fromString(typeName) == SINGLE_USER_CASE) { return Bundle.Case_caseType_singleUser(); } else { return Bundle.Case_caseType_multiUser(); } } /** * Constructs a case type. * * @param typeName The type name. */ private CaseType(String typeName) { this.typeName = typeName; } /** * Tests the equality of the type name of this case type with another * case type name. * * @param otherTypeName A case type name, * * @return True or false, * * @deprecated Do not use. */ @Deprecated public boolean equalsName(String otherTypeName) { return (otherTypeName == null) ? false : typeName.equals(otherTypeName); } }; /** * An enumeration of the case events (property change events) a case may * publish (fire). */ public enum Events { /** * The name of the current case has changed. The old value of the * PropertyChangeEvent is the old case name (type: String), the new * value is the new case name (type: String). * * @deprecated CASE_DETAILS event should be used instead */ @Deprecated NAME, /** * The number of the current case has changed. The old value of the * PropertyChangeEvent is the old case number (type: String), the new * value is the new case number (type: String). * * @deprecated CASE_DETAILS event should be used instead */ @Deprecated NUMBER, /** * The examiner associated with the current case has changed. The old * value of the PropertyChangeEvent is the old examiner (type: String), * the new value is the new examiner (type: String). * * @deprecated CASE_DETAILS event should be used instead */ @Deprecated EXAMINER, /** * An attempt to add a new data source to the current case is being * made. The old and new values of the PropertyChangeEvent are null. * Cast the PropertyChangeEvent to * org.sleuthkit.autopsy.casemodule.events.AddingDataSourceEvent to * access additional event data. */ ADDING_DATA_SOURCE, /** * A failure to add a new data source to the current case has occurred. * The old and new values of the PropertyChangeEvent are null. Cast the * PropertyChangeEvent to * org.sleuthkit.autopsy.casemodule.events.AddingDataSourceFailedEvent * to access additional event data. */ ADDING_DATA_SOURCE_FAILED, /** * A new data source or series of data sources have been added to the * current case. The old value of the PropertyChangeEvent is null, the * new value is the newly-added data source (type: Content). Cast the * PropertyChangeEvent to * org.sleuthkit.autopsy.casemodule.events.DataSourceAddedEvent to * access additional event data. */ DATA_SOURCE_ADDED, /** * A data source has been deleted from the current case. The old value * of the PropertyChangeEvent is the object id of the data source that * was deleted (type: Long), the new value is null. */ DATA_SOURCE_DELETED, /** * A data source's name has changed. The new value of the property * change event is the new name. */ DATA_SOURCE_NAME_CHANGED, /** * The current case has changed. * * If a new case has been opened as the current case, the old value of * the PropertyChangeEvent is null, and the new value is the new case * (type: Case). * * If the current case has been closed, the old value of the * PropertyChangeEvent is the closed case (type: Case), and the new * value is null. IMPORTANT: Subscribers to this event should not call * isCaseOpen or getCurrentCase in the interval between a case closed * event and a case opened event. If there is any need for upon closing * interaction with a closed case, the case in the old value should be * used, and it should be done synchronously in the CURRENT_CASE event * handler. */ CURRENT_CASE, /** * A report has been added to the current case. The old value of the * PropertyChangeEvent is null, the new value is the report (type: * Report). */ REPORT_ADDED, /** * A report has been deleted from the current case. The old value of the * PropertyChangeEvent is the report (type: Report), the new value is * null. */ REPORT_DELETED, /** * An artifact associated with the current case has been tagged. The old * value of the PropertyChangeEvent is null, the new value is the tag * (type: BlackBoardArtifactTag). */ BLACKBOARD_ARTIFACT_TAG_ADDED, /** * A tag has been removed from an artifact associated with the current * case. The old value of the PropertyChangeEvent is the tag info (type: * BlackBoardArtifactTagDeletedEvent.DeletedBlackboardArtifactTagInfo), * the new value is null. */ BLACKBOARD_ARTIFACT_TAG_DELETED, /** * Content associated with the current case has been tagged. The old * value of the PropertyChangeEvent is null, the new value is the tag * (type: ContentTag). */ CONTENT_TAG_ADDED, /** * A tag has been removed from content associated with the current case. * The old value of the PropertyChangeEvent is is the tag info (type: * ContentTagDeletedEvent.DeletedContentTagInfo), the new value is null. */ CONTENT_TAG_DELETED, /** * The case display name or an optional detail which can be provided * regarding a case has been changed. The optional details include the * case number, the examiner name, examiner phone, examiner email, and * the case notes. */ CASE_DETAILS, /** * A tag definition has changed (e.g., description, known status). The * old value of the PropertyChangeEvent is the display name of the tag * definition that has changed. */ TAG_DEFINITION_CHANGED, /** * An timeline event, such mac time or web activity was added to the * current case. The old value is null and the new value is the * TimelineEvent that was added. */ TIMELINE_EVENT_ADDED, /* * An item in the central repository has had its comment modified. The * old value is null, the new value is string for current comment. */ CR_COMMENT_CHANGED; }; /** * An instance of this class is registered as a listener on the event bus * associated with the case database so that selected SleuthKit layer * application events can be published as Autopsy application events. */ private final class SleuthkitEventListener { @Subscribe public void publishTimelineEventAddedEvent(TimelineManager.TimelineEventAddedEvent event) { eventPublisher.publish(new TimelineEventAddedEvent(event)); } @SuppressWarnings("deprecation") @Subscribe public void publishArtifactsPostedEvent(Blackboard.ArtifactsPostedEvent event) { for (BlackboardArtifact.Type artifactType : event.getArtifactTypes()) { /* * IngestServices.fireModuleDataEvent is deprecated to * discourage ingest module writers from using it (they should * use org.sleuthkit.datamodel.Blackboard.postArtifact(s) * instead), but a way to publish * Blackboard.ArtifactsPostedEvents from the SleuthKit layer as * Autopsy ModuleDataEvents is still needed. */ IngestServices.getInstance().fireModuleDataEvent(new ModuleDataEvent( event.getModuleName(), artifactType, event.getArtifacts(artifactType))); } } } /** * Adds a subscriber to all case events. To subscribe to only specific * events, use one of the overloads of addEventSubscriber. * * @param listener The subscriber (PropertyChangeListener) to add. */ public static void addPropertyChangeListener(PropertyChangeListener listener) { addEventSubscriber(Stream.of(Events.values()) .map(Events::toString) .collect(Collectors.toSet()), listener); } /** * Removes a subscriber to all case events. To remove a subscription to only * specific events, use one of the overloads of removeEventSubscriber. * * @param listener The subscriber (PropertyChangeListener) to remove. */ public static void removePropertyChangeListener(PropertyChangeListener listener) { removeEventSubscriber(Stream.of(Events.values()) .map(Events::toString) .collect(Collectors.toSet()), listener); } /** * Adds a subscriber to specific case events. * * @param eventNames The events the subscriber is interested in. * @param subscriber The subscriber (PropertyChangeListener) to add. * * @deprecated Use addEventTypeSubscriber instead. */ @Deprecated public static void addEventSubscriber(Set<String> eventNames, PropertyChangeListener subscriber) { eventPublisher.addSubscriber(eventNames, subscriber); } /** * Adds a subscriber to specific case events. * * @param eventTypes The events the subscriber is interested in. * @param subscriber The subscriber (PropertyChangeListener) to add. */ public static void addEventTypeSubscriber(Set<Events> eventTypes, PropertyChangeListener subscriber) { eventTypes.forEach((Events event) -> { eventPublisher.addSubscriber(event.toString(), subscriber); }); } /** * Adds a subscriber to specific case events. * * @param eventName The event the subscriber is interested in. * @param subscriber The subscriber (PropertyChangeListener) to add. * * @deprecated Use addEventTypeSubscriber instead. */ @Deprecated public static void addEventSubscriber(String eventName, PropertyChangeListener subscriber) { eventPublisher.addSubscriber(eventName, subscriber); } /** * Removes a subscriber to specific case events. * * @param eventName The event the subscriber is no longer interested in. * @param subscriber The subscriber (PropertyChangeListener) to remove. */ public static void removeEventSubscriber(String eventName, PropertyChangeListener subscriber) { eventPublisher.removeSubscriber(eventName, subscriber); } /** * Removes a subscriber to specific case events. * * @param eventNames The event the subscriber is no longer interested in. * @param subscriber The subscriber (PropertyChangeListener) to remove. */ public static void removeEventSubscriber(Set<String> eventNames, PropertyChangeListener subscriber) { eventPublisher.removeSubscriber(eventNames, subscriber); } /** * Removes a subscriber to specific case events. * * @param eventTypes The events the subscriber is no longer interested in. * @param subscriber The subscriber (PropertyChangeListener) to remove. */ public static void removeEventTypeSubscriber(Set<Events> eventTypes, PropertyChangeListener subscriber) { eventTypes.forEach((Events event) -> { eventPublisher.removeSubscriber(event.toString(), subscriber); }); } /** * Checks if a case display name is valid, i.e., does not include any * characters that cannot be used in file names. * * @param caseName The candidate case name. * * @return True or false. */ public static boolean isValidName(String caseName) { return !(caseName.contains("\\") || caseName.contains("/") || caseName.contains(":") || caseName.contains("*") || caseName.contains("?") || caseName.contains("\"") || caseName.contains("<") || caseName.contains(">") || caseName.contains("|")); } /** * Creates a new case and makes it the current case. * * IMPORTANT: This method should not be called in the event dispatch thread * (EDT). * * @param caseDir The full path of the case directory. The directory * will be created if it doesn't already exist; if it * exists, it is ASSUMED it was created by calling * createCaseDirectory. * @param caseDisplayName The display name of case, which may be changed * later by the user. * @param caseNumber The case number, can be the empty string. * @param examiner The examiner to associate with the case, can be * the empty string. * @param caseType The type of case (single-user or multi-user). * * @throws CaseActionException If there is a problem creating the * case. * @throws CaseActionCancelledException If creating the case is cancelled. * * @deprecated use createAsCurrentCase(CaseType caseType, String caseDir, * CaseDetails caseDetails) instead */ @Deprecated public static void createAsCurrentCase(String caseDir, String caseDisplayName, String caseNumber, String examiner, CaseType caseType) throws CaseActionException, CaseActionCancelledException { createAsCurrentCase(caseType, caseDir, new CaseDetails(caseDisplayName, caseNumber, examiner, "", "", "")); } /** * Creates a new case and makes it the current case. * * IMPORTANT: This method should not be called in the event dispatch thread * (EDT). * * @param caseDir The full path of the case directory. The directory * will be created if it doesn't already exist; if it * exists, it is ASSUMED it was created by calling * createCaseDirectory. * @param caseType The type of case (single-user or multi-user). * @param caseDetails Contains the modifiable details of the case such as * the case display name, the case number, and the * examiner related data. * * @throws CaseActionException If there is a problem creating the * case. * @throws CaseActionCancelledException If creating the case is cancelled. */ @Messages({ "Case.exceptionMessage.emptyCaseName=Must specify a case name.", "Case.exceptionMessage.emptyCaseDir=Must specify a case directory path." }) public static void createAsCurrentCase(CaseType caseType, String caseDir, CaseDetails caseDetails) throws CaseActionException, CaseActionCancelledException { if (caseDetails.getCaseDisplayName().isEmpty()) { throw new CaseActionException(Bundle.Case_exceptionMessage_emptyCaseName()); } if (caseDir.isEmpty()) { throw new CaseActionException(Bundle.Case_exceptionMessage_emptyCaseDir()); } openAsCurrentCase(new Case(caseType, caseDir, caseDetails), true); } /** * Opens an existing case and makes it the current case. * * IMPORTANT: This method should not be called in the event dispatch thread * (EDT). * * @param caseMetadataFilePath The path of the case metadata (.aut) file. * * @throws CaseActionException If there is a problem opening the case. The * exception will have a user-friendly message * and may be a wrapper for a lower-level * exception. */ @Messages({ "# {0} - exception message", "Case.exceptionMessage.failedToReadMetadata=Failed to read case metadata:\n{0}.", "Case.exceptionMessage.cannotOpenMultiUserCaseNoSettings=Multi-user settings are missing (see Tools, Options, Multi-user tab), cannot open a multi-user case." }) public static void openAsCurrentCase(String caseMetadataFilePath) throws CaseActionException { CaseMetadata metadata; try { metadata = new CaseMetadata(Paths.get(caseMetadataFilePath)); } catch (CaseMetadataException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_failedToReadMetadata(ex.getLocalizedMessage()), ex); } if (CaseType.MULTI_USER_CASE == metadata.getCaseType() && !UserPreferences.getIsMultiUserModeEnabled()) { throw new CaseActionException(Bundle.Case_exceptionMessage_cannotOpenMultiUserCaseNoSettings()); } openAsCurrentCase(new Case(metadata), false); } /** * Checks if a case, the current case, is open at the time it is called. * * @return True or false. */ public static boolean isCaseOpen() { return currentCase != null; } /** * Gets the current case. This method should only be called by clients that * can be sure a case is currently open. Some examples of suitable clients * are data source processors, ingest modules, and report modules. * * @return The current case. */ public static Case getCurrentCase() { try { return getCurrentCaseThrows(); } catch (NoCurrentCaseException ex) { /* * Throw a runtime exception, since this is a programming error. */ throw new IllegalStateException(NbBundle.getMessage(Case.class, "Case.getCurCase.exception.noneOpen"), ex); } } /** * Gets the current case, if there is one, or throws an exception if there * is no current case. This method should only be called by methods known to * run in threads where it is possible that another thread has closed the * current case. The exception provides some protection from the * consequences of the race condition between the calling thread and a case * closing thread, but it is not fool-proof. Background threads calling this * method should put all operations in an exception firewall with a try and * catch-all block to handle the possibility of bad timing. * * @return The current case. * * @throws NoCurrentCaseException if there is no current case. */ public static Case getCurrentCaseThrows() throws NoCurrentCaseException { /* * TODO (JIRA-3825): Introduce a reference counting scheme for this get * case method. */ Case openCase = currentCase; if (openCase == null) { throw new NoCurrentCaseException(NbBundle.getMessage(Case.class, "Case.getCurCase.exception.noneOpen")); } else { return openCase; } } /** * Closes the current case. * * @throws CaseActionException If there is a problem closing the case. The * exception will have a user-friendly message * and may be a wrapper for a lower-level * exception. */ @Messages({ "# {0} - exception message", "Case.closeException.couldNotCloseCase=Error closing case: {0}", "Case.progressIndicatorTitle.closingCase=Closing Case" }) public static void closeCurrentCase() throws CaseActionException { synchronized (caseActionSerializationLock) { if (null == currentCase) { return; } Case closedCase = currentCase; try { eventPublisher.publishLocally(new AutopsyEvent(Events.CURRENT_CASE.toString(), closedCase, null)); logger.log(Level.INFO, "Closing current case {0} ({1}) in {2}", new Object[]{closedCase.getDisplayName(), closedCase.getName(), closedCase.getCaseDirectory()}); //NON-NLS currentCase = null; closedCase.doCloseCaseAction(); logger.log(Level.INFO, "Closed current case {0} ({1}) in {2}", new Object[]{closedCase.getDisplayName(), closedCase.getName(), closedCase.getCaseDirectory()}); //NON-NLS } catch (CaseActionException ex) { logger.log(Level.SEVERE, String.format("Error closing current case %s (%s) in %s", closedCase.getDisplayName(), closedCase.getName(), closedCase.getCaseDirectory()), ex); //NON-NLS throw ex; } finally { if (RuntimeProperties.runningWithGUI()) { updateGUIForCaseClosed(); } } } } /** * Deletes the current case. * * @throws CaseActionException If there is a problem deleting the case. The * exception will have a user-friendly message * and may be a wrapper for a lower-level * exception. */ public static void deleteCurrentCase() throws CaseActionException { synchronized (caseActionSerializationLock) { if (null == currentCase) { return; } CaseMetadata metadata = currentCase.getMetadata(); closeCurrentCase(); deleteCase(metadata); } } /** * Deletes a data source from the current case. * * @param dataSourceObjectID The object ID of the data source to delete. * * @throws CaseActionException If there is a problem deleting the case. The * exception will have a user-friendly message * and may be a wrapper for a lower-level * exception. */ @Messages({ "Case.progressIndicatorTitle.deletingDataSource=Removing Data Source" }) static void deleteDataSourceFromCurrentCase(Long dataSourceObjectID) throws CaseActionException { synchronized (caseActionSerializationLock) { if (null == currentCase) { return; } /* * Close the current case to release the shared case lock. */ CaseMetadata caseMetadata = currentCase.getMetadata(); closeCurrentCase(); /* * Re-open the case with an exclusive case lock, delete the data * source, and close the case again, releasing the exclusive case * lock. */ Case theCase = new Case(caseMetadata); theCase.doOpenCaseAction(Bundle.Case_progressIndicatorTitle_deletingDataSource(), theCase::deleteDataSource, CaseLockType.EXCLUSIVE, false, dataSourceObjectID); /* * Re-open the case with a shared case lock. */ openAsCurrentCase(new Case(caseMetadata), false); } } /** * Deletes a case. The case to be deleted must not be the "current case." * Deleting the current case must be done by calling Case.deleteCurrentCase. * * @param metadata The case metadata. * * @throws CaseActionException If there were one or more errors deleting the * case. The exception will have a user-friendly * message and may be a wrapper for a * lower-level exception. */ @Messages({ "Case.progressIndicatorTitle.deletingCase=Deleting Case", "Case.exceptionMessage.cannotDeleteCurrentCase=Cannot delete current case, it must be closed first.", "# {0} - case display name", "Case.exceptionMessage.deletionInterrupted=Deletion of the case {0} was cancelled." }) public static void deleteCase(CaseMetadata metadata) throws CaseActionException { synchronized (caseActionSerializationLock) { if (null != currentCase) { throw new CaseActionException(Bundle.Case_exceptionMessage_cannotDeleteCurrentCase()); } } ProgressIndicator progressIndicator; if (RuntimeProperties.runningWithGUI()) { progressIndicator = new ModalDialogProgressIndicator(mainFrame, Bundle.Case_progressIndicatorTitle_deletingCase()); } else { progressIndicator = new LoggingProgressIndicator(); } progressIndicator.start(Bundle.Case_progressMessage_preparing()); try { if (CaseType.SINGLE_USER_CASE == metadata.getCaseType()) { deleteSingleUserCase(metadata, progressIndicator); } else { try { deleteMultiUserCase(metadata, progressIndicator); } catch (InterruptedException ex) { /* * Note that task cancellation is not currently supported * for this code path, so this catch block is not expected * to be executed. */ throw new CaseActionException(Bundle.Case_exceptionMessage_deletionInterrupted(metadata.getCaseDisplayName()), ex); } } } finally { progressIndicator.finish(); } } /** * Opens a new or existing case as the current case. * * @param newCurrentCase The case. * @param isNewCase True for a new case, false otherwise. * * @throws CaseActionException If there is a problem creating the * case. * @throws CaseActionCancelledException If creating the case is cancelled. */ @Messages({ "Case.progressIndicatorTitle.creatingCase=Creating Case", "Case.progressIndicatorTitle.openingCase=Opening Case", "Case.exceptionMessage.cannotLocateMainWindow=Cannot locate main application window" }) private static void openAsCurrentCase(Case newCurrentCase, boolean isNewCase) throws CaseActionException, CaseActionCancelledException { synchronized (caseActionSerializationLock) { if (null != currentCase) { try { closeCurrentCase(); } catch (CaseActionException ex) { /* * Notify the user and continue (the error has already been * logged in closeCurrentCase. */ MessageNotifyUtil.Message.error(ex.getLocalizedMessage()); } } try { logger.log(Level.INFO, "Opening {0} ({1}) in {2} as the current case", new Object[]{newCurrentCase.getDisplayName(), newCurrentCase.getName(), newCurrentCase.getCaseDirectory()}); //NON-NLS String progressIndicatorTitle; CaseAction<ProgressIndicator, Object, Void> openCaseAction; if (isNewCase) { progressIndicatorTitle = Bundle.Case_progressIndicatorTitle_creatingCase(); openCaseAction = newCurrentCase::create; } else { progressIndicatorTitle = Bundle.Case_progressIndicatorTitle_openingCase(); openCaseAction = newCurrentCase::open; } newCurrentCase.doOpenCaseAction(progressIndicatorTitle, openCaseAction, CaseLockType.SHARED, true, null); currentCase = newCurrentCase; logger.log(Level.INFO, "Opened {0} ({1}) in {2} as the current case", new Object[]{newCurrentCase.getDisplayName(), newCurrentCase.getName(), newCurrentCase.getCaseDirectory()}); //NON-NLS if (RuntimeProperties.runningWithGUI()) { updateGUIForCaseOpened(newCurrentCase); } eventPublisher.publishLocally(new AutopsyEvent(Events.CURRENT_CASE.toString(), null, currentCase)); } catch (CaseActionCancelledException ex) { logger.log(Level.INFO, String.format("Cancelled opening %s (%s) in %s as the current case", newCurrentCase.getDisplayName(), newCurrentCase.getName(), newCurrentCase.getCaseDirectory())); //NON-NLS throw ex; } catch (CaseActionException ex) { logger.log(Level.SEVERE, String.format("Error opening %s (%s) in %s as the current case", newCurrentCase.getDisplayName(), newCurrentCase.getName(), newCurrentCase.getCaseDirectory()), ex); //NON-NLS throw ex; } } } /** * Transforms a case display name into a unique case name that can be used * to identify the case even if the display name is changed. * * @param caseDisplayName A case display name. * * @return The unique case name. */ private static String displayNameToUniqueName(String caseDisplayName) { /* * Replace all non-ASCII characters. */ String uniqueCaseName = caseDisplayName.replaceAll("[^\\p{ASCII}]", "_"); //NON-NLS /* * Replace all control characters. */ uniqueCaseName = uniqueCaseName.replaceAll("[\\p{Cntrl}]", "_"); //NON-NLS /* * Replace /, \, :, ?, space, ' ". */ uniqueCaseName = uniqueCaseName.replaceAll("[ /?:'\"\\\\]", "_"); //NON-NLS /* * Make it all lowercase. */ uniqueCaseName = uniqueCaseName.toLowerCase(); /* * Add a time stamp for uniqueness. */ SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss"); Date date = new Date(); uniqueCaseName = uniqueCaseName + "_" + dateFormat.format(date); return uniqueCaseName; } /** * Creates a case directory and its subdirectories. * * @param caseDirPath Path to the case directory (typically base + case * name). * @param caseType The type of case, single-user or multi-user. * * @throws CaseActionException throw if could not create the case dir */ public static void createCaseDirectory(String caseDirPath, CaseType caseType) throws CaseActionException { /* * Check the case directory path and permissions. The case directory may * already exist. */ File caseDir = new File(caseDirPath); if (caseDir.exists()) { if (caseDir.isFile()) { throw new CaseActionException(NbBundle.getMessage(Case.class, "Case.createCaseDir.exception.existNotDir", caseDirPath)); } else if (!caseDir.canRead() || !caseDir.canWrite()) { throw new CaseActionException(NbBundle.getMessage(Case.class, "Case.createCaseDir.exception.existCantRW", caseDirPath)); } } /* * Create the case directory, if it does not already exist. */ if (!caseDir.mkdirs()) { throw new CaseActionException(NbBundle.getMessage(Case.class, "Case.createCaseDir.exception.cantCreate", caseDirPath)); } /* * Create the subdirectories of the case directory, if they do not * already exist. Note that multi-user cases get an extra layer of * subdirectories, one subdirectory per application host machine. */ String hostPathComponent = ""; if (caseType == CaseType.MULTI_USER_CASE) { hostPathComponent = File.separator + NetworkUtils.getLocalHostName(); } Path exportDir = Paths.get(caseDirPath, hostPathComponent, EXPORT_FOLDER); if (!exportDir.toFile().mkdirs()) { throw new CaseActionException(NbBundle.getMessage(Case.class, "Case.createCaseDir.exception.cantCreateCaseDir", exportDir)); } Path logsDir = Paths.get(caseDirPath, hostPathComponent, LOG_FOLDER); if (!logsDir.toFile().mkdirs()) { throw new CaseActionException(NbBundle.getMessage(Case.class, "Case.createCaseDir.exception.cantCreateCaseDir", logsDir)); } Path tempDir = Paths.get(caseDirPath, hostPathComponent, TEMP_FOLDER); if (!tempDir.toFile().mkdirs()) { throw new CaseActionException(NbBundle.getMessage(Case.class, "Case.createCaseDir.exception.cantCreateCaseDir", tempDir)); } Path cacheDir = Paths.get(caseDirPath, hostPathComponent, CACHE_FOLDER); if (!cacheDir.toFile().mkdirs()) { throw new CaseActionException(NbBundle.getMessage(Case.class, "Case.createCaseDir.exception.cantCreateCaseDir", cacheDir)); } Path moduleOutputDir = Paths.get(caseDirPath, hostPathComponent, MODULE_FOLDER); if (!moduleOutputDir.toFile().mkdirs()) { throw new CaseActionException(NbBundle.getMessage(Case.class, "Case.createCaseDir.exception.cantCreateModDir", moduleOutputDir)); } Path reportsDir = Paths.get(caseDirPath, hostPathComponent, REPORTS_FOLDER); if (!reportsDir.toFile().mkdirs()) { throw new CaseActionException(NbBundle.getMessage(Case.class, "Case.createCaseDir.exception.cantCreateReportsDir", reportsDir)); } } /** * Gets the paths of data sources that are images. * * @param db A case database. * * @return A mapping of object ids to image paths. */ static Map<Long, String> getImagePaths(SleuthkitCase db) { Map<Long, String> imgPaths = new HashMap<>(); try { Map<Long, List<String>> imgPathsList = db.getImagePaths(); for (Map.Entry<Long, List<String>> entry : imgPathsList.entrySet()) { if (entry.getValue().size() > 0) { imgPaths.put(entry.getKey(), entry.getValue().get(0)); } } } catch (TskCoreException ex) { logger.log(Level.SEVERE, "Error getting image paths", ex); //NON-NLS } return imgPaths; } /** * Acquires an exclusive case resources lock. * * @param caseDir The full path of the case directory. * * @return The lock or null if the lock could not be acquired. * * @throws CaseActionException with a user-friendly message if the lock * cannot be acquired due to an exception. */ @Messages({ "Case.creationException.couldNotAcquireResourcesLock=Failed to get lock on case resources" }) private static CoordinationService.Lock acquireCaseResourcesLock(String caseDir) throws CaseActionException { try { Path caseDirPath = Paths.get(caseDir); String resourcesNodeName = CoordinationServiceUtils.getCaseResourcesNodePath(caseDirPath); Lock lock = CoordinationService.getInstance().tryGetExclusiveLock(CategoryNode.CASES, resourcesNodeName, CASE_RESOURCES_LOCK_TIMEOUT_HOURS, TimeUnit.HOURS); return lock; } catch (InterruptedException ex) { throw new CaseActionCancelledException(Bundle.Case_exceptionMessage_cancelled()); } catch (CoordinationServiceException ex) { throw new CaseActionException(Bundle.Case_creationException_couldNotAcquireResourcesLock(), ex); } } private static String getNameForTitle() { //Method should become unnecessary once technical debt story 3334 is done. if (UserPreferences.getAppName().equals(Version.getName())) { //Available version number is version number for this application return String.format("%s %s", UserPreferences.getAppName(), Version.getVersion()); } else { return UserPreferences.getAppName(); } } /** * Update the GUI to to reflect the current case. */ private static void updateGUIForCaseOpened(Case newCurrentCase) { if (RuntimeProperties.runningWithGUI()) { SwingUtilities.invokeLater(() -> { /* * If the case database was upgraded for a new schema and a * backup database was created, notify the user. */ SleuthkitCase caseDb = newCurrentCase.getSleuthkitCase(); String backupDbPath = caseDb.getBackupDatabasePath(); if (null != backupDbPath) { JOptionPane.showMessageDialog( mainFrame, NbBundle.getMessage(Case.class, "Case.open.msgDlg.updated.msg", backupDbPath), NbBundle.getMessage(Case.class, "Case.open.msgDlg.updated.title"), JOptionPane.INFORMATION_MESSAGE); } /* * Look for the files for the data sources listed in the case * database and give the user the opportunity to locate any that * are missing. */ Map<Long, String> imgPaths = getImagePaths(caseDb); for (Map.Entry<Long, String> entry : imgPaths.entrySet()) { long obj_id = entry.getKey(); String path = entry.getValue(); boolean fileExists = (new File(path).isFile() || DriveUtils.driveExists(path)); if (!fileExists) { int response = JOptionPane.showConfirmDialog( mainFrame, NbBundle.getMessage(Case.class, "Case.checkImgExist.confDlg.doesntExist.msg", path), NbBundle.getMessage(Case.class, "Case.checkImgExist.confDlg.doesntExist.title"), JOptionPane.YES_NO_OPTION); if (response == JOptionPane.YES_OPTION) { MissingImageDialog.makeDialog(obj_id, caseDb); } else { logger.log(Level.SEVERE, "User proceeding with missing image files"); //NON-NLS } } } /* * Enable the case-specific actions. */ CallableSystemAction.get(AddImageAction.class).setEnabled(FeatureAccessUtils.canAddDataSources()); CallableSystemAction.get(CaseCloseAction.class).setEnabled(true); CallableSystemAction.get(CaseDetailsAction.class).setEnabled(true); CallableSystemAction.get(DataSourceSummaryAction.class).setEnabled(true); CallableSystemAction.get(CaseDeleteAction.class).setEnabled(FeatureAccessUtils.canDeleteCurrentCase()); CallableSystemAction.get(OpenTimelineAction.class).setEnabled(true); CallableSystemAction.get(OpenCommVisualizationToolAction.class).setEnabled(true); CallableSystemAction.get(CommonAttributeSearchAction.class).setEnabled(true); CallableSystemAction.get(OpenOutputFolderAction.class).setEnabled(false); CallableSystemAction.get(OpenFileDiscoveryAction.class).setEnabled(true); /* * Add the case to the recent cases tracker that supplies a list * of recent cases to the recent cases menu item and the * open/create case dialog. */ RecentCases.getInstance().addRecentCase(newCurrentCase.getDisplayName(), newCurrentCase.getMetadata().getFilePath().toString()); /* * Open the top components (windows within the main application * window). * * Note: If the core windows are not opened here, they will be * opened via the DirectoryTreeTopComponent 'propertyChange()' * method on a DATA_SOURCE_ADDED event. */ if (newCurrentCase.hasData()) { CoreComponentControl.openCoreWindows(); } /* * Reset the main window title to: * * [curent case display name] - [application name]. */ mainFrame.setTitle(newCurrentCase.getDisplayName() + " - " + getNameForTitle()); }); } } /* * Update the GUI to to reflect the lack of a current case. */ private static void updateGUIForCaseClosed() { if (RuntimeProperties.runningWithGUI()) { SwingUtilities.invokeLater(() -> { /* * Close the top components (windows within the main application * window). */ CoreComponentControl.closeCoreWindows(); /* * Disable the case-specific menu items. */ CallableSystemAction.get(AddImageAction.class).setEnabled(false); CallableSystemAction.get(CaseCloseAction.class).setEnabled(false); CallableSystemAction.get(CaseDetailsAction.class).setEnabled(false); CallableSystemAction.get(DataSourceSummaryAction.class).setEnabled(false); CallableSystemAction.get(CaseDeleteAction.class).setEnabled(false); CallableSystemAction.get(OpenTimelineAction.class).setEnabled(false); CallableSystemAction.get(OpenCommVisualizationToolAction.class).setEnabled(false); CallableSystemAction.get(OpenOutputFolderAction.class).setEnabled(false); CallableSystemAction.get(CommonAttributeSearchAction.class).setEnabled(false); CallableSystemAction.get(OpenFileDiscoveryAction.class).setEnabled(false); /* * Clear the notifications in the notfier component in the lower * right hand corner of the main application window. */ MessageNotifyUtil.Notify.clear(); /* * Reset the main window title to be just the application name, * instead of [curent case display name] - [application name]. */ mainFrame.setTitle(getNameForTitle()); }); } } /** * Empties the temp subdirectory for the current case. */ private static void clearTempSubDir(String tempSubDirPath) { File tempFolder = new File(tempSubDirPath); if (tempFolder.isDirectory()) { File[] files = tempFolder.listFiles(); if (files.length > 0) { for (File file : files) { if (file.isDirectory()) { FileUtil.deleteDir(file); } else { file.delete(); } } } } } /** * Gets the case database. * * @return The case database. */ public SleuthkitCase getSleuthkitCase() { return this.caseDb; } /** * Gets the case services manager. * * @return The case services manager. */ public Services getServices() { return caseServices; } /** * Gets the case type. * * @return The case type. */ public CaseType getCaseType() { return metadata.getCaseType(); } /** * Gets the case create date. * * @return case The case create date. */ public String getCreatedDate() { return metadata.getCreatedDate(); } /** * Gets the unique and immutable case name. * * @return The case name. */ public String getName() { return metadata.getCaseName(); } /** * Gets the case name that can be changed by the user. * * @return The case display name. */ public String getDisplayName() { return metadata.getCaseDisplayName(); } /** * Gets the case number. * * @return The case number */ public String getNumber() { return metadata.getCaseNumber(); } /** * Gets the examiner name. * * @return The examiner name. */ public String getExaminer() { return metadata.getExaminer(); } /** * Gets the examiner phone number. * * @return The examiner phone number. */ public String getExaminerPhone() { return metadata.getExaminerPhone(); } /** * Gets the examiner email address. * * @return The examiner email address. */ public String getExaminerEmail() { return metadata.getExaminerEmail(); } /** * Gets the case notes. * * @return The case notes. */ public String getCaseNotes() { return metadata.getCaseNotes(); } /** * Gets the path to the top-level case directory. * * @return The top-level case directory path. */ public String getCaseDirectory() { return metadata.getCaseDirectory(); } /** * Gets the root case output directory for this case, creating it if it does * not exist. If the case is a single-user case, this is the case directory. * If the case is a multi-user case, this is a subdirectory of the case * directory specific to the host machine. * * @return the path to the host output directory. */ public String getOutputDirectory() { String caseDirectory = getCaseDirectory(); Path hostPath; if (CaseType.MULTI_USER_CASE == metadata.getCaseType()) { hostPath = Paths.get(caseDirectory, NetworkUtils.getLocalHostName()); } else { hostPath = Paths.get(caseDirectory); } if (!hostPath.toFile().exists()) { hostPath.toFile().mkdirs(); } return hostPath.toString(); } /** * Gets the full path to the temp directory for this case, creating it if it * does not exist. * * @return The temp subdirectory path. */ public String getTempDirectory() { return getOrCreateSubdirectory(TEMP_FOLDER); } /** * Gets the full path to the cache directory for this case, creating it if * it does not exist. * * @return The cache directory path. */ public String getCacheDirectory() { return getOrCreateSubdirectory(CACHE_FOLDER); } /** * Gets the full path to the export directory for this case, creating it if * it does not exist. * * @return The export directory path. */ public String getExportDirectory() { return getOrCreateSubdirectory(EXPORT_FOLDER); } /** * Gets the full path to the log directory for this case, creating it if it * does not exist. * * @return The log directory path. */ public String getLogDirectoryPath() { return getOrCreateSubdirectory(LOG_FOLDER); } /** * Gets the full path to the reports directory for this case, creating it if * it does not exist. * * @return The report directory path. */ public String getReportDirectory() { return getOrCreateSubdirectory(REPORTS_FOLDER); } /** * Gets the full path to the config directory for this case, creating it if * it does not exist. * * @return The config directory path. */ public String getConfigDirectory() { return getOrCreateSubdirectory(CONFIG_FOLDER); } /** * Gets the full path to the module output directory for this case, creating * it if it does not exist. * * @return The module output directory path. */ public String getModuleDirectory() { return getOrCreateSubdirectory(MODULE_FOLDER); } /** * Gets the path of the module output directory for this case, relative to * the case directory, creating it if it does not exist. * * @return The path to the module output directory, relative to the case * directory. */ public String getModuleOutputDirectoryRelativePath() { Path path = Paths.get(getModuleDirectory()); if (getCaseType() == CaseType.MULTI_USER_CASE) { return path.subpath(path.getNameCount() - 2, path.getNameCount()).toString(); } else { return path.subpath(path.getNameCount() - 1, path.getNameCount()).toString(); } } /** * Gets the data sources for the case. * * @return A list of data sources, possibly empty. * * @throws org.sleuthkit.datamodel.TskCoreException if there is a problem * querying the case * database. */ public List<Content> getDataSources() throws TskCoreException { return caseDb.getRootObjects(); } /** * Gets the time zone(s) of the image data source(s) in this case. * * @return The set of time zones in use. */ public Set<TimeZone> getTimeZones() { Set<TimeZone> timezones = new HashSet<>(); try { for (Content c : getDataSources()) { final Content dataSource = c.getDataSource(); if ((dataSource != null) && (dataSource instanceof Image)) { Image image = (Image) dataSource; timezones.add(TimeZone.getTimeZone(image.getTimeZone())); } } } catch (TskCoreException ex) { logger.log(Level.SEVERE, "Error getting data source time zones", ex); //NON-NLS } return timezones; } /** * Gets the name of the legacy keyword search index for the case. Not for * general use. * * @return The index name. */ public String getTextIndexName() { return getMetadata().getTextIndexName(); } /** * Queries whether or not the case has data, i.e., whether or not at least * one data source has been added to the case. * * @return True or false. */ public boolean hasData() { boolean hasDataSources = false; try { hasDataSources = (getDataSources().size() > 0); } catch (TskCoreException ex) { logger.log(Level.SEVERE, "Error accessing case database", ex); //NON-NLS } return hasDataSources; } /** * Notifies case event subscribers that a data source is being added to the * case. * * This should not be called from the event dispatch thread (EDT) * * @param eventId A unique identifier for the event. This UUID must be used * to call notifyFailedAddingDataSource or * notifyNewDataSource after the data source is added. */ public void notifyAddingDataSource(UUID eventId) { eventPublisher.publish(new AddingDataSourceEvent(eventId)); } /** * Notifies case event subscribers that a data source failed to be added to * the case. * * This should not be called from the event dispatch thread (EDT) * * @param addingDataSourceEventId The unique identifier for the * corresponding adding data source event * (see notifyAddingDataSource). */ public void notifyFailedAddingDataSource(UUID addingDataSourceEventId) { eventPublisher.publish(new AddingDataSourceFailedEvent(addingDataSourceEventId)); } /** * Notifies case event subscribers that a data source has been added to the * case database. * * This should not be called from the event dispatch thread (EDT) * * @param dataSource The data source. * @param addingDataSourceEventId The unique identifier for the * corresponding adding data source event * (see notifyAddingDataSource). */ public void notifyDataSourceAdded(Content dataSource, UUID addingDataSourceEventId) { eventPublisher.publish(new DataSourceAddedEvent(dataSource, addingDataSourceEventId)); } /** * Notifies case event subscribers that a data source has been added to the * case database. * * This should not be called from the event dispatch thread (EDT) * * @param dataSource The data source. * @param newName The new name for the data source */ public void notifyDataSourceNameChanged(Content dataSource, String newName) { eventPublisher.publish(new DataSourceNameChangedEvent(dataSource, newName)); } /** * Notifies case event subscribers that a content tag has been added. * * This should not be called from the event dispatch thread (EDT) * * @param newTag new ContentTag added */ public void notifyContentTagAdded(ContentTag newTag) { eventPublisher.publish(new ContentTagAddedEvent(newTag)); } /** * Notifies case event subscribers that a content tag has been deleted. * * This should not be called from the event dispatch thread (EDT) * * @param deletedTag ContentTag deleted */ public void notifyContentTagDeleted(ContentTag deletedTag) { eventPublisher.publish(new ContentTagDeletedEvent(deletedTag)); } /** * Notifies case event subscribers that a tag definition has changed. * * This should not be called from the event dispatch thread (EDT) * * @param changedTagName the name of the tag definition which was changed */ public void notifyTagDefinitionChanged(String changedTagName) { //leaving new value of changedTagName as null, because we do not currently support changing the display name of a tag. eventPublisher.publish(new AutopsyEvent(Events.TAG_DEFINITION_CHANGED.toString(), changedTagName, null)); } /** * Notifies case event subscribers that a central repository comment has * been changed. * * This should not be called from the event dispatch thread (EDT) * * @param contentId the objectId for the Content which has had its central * repo comment changed * @param newComment the new value of the comment */ public void notifyCentralRepoCommentChanged(long contentId, String newComment) { try { eventPublisher.publish(new CommentChangedEvent(contentId, newComment)); } catch (NoCurrentCaseException ex) { logger.log(Level.WARNING, "Unable to send notifcation regarding comment change due to no current case being open", ex); } } /** * Notifies case event subscribers that an artifact tag has been added. * * This should not be called from the event dispatch thread (EDT) * * @param newTag new BlackboardArtifactTag added */ public void notifyBlackBoardArtifactTagAdded(BlackboardArtifactTag newTag) { eventPublisher.publish(new BlackBoardArtifactTagAddedEvent(newTag)); } /** * Notifies case event subscribers that an artifact tag has been deleted. * * This should not be called from the event dispatch thread (EDT) * * @param deletedTag BlackboardArtifactTag deleted */ public void notifyBlackBoardArtifactTagDeleted(BlackboardArtifactTag deletedTag) { eventPublisher.publish(new BlackBoardArtifactTagDeletedEvent(deletedTag)); } /** * Adds a report to the case. * * @param localPath The path of the report file, must be in the case * directory or one of its subdirectories. * @param srcModuleName The name of the module that created the report. * @param reportName The report name, may be empty. * * @throws TskCoreException if there is a problem adding the report to the * case database. */ public void addReport(String localPath, String srcModuleName, String reportName) throws TskCoreException { addReport(localPath, srcModuleName, reportName, null); } /** * Adds a report to the case. * * @param localPath The path of the report file, must be in the case * directory or one of its subdirectories. * @param srcModuleName The name of the module that created the report. * @param reportName The report name, may be empty. * @param parent The Content used to create the report, if available. * * @return The new Report instance. * * @throws TskCoreException if there is a problem adding the report to the * case database. */ public Report addReport(String localPath, String srcModuleName, String reportName, Content parent) throws TskCoreException { String normalizedLocalPath; try { if (localPath.toLowerCase().contains("http:")) { normalizedLocalPath = localPath; } else { normalizedLocalPath = Paths.get(localPath).normalize().toString(); } } catch (InvalidPathException ex) { String errorMsg = "Invalid local path provided: " + localPath; // NON-NLS throw new TskCoreException(errorMsg, ex); } Report report = this.caseDb.addReport(normalizedLocalPath, srcModuleName, reportName, parent); eventPublisher.publish(new ReportAddedEvent(report)); return report; } /** * Gets the reports that have been added to the case. * * @return A collection of report objects. * * @throws TskCoreException if there is a problem querying the case * database. */ public List<Report> getAllReports() throws TskCoreException { return this.caseDb.getAllReports(); } /** * Deletes one or more reports from the case database. Does not delete the * report files. * * @param reports The report(s) to be deleted from the case. * * @throws TskCoreException if there is an error deleting the report(s). */ public void deleteReports(Collection<? extends Report> reports) throws TskCoreException { for (Report report : reports) { this.caseDb.deleteReport(report); eventPublisher.publish(new AutopsyEvent(Events.REPORT_DELETED.toString(), report, null)); } } /** * Gets the case metadata. * * @return A CaseMetaData object. */ CaseMetadata getMetadata() { return metadata; } /** * Updates the case details. * * @param newDisplayName the new display name for the case * * @throws org.sleuthkit.autopsy.casemodule.CaseActionException */ @Messages({ "Case.exceptionMessage.metadataUpdateError=Failed to update case metadata" }) void updateCaseDetails(CaseDetails caseDetails) throws CaseActionException { CaseDetails oldCaseDetails = metadata.getCaseDetails(); try { metadata.setCaseDetails(caseDetails); } catch (CaseMetadataException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_metadataUpdateError(), ex); } if (getCaseType() == CaseType.MULTI_USER_CASE && !oldCaseDetails.getCaseDisplayName().equals(caseDetails.getCaseDisplayName())) { try { CaseNodeData nodeData = CaseNodeData.readCaseNodeData(metadata.getCaseDirectory()); nodeData.setDisplayName(caseDetails.getCaseDisplayName()); CaseNodeData.writeCaseNodeData(nodeData); } catch (CaseNodeDataException | InterruptedException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_couldNotUpdateCaseNodeData(ex.getLocalizedMessage()), ex); } } if (!oldCaseDetails.getCaseNumber().equals(caseDetails.getCaseNumber())) { eventPublisher.publish(new AutopsyEvent(Events.NUMBER.toString(), oldCaseDetails.getCaseNumber(), caseDetails.getCaseNumber())); } if (!oldCaseDetails.getExaminerName().equals(caseDetails.getExaminerName())) { eventPublisher.publish(new AutopsyEvent(Events.NUMBER.toString(), oldCaseDetails.getExaminerName(), caseDetails.getExaminerName())); } if (!oldCaseDetails.getCaseDisplayName().equals(caseDetails.getCaseDisplayName())) { eventPublisher.publish(new AutopsyEvent(Events.NAME.toString(), oldCaseDetails.getCaseDisplayName(), caseDetails.getCaseDisplayName())); } eventPublisher.publish(new AutopsyEvent(Events.CASE_DETAILS.toString(), oldCaseDetails, caseDetails)); if (RuntimeProperties.runningWithGUI()) { SwingUtilities.invokeLater(() -> { mainFrame.setTitle(caseDetails.getCaseDisplayName() + " - " + getNameForTitle()); try { RecentCases.getInstance().updateRecentCase(oldCaseDetails.getCaseDisplayName(), metadata.getFilePath().toString(), caseDetails.getCaseDisplayName(), metadata.getFilePath().toString()); } catch (Exception ex) { logger.log(Level.SEVERE, "Error updating case name in UI", ex); //NON-NLS } }); } } /** * Constructs a Case object for a new Autopsy case. * * @param caseType The type of case (single-user or multi-user). * @param caseDir The full path of the case directory. The directory * will be created if it doesn't already exist; if it * exists, it is ASSUMED it was created by calling * createCaseDirectory. * @param caseDetails Contains details of the case, such as examiner, * display name, etc * */ private Case(CaseType caseType, String caseDir, CaseDetails caseDetails) { this(new CaseMetadata(caseType, caseDir, displayNameToUniqueName(caseDetails.getCaseDisplayName()), caseDetails)); } /** * Constructs a Case object for an existing Autopsy case. * * @param caseMetaData The metadata for the case. */ private Case(CaseMetadata caseMetaData) { metadata = caseMetaData; sleuthkitEventListener = new SleuthkitEventListener(); } /** * Performs a case action that involves creating or opening a case. If the * case is a multi-user case, the action is done after acquiring a * coordination service case lock. This case lock must be released in the * same thread in which it was acquired, as required by the coordination * service. A single-threaded executor is therefore created to do the case * opening action, and is saved for an eventual case closing action. * * IMPORTANT: If an open case action for a multi-user case is terminated * because an exception is thrown or the action is cancelled, the action is * responsible for releasing the case lock while still running in the case * action executor's thread. This method assumes this has been done and * performs an orderly shut down of the case action executor. * * @param progressIndicatorTitle A title for the progress indicator for the * case action. * @param caseAction The case action method. * @param caseLockType The type of case lock required for the case * action. * @param allowCancellation Whether or not to allow the action to be * cancelled. * @param additionalParams An Object that holds any additional * parameters for a case action. * * @throws CaseActionException If there is a problem completing the action. * The exception will have a user-friendly * message and may be a wrapper for a * lower-level exception. */ @Messages({ "Case.progressIndicatorCancelButton.label=Cancel", "Case.progressMessage.preparing=Preparing...", "Case.progressMessage.cancelling=Cancelling...", "Case.exceptionMessage.cancelled=Cancelled.", "# {0} - exception message", "Case.exceptionMessage.execExceptionWrapperMessage={0}" }) private void doOpenCaseAction(String progressIndicatorTitle, CaseAction<ProgressIndicator, Object, Void> caseAction, CaseLockType caseLockType, boolean allowCancellation, Object additionalParams) throws CaseActionException { /* * Create and start either a GUI progress indicator (with or without a * cancel button) or a logging progress indicator. */ CancelButtonListener cancelButtonListener = null; ProgressIndicator progressIndicator; if (RuntimeProperties.runningWithGUI()) { if (allowCancellation) { cancelButtonListener = new CancelButtonListener(Bundle.Case_progressMessage_cancelling()); progressIndicator = new ModalDialogProgressIndicator( mainFrame, progressIndicatorTitle, new String[]{Bundle.Case_progressIndicatorCancelButton_label()}, Bundle.Case_progressIndicatorCancelButton_label(), cancelButtonListener); } else { progressIndicator = new ModalDialogProgressIndicator( mainFrame, progressIndicatorTitle); } } else { progressIndicator = new LoggingProgressIndicator(); } progressIndicator.start(Bundle.Case_progressMessage_preparing()); /* * Do the case action in the single thread in the case action executor. * If the case is a multi-user case, a case lock is acquired and held * until explictly released and an exclusive case resources lock is * aquired and held for the duration of the action. */ TaskThreadFactory threadFactory = new TaskThreadFactory(String.format(CASE_ACTION_THREAD_NAME, metadata.getCaseName())); caseActionExecutor = Executors.newSingleThreadExecutor(threadFactory); Future<Void> future = caseActionExecutor.submit(() -> { if (CaseType.SINGLE_USER_CASE == metadata.getCaseType()) { caseAction.execute(progressIndicator, additionalParams); } else { acquireCaseLock(caseLockType); try (CoordinationService.Lock resourcesLock = acquireCaseResourcesLock(metadata.getCaseDirectory())) { if (null == resourcesLock) { throw new CaseActionException(Bundle.Case_creationException_couldNotAcquireResourcesLock()); } caseAction.execute(progressIndicator, additionalParams); } catch (CaseActionException ex) { releaseCaseLock(); throw ex; } } return null; }); if (null != cancelButtonListener) { cancelButtonListener.setCaseActionFuture(future); } /* * Wait for the case action task to finish. */ try { future.get(); } catch (InterruptedException discarded) { /* * The thread this method is running in has been interrupted. */ if (null != cancelButtonListener) { cancelButtonListener.actionPerformed(null); } else { future.cancel(true); } ThreadUtils.shutDownTaskExecutor(caseActionExecutor); } catch (CancellationException discarded) { /* * The case action has been cancelled. */ ThreadUtils.shutDownTaskExecutor(caseActionExecutor); throw new CaseActionCancelledException(Bundle.Case_exceptionMessage_cancelled()); } catch (ExecutionException ex) { /* * The case action has thrown an exception. */ ThreadUtils.shutDownTaskExecutor(caseActionExecutor); throw new CaseActionException(Bundle.Case_exceptionMessage_execExceptionWrapperMessage(ex.getCause().getLocalizedMessage()), ex); } finally { progressIndicator.finish(); } } /** * A case action (interface CaseAction<T, V, R>) that creates the case * directory and case database and opens the application services for this * case. * * @param progressIndicator A progress indicator. * @param additionalParams An Object that holds any additional parameters * for a case action. For this action, this is * null. * * @throws CaseActionException If there is a problem completing the action. * The exception will have a user-friendly * message and may be a wrapper for a * lower-level exception. */ private Void create(ProgressIndicator progressIndicator, Object additionalParams) throws CaseActionException { assert (additionalParams == null); try { checkForCancellation(); createCaseDirectoryIfDoesNotExist(progressIndicator); checkForCancellation(); switchLoggingToCaseLogsDirectory(progressIndicator); checkForCancellation(); saveCaseMetadataToFile(progressIndicator); checkForCancellation(); createCaseNodeData(progressIndicator); checkForCancellation(); checkForCancellation(); createCaseDatabase(progressIndicator); checkForCancellation(); openCaseLevelServices(progressIndicator); checkForCancellation(); openAppServiceCaseResources(progressIndicator); checkForCancellation(); openCommunicationChannels(progressIndicator); return null; } catch (CaseActionException ex) { /* * Cancellation or failure. The sleep is a little hack to clear the * interrupted flag for this thread if this is a cancellation * scenario, so that the clean up can run to completion in the * current thread. */ try { Thread.sleep(1); } catch (InterruptedException discarded) { } close(progressIndicator); throw ex; } } /** * A case action (interface CaseAction<T, V, R>) that opens the case * database and application services for this case. * * @param progressIndicator A progress indicator. * @param additionalParams An Object that holds any additional parameters * for a case action. For this action, this is * null. * * @throws CaseActionException If there is a problem completing the action. * The exception will have a user-friendly * message and may be a wrapper for a * lower-level exception. */ private Void open(ProgressIndicator progressIndicator, Object additionalParams) throws CaseActionException { assert (additionalParams == null); try { checkForCancellation(); switchLoggingToCaseLogsDirectory(progressIndicator); checkForCancellation(); updateCaseNodeData(progressIndicator); checkForCancellation(); deleteTempfilesFromCaseDirectory(progressIndicator); checkForCancellation(); openCaseDataBase(progressIndicator); checkForCancellation(); openCaseLevelServices(progressIndicator); checkForCancellation(); openAppServiceCaseResources(progressIndicator); checkForCancellation(); openCommunicationChannels(progressIndicator); checkForCancellation(); openFileSystems(); return null; } catch (CaseActionException ex) { /* * Cancellation or failure. The sleep is a little hack to clear the * interrupted flag for this thread if this is a cancellation * scenario, so that the clean up can run to completion in the * current thread. */ try { Thread.sleep(1); } catch (InterruptedException discarded) { } close(progressIndicator); throw ex; } } /** * Reads a sector from each file system of each image of a case to do an eager open of the filesystems in case. * @throws CaseActionCancelledException Exception thrown if task is cancelled. */ private void openFileSystems() throws CaseActionCancelledException { String caseName = (this.caseDb != null) ? this.caseDb.getDatabaseName() : "null"; List<Image> images = null; try { images = this.caseDb.getImages(); } catch (TskCoreException ex) { logger.log( Level.SEVERE, String.format("Could not obtain images while opening case: %s.", caseName), ex); return; } checkForCancellation(); byte[] tempBuff = new byte[512]; for (Image image : images) { Collection<FileSystem> fileSystems = this.caseDb.getFileSystems(image); checkForCancellation(); for (FileSystem fileSystem : fileSystems) { try { fileSystem.read(tempBuff, 0, 512); } catch (TskCoreException ex) { String imageStr = image.getName(); String fileSysStr = fileSystem.getName(); logger.log( Level.WARNING, String.format("Could not open filesystem: %s in image: %s for case: %s.", fileSysStr, imageStr, caseName), ex); } checkForCancellation(); } } } /** * A case action (interface CaseAction<T, V, R>) that opens a case, deletes * a data source from the case, and closes the case. * * @param progressIndicator A progress indicator. * @param additionalParams An Object that holds any additional parameters * for a case action. For this action, this the * object ID of the data source to be deleted. * * @throws CaseActionException If there is a problem completing the action. * The exception will have a user-friendly * message and may be a wrapper for a * lower-level exception. */ @Messages({ "Case.progressMessage.deletingDataSource=Removing the data source from the case...", "Case.exceptionMessage.dataSourceNotFound=The data source was not found.", "Case.exceptionMessage.errorDeletingDataSourceFromCaseDb=An error occurred while removing the data source from the case database.", "Case.exceptionMessage.errorDeletingDataSourceFromTextIndex=An error occurred while removing the data source from the text index.",}) Void deleteDataSource(ProgressIndicator progressIndicator, Object additionalParams) throws CaseActionException { assert (additionalParams instanceof Long); open(progressIndicator, null); try { progressIndicator.progress(Bundle.Case_progressMessage_deletingDataSource()); Long dataSourceObjectID = (Long) additionalParams; try { DataSource dataSource = this.caseDb.getDataSource(dataSourceObjectID); if (dataSource == null) { throw new CaseActionException(Bundle.Case_exceptionMessage_dataSourceNotFound()); } SleuthkitCaseAdminUtil.deleteDataSource(this.caseDb, dataSourceObjectID); } catch (TskDataException | TskCoreException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_errorDeletingDataSourceFromCaseDb(), ex); } try { this.caseServices.getKeywordSearchService().deleteDataSource(dataSourceObjectID); } catch (KeywordSearchServiceException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_errorDeletingDataSourceFromTextIndex(), ex); } eventPublisher.publish(new DataSourceDeletedEvent(dataSourceObjectID)); return null; } finally { close(progressIndicator); releaseCaseLock(); } } /** * Create an empty portable case from the current case * * @param caseName Case name * @param portableCaseFolder Case folder - must not exist * * @return The portable case database * * @throws TskCoreException */ public SleuthkitCase createPortableCase(String caseName, File portableCaseFolder) throws TskCoreException { if (portableCaseFolder.exists()) { throw new TskCoreException("Portable case folder " + portableCaseFolder.toString() + " already exists"); } if (!portableCaseFolder.mkdirs()) { throw new TskCoreException("Error creating portable case folder " + portableCaseFolder.toString()); } CaseDetails details = new CaseDetails(caseName, getNumber(), getExaminer(), getExaminerPhone(), getExaminerEmail(), getCaseNotes()); try { CaseMetadata portableCaseMetadata = new CaseMetadata(Case.CaseType.SINGLE_USER_CASE, portableCaseFolder.toString(), caseName, details, metadata); portableCaseMetadata.setCaseDatabaseName(SINGLE_USER_CASE_DB_NAME); } catch (CaseMetadataException ex) { throw new TskCoreException("Error creating case metadata", ex); } // Create the Sleuthkit case SleuthkitCase portableSleuthkitCase; String dbFilePath = Paths.get(portableCaseFolder.toString(), SINGLE_USER_CASE_DB_NAME).toString(); portableSleuthkitCase = SleuthkitCase.newCase(dbFilePath); return portableSleuthkitCase; } /** * Checks current thread for an interrupt. Usage: checking for user * cancellation of a case creation/opening operation, as reflected in the * exception message. * * @throws CaseActionCancelledException If the current thread is * interrupted, assumes interrupt was * due to a user action. */ private static void checkForCancellation() throws CaseActionCancelledException { if (Thread.currentThread().isInterrupted()) { throw new CaseActionCancelledException(Bundle.Case_exceptionMessage_cancelled()); } } /** * Creates the case directory, if it does not already exist. * * @param progressIndicator A progress indicator. * * @throws CaseActionException If there is a problem completing the * operation. The exception will have a * user-friendly message and may be a wrapper * for a lower-level exception. */ @Messages({ "Case.progressMessage.creatingCaseDirectory=Creating case directory..." }) private void createCaseDirectoryIfDoesNotExist(ProgressIndicator progressIndicator) throws CaseActionException { /* * TODO (JIRA-2180): Always create the case directory as part of the * case creation process. */ progressIndicator.progress(Bundle.Case_progressMessage_creatingCaseDirectory()); if (new File(metadata.getCaseDirectory()).exists() == false) { progressIndicator.progress(Bundle.Case_progressMessage_creatingCaseDirectory()); Case.createCaseDirectory(metadata.getCaseDirectory(), metadata.getCaseType()); } } /** * Switches from writing log messages to the application logs to the logs * subdirectory of the case directory. * * @param progressIndicator A progress indicator. */ @Messages({ "Case.progressMessage.switchingLogDirectory=Switching log directory..." }) private void switchLoggingToCaseLogsDirectory(ProgressIndicator progressIndicator) { progressIndicator.progress(Bundle.Case_progressMessage_switchingLogDirectory()); Logger.setLogDirectory(getLogDirectoryPath()); } /** * Saves teh case metadata to a file.SHould not be called until the case * directory has been created. * * @param progressIndicator A progress indicator. * * @throws CaseActionException If there is a problem completing the * operation. The exception will have a * user-friendly message and may be a wrapper * for a lower-level exception. */ @Messages({ "Case.progressMessage.savingCaseMetadata=Saving case metadata to file...", "# {0} - exception message", "Case.exceptionMessage.couldNotSaveCaseMetadata=Failed to save case metadata:\n{0}." }) private void saveCaseMetadataToFile(ProgressIndicator progressIndicator) throws CaseActionException { progressIndicator.progress(Bundle.Case_progressMessage_savingCaseMetadata()); try { this.metadata.writeToFile(); } catch (CaseMetadataException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_couldNotSaveCaseMetadata(ex.getLocalizedMessage()), ex); } } /** * Creates the node data for the case directory lock coordination service * node. * * @param progressIndicator A progress indicator. * * @throws CaseActionException If there is a problem completing the * operation. The exception will have a * user-friendly message and may be a wrapper * for a lower-level exception. */ @Messages({ "Case.progressMessage.creatingCaseNodeData=Creating coordination service node data...", "# {0} - exception message", "Case.exceptionMessage.couldNotCreateCaseNodeData=Failed to create coordination service node data:\n{0}." }) private void createCaseNodeData(ProgressIndicator progressIndicator) throws CaseActionException { if (getCaseType() == CaseType.MULTI_USER_CASE) { progressIndicator.progress(Bundle.Case_progressMessage_creatingCaseNodeData()); try { CaseNodeData.createCaseNodeData(metadata); } catch (CaseNodeDataException | InterruptedException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_couldNotCreateCaseNodeData(ex.getLocalizedMessage()), ex); } } } /** * Updates the node data for the case directory lock coordination service * node. * * @param progressIndicator A progress indicator. * * @throws CaseActionException If there is a problem completing the * operation. The exception will have a * user-friendly message and may be a wrapper * for a lower-level exception. */ @Messages({ "Case.progressMessage.updatingCaseNodeData=Updating coordination service node data...", "# {0} - exception message", "Case.exceptionMessage.couldNotUpdateCaseNodeData=Failed to update coordination service node data:\n{0}." }) private void updateCaseNodeData(ProgressIndicator progressIndicator) throws CaseActionException { if (getCaseType() == CaseType.MULTI_USER_CASE) { progressIndicator.progress(Bundle.Case_progressMessage_updatingCaseNodeData()); try { CaseNodeData nodeData = CaseNodeData.readCaseNodeData(metadata.getCaseDirectory()); nodeData.setLastAccessDate(new Date()); CaseNodeData.writeCaseNodeData(nodeData); } catch (CaseNodeDataException | InterruptedException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_couldNotUpdateCaseNodeData(ex.getLocalizedMessage()), ex); } } } /** * Deletes any files in the temp subdirectory of the case directory. * * @param progressIndicator A progress indicator. */ @Messages({ "Case.progressMessage.clearingTempDirectory=Clearing case temp directory..." }) private void deleteTempfilesFromCaseDirectory(ProgressIndicator progressIndicator) { /* * Clear the temp subdirectory of the case directory. */ progressIndicator.progress(Bundle.Case_progressMessage_clearingTempDirectory()); Case.clearTempSubDir(this.getTempDirectory()); } /** * Creates the node data for the case directory lock coordination service * node, the case directory, the case database and the case metadata file. * * @param progressIndicator A progress indicator. * * @throws CaseActionException If there is a problem completing the * operation. The exception will have a * user-friendly message and may be a wrapper * for a lower-level exception. */ @Messages({ "Case.progressMessage.creatingCaseDatabase=Creating case database...", "# {0} - exception message", "Case.exceptionMessage.couldNotGetDbServerConnectionInfo=Failed to get case database server conneciton info:\n{0}.", "# {0} - exception message", "Case.exceptionMessage.couldNotCreateCaseDatabase=Failed to create case database:\n{0}.", "# {0} - exception message", "Case.exceptionMessage.couldNotSaveDbNameToMetadataFile=Failed to save case database name to case metadata file:\n{0}." }) private void createCaseDatabase(ProgressIndicator progressIndicator) throws CaseActionException { progressIndicator.progress(Bundle.Case_progressMessage_creatingCaseDatabase()); try { if (CaseType.SINGLE_USER_CASE == metadata.getCaseType()) { /* * For single-user cases, the case database is a SQLite database * with a standard name, physically located in the case * directory. */ caseDb = SleuthkitCase.newCase(Paths.get(metadata.getCaseDirectory(), SINGLE_USER_CASE_DB_NAME).toString()); metadata.setCaseDatabaseName(SINGLE_USER_CASE_DB_NAME); } else { /* * For multi-user cases, the case database is a PostgreSQL * database with a name derived from the case display name, * physically located on the PostgreSQL database server. */ caseDb = SleuthkitCase.newCase(metadata.getCaseDisplayName(), UserPreferences.getDatabaseConnectionInfo(), metadata.getCaseDirectory()); metadata.setCaseDatabaseName(caseDb.getDatabaseName()); } } catch (TskCoreException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_couldNotCreateCaseDatabase(ex.getLocalizedMessage()), ex); } catch (UserPreferencesException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_couldNotGetDbServerConnectionInfo(ex.getLocalizedMessage()), ex); } catch (CaseMetadataException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_couldNotSaveDbNameToMetadataFile(ex.getLocalizedMessage()), ex); } } /** * Updates the node data for an existing case directory lock coordination * service node and opens an existing case database. * * @param progressIndicator A progress indicator. * * @throws CaseActionException If there is a problem completing the * operation. The exception will have a * user-friendly message and may be a wrapper * for a lower-level exception. */ @Messages({ "Case.progressMessage.openingCaseDatabase=Opening case database...", "# {0} - exception message", "Case.exceptionMessage.couldNotOpenCaseDatabase=Failed to open case database:\n{0}.", "# {0} - exception message", "Case.exceptionMessage.unsupportedSchemaVersionMessage=Unsupported case database schema version:\n{0}.", "Case.open.exception.multiUserCaseNotEnabled=Cannot open a multi-user case if multi-user cases are not enabled. See Tools, Options, Multi-User." }) private void openCaseDataBase(ProgressIndicator progressIndicator) throws CaseActionException { progressIndicator.progress(Bundle.Case_progressMessage_openingCaseDatabase()); try { String databaseName = metadata.getCaseDatabaseName(); if (CaseType.SINGLE_USER_CASE == metadata.getCaseType()) { caseDb = SleuthkitCase.openCase(Paths.get(metadata.getCaseDirectory(), databaseName).toString()); } else if (UserPreferences.getIsMultiUserModeEnabled()) { caseDb = SleuthkitCase.openCase(databaseName, UserPreferences.getDatabaseConnectionInfo(), metadata.getCaseDirectory()); } else { throw new CaseActionException(Bundle.Case_open_exception_multiUserCaseNotEnabled()); } } catch (TskUnsupportedSchemaVersionException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_unsupportedSchemaVersionMessage(ex.getLocalizedMessage()), ex); } catch (UserPreferencesException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_couldNotGetDbServerConnectionInfo(ex.getLocalizedMessage()), ex); } catch (TskCoreException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_couldNotOpenCaseDatabase(ex.getLocalizedMessage()), ex); } } /** * Opens the case-level services: the files manager, tags manager and * blackboard. * * @param progressIndicator A progress indicator. */ @Messages({ "Case.progressMessage.openingCaseLevelServices=Opening case-level services...",}) private void openCaseLevelServices(ProgressIndicator progressIndicator) { progressIndicator.progress(Bundle.Case_progressMessage_openingCaseLevelServices()); this.caseServices = new Services(caseDb); /* * RC Note: JM put this initialization here. I'm not sure why. However, * my attempt to put it in the openCaseDatabase method seems to lead to * intermittent unchecked exceptions concerning a missing subscriber. */ caseDb.registerForEvents(sleuthkitEventListener); } /** * Allows any registered application-level services to open resources * specific to this case. * * @param progressIndicator A progress indicator. * * @throws CaseActionException If there is a problem completing the * operation. The exception will have a * user-friendly message and may be a wrapper * for a lower-level exception. */ @NbBundle.Messages({ "Case.progressMessage.openingApplicationServiceResources=Opening application service case resources...", "# {0} - service name", "Case.serviceOpenCaseResourcesProgressIndicator.title={0} Opening Case Resources", "# {0} - service name", "Case.serviceOpenCaseResourcesProgressIndicator.cancellingMessage=Cancelling opening case resources by {0}...", "# {0} - service name", "Case.servicesException.notificationTitle={0} Error" }) private void openAppServiceCaseResources(ProgressIndicator progressIndicator) throws CaseActionException { /* * Each service gets its own independently cancellable/interruptible * task, running in a named thread managed by an executor service, with * its own progress indicator. This allows for cancellation of the * opening of case resources for individual services. It also makes it * possible to ensure that each service task completes before the next * one starts by awaiting termination of the executor service. */ progressIndicator.progress(Bundle.Case_progressMessage_openingApplicationServiceResources()); for (AutopsyService service : Lookup.getDefault().lookupAll(AutopsyService.class )) { /* * Create a progress indicator for the task and start the task. If * running with a GUI, the progress indicator will be a dialog box * with a Cancel button. */ CancelButtonListener cancelButtonListener = null; ProgressIndicator appServiceProgressIndicator; if (RuntimeProperties.runningWithGUI()) { cancelButtonListener = new CancelButtonListener(Bundle.Case_serviceOpenCaseResourcesProgressIndicator_cancellingMessage(service.getServiceName())); appServiceProgressIndicator = new ModalDialogProgressIndicator( mainFrame, Bundle.Case_serviceOpenCaseResourcesProgressIndicator_title(service.getServiceName()), new String[]{Bundle.Case_progressIndicatorCancelButton_label()}, Bundle.Case_progressIndicatorCancelButton_label(), cancelButtonListener); } else { appServiceProgressIndicator = new LoggingProgressIndicator(); } appServiceProgressIndicator.start(Bundle.Case_progressMessage_preparing()); AutopsyService.CaseContext context = new AutopsyService.CaseContext(this, appServiceProgressIndicator); String threadNameSuffix = service.getServiceName().replaceAll("[ ]", "-"); //NON-NLS threadNameSuffix = threadNameSuffix.toLowerCase(); TaskThreadFactory threadFactory = new TaskThreadFactory(String.format(CASE_RESOURCES_THREAD_NAME, threadNameSuffix)); ExecutorService executor = Executors.newSingleThreadExecutor(threadFactory); Future<Void> future = executor.submit(() -> { service.openCaseResources(context); return null; }); if (null != cancelButtonListener) { cancelButtonListener.setCaseContext(context); cancelButtonListener.setCaseActionFuture(future); } /* * Wait for the task to either be completed or * cancelled/interrupted, or for the opening of the case to be * cancelled. */ try { future.get(); } catch (InterruptedException discarded) { /* * The parent create/open case task has been cancelled. */ Case.logger.log(Level.WARNING, String.format("Opening of %s (%s) in %s cancelled during opening of case resources by %s", getDisplayName(), getName(), getCaseDirectory(), service.getServiceName())); future.cancel(true); } catch (CancellationException discarded) { /* * The opening of case resources by the application service has * been cancelled, so the executor service has thrown. Note that * there is no guarantee the task itself has responded to the * cancellation request yet. */ Case.logger.log(Level.WARNING, String.format("Opening of case resources by %s for %s (%s) in %s cancelled", service.getServiceName(), getDisplayName(), getName(), getCaseDirectory(), service.getServiceName())); } catch (ExecutionException ex) { /* * An exception was thrown while executing the task. The * case-specific application service resources are not * essential. Log an error and notify the user if running the * desktop GUI, but do not throw. */ Case.logger.log(Level.SEVERE, String.format("%s failed to open case resources for %s", service.getServiceName(), this.getDisplayName()), ex); if (RuntimeProperties.runningWithGUI()) { SwingUtilities.invokeLater(() -> { MessageNotifyUtil.Notify.error(Bundle.Case_servicesException_notificationTitle(service.getServiceName()), ex.getLocalizedMessage()); }); } } finally { /* * Shut down the executor service and wait for it to finish. * This ensures that the task has finished. Without this, it * would be possible to start the next task before the current * task responded to a cancellation request. */ ThreadUtils.shutDownTaskExecutor(executor); appServiceProgressIndicator.finish(); } checkForCancellation(); } } /** * If this case is a multi-user case, sets up for communication with other * application nodes. * * @param progressIndicator A progress indicator. * * @throws CaseActionException If there is a problem completing the * operation. The exception will have a * user-friendly message and may be a wrapper * for a lower-level exception. */ @Messages({ "Case.progressMessage.settingUpNetworkCommunications=Setting up network communications...", "# {0} - exception message", "Case.exceptionMessage.couldNotOpenRemoteEventChannel=Failed to open remote events channel:\n{0}.", "# {0} - exception message", "Case.exceptionMessage.couldNotCreatCollaborationMonitor=Failed to create collaboration monitor:\n{0}." }) private void openCommunicationChannels(ProgressIndicator progressIndicator) throws CaseActionException { if (CaseType.MULTI_USER_CASE == metadata.getCaseType()) { progressIndicator.progress(Bundle.Case_progressMessage_settingUpNetworkCommunications()); try { eventPublisher.openRemoteEventChannel(String.format(EVENT_CHANNEL_NAME, metadata.getCaseName())); checkForCancellation(); collaborationMonitor = new CollaborationMonitor(metadata.getCaseName()); } catch (AutopsyEventException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_couldNotOpenRemoteEventChannel(ex.getLocalizedMessage()), ex); } catch (CollaborationMonitor.CollaborationMonitorException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_couldNotCreatCollaborationMonitor(ex.getLocalizedMessage()), ex); } } } /** * Performs a case action that involves closing a case opened by calling * doOpenCaseAction. If the case is a multi-user case, the coordination * service case lock acquired by the call to doOpenCaseAction is released. * This case lock must be released in the same thread in which it was * acquired, as required by the coordination service. The single-threaded * executor saved during the case opening action is therefore used to do the * case closing action. * * @throws CaseActionException If there is a problem completing the action. * The exception will have a user-friendly * message and may be a wrapper for a * lower-level exception. */ private void doCloseCaseAction() throws CaseActionException { /* * Set up either a GUI progress indicator without a Cancel button or a * logging progress indicator. */ ProgressIndicator progressIndicator; if (RuntimeProperties.runningWithGUI()) { progressIndicator = new ModalDialogProgressIndicator( mainFrame, Bundle.Case_progressIndicatorTitle_closingCase()); } else { progressIndicator = new LoggingProgressIndicator(); } progressIndicator.start(Bundle.Case_progressMessage_preparing()); /* * Closing a case is always done in the same non-UI thread that * opened/created the case. If the case is a multi-user case, this * ensures that case lock that is held as long as the case is open is * released in the same thread in which it was acquired, as is required * by the coordination service. */ Future<Void> future = caseActionExecutor.submit(() -> { if (CaseType.SINGLE_USER_CASE == metadata.getCaseType()) { close(progressIndicator); } else { /* * Acquire an exclusive case resources lock to ensure only one * node at a time can create/open/upgrade/close the case * resources. */ progressIndicator.progress(Bundle.Case_progressMessage_preparing()); try (CoordinationService.Lock resourcesLock = acquireCaseResourcesLock(metadata.getCaseDirectory())) { if (null == resourcesLock) { throw new CaseActionException(Bundle.Case_creationException_couldNotAcquireResourcesLock()); } close(progressIndicator); } finally { /* * Always release the case directory lock that was acquired * when the case was opened. */ releaseCaseLock(); } } return null; }); try { future.get(); } catch (InterruptedException | CancellationException unused) { /* * The wait has been interrupted by interrupting the thread running * this method. Not allowing cancellation of case closing, so ignore * the interrupt. Likewise, cancellation of the case closing task is * not supported. */ } catch (ExecutionException ex) { throw new CaseActionException(Bundle.Case_exceptionMessage_execExceptionWrapperMessage(ex.getCause().getMessage()), ex); } finally { ThreadUtils.shutDownTaskExecutor(caseActionExecutor); progressIndicator.finish(); } } /** * Closes the case. * * @param progressIndicator A progress indicator. */ @Messages({ "Case.progressMessage.shuttingDownNetworkCommunications=Shutting down network communications...", "Case.progressMessage.closingApplicationServiceResources=Closing case-specific application service resources...", "Case.progressMessage.closingCaseDatabase=Closing case database..." }) private void close(ProgressIndicator progressIndicator) { IngestManager.getInstance().cancelAllIngestJobs(IngestJob.CancellationReason.CASE_CLOSED); /* * Stop sending/receiving case events to and from other nodes if this is * a multi-user case. */ if (CaseType.MULTI_USER_CASE == metadata.getCaseType()) { progressIndicator.progress(Bundle.Case_progressMessage_shuttingDownNetworkCommunications()); if (null != collaborationMonitor) { collaborationMonitor.shutdown(); } eventPublisher.closeRemoteEventChannel(); } /* * Allow all registered application services providers to close * resources related to the case. */ progressIndicator.progress(Bundle.Case_progressMessage_closingApplicationServiceResources()); closeAppServiceCaseResources(); /* * Close the case database. */ if (null != caseDb) { progressIndicator.progress(Bundle.Case_progressMessage_closingCaseDatabase()); caseDb.unregisterForEvents(sleuthkitEventListener); caseDb.close(); } /* * Switch the log directory. */ progressIndicator.progress(Bundle.Case_progressMessage_switchingLogDirectory()); Logger.setLogDirectory(PlatformUtil.getLogDirectory()); } /** * Allows any registered application-level services to close any resources * specific to this case. */ @Messages({ "# {0} - serviceName", "Case.serviceCloseResourcesProgressIndicator.title={0} Closing Case Resources", "# {0} - service name", "# {1} - exception message", "Case.servicesException.serviceResourcesCloseError=Could not close case resources for {0} service: {1}" }) private void closeAppServiceCaseResources() { /* * Each service gets its own independently cancellable task, and thus * its own task progress indicator. */ for (AutopsyService service : Lookup.getDefault().lookupAll(AutopsyService.class )) { ProgressIndicator progressIndicator; if (RuntimeProperties.runningWithGUI()) { progressIndicator = new ModalDialogProgressIndicator( mainFrame, Bundle.Case_serviceCloseResourcesProgressIndicator_title(service.getServiceName())); } else { progressIndicator = new LoggingProgressIndicator(); } progressIndicator.start(Bundle.Case_progressMessage_preparing()); AutopsyService.CaseContext context = new AutopsyService.CaseContext(this, progressIndicator); String threadNameSuffix = service.getServiceName().replaceAll("[ ]", "-"); //NON-NLS threadNameSuffix = threadNameSuffix.toLowerCase(); TaskThreadFactory threadFactory = new TaskThreadFactory(String.format(CASE_RESOURCES_THREAD_NAME, threadNameSuffix)); ExecutorService executor = Executors.newSingleThreadExecutor(threadFactory); Future<Void> future = executor.submit(() -> { service.closeCaseResources(context); return null; }); try { future.get(); } catch (InterruptedException ex) { Case.logger.log(Level.SEVERE, String.format("Unexpected interrupt while waiting on %s service to close case resources", service.getServiceName()), ex); } catch (CancellationException ex) { Case.logger.log(Level.SEVERE, String.format("Unexpected cancellation while waiting on %s service to close case resources", service.getServiceName()), ex); } catch (ExecutionException ex) { Case.logger.log(Level.SEVERE, String.format("%s service failed to open case resources", service.getServiceName()), ex); if (RuntimeProperties.runningWithGUI()) { SwingUtilities.invokeLater(() -> MessageNotifyUtil.Notify.error( Bundle.Case_servicesException_notificationTitle(service.getServiceName()), Bundle.Case_servicesException_serviceResourcesCloseError(service.getServiceName(), ex.getLocalizedMessage()))); } } finally { ThreadUtils.shutDownTaskExecutor(executor); progressIndicator.finish(); } } } /** * Acquires a case (case directory) lock for the current case. * * @throws CaseActionException If the lock cannot be acquired. */ @Messages({ "Case.lockingException.couldNotAcquireSharedLock=Failed to get an shared lock on the case.", "Case.lockingException.couldNotAcquireExclusiveLock=Failed to get a exclusive lock on the case." }) private void acquireCaseLock(CaseLockType lockType) throws CaseActionException { String caseDir = metadata.getCaseDirectory(); try { CoordinationService coordinationService = CoordinationService.getInstance(); caseLock = lockType == CaseLockType.SHARED ? coordinationService.tryGetSharedLock(CategoryNode.CASES, caseDir, CASE_LOCK_TIMEOUT_MINS, TimeUnit.MINUTES) : coordinationService.tryGetExclusiveLock(CategoryNode.CASES, caseDir, CASE_LOCK_TIMEOUT_MINS, TimeUnit.MINUTES); if (caseLock == null) { if (lockType == CaseLockType.SHARED) { throw new CaseActionException(Bundle.Case_lockingException_couldNotAcquireSharedLock()); } else { throw new CaseActionException(Bundle.Case_lockingException_couldNotAcquireExclusiveLock()); } } } catch (InterruptedException | CoordinationServiceException ex) { if (lockType == CaseLockType.SHARED) { throw new CaseActionException(Bundle.Case_lockingException_couldNotAcquireSharedLock(), ex); } else { throw new CaseActionException(Bundle.Case_lockingException_couldNotAcquireExclusiveLock(), ex); } } } /** * Releases a case (case directory) lock for the current case. */ private void releaseCaseLock() { if (caseLock != null) { try { caseLock.release(); caseLock = null; } catch (CoordinationService.CoordinationServiceException ex) { logger.log(Level.SEVERE, String.format("Failed to release shared case directory lock for %s", getMetadata().getCaseDirectory()), ex); } } } /** * Gets the path to the specified subdirectory of the case directory, * creating it if it does not already exist. * * @return The absolute path to the specified subdirectory. */ private String getOrCreateSubdirectory(String subDirectoryName) { File subDirectory = Paths.get(getOutputDirectory(), subDirectoryName).toFile(); if (!subDirectory.exists()) { subDirectory.mkdirs(); } return subDirectory.toString(); } /** * Deletes a single-user case. * * @param metadata The case metadata. * @param progressIndicator A progress indicator. * * @throws CaseActionException If there were one or more errors deleting the * case. The exception will have a user-friendly * message and may be a wrapper for a * lower-level exception. */ @Messages({ "Case.exceptionMessage.errorsDeletingCase=Errors occured while deleting the case. See the application log for details." }) private static void deleteSingleUserCase(CaseMetadata metadata, ProgressIndicator progressIndicator) throws CaseActionException { boolean errorsOccurred = false; try { deleteTextIndex(metadata, progressIndicator); } catch (KeywordSearchServiceException ex) { errorsOccurred = true; logger.log(Level.WARNING, String.format("Failed to delete text index for %s (%s) in %s", metadata.getCaseDisplayName(), metadata.getCaseName(), metadata.getCaseDirectory()), ex); //NON-NLS } try { deleteCaseDirectory(metadata, progressIndicator); } catch (CaseActionException ex) { errorsOccurred = true; logger.log(Level.WARNING, String.format("Failed to delete case directory for %s (%s) in %s", metadata.getCaseDisplayName(), metadata.getCaseName(), metadata.getCaseDirectory()), ex); //NON-NLS } deleteFromRecentCases(metadata, progressIndicator); if (errorsOccurred) { throw new CaseActionException(Bundle.Case_exceptionMessage_errorsDeletingCase()); } } /** * Deletes a multi-user case. This method does so after acquiring the case * directory coordination service lock and is intended to be used for * deleting simple multi-user cases without auto ingest input. Note that the * case directory coordination service node for the case is only deleted if * no errors occurred. * * @param metadata The case metadata. * @param progressIndicator A progress indicator. * * @throws CaseActionException If there were one or more errors deleting * the case. The exception will have a * user-friendly message and may be a wrapper * for a lower-level exception. * @throws InterruptedException If the thread this code is running in is * interrupted while blocked, i.e., if * cancellation of the operation is detected * during a wait. */ @Messages({ "Case.progressMessage.connectingToCoordSvc=Connecting to coordination service...", "# {0} - exception message", "Case.exceptionMessage.failedToConnectToCoordSvc=Failed to connect to coordination service:\n{0}.", "Case.exceptionMessage.cannotGetLockToDeleteCase=Cannot delete case because it is open for another user or host.", "# {0} - exception message", "Case.exceptionMessage.failedToLockCaseForDeletion=Failed to exclusively lock case for deletion:\n{0}.", "Case.progressMessage.fetchingCoordSvcNodeData=Fetching coordination service node data for the case...", "# {0} - exception message", "Case.exceptionMessage.failedToFetchCoordSvcNodeData=Failed to fetch coordination service node data:\n{0}.", "Case.progressMessage.deletingResourcesCoordSvcNode=Deleting case resources coordination service node...", "Case.progressMessage.deletingCaseDirCoordSvcNode=Deleting case directory coordination service node..." }) private static void deleteMultiUserCase(CaseMetadata metadata, ProgressIndicator progressIndicator) throws CaseActionException, InterruptedException { progressIndicator.progress(Bundle.Case_progressMessage_connectingToCoordSvc()); CoordinationService coordinationService; try { coordinationService = CoordinationService.getInstance(); } catch (CoordinationServiceException ex) { logger.log(Level.SEVERE, String.format("Failed to connect to coordination service when attempting to delete %s (%s) in %s", metadata.getCaseDisplayName(), metadata.getCaseName(), metadata.getCaseDirectory()), ex); //NON-NLS throw new CaseActionException(Bundle.Case_exceptionMessage_failedToConnectToCoordSvc(ex.getLocalizedMessage())); } CaseNodeData caseNodeData; boolean errorsOccurred = false; try (CoordinationService.Lock dirLock = coordinationService.tryGetExclusiveLock(CategoryNode.CASES, metadata.getCaseDirectory())) { if (dirLock == null) { logger.log(Level.INFO, String.format("Could not delete %s (%s) in %s because a case directory lock was held by another host", metadata.getCaseDisplayName(), metadata.getCaseName(), metadata.getCaseDirectory())); //NON-NLS throw new CaseActionException(Bundle.Case_exceptionMessage_cannotGetLockToDeleteCase()); } progressIndicator.progress(Bundle.Case_progressMessage_fetchingCoordSvcNodeData()); try { caseNodeData = CaseNodeData.readCaseNodeData(metadata.getCaseDirectory()); } catch (CaseNodeDataException | InterruptedException ex) { logger.log(Level.SEVERE, String.format("Failed to get coordination service node data %s (%s) in %s", metadata.getCaseDisplayName(), metadata.getCaseName(), metadata.getCaseDirectory()), ex); //NON-NLS throw new CaseActionException(Bundle.Case_exceptionMessage_failedToFetchCoordSvcNodeData(ex.getLocalizedMessage())); } errorsOccurred = deleteMultiUserCase(caseNodeData, metadata, progressIndicator, logger); progressIndicator.progress(Bundle.Case_progressMessage_deletingResourcesCoordSvcNode()); try { String resourcesLockNodePath = CoordinationServiceUtils.getCaseResourcesNodePath(caseNodeData.getDirectory()); coordinationService.deleteNode(CategoryNode.CASES, resourcesLockNodePath); } catch (CoordinationServiceException ex) { if (!isNoNodeException(ex)) { errorsOccurred = true; logger.log(Level.WARNING, String.format("Error deleting the case resources coordination service node for the case at %s (%s) in %s", metadata.getCaseDisplayName(), metadata.getCaseName(), metadata.getCaseDirectory()), ex); //NON-NLS } } catch (InterruptedException ex) { logger.log(Level.WARNING, String.format("Error deleting the case resources coordination service node for the case at %s (%s) in %s", metadata.getCaseDisplayName(), metadata.getCaseName(), metadata.getCaseDirectory()), ex); //NON-NLS } } catch (CoordinationServiceException ex) { logger.log(Level.SEVERE, String.format("Error exclusively locking the case directory for %s (%s) in %s", metadata.getCaseDisplayName(), metadata.getCaseName(), metadata.getCaseDirectory()), ex); //NON-NLS throw new CaseActionException(Bundle.Case_exceptionMessage_failedToLockCaseForDeletion(ex.getLocalizedMessage())); } if (!errorsOccurred) { progressIndicator.progress(Bundle.Case_progressMessage_deletingCaseDirCoordSvcNode()); try { String casDirNodePath = CoordinationServiceUtils.getCaseDirectoryNodePath(caseNodeData.getDirectory()); coordinationService.deleteNode(CategoryNode.CASES, casDirNodePath); } catch (CoordinationServiceException | InterruptedException ex) { logger.log(Level.SEVERE, String.format("Error deleting the case directory lock node for %s (%s) in %s", metadata.getCaseDisplayName(), metadata.getCaseName(), metadata.getCaseDirectory()), ex); //NON-NLS errorsOccurred = true; } } if (errorsOccurred) { throw new CaseActionException(Bundle.Case_exceptionMessage_errorsDeletingCase()); } } /** * IMPORTANT: This is a "beta" method and is subject to change or removal * without notice! * * Deletes a mulit-user case by attempting to delete the case database, the * text index, the case directory, and the case resources coordination * service node for a case, and removes the case from the recent cases menu * of the main application window. Callers of this method MUST acquire and * release the case directory lock for the case and are responsible for * deleting the corresponding coordination service nodes, if desired. * * @param caseNodeData The coordination service node data for the case. * @param metadata The case metadata. * @param progressIndicator A progress indicator. * @param logger A logger. * * @return True if one or more errors occurred (see log for details), false * otherwise. * * @throws InterruptedException If the thread this code is running in is * interrupted while blocked, i.e., if * cancellation of the operation is detected * during a wait. */ @Beta public static boolean deleteMultiUserCase(CaseNodeData caseNodeData, CaseMetadata metadata, ProgressIndicator progressIndicator, Logger logger) throws InterruptedException { boolean errorsOccurred = false; try { deleteMultiUserCaseDatabase(caseNodeData, metadata, progressIndicator, logger); deleteMultiUserCaseTextIndex(caseNodeData, metadata, progressIndicator, logger); deleteMultiUserCaseDirectory(caseNodeData, metadata, progressIndicator, logger); deleteFromRecentCases(metadata, progressIndicator); } catch (UserPreferencesException | ClassNotFoundException | SQLException ex) { errorsOccurred = true; logger.log(Level.WARNING, String.format("Failed to delete the case database for %s (%s) in %s", metadata.getCaseDisplayName(), metadata.getCaseName(), metadata.getCaseDirectory()), ex); //NON-NLS } catch (KeywordSearchServiceException ex) { errorsOccurred = true; logger.log(Level.WARNING, String.format("Failed to delete the text index for %s (%s) in %s", metadata.getCaseDisplayName(), metadata.getCaseName(), metadata.getCaseDirectory()), ex); //NON-NLS } catch (CaseActionException ex) { errorsOccurred = true; logger.log(Level.WARNING, String.format("Failed to delete the case directory for %s (%s) in %s", metadata.getCaseDisplayName(), metadata.getCaseName(), metadata.getCaseDirectory()), ex); //NON-NLS } return errorsOccurred; } /** * Attempts to delete the case database for a multi-user case. * * @param caseNodeData The coordination service node data for the case. * @param metadata The case metadata. * @param progressIndicator A progress indicator. * @param logger A logger. * * @throws UserPreferencesException if there is an error getting the * database server connection info. * @throws ClassNotFoundException if there is an error gettting the * required JDBC driver. * @throws SQLException if there is an error executing the SQL * to drop the database from the database * server. * @throws InterruptedException If interrupted while blocked waiting for * coordination service data to be written * to the coordination service node * database. */ @Messages({ "Case.progressMessage.deletingCaseDatabase=Deleting case database..." }) private static void deleteMultiUserCaseDatabase(CaseNodeData caseNodeData, CaseMetadata metadata, ProgressIndicator progressIndicator, Logger logger) throws UserPreferencesException, ClassNotFoundException, SQLException, InterruptedException { if (!caseNodeData.isDeletedFlagSet(CaseNodeData.DeletedFlags.CASE_DB)) { progressIndicator.progress(Bundle.Case_progressMessage_deletingCaseDatabase()); logger.log(Level.INFO, String.format("Deleting case database for %s (%s) in %s", caseNodeData.getDisplayName(), caseNodeData.getName(), caseNodeData.getDirectory())); //NON-NLS CaseDbConnectionInfo info = UserPreferences.getDatabaseConnectionInfo(); String url = "jdbc:postgresql://" + info.getHost() + ":" + info.getPort() + "/postgres"; //NON-NLS Class.forName("org.postgresql.Driver"); //NON-NLS try (Connection connection = DriverManager.getConnection(url, info.getUserName(), info.getPassword()); Statement statement = connection.createStatement()) { String dbExistsQuery = "SELECT 1 from pg_database WHERE datname = '" + metadata.getCaseDatabaseName() + "'"; //NON-NLS try (ResultSet queryResult = statement.executeQuery(dbExistsQuery)) { if (queryResult.next()) { String deleteCommand = "DROP DATABASE \"" + metadata.getCaseDatabaseName() + "\""; //NON-NLS statement.execute(deleteCommand); } } } setDeletedItemFlag(caseNodeData, CaseNodeData.DeletedFlags.CASE_DB); } } /** * Attempts to delete the text index for a multi-user case. * * @param caseNodeData The coordination service node data for the case. * @param metadata The case metadata. * @param progressIndicator A progress indicator. * @param logger A logger. * * @throws KeywordSearchServiceException If there is an error deleting the * text index. * @throws InterruptedException If interrupted while blocked * waiting for coordination service * data to be written to the * coordination service node database. */ private static void deleteMultiUserCaseTextIndex(CaseNodeData caseNodeData, CaseMetadata metadata, ProgressIndicator progressIndicator, Logger logger) throws KeywordSearchServiceException, InterruptedException { if (!caseNodeData.isDeletedFlagSet(CaseNodeData.DeletedFlags.TEXT_INDEX)) { logger.log(Level.INFO, String.format("Deleting text index for %s", caseNodeData.getDisplayName(), caseNodeData.getName(), caseNodeData.getDirectory())); //NON-NLS deleteTextIndex(metadata, progressIndicator); setDeletedItemFlag(caseNodeData, CaseNodeData.DeletedFlags.TEXT_INDEX); } } /** * Attempts to delete the text index for a case. * * @param metadata The case metadata. * @param progressIndicator A progress indicator. * * @throws KeywordSearchServiceException If there is an error deleting the * text index. */ @Messages({ "Case.progressMessage.deletingTextIndex=Deleting text index..." }) private static void deleteTextIndex(CaseMetadata metadata, ProgressIndicator progressIndicator) throws KeywordSearchServiceException { progressIndicator.progress(Bundle.Case_progressMessage_deletingTextIndex()); for (KeywordSearchService searchService : Lookup.getDefault().lookupAll(KeywordSearchService.class )) { searchService.deleteTextIndex(metadata); } } /** * Attempts to delete the case directory for a multi-user case. * * @param caseNodeData The coordination service node data for the case. * @param metadata The case metadata. * @param progressIndicator A progress indicator. * @param logger A logger. * * @throws CaseActionException if there is an error deleting the case * directory. * @throws InterruptedException If interrupted while blocked waiting for * coordination service data to be written to * the coordination service node database. */ private static void deleteMultiUserCaseDirectory(CaseNodeData caseNodeData, CaseMetadata metadata, ProgressIndicator progressIndicator, Logger logger) throws CaseActionException, InterruptedException { if (!caseNodeData.isDeletedFlagSet(CaseNodeData.DeletedFlags.CASE_DIR)) { logger.log(Level.INFO, String.format("Deleting case directory for %s", caseNodeData.getDisplayName(), caseNodeData.getName(), caseNodeData.getDirectory())); //NON-NLS deleteCaseDirectory(metadata, progressIndicator); setDeletedItemFlag(caseNodeData, CaseNodeData.DeletedFlags.CASE_DIR); } } /** * Attempts to delete the case directory for a case. * * @param metadata The case metadata. * @param progressIndicator A progress indicator. * * @throws CaseActionException If there is an error deleting the case * directory. */ @Messages({ "Case.progressMessage.deletingCaseDirectory=Deleting case directory..." }) private static void deleteCaseDirectory(CaseMetadata metadata, ProgressIndicator progressIndicator) throws CaseActionException { progressIndicator.progress(Bundle.Case_progressMessage_deletingCaseDirectory()); if (!FileUtil.deleteDir(new File(metadata.getCaseDirectory()))) { throw new CaseActionException(String.format("Failed to delete %s", metadata.getCaseDirectory())); //NON-NLS } } /** * Attempts to remove a case from the recent cases menu if the main * application window is present. * * @param metadata The case metadata. * @param progressIndicator A progress indicator. */ @Messages({ "Case.progressMessage.removingCaseFromRecentCases=Removing case from Recent Cases menu..." }) private static void deleteFromRecentCases(CaseMetadata metadata, ProgressIndicator progressIndicator) { if (RuntimeProperties.runningWithGUI()) { progressIndicator.progress(Bundle.Case_progressMessage_removingCaseFromRecentCases()); SwingUtilities.invokeLater(() -> { RecentCases.getInstance().removeRecentCase(metadata.getCaseDisplayName(), metadata.getFilePath().toString()); }); } } /** * Examines a coordination service exception to try to determine if it is a * "no node" exception, i.e., an operation was attempted on a node that does * not exist. * * @param ex A coordination service exception. * * @return True or false. */ private static boolean isNoNodeException(CoordinationServiceException ex) { boolean isNodeNodeEx = false; Throwable cause = ex.getCause(); if (cause != null) { String causeMessage = cause.getMessage(); isNodeNodeEx = causeMessage.contains(NO_NODE_ERROR_MSG_FRAGMENT); } return isNodeNodeEx; } /** * Sets a deleted item flag in the coordination service node data for a * multi-user case. * * @param caseNodeData The coordination service node data for the case. * @param flag The flag to set. * * @throws InterruptedException If interrupted while blocked waiting for * coordination service data to be written to * the coordination service node database. */ private static void setDeletedItemFlag(CaseNodeData caseNodeData, CaseNodeData.DeletedFlags flag) throws InterruptedException { try { caseNodeData.setDeletedFlag(flag); CaseNodeData.writeCaseNodeData(caseNodeData); } catch (CaseNodeDataException ex) { logger.log(Level.SEVERE, String.format("Error updating deleted item flag %s for %s (%s) in %s", flag.name(), caseNodeData.getDisplayName(), caseNodeData.getName(), caseNodeData.getDirectory()), ex); } } /** * Defines the signature for case action methods that can be passed as * arguments to the doCaseAction method. * * @param <T> A ProgressIndicator * @param <V> The optional parameters stored in an Object. * @param <R> The return type of Void. */ private interface CaseAction<T, V, R> { /** * The signature for a case action method. * * @param progressIndicator A ProgressIndicator. * @param additionalParams The optional parameters stored in an Object. * * @return A Void object (null). * * @throws CaseActionException */ R execute(T progressIndicator, V additionalParams) throws CaseActionException; } /** * The choices for the case (case directory) coordination service lock used * for multi-user cases. */ private enum CaseLockType { SHARED, EXCLUSIVE; } /** * A case operation Cancel button listener for use with a * ModalDialogProgressIndicator when running with a GUI. */ @ThreadSafe private final static class CancelButtonListener implements ActionListener { private final String cancellationMessage; @GuardedBy("this") private boolean cancelRequested; @GuardedBy("this") private CaseContext caseContext; @GuardedBy("this") private Future<?> caseActionFuture; /** * Constructs a case operation Cancel button listener for use with a * ModalDialogProgressIndicator when running with a GUI. * * @param cancellationMessage The message to display in the * ModalDialogProgressIndicator when the * cancel button is pressed. */ private CancelButtonListener(String cancellationMessage) { this.cancellationMessage = cancellationMessage; } /** * Sets a case context for this listener. * * @param caseContext A case context object. */ private synchronized void setCaseContext(CaseContext caseContext) { this.caseContext = caseContext; /* * If the cancel button has already been pressed, pass the * cancellation on to the case context. */ if (cancelRequested) { cancel(); } } /** * Sets a Future object for a task associated with this listener. * * @param caseActionFuture A task Future object. */ private synchronized void setCaseActionFuture(Future<?> caseActionFuture) { this.caseActionFuture = caseActionFuture; /* * If the cancel button has already been pressed, cancel the Future * of the task. */ if (cancelRequested) { cancel(); } } /** * The event handler for Cancel button pushes. * * @param event The button event, ignored, can be null. */ @Override public synchronized void actionPerformed(ActionEvent event) { cancel(); } /** * Handles a cancellation request. */ private void cancel() { /* * At a minimum, set the cancellation requested flag of this * listener. */ this.cancelRequested = true; if (null != this.caseContext) { /* * Set the cancellation request flag and display the * cancellation message in the progress indicator for the case * context associated with this listener. */ if (RuntimeProperties.runningWithGUI()) { ProgressIndicator progressIndicator = this.caseContext.getProgressIndicator(); if (progressIndicator instanceof ModalDialogProgressIndicator) { ((ModalDialogProgressIndicator) progressIndicator).setCancelling(cancellationMessage); } } this.caseContext.requestCancel(); } if (null != this.caseActionFuture) { /* * Cancel the Future of the task associated with this listener. * Note that the task thread will be interrupted if the task is * blocked. */ this.caseActionFuture.cancel(true); } } } /** * A thread factory that provides named threads. */ private static class TaskThreadFactory implements ThreadFactory { private final String threadName; private TaskThreadFactory(String threadName) { this.threadName = threadName; } @Override public Thread newThread(Runnable task) { return new Thread(task, threadName); } } /** * Gets the application name. * * @return The application name. * * @deprecated */ @Deprecated public static String getAppName() { return UserPreferences.getAppName(); } /** * Creates a new, single-user Autopsy case. * * @param caseDir The full path of the case directory. The directory * will be created if it doesn't already exist; if it * exists, it is ASSUMED it was created by calling * createCaseDirectory. * @param caseDisplayName The display name of case, which may be changed * later by the user. * @param caseNumber The case number, can be the empty string. * @param examiner The examiner to associate with the case, can be * the empty string. * * @throws CaseActionException if there is a problem creating the case. The * exception will have a user-friendly message * and may be a wrapper for a lower-level * exception. * @deprecated Use createAsCurrentCase instead. */ @Deprecated public static void create(String caseDir, String caseDisplayName, String caseNumber, String examiner) throws CaseActionException { createAsCurrentCase(caseDir, caseDisplayName, caseNumber, examiner, CaseType.SINGLE_USER_CASE); } /** * Creates a new Autopsy case and makes it the current case. * * @param caseDir The full path of the case directory. The directory * will be created if it doesn't already exist; if it * exists, it is ASSUMED it was created by calling * createCaseDirectory. * @param caseDisplayName The display name of case, which may be changed * later by the user. * @param caseNumber The case number, can be the empty string. * @param examiner The examiner to associate with the case, can be * the empty string. * @param caseType The type of case (single-user or multi-user). * * @throws CaseActionException if there is a problem creating the case. The * exception will have a user-friendly message * and may be a wrapper for a lower-level * exception. * @deprecated Use createAsCurrentCase instead. */ @Deprecated public static void create(String caseDir, String caseDisplayName, String caseNumber, String examiner, CaseType caseType) throws CaseActionException { createAsCurrentCase(caseDir, caseDisplayName, caseNumber, examiner, caseType); } /** * Opens an existing Autopsy case and makes it the current case. * * @param caseMetadataFilePath The path of the case metadata (.aut) file. * * @throws CaseActionException if there is a problem opening the case. The * exception will have a user-friendly message * and may be a wrapper for a lower-level * exception. * @deprecated Use openAsCurrentCase instead. */ @Deprecated public static void open(String caseMetadataFilePath) throws CaseActionException { openAsCurrentCase(caseMetadataFilePath); } /** * Closes this Autopsy case. * * @throws CaseActionException if there is a problem closing the case. The * exception will have a user-friendly message * and may be a wrapper for a lower-level * exception. * @deprecated Use closeCurrentCase instead. */ @Deprecated public void closeCase() throws CaseActionException { closeCurrentCase(); } /** * Invokes the startup dialog window. * * @deprecated Use StartupWindowProvider.getInstance().open() instead. */ @Deprecated public static void invokeStartupDialog() { StartupWindowProvider.getInstance().open(); } /** * Converts a Java timezone id to a coded string with only alphanumeric * characters. Example: "America/New_York" is converted to "EST5EDT" by this * method. * * @param timeZoneId The time zone id. * * @return The converted time zone string. * * @deprecated Use * org.sleuthkit.autopsy.coreutils.TimeZoneUtils.convertToAlphaNumericFormat * instead. */ @Deprecated public static String convertTimeZone(String timeZoneId) { return TimeZoneUtils.convertToAlphaNumericFormat(timeZoneId); } /** * Check if file exists and is a normal file. * * @param filePath The file path. * * @return True or false. * * @deprecated Use java.io.File.exists or java.io.File.isFile instead */ @Deprecated public static boolean pathExists(String filePath) { return new File(filePath).isFile(); } /** * Gets the Autopsy version. * * @return The Autopsy version. * * @deprecated Use org.sleuthkit.autopsy.coreutils.Version.getVersion * instead */ @Deprecated public static String getAutopsyVersion() { return Version.getVersion(); } /** * Check if case is currently open. * * @return True if a case is open. * * @deprecated Use isCaseOpen instead. */ @Deprecated public static boolean existsCurrentCase() { return isCaseOpen(); } /** * Get relative (with respect to case dir) module output directory path * where modules should save their permanent data. The directory is a * subdirectory of this case dir. * * @return relative path to the module output dir * * @deprecated Use getModuleOutputDirectoryRelativePath() instead */ @Deprecated public static String getModulesOutputDirRelPath() { return "ModuleOutput"; //NON-NLS } /** * Gets a PropertyChangeSupport object. The PropertyChangeSupport object * returned is not used by instances of this class and does not have any * PropertyChangeListeners. * * @return A new PropertyChangeSupport object. * * @deprecated Do not use. */ @Deprecated public static PropertyChangeSupport getPropertyChangeSupport() { return new PropertyChangeSupport(Case.class ); } /** * Get module output directory path where modules should save their * permanent data. * * @return absolute path to the module output directory * * @deprecated Use getModuleDirectory() instead. */ @Deprecated public String getModulesOutputDirAbsPath() { return getModuleDirectory(); } /** * Adds an image to the current case after it has been added to the DB. * Sends out event and reopens windows if needed. * * @param imgPath The path of the image file. * @param imgId The ID of the image. * @param timeZone The time zone of the image. * * @return * * @throws org.sleuthkit.autopsy.casemodule.CaseActionException * * @deprecated As of release 4.0 */ @Deprecated public Image addImage(String imgPath, long imgId, String timeZone) throws CaseActionException { try { Image newDataSource = caseDb.getImageById(imgId); notifyDataSourceAdded(newDataSource, UUID.randomUUID()); return newDataSource; } catch (TskCoreException ex) { throw new CaseActionException(NbBundle.getMessage(this.getClass(), "Case.addImg.exception.msg"), ex); } } /** * Gets the time zone(s) of the image data source(s) in this case. * * @return The set of time zones in use. * * @deprecated Use getTimeZones instead. */ @Deprecated public Set<TimeZone> getTimeZone() { return getTimeZones(); } /** * Deletes reports from the case. * * @param reports Collection of Report to be deleted from the case. * @param deleteFromDisk No longer supported - ignored. * * @throws TskCoreException * @deprecated Use deleteReports(Collection<? extends Report> reports) * instead. */ @Deprecated public void deleteReports(Collection<? extends Report> reports, boolean deleteFromDisk) throws TskCoreException { deleteReports(reports); } }
adding progress updates
Core/src/org/sleuthkit/autopsy/casemodule/Case.java
adding progress updates
<ide><path>ore/src/org/sleuthkit/autopsy/casemodule/Case.java <ide> checkForCancellation(); <ide> openCommunicationChannels(progressIndicator); <ide> checkForCancellation(); <del> openFileSystems(); <add> openFileSystems(progressIndicator); <ide> return null; <ide> <ide> } catch (CaseActionException ex) { <ide> } <ide> } <ide> <add> <ide> /** <ide> * Reads a sector from each file system of each image of a case to do an eager open of the filesystems in case. <add> * @param progressIndicator The progress indicator for the operation. <ide> * @throws CaseActionCancelledException Exception thrown if task is cancelled. <ide> */ <del> private void openFileSystems() throws CaseActionCancelledException { <del> String caseName = (this.caseDb != null) ? this.caseDb.getDatabaseName() : "null"; <add> @Messages({ <add> "# {0} - case", "Case.openFileSystems.retrievingImages=Retrieving images for case: {0}...", <add> "# {0} - image", "Case.openFileSystems.openingImage=Opening all filesystems for image: {0}..." <add> }) <add> private void openFileSystems(ProgressIndicator progressIndicator) throws CaseActionCancelledException { <add> String caseName = (this.caseDb != null) ? this.caseDb.getDatabaseName() : ""; <ide> <add> progressIndicator.progress(Bundle.Case_openFileSystems_retrievingImages(caseName)); <ide> List<Image> images = null; <ide> try { <ide> images = this.caseDb.getImages(); <ide> byte[] tempBuff = new byte[512]; <ide> <ide> for (Image image : images) { <add> String imageStr = image.getName(); <add> <add> progressIndicator.progress(Bundle.Case_openFileSystems_openingImage(imageStr)); <add> <ide> Collection<FileSystem> fileSystems = this.caseDb.getFileSystems(image); <ide> checkForCancellation(); <ide> for (FileSystem fileSystem : fileSystems) { <ide> fileSystem.read(tempBuff, 0, 512); <ide> } <ide> catch (TskCoreException ex) { <del> String imageStr = image.getName(); <ide> String fileSysStr = fileSystem.getName(); <ide> <ide> logger.log(
Java
mit
a61c79b6fafc34ce1ed5cb25d6c0fb836b289386
0
cdai/interview
package advanced.dp.statemac.lc188_besttimetobuyandsellstock4; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import sun.plugin.javascript.navig.Array; import java.util.Arrays; /** * Say you have an array for which the ith element is the price of a given stock on day i. * Design an algorithm to find the maximum profit. You may complete at most k transactions. * Note: You may not engage in multiple transactions at the same time * (ie, you must sell the stock before you buy again). */ public class Solution { @Test void testBuyThenSellAtOneDay() { Assertions.assertEquals(15, maxProfit(4, new int[]{1, 2, 4, 2, 5, 7, 2, 4, 9, 0})); } // Note max(dp[i-1][?] not dp[i], since we have 2D matrix, last value of state wouldn't copy by itself public int maxProfit(int k, int[] prices) { if (k >= prices.length / 2) { int profit = 0, min = Integer.MAX_VALUE; for (int price : prices) { if (min < price) profit += price - min; min = price; } return profit; } int n = prices.length; int[][] dp = new int[n + 1][2 * k + 2]; // Add two extra position to avoid boundary check for (int[] row : dp) for (int i = 2; i <= 2 * k; i += 2) row[i] = Integer.MIN_VALUE; // Initial all buy to MIN for (int i = 1; i <= n; i++) { for (int j = 2; j <= 2 * k; j += 2) { dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1] - prices[i - 1]); dp[i][j + 1] = Math.max(dp[i - 1][j + 1], dp[i][j] + prices[i - 1]); } } for (int[] row : dp) System.out.println(Arrays.toString(row)); return dp[n][2 * k + 1]; } // Why sell[i]=max(sell[i], buy[i]+p) not buy[i-1] // Because i here means ith transaction not ith day (variation of III) // sell[i] and buy[i] are in the same pair public int maxProfit4_multivar(int k, int[] prices) { if (k >= prices.length / 2) { // Degrade to II, make transactions as many as possible int profit = 0, min = Integer.MAX_VALUE; for (int price : prices) { if (min < price) profit += price - min; min = price; } return profit; } int[] buy = new int[k + 1], sell = new int[k + 1]; Arrays.fill(buy, Integer.MIN_VALUE); for (int price : prices) { for (int i = 1; i <= k; i++) { buy[i] = Math.max(buy[i], sell[i - 1] - price); sell[i] = Math.max(sell[i], buy[i] + price); } } return sell[k]; } // My 3AC. O(NK) time. Reuse Problem III idea. // Represent K*2 states (Each transaction has two states: buy[i] and sell[i]). public int maxProfit3(int k, int[] prices) { if (k >= prices.length / 2) { // if k >= n/2, then you can make maximum number of transactions int profit = 0; for (int i = 1; i < prices.length; i++) if (prices[i] > prices[i - 1]) profit += prices[i] - prices[i - 1]; return profit; } int[] buy = new int[k + 1], sell = new int[k + 1]; Arrays.fill(buy, Integer.MIN_VALUE); for (int price : prices) { for (int i = 1; i <= k; i++) { buy[i] = Math.max(buy[i], sell[i - 1] - price); sell[i] = Math.max(sell[i], buy[i] + price); } } return sell[k]; } // My 2AC: O(N^2) public int maxProfit2(int k, int[] prices) { if (prices.length < 2) return 0; int n = prices.length; if (k >= n / 2) { // if k >= n/2, then you can make maximum number of transactions int pro = 0; for (int i = 1; i < n; i++) if (prices[i] > prices[i - 1]) pro += prices[i] - prices[i - 1]; return pro; } int[][] dp = new int[k + 1][n]; // sell states of K transactions for (int i = 1; i <= k; i++) { int buy = -prices[0]; // buy state for (int j = 1; j < n; j++) { dp[i][j] = Math.max(dp[i][j - 1], buy + prices[j]); buy = Math.max(buy, dp[i - 1][j] - prices[j]); } } return dp[k][n - 1]; } }
1-algorithm/13-leetcode/java/src/advanced/dp/statemac/lc188_besttimetobuyandsellstock4/Solution.java
package advanced.dp.statemac.lc188_besttimetobuyandsellstock4; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import sun.plugin.javascript.navig.Array; import java.util.Arrays; /** * Say you have an array for which the ith element is the price of a given stock on day i. * Design an algorithm to find the maximum profit. You may complete at most k transactions. * Note: You may not engage in multiple transactions at the same time * (ie, you must sell the stock before you buy again). */ public class Solution { @Test void testBuyThenSellAtOneDay() { Assertions.assertEquals(15, maxProfit(4, new int[]{1, 2, 4, 2, 5, 7, 2, 4, 9, 0})); } // Why sell[i]=max(sell[i], buy[i]+p) not buy[i-1] // Because i here means ith transaction not ith day (variation of III) // sell[i] and buy[i] are in the same pair public int maxProfit(int k, int[] prices) { if (k >= prices.length / 2) { // Degrade to II, make transactions as many as possible int profit = 0, min = Integer.MAX_VALUE; for (int price : prices) { if (min < price) profit += price - min; min = price; } return profit; } int[] buy = new int[k + 1], sell = new int[k + 1]; Arrays.fill(buy, Integer.MIN_VALUE); for (int price : prices) { for (int i = 1; i <= k; i++) { buy[i] = Math.max(buy[i], sell[i - 1] - price); sell[i] = Math.max(sell[i], buy[i] + price); } } System.out.println(Arrays.toString(sell)); return sell[k]; } // My 3AC. O(NK) time. Reuse Problem III idea. // Represent K*2 states (Each transaction has two states: buy[i] and sell[i]). public int maxProfit3(int k, int[] prices) { if (k >= prices.length / 2) { // if k >= n/2, then you can make maximum number of transactions int profit = 0; for (int i = 1; i < prices.length; i++) if (prices[i] > prices[i - 1]) profit += prices[i] - prices[i - 1]; return profit; } int[] buy = new int[k + 1], sell = new int[k + 1]; Arrays.fill(buy, Integer.MIN_VALUE); for (int price : prices) { for (int i = 1; i <= k; i++) { buy[i] = Math.max(buy[i], sell[i - 1] - price); sell[i] = Math.max(sell[i], buy[i] + price); } } return sell[k]; } // My 2AC: O(N^2) public int maxProfit2(int k, int[] prices) { if (prices.length < 2) return 0; int n = prices.length; if (k >= n / 2) { // if k >= n/2, then you can make maximum number of transactions int pro = 0; for (int i = 1; i < n; i++) if (prices[i] > prices[i - 1]) pro += prices[i] - prices[i - 1]; return pro; } int[][] dp = new int[k + 1][n]; // sell states of K transactions for (int i = 1; i <= k; i++) { int buy = -prices[0]; // buy state for (int j = 1; j < n; j++) { dp[i][j] = Math.max(dp[i][j - 1], buy + prices[j]); buy = Math.max(buy, dp[i - 1][j] - prices[j]); } } return dp[k][n - 1]; } }
leetcode-188: best time to buy and sell stock 4
1-algorithm/13-leetcode/java/src/advanced/dp/statemac/lc188_besttimetobuyandsellstock4/Solution.java
leetcode-188: best time to buy and sell stock 4
<ide><path>-algorithm/13-leetcode/java/src/advanced/dp/statemac/lc188_besttimetobuyandsellstock4/Solution.java <ide> Assertions.assertEquals(15, maxProfit(4, new int[]{1, 2, 4, 2, 5, 7, 2, 4, 9, 0})); <ide> } <ide> <add> // Note max(dp[i-1][?] not dp[i], since we have 2D matrix, last value of state wouldn't copy by itself <add> public int maxProfit(int k, int[] prices) { <add> if (k >= prices.length / 2) { <add> int profit = 0, min = Integer.MAX_VALUE; <add> for (int price : prices) { <add> if (min < price) profit += price - min; <add> min = price; <add> } <add> return profit; <add> } <add> <add> int n = prices.length; <add> int[][] dp = new int[n + 1][2 * k + 2]; // Add two extra position to avoid boundary check <add> for (int[] row : dp) <add> for (int i = 2; i <= 2 * k; i += 2) <add> row[i] = Integer.MIN_VALUE; // Initial all buy to MIN <add> <add> for (int i = 1; i <= n; i++) { <add> for (int j = 2; j <= 2 * k; j += 2) { <add> dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1] - prices[i - 1]); <add> dp[i][j + 1] = Math.max(dp[i - 1][j + 1], dp[i][j] + prices[i - 1]); <add> } <add> } <add> for (int[] row : dp) System.out.println(Arrays.toString(row)); <add> return dp[n][2 * k + 1]; <add> } <add> <ide> // Why sell[i]=max(sell[i], buy[i]+p) not buy[i-1] <ide> // Because i here means ith transaction not ith day (variation of III) <ide> // sell[i] and buy[i] are in the same pair <del> public int maxProfit(int k, int[] prices) { <add> public int maxProfit4_multivar(int k, int[] prices) { <ide> if (k >= prices.length / 2) { // Degrade to II, make transactions as many as possible <ide> int profit = 0, min = Integer.MAX_VALUE; <ide> for (int price : prices) { <ide> sell[i] = Math.max(sell[i], buy[i] + price); <ide> } <ide> } <del> System.out.println(Arrays.toString(sell)); <ide> return sell[k]; <ide> } <ide>
Java
mit
90bda028ec4eaee3e59d8420893414de218289a1
0
frosch95/SmartCSV.fx
/* The MIT License (MIT) ----------------------------------------------------------------------------- Copyright (c) 2015-2016 javafx.ninja <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package ninja.javafx.smartcsv.validation.configuration; /** * Enumeration for format values for type string in JSON Table Schema * @see <a href="http://specs.frictionlessdata.io/json-table-schema/">JSON Table Schema</a> */ public enum StringFormat { DEFAULT(null), EMAIL("email"), URI("uri"), BINARY("binary"), UUID("uuid"); private String externalValue; StringFormat(String externalValue) { this.externalValue = externalValue; } public String getExternalValue() { return externalValue; } public static StringFormat fromExternalValue(String externalValue) { if (externalValue != null) { for (StringFormat value : StringFormat.values()) { if (externalValue.equals(value.getExternalValue())) { return value; } } } return DEFAULT; } }
src/main/java/ninja/javafx/smartcsv/validation/configuration/StringFormat.java
/* The MIT License (MIT) ----------------------------------------------------------------------------- Copyright (c) 2015-2016 javafx.ninja <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package ninja.javafx.smartcsv.validation.configuration; /** * Enumeration for format values for type string in JSON Table Schema * @see <a href="http://specs.frictionlessdata.io/json-table-schema/">JSON Table Schema</a> */ public enum StringFormat { DEFAULT(null), EMAIL("email"), URI("uri"), BINARY("binary"), UUID("uuid"); private String externalValue; StringFormat(String externalValue) { this.externalValue = externalValue; } public String getExternalValue() { return externalValue; } public static StringFormat fromExternalValue(String externalValue) { for (StringFormat value: StringFormat.values()) { if (value.name().equals(externalValue)) { return value; } } return DEFAULT; } }
finding enum based on external value should use external value as compare value
src/main/java/ninja/javafx/smartcsv/validation/configuration/StringFormat.java
finding enum based on external value should use external value as compare value
<ide><path>rc/main/java/ninja/javafx/smartcsv/validation/configuration/StringFormat.java <ide> } <ide> <ide> public static StringFormat fromExternalValue(String externalValue) { <del> for (StringFormat value: StringFormat.values()) { <del> if (value.name().equals(externalValue)) { <del> return value; <add> if (externalValue != null) { <add> for (StringFormat value : StringFormat.values()) { <add> if (externalValue.equals(value.getExternalValue())) { <add> return value; <add> } <ide> } <ide> } <ide> return DEFAULT;
JavaScript
mit
8c6ed151bdfd03b8a8ec3707963caada8e73d041
0
mzgol/sizzle,npmcomponent/cristiandouce-sizzle
/*global QUnit: true, q: true, t: true, url: true, createWithFriesXML: true, Sizzle: true, module: true, test: true, asyncTest: true, expect: true, stop: true, start: true, ok: true, equal: true, notEqual: true, deepEqual: true, notDeepEqual: true, strictEqual: true, notStrictEqual: true, raises: true, moduleTeardown: true */ module("selector", { teardown: moduleTeardown }); // #### NOTE: #### // jQuery should not be used in this module // except for DOM manipulation // If jQuery is mandatory for the selection, move the test to jquery/test/unit/selector.js // Use t() or Sizzle() // ############### /* ======== QUnit Reference ======== http://docs.jquery.com/QUnit Test methods: expect(numAssertions) stop() start() note: QUnit's eventual addition of an argument to stop/start is ignored in this test suite so that start and stop can be passed as callbacks without worrying about their parameters Test assertions: ok(value, [message]) equal(actual, expected, [message]) notEqual(actual, expected, [message]) deepEqual(actual, expected, [message]) notDeepEqual(actual, expected, [message]) strictEqual(actual, expected, [message]) notStrictEqual(actual, expected, [message]) raises(block, [expected], [message]) ======== testinit.js reference ======== See data/testinit.js q(...); Returns an array of elements with the given IDs @example q("main", "foo", "bar") => [<div id="main">, <span id="foo">, <input id="bar">] t( testName, selector, [ "array", "of", "ids" ] ); Asserts that a select matches the given IDs @example t("Check for something", "//[a]", ["foo", "baar"]); url( "some/url.php" ); Add random number to url to stop caching @example url("data/test.html") => "data/test.html?10538358428943" @example url("data/test.php?foo=bar") => "data/test.php?foo=bar&10538358345554" */ test("element", function() { expect( 37 ); equal( Sizzle("").length, 0, "Empty selector returns an empty array" ); equal( Sizzle(" ").length, 0, "Empty selector returns an empty array" ); equal( Sizzle("\t").length, 0, "Empty selector returns an empty array" ); var form = document.getElementById("form"); ok( !Sizzle.matchesSelector( form, "" ), "Empty string passed to matchesSelector does not match" ); ok( Sizzle("*").length >= 30, "Select all" ); var all = Sizzle("*"), good = true; for ( var i = 0; i < all.length; i++ ) { if ( all[i].nodeType == 8 ) { good = false; } } ok( good, "Select all elements, no comment nodes" ); t( "Element Selector", "html", ["html"] ); t( "Element Selector", "body", ["body"] ); t( "Element Selector", "#qunit-fixture p", ["firstp","ap","sndp","en","sap","first"] ); t( "Leading space", " #qunit-fixture p", ["firstp","ap","sndp","en","sap","first"] ); t( "Leading tab", "\t#qunit-fixture p", ["firstp","ap","sndp","en","sap","first"] ); t( "Leading carriage return", "\r#qunit-fixture p", ["firstp","ap","sndp","en","sap","first"] ); t( "Leading line feed", "\n#qunit-fixture p", ["firstp","ap","sndp","en","sap","first"] ); t( "Leading form feed", "\f#qunit-fixture p", ["firstp","ap","sndp","en","sap","first"] ); t( "Trailing space", "#qunit-fixture p ", ["firstp","ap","sndp","en","sap","first"] ); t( "Trailing tab", "#qunit-fixture p\t", ["firstp","ap","sndp","en","sap","first"] ); t( "Trailing carriage return", "#qunit-fixture p\r", ["firstp","ap","sndp","en","sap","first"] ); t( "Trailing line feed", "#qunit-fixture p\n", ["firstp","ap","sndp","en","sap","first"] ); t( "Trailing form feed", "#qunit-fixture p\f", ["firstp","ap","sndp","en","sap","first"] ); t( "Parent Element", "dl ol", ["empty", "listWithTabIndex"] ); t( "Parent Element (non-space descendant combinator)", "dl\tol", ["empty", "listWithTabIndex"] ); var obj1 = document.getElementById("object1"); equal( Sizzle("param", obj1).length, 2, "Object/param as context" ); deepEqual( Sizzle("select", form), q("select1","select2","select3","select4","select5"), "Finding selects with a context." ); // Check for unique-ness and sort order deepEqual( Sizzle("p, div p"), Sizzle("p"), "Check for duplicates: p, div p" ); t( "Checking sort order", "h2, h1", ["qunit-header", "qunit-banner", "qunit-userAgent"] ); t( "Checking sort order", "h2:first, h1:first", ["qunit-header", "qunit-banner"] ); t( "Checking sort order", "#qunit-fixture p, #qunit-fixture p a", ["firstp", "simon1", "ap", "google", "groups", "anchor1", "mark", "sndp", "en", "yahoo", "sap", "anchor2", "simon", "first"] ); // Test Conflict ID var lengthtest = document.getElementById("lengthtest"); deepEqual( Sizzle("#idTest", lengthtest), q("idTest"), "Finding element with id of ID." ); deepEqual( Sizzle("[name='id']", lengthtest), q("idTest"), "Finding element with id of ID." ); deepEqual( Sizzle("input[id='idTest']", lengthtest), q("idTest"), "Finding elements with id of ID." ); var siblingTest = document.getElementById("siblingTest"); deepEqual( Sizzle("div em", siblingTest), [], "Element-rooted QSA does not select based on document context" ); deepEqual( Sizzle("div em, div em, div em:not(div em)", siblingTest), [], "Element-rooted QSA does not select based on document context" ); deepEqual( Sizzle("div em, em\\,", siblingTest), [], "Escaped commas do not get treated with an id in element-rooted QSA" ); var iframe = document.getElementById("iframe"), iframeDoc = iframe.contentDocument || iframe.contentWindow.document; iframeDoc.open(); iframeDoc.write("<body><p id='foo'>bar</p></body>"); iframeDoc.close(); deepEqual( Sizzle( "p:contains(bar)", iframeDoc ), [ iframeDoc.getElementById("foo") ], "Other document as context" ); var html = ""; for ( i = 0; i < 100; i++ ) { html = "<div>" + html + "</div>"; } html = jQuery( html ).appendTo( document.body ); ok( !!Sizzle("body div div div").length, "No stack or performance problems with large amounts of descendents" ); ok( !!Sizzle("body>div div div").length, "No stack or performance problems with large amounts of descendents" ); html.remove(); // Real use case would be using .watch in browsers with window.watch (see Issue #157) q("qunit-fixture")[0].appendChild( document.createElement("toString") ).id = "toString"; t( "Element name matches Object.prototype property", "toString#toString", ["toString"] ); }); test("XML Document Selectors", function() { var xml = createWithFriesXML(); expect( 10 ); equal( Sizzle("foo_bar", xml).length, 1, "Element Selector with underscore" ); equal( Sizzle(".component", xml).length, 1, "Class selector" ); equal( Sizzle("[class*=component]", xml).length, 1, "Attribute selector for class" ); equal( Sizzle("property[name=prop2]", xml).length, 1, "Attribute selector with name" ); equal( Sizzle("[name=prop2]", xml).length, 1, "Attribute selector with name" ); equal( Sizzle("#seite1", xml).length, 1, "Attribute selector with ID" ); equal( Sizzle("component#seite1", xml).length, 1, "Attribute selector with ID" ); equal( Sizzle.matches( "#seite1", Sizzle("component", xml) ).length, 1, "Attribute selector filter with ID" ); equal( Sizzle("meta property thing", xml).length, 2, "Descendent selector and dir caching" ); ok( Sizzle.matchesSelector( xml.lastChild, "soap\\:Envelope" ), "Check for namespaced element" ); }); test("broken", function() { expect( 26 ); function broken( name, selector ) { raises(function() { // Setting context to null here somehow avoids QUnit's window.error handling // making the e & e.message correct // For whatever reason, without this, // Sizzle.error will be called but no error will be seen in oldIE Sizzle.call( null, selector ); }, function( e ) { return e.message.indexOf("Syntax error") >= 0; }, name + ": " + selector ); } broken( "Broken Selector", "[" ); broken( "Broken Selector", "(" ); broken( "Broken Selector", "{" ); broken( "Broken Selector", "<" ); broken( "Broken Selector", "()" ); broken( "Broken Selector", "<>" ); broken( "Broken Selector", "{}" ); broken( "Broken Selector", "," ); broken( "Broken Selector", ",a" ); broken( "Broken Selector", "a," ); // Hangs on IE 9 if regular expression is inefficient broken( "Broken Selector", "[id=012345678901234567890123456789"); broken( "Doesn't exist", ":visble" ); broken( "Nth-child", ":nth-child" ); // Sigh again. IE 9 thinks this is also a real selector // not super critical that we fix this case //broken( "Nth-child", ":nth-child(-)" ); // Sigh. WebKit thinks this is a real selector in qSA // They've already fixed this and it'll be coming into // current browsers soon. Currently, Safari 5.0 still has this problem // broken( "Nth-child", ":nth-child(asdf)", [] ); broken( "Nth-child", ":nth-child(2n+-0)" ); broken( "Nth-child", ":nth-child(2+0)" ); broken( "Nth-child", ":nth-child(- 1n)" ); broken( "Nth-child", ":nth-child(-1 n)" ); broken( "First-child", ":first-child(n)" ); broken( "Last-child", ":last-child(n)" ); broken( "Only-child", ":only-child(n)" ); broken( "Nth-last-last-child", ":nth-last-last-child(1)" ); broken( "First-last-child", ":first-last-child" ); broken( "Last-last-child", ":last-last-child" ); broken( "Only-last-child", ":only-last-child" ); // Make sure attribute value quoting works correctly. See: #6093 var attrbad = jQuery('<input type="hidden" value="2" name="foo.baz" id="attrbad1"/><input type="hidden" value="2" name="foo[baz]" id="attrbad2"/>').appendTo("body"); broken( "Attribute not escaped", "input[name=foo.baz]", [] ); // Shouldn't be matching those inner brackets broken( "Attribute not escaped", "input[name=foo[baz]]", [] ); attrbad.remove(); }); test("id", function() { expect( 31 ); t( "ID Selector", "#body", ["body"] ); t( "ID Selector w/ Element", "body#body", ["body"] ); t( "ID Selector w/ Element", "ul#first", [] ); t( "ID selector with existing ID descendant", "#firstp #simon1", ["simon1"] ); t( "ID selector with non-existant descendant", "#firstp #foobar", [] ); t( "ID selector using UTF8", "#台北Táiběi", ["台北Táiběi"] ); t( "Multiple ID selectors using UTF8", "#台北Táiběi, #台北", ["台北Táiběi","台北"] ); t( "Descendant ID selector using UTF8", "div #台北", ["台北"] ); t( "Child ID selector using UTF8", "form > #台北", ["台北"] ); t( "Escaped ID", "#foo\\:bar", ["foo:bar"] ); t( "Escaped ID with descendent", "#foo\\:bar span:not(:input)", ["foo_descendent"] ); t( "Escaped ID", "#test\\.foo\\[5\\]bar", ["test.foo[5]bar"] ); t( "Descendant escaped ID", "div #foo\\:bar", ["foo:bar"] ); t( "Descendant escaped ID", "div #test\\.foo\\[5\\]bar", ["test.foo[5]bar"] ); t( "Child escaped ID", "form > #foo\\:bar", ["foo:bar"] ); t( "Child escaped ID", "form > #test\\.foo\\[5\\]bar", ["test.foo[5]bar"] ); var fiddle = jQuery("<div id='fiddle\\Foo'><span id='fiddleSpan'></span></div>").appendTo("#qunit-fixture"); deepEqual( Sizzle( "> span", Sizzle("#fiddle\\\\Foo")[0] ), q([ "fiddleSpan" ]), "Escaped ID as context" ); fiddle.remove(); t( "ID Selector, child ID present", "#form > #radio1", ["radio1"] ); // bug #267 t( "ID Selector, not an ancestor ID", "#form #first", [] ); t( "ID Selector, not a child ID", "#form > #option1a", [] ); t( "All Children of ID", "#foo > *", ["sndp", "en", "sap"] ); t( "All Children of ID with no children", "#firstUL > *", [] ); var a = jQuery("<div><a name=\"tName1\">tName1 A</a><a name=\"tName2\">tName2 A</a><div id=\"tName1\">tName1 Div</div></div>").appendTo("#qunit-fixture"); equal( Sizzle("#tName1")[0].id, 'tName1', "ID selector with same value for a name attribute" ); equal( Sizzle("#tName2").length, 0, "ID selector non-existing but name attribute on an A tag" ); a.remove(); a = jQuery("<a id='backslash\\foo'></a>").appendTo("#qunit-fixture"); t( "ID Selector contains backslash", "#backslash\\\\foo", ["backslash\\foo"] ); t( "ID Selector on Form with an input that has a name of 'id'", "#lengthtest", ["lengthtest"] ); t( "ID selector with non-existant ancestor", "#asdfasdf #foobar", [] ); // bug #986 deepEqual( Sizzle("div#form", document.body), [], "ID selector within the context of another element" ); t( "Underscore ID", "#types_all", ["types_all"] ); t( "Dash ID", "#qunit-fixture", ["qunit-fixture"] ); t( "ID with weird characters in it", "#name\\+value", ["name+value"] ); }); test("class", function() { expect( 25 ); t( "Class Selector", ".blog", ["mark","simon"] ); t( "Class Selector", ".GROUPS", ["groups"] ); t( "Class Selector", ".blog.link", ["simon"] ); t( "Class Selector w/ Element", "a.blog", ["mark","simon"] ); t( "Parent Class Selector", "p .blog", ["mark","simon"] ); t( "Class selector using UTF8", ".台北Táiběi", ["utf8class1"] ); //t( "Class selector using UTF8", ".台北", ["utf8class1","utf8class2"] ); t( "Class selector using UTF8", ".台北Táiběi.台北", ["utf8class1"] ); t( "Class selector using UTF8", ".台北Táiběi, .台北", ["utf8class1","utf8class2"] ); t( "Descendant class selector using UTF8", "div .台北Táiběi", ["utf8class1"] ); t( "Child class selector using UTF8", "form > .台北Táiběi", ["utf8class1"] ); t( "Escaped Class", ".foo\\:bar", ["foo:bar"] ); t( "Escaped Class", ".test\\.foo\\[5\\]bar", ["test.foo[5]bar"] ); t( "Descendant escaped Class", "div .foo\\:bar", ["foo:bar"] ); t( "Descendant escaped Class", "div .test\\.foo\\[5\\]bar", ["test.foo[5]bar"] ); t( "Child escaped Class", "form > .foo\\:bar", ["foo:bar"] ); t( "Child escaped Class", "form > .test\\.foo\\[5\\]bar", ["test.foo[5]bar"] ); var div = document.createElement("div"); div.innerHTML = "<div class='test e'></div><div class='test'></div>"; deepEqual( Sizzle(".e", div), [ div.firstChild ], "Finding a second class." ); div.lastChild.className = "e"; deepEqual( Sizzle(".e", div), [ div.firstChild, div.lastChild ], "Finding a modified class." ); ok( !Sizzle.matchesSelector( div, ".null"), ".null does not match an element with no class" ); ok( !Sizzle.matchesSelector( div.firstChild, ".null div"), ".null does not match an element with no class" ); div.className = "null"; ok( Sizzle.matchesSelector( div, ".null"), ".null matches element with class 'null'" ); ok( Sizzle.matchesSelector( div.firstChild, ".null div"), "caching system respects DOM changes" ); ok( !Sizzle.matchesSelector( document, ".foo" ), "testing class on document doesn't error" ); ok( !Sizzle.matchesSelector( window, ".foo" ), "testing class on window doesn't error" ); div.lastChild.className += " hasOwnProperty toString"; deepEqual( Sizzle(".e.hasOwnProperty.toString", div), [ div.lastChild ], "Classes match Object.prototype properties" ); }); test("name", function() { expect( 15 ); t( "Name selector", "input[name=action]", ["text1"] ); t( "Name selector with single quotes", "input[name='action']", ["text1"] ); t( "Name selector with double quotes", 'input[name="action"]', ["text1"] ); t( "Name selector non-input", "[name=example]", ["name-is-example"] ); t( "Name selector non-input", "[name=div]", ["name-is-div"] ); t( "Name selector non-input", "*[name=iframe]", ["iframe"] ); t( "Name selector for grouped input", "input[name='types[]']", ["types_all", "types_anime", "types_movie"] ); var form = document.getElementById("form"); deepEqual( Sizzle("input[name=action]", form), q("text1"), "Name selector within the context of another element" ); deepEqual( Sizzle("input[name='foo[bar]']", form), q("hidden2"), "Name selector for grouped form element within the context of another element" ); form = jQuery("<form><input name='id'/></form>").appendTo("body"); equal( Sizzle("input", form[0]).length, 1, "Make sure that rooted queries on forms (with possible expandos) work." ); form.remove(); var a = jQuery("<div><a id=\"tName1ID\" name=\"tName1\">tName1 A</a><a id=\"tName2ID\" name=\"tName2\">tName2 A</a><div id=\"tName1\">tName1 Div</div></div>") .appendTo("#qunit-fixture").children(); equal( a.length, 3, "Make sure the right number of elements were inserted." ); equal( a[1].id, "tName2ID", "Make sure the right number of elements were inserted." ); equal( Sizzle("[name=tName1]")[0], a[0], "Find elements that have similar IDs" ); equal( Sizzle("[name=tName2]")[0], a[1], "Find elements that have similar IDs" ); t( "Find elements that have similar IDs", "#tName2ID", ["tName2ID"] ); a.parent().remove(); }); test("multiple", function() { expect(6); t( "Comma Support", "h2, #qunit-fixture p", ["qunit-banner","qunit-userAgent","firstp","ap","sndp","en","sap","first"]); t( "Comma Support", "h2 , #qunit-fixture p", ["qunit-banner","qunit-userAgent","firstp","ap","sndp","en","sap","first"]); t( "Comma Support", "h2 , #qunit-fixture p", ["qunit-banner","qunit-userAgent","firstp","ap","sndp","en","sap","first"]); t( "Comma Support", "h2,#qunit-fixture p", ["qunit-banner","qunit-userAgent","firstp","ap","sndp","en","sap","first"]); t( "Comma Support", "h2,#qunit-fixture p ", ["qunit-banner","qunit-userAgent","firstp","ap","sndp","en","sap","first"]); t( "Comma Support", "h2\t,\r#qunit-fixture p\n", ["qunit-banner","qunit-userAgent","firstp","ap","sndp","en","sap","first"]); }); test("child and adjacent", function() { expect( 42 ); t( "Child", "p > a", ["simon1","google","groups","mark","yahoo","simon"] ); t( "Child", "p> a", ["simon1","google","groups","mark","yahoo","simon"] ); t( "Child", "p >a", ["simon1","google","groups","mark","yahoo","simon"] ); t( "Child", "p>a", ["simon1","google","groups","mark","yahoo","simon"] ); t( "Child w/ Class", "p > a.blog", ["mark","simon"] ); t( "All Children", "code > *", ["anchor1","anchor2"] ); t( "All Grandchildren", "p > * > *", ["anchor1","anchor2"] ); t( "Adjacent", "#qunit-fixture a + a", ["groups"] ); t( "Adjacent", "#qunit-fixture a +a", ["groups"] ); t( "Adjacent", "#qunit-fixture a+ a", ["groups"] ); t( "Adjacent", "#qunit-fixture a+a", ["groups"] ); t( "Adjacent", "p + p", ["ap","en","sap"] ); t( "Adjacent", "p#firstp + p", ["ap"] ); t( "Adjacent", "p[lang=en] + p", ["sap"] ); t( "Adjacent", "a.GROUPS + code + a", ["mark"] ); t( "Comma, Child, and Adjacent", "#qunit-fixture a + a, code > a", ["groups","anchor1","anchor2"] ); t( "Element Preceded By", "#qunit-fixture p ~ div", ["foo", "nothiddendiv", "moretests","tabindex-tests", "liveHandlerOrder", "siblingTest"] ); t( "Element Preceded By", "#first ~ div", ["moretests","tabindex-tests", "liveHandlerOrder", "siblingTest"] ); t( "Element Preceded By", "#groups ~ a", ["mark"] ); t( "Element Preceded By", "#length ~ input", ["idTest"] ); t( "Element Preceded By", "#siblingfirst ~ em", ["siblingnext", "siblingthird"] ); t( "Element Preceded By (multiple)", "#siblingTest em ~ em ~ em ~ span", ["siblingspan"] ); t( "Element Preceded By, Containing", "#liveHandlerOrder ~ div em:contains('1')", ["siblingfirst"] ); var siblingFirst = document.getElementById("siblingfirst"); deepEqual( Sizzle("~ em", siblingFirst), q("siblingnext", "siblingthird"), "Element Preceded By with a context." ); deepEqual( Sizzle("+ em", siblingFirst), q("siblingnext"), "Element Directly Preceded By with a context." ); deepEqual( Sizzle("~ em:first", siblingFirst), q("siblingnext"), "Element Preceded By positional with a context." ); var en = document.getElementById("en"); deepEqual( Sizzle("+ p, a", en), q("yahoo", "sap"), "Compound selector with context, beginning with sibling test." ); deepEqual( Sizzle("a, + p", en), q("yahoo", "sap"), "Compound selector with context, containing sibling test." ); t( "Multiple combinators selects all levels", "#siblingTest em *", ["siblingchild", "siblinggrandchild", "siblinggreatgrandchild"] ); t( "Multiple combinators selects all levels", "#siblingTest > em *", ["siblingchild", "siblinggrandchild", "siblinggreatgrandchild"] ); t( "Multiple sibling combinators doesn't miss general siblings", "#siblingTest > em:first-child + em ~ span", ["siblingspan"] ); t( "Combinators are not skipped when mixing general and specific", "#siblingTest > em:contains('x') + em ~ span", [] ); equal( Sizzle("#listWithTabIndex").length, 1, "Parent div for next test is found via ID (#8310)" ); equal( Sizzle("#listWithTabIndex li:eq(2) ~ li").length, 1, "Find by general sibling combinator (#8310)" ); equal( Sizzle("#__sizzle__").length, 0, "Make sure the temporary id assigned by sizzle is cleared out (#8310)" ); equal( Sizzle("#listWithTabIndex").length, 1, "Parent div for previous test is still found via ID (#8310)" ); t( "Verify deep class selector", "div.blah > p > a", [] ); t( "No element deep selector", "div.foo > span > a", [] ); var nothiddendiv = document.getElementById("nothiddendiv"); deepEqual( Sizzle("> :first", nothiddendiv), q("nothiddendivchild"), "Verify child context positional selector" ); deepEqual( Sizzle("> :eq(0)", nothiddendiv), q("nothiddendivchild"), "Verify child context positional selector" ); deepEqual( Sizzle("> *:first", nothiddendiv), q("nothiddendivchild"), "Verify child context positional selector" ); t( "Non-existant ancestors", ".fototab > .thumbnails > a", [] ); }); test("attributes", function() { expect( 62 ); t( "Attribute Exists", "#qunit-fixture a[title]", ["google"] ); t( "Attribute Exists (case-insensitive)", "#qunit-fixture a[TITLE]", ["google"] ); t( "Attribute Exists", "#qunit-fixture *[title]", ["google"] ); t( "Attribute Exists", "#qunit-fixture [title]", ["google"] ); t( "Attribute Exists", "#qunit-fixture a[ title ]", ["google"] ); t( "Boolean attribute exists", "#select2 option[selected]", ["option2d"]); t( "Boolean attribute equals", "#select2 option[selected='selected']", ["option2d"]); t( "Attribute Equals", "#qunit-fixture a[rel='bookmark']", ["simon1"] ); t( "Attribute Equals", "#qunit-fixture a[rel='bookmark']", ["simon1"] ); t( "Attribute Equals", "#qunit-fixture a[rel=bookmark]", ["simon1"] ); t( "Attribute Equals", "#qunit-fixture a[href='http://www.google.com/']", ["google"] ); t( "Attribute Equals", "#qunit-fixture a[ rel = 'bookmark' ]", ["simon1"] ); t( "Attribute Equals Number", "#qunit-fixture option[value=1]", ["option1b","option2b","option3b","option4b","option5c"] ); t( "Attribute Equals Number", "#qunit-fixture li[tabIndex=-1]", ["foodWithNegativeTabIndex"] ); document.getElementById("anchor2").href = "#2"; t( "href Attribute", "p a[href^=#]", ["anchor2"] ); t( "href Attribute", "p a[href*=#]", ["simon1", "anchor2"] ); t( "for Attribute", "form label[for]", ["label-for"] ); t( "for Attribute in form", "#form [for=action]", ["label-for"] ); t( "Attribute containing []", "input[name^='foo[']", ["hidden2"] ); t( "Attribute containing []", "input[name^='foo[bar]']", ["hidden2"] ); t( "Attribute containing []", "input[name*='[bar]']", ["hidden2"] ); t( "Attribute containing []", "input[name$='bar]']", ["hidden2"] ); t( "Attribute containing []", "input[name$='[bar]']", ["hidden2"] ); t( "Attribute containing []", "input[name$='foo[bar]']", ["hidden2"] ); t( "Attribute containing []", "input[name*='foo[bar]']", ["hidden2"] ); deepEqual( Sizzle( "input[data-comma='0,1']" ), [ document.getElementById("el12087") ], "Without context, single-quoted attribute containing ','" ); deepEqual( Sizzle( 'input[data-comma="0,1"]' ), [ document.getElementById("el12087") ], "Without context, double-quoted attribute containing ','" ); deepEqual( Sizzle( "input[data-comma='0,1']", document.getElementById("t12087") ), [ document.getElementById("el12087") ], "With context, single-quoted attribute containing ','" ); deepEqual( Sizzle( 'input[data-comma="0,1"]', document.getElementById("t12087") ), [ document.getElementById("el12087") ], "With context, double-quoted attribute containing ','" ); t( "Multiple Attribute Equals", "#form input[type='radio'], #form input[type='hidden']", ["radio1", "radio2", "hidden1"] ); t( "Multiple Attribute Equals", "#form input[type='radio'], #form input[type=\"hidden\"]", ["radio1", "radio2", "hidden1"] ); t( "Multiple Attribute Equals", "#form input[type='radio'], #form input[type=hidden]", ["radio1", "radio2", "hidden1"] ); t( "Attribute selector using UTF8", "span[lang=中文]", ["台北"] ); t( "Attribute Begins With", "a[href ^= 'http://www']", ["google","yahoo"] ); t( "Attribute Ends With", "a[href $= 'org/']", ["mark"] ); t( "Attribute Contains", "a[href *= 'google']", ["google","groups"] ); t( "Attribute Is Not Equal", "#ap a[hreflang!='en']", ["google","groups","anchor1"] ); var opt = document.getElementById("option1a"), match = Sizzle.matchesSelector; opt.setAttribute( "test", "" ); ok( match( opt, "[id*=option1][type!=checkbox]" ), "Attribute Is Not Equal Matches" ); ok( match( opt, "[id*=option1]" ), "Attribute With No Quotes Contains Matches" ); ok( match( opt, "[test=]" ), "Attribute With No Quotes No Content Matches" ); ok( !match( opt, "[test^='']" ), "Attribute with empty string value does not match startsWith selector (^=)" ); ok( match( opt, "[id=option1a]" ), "Attribute With No Quotes Equals Matches" ); ok( match( document.getElementById("simon1"), "a[href*=#]" ), "Attribute With No Quotes Href Contains Matches" ); t( "Empty values", "#select1 option[value='']", ["option1a"] ); t( "Empty values", "#select1 option[value!='']", ["option1b","option1c","option1d"] ); t( "Select options via :selected", "#select1 option:selected", ["option1a"] ); t( "Select options via :selected", "#select2 option:selected", ["option2d"] ); t( "Select options via :selected", "#select3 option:selected", ["option3b", "option3c"] ); t( "Select options via :selected", "select[name='select2'] option:selected", ["option2d"] ); t( "Grouped Form Elements", "input[name='foo[bar]']", ["hidden2"] ); var input = document.getElementById("text1"); input.title = "Don't click me"; ok( match( input, "input[title=\"Don't click me\"]" ), "Quote within attribute value does not mess up tokenizer" ); // Uncomment if the boolHook is removed // var check2 = document.getElementById("check2"); // check2.checked = true; // ok( !Sizzle.matches("[checked]", [ check2 ] ), "Dynamic boolean attributes match when they should with Sizzle.matches (#11115)" ); // jQuery #12303 input.setAttribute( "data-pos", ":first" ); ok( match( input, "input[data-pos=\\:first]"), "POS within attribute value is treated as an attribute value" ); ok( match( input, "input[data-pos=':first']"), "POS within attribute value is treated as an attribute value" ); ok( match( input, ":input[data-pos=':first']"), "POS within attribute value after pseudo is treated as an attribute value" ); input.removeAttribute("data-pos"); // Make sure attribute value quoting works correctly. See: #6093 var attrbad = jQuery("<input type=\"hidden\" value=\"2\" name=\"foo.baz\" id=\"attrbad1\"/><input type=\"hidden\" value=\"2\" name=\"foo[baz]\" id=\"attrbad2\"/><input type=\"hidden\" data-attr=\"foo_baz']\" id=\"attrbad3\"/>").appendTo("body"); t( "Underscores are valid unquoted", "input[id=types_all]", ["types_all"] ); t( "Find escaped attribute value", "input[name=foo\\.baz]", ["attrbad1"] ); t( "Find escaped attribute value", "input[name=foo\\[baz\\]]", ["attrbad2"] ); t( "Find escaped attribute value", "input[data-attr='foo_baz\\']']", ["attrbad3"] ); t( "input[type=text]", "#form input[type=text]", ["text1", "text2", "hidden2", "name"] ); t( "input[type=search]", "#form input[type=search]", ["search"] ); attrbad.remove(); // #6428 t( "Find escaped attribute value", "#form input[name=foo\\[bar\\]]", ["hidden2"] ); // #3279 var div = document.createElement("div"); div.innerHTML = "<div id='foo' xml:test='something'></div>"; deepEqual( Sizzle( "[xml\\:test]", div ), [ div.firstChild ], "Finding by attribute with escaped characters." ); div = null; }); test("pseudo - (parent|empty)", function() { expect( 3 ); t( "Empty", "ul:empty", ["firstUL"] ); t( "Empty with comment node", "ol:empty", ["empty"] ); t( "Is A Parent", "#qunit-fixture p:parent", ["firstp","ap","sndp","en","sap","first"] ); }); test("pseudo - (first|last|only)-(child|of-type)", function() { expect( 12 ); t( "First Child", "p:first-child", ["firstp","sndp"] ); t( "First Child (leading id)", "#qunit-fixture p:first-child", ["firstp","sndp"] ); t( "First Child (leading class)", ".nothiddendiv div:first-child", ["nothiddendivchild"] ); t( "First Child (case-insensitive)", "#qunit-fixture p:FIRST-CHILD", ["firstp","sndp"] ); t( "Last Child", "p:last-child", ["sap"] ); t( "Last Child (leading id)", "#qunit-fixture a:last-child", ["simon1","anchor1","mark","yahoo","anchor2","simon","liveLink1","liveLink2"] ); t( "Only Child", "#qunit-fixture a:only-child", ["simon1","anchor1","yahoo","anchor2","liveLink1","liveLink2"] ); t( "First-of-type", "#qunit-fixture > p:first-of-type", ["firstp"] ); t( "Last-of-type", "#qunit-fixture > p:last-of-type", ["first"] ); t( "Only-of-type", "#qunit-fixture > :only-of-type", ["name+value", "firstUL", "empty", "floatTest", "iframe", "table"] ); // Verify that the child position isn't being cached improperly var secondChildren = jQuery("p:nth-child(2)").before("<div></div>"); t( "No longer second child", "p:nth-child(2)", [] ); secondChildren.prev().remove(); t( "Restored second child", "p:nth-child(2)", ["ap","en"] ); }); test("pseudo - nth-child", function() { expect( 30 ); t( "Nth-child", "p:nth-child(1)", ["firstp","sndp"] ); t( "Nth-child (with whitespace)", "p:nth-child( 1 )", ["firstp","sndp"] ); t( "Nth-child (case-insensitive)", "#form select:first option:NTH-child(3)", ["option1c"] ); t( "Not nth-child", "#qunit-fixture p:not(:nth-child(1))", ["ap","en","sap","first"] ); t( "Nth-child(2)", "#qunit-fixture form#form > *:nth-child(2)", ["text1"] ); t( "Nth-child(2)", "#qunit-fixture form#form > :nth-child(2)", ["text1"] ); t( "Nth-child(-1)", "#form select:first option:nth-child(-1)", [] ); t( "Nth-child(3)", "#form select:first option:nth-child(3)", ["option1c"] ); t( "Nth-child(0n+3)", "#form select:first option:nth-child(0n+3)", ["option1c"] ); t( "Nth-child(1n+0)", "#form select:first option:nth-child(1n+0)", ["option1a", "option1b", "option1c", "option1d"] ); t( "Nth-child(1n)", "#form select:first option:nth-child(1n)", ["option1a", "option1b", "option1c", "option1d"] ); t( "Nth-child(n)", "#form select:first option:nth-child(n)", ["option1a", "option1b", "option1c", "option1d"] ); t( "Nth-child(even)", "#form select:first option:nth-child(even)", ["option1b", "option1d"] ); t( "Nth-child(odd)", "#form select:first option:nth-child(odd)", ["option1a", "option1c"] ); t( "Nth-child(2n)", "#form select:first option:nth-child(2n)", ["option1b", "option1d"] ); t( "Nth-child(2n+1)", "#form select:first option:nth-child(2n+1)", ["option1a", "option1c"] ); t( "Nth-child(2n + 1)", "#form select:first option:nth-child(2n + 1)", ["option1a", "option1c"] ); t( "Nth-child(+2n + 1)", "#form select:first option:nth-child(+2n + 1)", ["option1a", "option1c"] ); t( "Nth-child(3n)", "#form select:first option:nth-child(3n)", ["option1c"] ); t( "Nth-child(3n+1)", "#form select:first option:nth-child(3n+1)", ["option1a", "option1d"] ); t( "Nth-child(3n+2)", "#form select:first option:nth-child(3n+2)", ["option1b"] ); t( "Nth-child(3n+3)", "#form select:first option:nth-child(3n+3)", ["option1c"] ); t( "Nth-child(3n-1)", "#form select:first option:nth-child(3n-1)", ["option1b"] ); t( "Nth-child(3n-2)", "#form select:first option:nth-child(3n-2)", ["option1a", "option1d"] ); t( "Nth-child(3n-3)", "#form select:first option:nth-child(3n-3)", ["option1c"] ); t( "Nth-child(3n+0)", "#form select:first option:nth-child(3n+0)", ["option1c"] ); t( "Nth-child(-1n+3)", "#form select:first option:nth-child(-1n+3)", ["option1a", "option1b", "option1c"] ); t( "Nth-child(-n+3)", "#form select:first option:nth-child(-n+3)", ["option1a", "option1b", "option1c"] ); t( "Nth-child(-1n + 3)", "#form select:first option:nth-child(-1n + 3)", ["option1a", "option1b", "option1c"] ); deepEqual( Sizzle( ":nth-child(n)", null, null, [ document.createElement("a") ].concat( q("ap") ) ), q("ap"), "Seeded nth-child" ); }); test("pseudo - nth-last-child", function() { expect( 30 ); t( "Nth-last-child", "form:nth-last-child(5)", ["testForm"] ); t( "Nth-last-child (with whitespace)", "form:nth-last-child( 5 )", ["testForm"] ); t( "Nth-last-child (case-insensitive)", "#form select:first option:NTH-last-child(3)", ["option1b"] ); t( "Not nth-last-child", "#qunit-fixture p:not(:nth-last-child(1))", ["firstp", "ap", "sndp", "en", "first"] ); t( "Nth-last-child(-1)", "#form select:first option:nth-last-child(-1)", [] ); t( "Nth-last-child(3)", "#form select:first :nth-last-child(3)", ["option1b"] ); t( "Nth-last-child(3)", "#form select:first *:nth-last-child(3)", ["option1b"] ); t( "Nth-last-child(3)", "#form select:first option:nth-last-child(3)", ["option1b"] ); t( "Nth-last-child(0n+3)", "#form select:first option:nth-last-child(0n+3)", ["option1b"] ); t( "Nth-last-child(1n+0)", "#form select:first option:nth-last-child(1n+0)", ["option1a", "option1b", "option1c", "option1d"] ); t( "Nth-last-child(1n)", "#form select:first option:nth-last-child(1n)", ["option1a", "option1b", "option1c", "option1d"] ); t( "Nth-last-child(n)", "#form select:first option:nth-last-child(n)", ["option1a", "option1b", "option1c", "option1d"] ); t( "Nth-last-child(even)", "#form select:first option:nth-last-child(even)", ["option1a", "option1c"] ); t( "Nth-last-child(odd)", "#form select:first option:nth-last-child(odd)", ["option1b", "option1d"] ); t( "Nth-last-child(2n)", "#form select:first option:nth-last-child(2n)", ["option1a", "option1c"] ); t( "Nth-last-child(2n+1)", "#form select:first option:nth-last-child(2n+1)", ["option1b", "option1d"] ); t( "Nth-last-child(2n + 1)", "#form select:first option:nth-last-child(2n + 1)", ["option1b", "option1d"] ); t( "Nth-last-child(+2n + 1)", "#form select:first option:nth-last-child(+2n + 1)", ["option1b", "option1d"] ); t( "Nth-last-child(3n)", "#form select:first option:nth-last-child(3n)", ["option1b"] ); t( "Nth-last-child(3n+1)", "#form select:first option:nth-last-child(3n+1)", ["option1a", "option1d"] ); t( "Nth-last-child(3n+2)", "#form select:first option:nth-last-child(3n+2)", ["option1c"] ); t( "Nth-last-child(3n+3)", "#form select:first option:nth-last-child(3n+3)", ["option1b"] ); t( "Nth-last-child(3n-1)", "#form select:first option:nth-last-child(3n-1)", ["option1c"] ); t( "Nth-last-child(3n-2)", "#form select:first option:nth-last-child(3n-2)", ["option1a", "option1d"] ); t( "Nth-last-child(3n-3)", "#form select:first option:nth-last-child(3n-3)", ["option1b"] ); t( "Nth-last-child(3n+0)", "#form select:first option:nth-last-child(3n+0)", ["option1b"] ); t( "Nth-last-child(-1n+3)", "#form select:first option:nth-last-child(-1n+3)", ["option1b", "option1c", "option1d"] ); t( "Nth-last-child(-n+3)", "#form select:first option:nth-last-child(-n+3)", ["option1b", "option1c", "option1d"] ); t( "Nth-last-child(-1n + 3)", "#form select:first option:nth-last-child(-1n + 3)", ["option1b", "option1c", "option1d"] ); deepEqual( Sizzle( ":nth-last-child(n)", null, null, [ document.createElement("a") ].concat( q("ap") ) ), q("ap"), "Seeded nth-last-child" ); }); test("pseudo - nth-of-type", function() { expect( 9 ); t( "Nth-of-type(-1)", ":nth-of-type(-1)", [] ); t( "Nth-of-type(3)", "#ap :nth-of-type(3)", ["mark"] ); t( "Nth-of-type(n)", "#ap :nth-of-type(n)", ["google", "groups", "code1", "anchor1", "mark"] ); t( "Nth-of-type(0n+3)", "#ap :nth-of-type(0n+3)", ["mark"] ); t( "Nth-of-type(2n)", "#ap :nth-of-type(2n)", ["groups"] ); t( "Nth-of-type(even)", "#ap :nth-of-type(even)", ["groups"] ); t( "Nth-of-type(2n+1)", "#ap :nth-of-type(2n+1)", ["google", "code1", "anchor1", "mark"] ); t( "Nth-of-type(odd)", "#ap :nth-of-type(odd)", ["google", "code1", "anchor1", "mark"] ); t( "Nth-of-type(-n+2)", "#qunit-fixture > :nth-of-type(-n+2)", ["firstp", "ap", "foo", "nothiddendiv", "name+value", "firstUL", "empty", "form", "floatTest", "iframe", "lengthtest", "table"] ); }); test("pseudo - nth-last-of-type", function() { expect( 9 ); t( "Nth-last-of-type(-1)", ":nth-last-of-type(-1)", [] ); t( "Nth-last-of-type(3)", "#ap :nth-last-of-type(3)", ["google"] ); t( "Nth-last-of-type(n)", "#ap :nth-last-of-type(n)", ["google", "groups", "code1", "anchor1", "mark"] ); t( "Nth-last-of-type(0n+3)", "#ap :nth-last-of-type(0n+3)", ["google"] ); t( "Nth-last-of-type(2n)", "#ap :nth-last-of-type(2n)", ["groups"] ); t( "Nth-last-of-type(even)", "#ap :nth-last-of-type(even)", ["groups"] ); t( "Nth-last-of-type(2n+1)", "#ap :nth-last-of-type(2n+1)", ["google", "code1", "anchor1", "mark"] ); t( "Nth-last-of-type(odd)", "#ap :nth-last-of-type(odd)", ["google", "code1", "anchor1", "mark"] ); t( "Nth-last-of-type(-n+2)", "#qunit-fixture > :nth-last-of-type(-n+2)", ["ap", "name+value", "first", "firstUL", "empty", "floatTest", "iframe", "table", "name-tests", "testForm", "liveHandlerOrder", "siblingTest"] ); }); test("pseudo - misc", function() { expect( 45 ); t( "Headers", ":header", ["qunit-header", "qunit-banner", "qunit-userAgent"] ); t( "Headers(case-insensitive)", ":Header", ["qunit-header", "qunit-banner", "qunit-userAgent"] ); t( "Has Children - :has()", "p:has(a)", ["firstp","ap","en","sap"] ); t( "Has Children - :has()", "p:has( a )", ["firstp","ap","en","sap"] ); t( "Multiple matches with the same context (cache check)", "#form select:has(option:first-child:contains('o'))", ["select1", "select2", "select3", "select4"] ); ok( Sizzle("#qunit-fixture :not(:has(:has(*)))").length, "All not grandparents" ); var select = document.getElementById("select1"), match = Sizzle.matchesSelector; ok( match( select, ":has(option)" ), "Has Option Matches" ); t( "Text Contains", "a:contains(Google)", ["google","groups"] ); t( "Text Contains", "a:contains(Google Groups)", ["groups"] ); t( "Text Contains", "a:contains('Google Groups (Link)')", ["groups"] ); t( "Text Contains", "a:contains(\"(Link)\")", ["groups"] ); t( "Text Contains", "a:contains(Google Groups (Link))", ["groups"] ); t( "Text Contains", "a:contains((Link))", ["groups"] ); var tmp = document.createElement("div"); tmp.id = "tmp_input"; document.body.appendChild( tmp ); jQuery.each( [ "button", "submit", "reset" ], function( i, type ) { jQuery( tmp ).append( "<input id='input_T' type='T'/><button id='button_T' type='T'>test</button>".replace(/T/g, type) ); t( "Input Buttons :" + type, "#tmp_input :" + type, [ "input_" + type, "button_" + type ] ); ok( match( Sizzle("#input_" + type)[0], ":" + type ), "Input Matches :" + type ); ok( match( Sizzle("#button_" + type)[0], ":" + type ), "Button Matches :" + type ); }); document.body.removeChild( tmp ); // Recreate tmp tmp = document.createElement("div"); tmp.id = "tmp_input"; tmp.innerHTML = "<span>Hello I am focusable.</span>"; // Setting tabIndex should make the element focusable // http://dev.w3.org/html5/spec/single-page.html#focus-management document.body.appendChild( tmp ); tmp.tabIndex = 0; tmp.focus(); if ( document.activeElement !== tmp || (document.hasFocus && !document.hasFocus()) || (document.querySelectorAll && !document.querySelectorAll("div:focus").length) ) { ok( true, "The div was not focused. Skip checking the :focus match." ); ok( true, "The div was not focused. Skip checking the :focus match." ); } else { t( "tabIndex element focused", ":focus", [ "tmp_input" ] ); ok( match( tmp, ":focus" ), ":focus matches tabIndex div" ); } // Blur tmp tmp.blur(); document.body.focus(); ok( !match( tmp, ":focus" ), ":focus doesn't match tabIndex div" ); document.body.removeChild( tmp ); // Input focus/active var input = document.createElement("input"); input.type = "text"; input.id = "focus-input"; document.body.appendChild( input ); input.focus(); // Inputs can't be focused unless the document has focus if ( document.activeElement !== input || (document.hasFocus && !document.hasFocus()) || (document.querySelectorAll && !document.querySelectorAll("input:focus").length) ) { ok( true, "The input was not focused. Skip checking the :focus match." ); ok( true, "The input was not focused. Skip checking the :focus match." ); } else { t( "Element focused", "input:focus", [ "focus-input" ] ); ok( match( input, ":focus" ), ":focus matches" ); } // :active selector: this selector does not depend on document focus if ( document.activeElement === input ) { ok( match( input, ":active" ), ":active Matches" ); } else { ok( true, "The input did not become active. Skip checking the :active match." ); } input.blur(); // When IE is out of focus, blur does not work. Force it here. if ( document.activeElement === input ) { document.body.focus(); } ok( !match( input, ":focus" ), ":focus doesn't match" ); ok( !match( input, ":active" ), ":active doesn't match" ); document.body.removeChild( input ); deepEqual( Sizzle( "[id='select1'] *:not(:last-child), [id='select2'] *:not(:last-child)", q("qunit-fixture")[0] ), q( "option1a", "option1b", "option1c", "option2a", "option2b", "option2c" ), "caching system tolerates recursive selection" ); // Tokenization edge cases t( "Sequential pseudos", "#qunit-fixture p:has(:contains(mark)):has(code)", ["ap"] ); t( "Sequential pseudos", "#qunit-fixture p:has(:contains(mark)):has(code):contains(This link)", ["ap"] ); t( "Pseudo argument containing ')'", "p:has(>a.GROUPS[src!=')'])", ["ap"] ); t( "Pseudo argument containing ')'", "p:has(>a.GROUPS[src!=')'])", ["ap"] ); t( "Pseudo followed by token containing ')'", "p:contains(id=\"foo\")[id!=\\)]", ["sndp"] ); t( "Pseudo followed by token containing ')'", "p:contains(id=\"foo\")[id!=')']", ["sndp"] ); t( "Multi-pseudo", "#ap:has(*), #ap:has(*)", ["ap"] ); t( "Multi-positional", "#ap:gt(0), #ap:lt(1)", ["ap"] ); t( "Multi-pseudo with leading nonexistent id", "#nonexistent:has(*), #ap:has(*)", ["ap"] ); t( "Multi-positional with leading nonexistent id", "#nonexistent:gt(0), #ap:lt(1)", ["ap"] ); Sizzle.selectors.filters.icontains = function( elem, i, match ) { return Sizzle.getText( elem ).toLowerCase().indexOf( (match[3] || "").toLowerCase() ) > -1; }; Sizzle.selectors.setFilters.podium = function( elements, argument ) { var count = argument == null || argument === "" ? 3 : +argument; return elements.slice( 0, count ); }; t( "Backwards-compatible custom pseudos", "a:icontains(THIS BLOG ENTRY)", ["simon1"] ); t( "Backwards-compatible custom setFilters", "#form :PODIUM", ["label-for", "text1", "text2"] ); t( "Backwards-compatible custom setFilters with argument", "#form input:Podium(1)", ["text1"] ); delete Sizzle.selectors.filters.icontains; delete Sizzle.selectors.setFilters.podium; t( "Tokenization stressor", "a[class*=blog]:not(:has(*, :contains(!)), :contains(!)), br:contains(]), p:contains(]), :not(:empty):not(:parent)", ["ap", "mark","yahoo","simon"] ); }); test("pseudo - :not", function() { expect( 43 ); t( "Not", "a.blog:not(.link)", ["mark"] ); t( ":not() with :first", "#foo p:not(:first) .link", ["simon"] ); t( "Not - multiple", "#form option:not(:contains(Nothing),#option1b,:selected)", ["option1c", "option1d", "option2b", "option2c", "option3d", "option3e", "option4e", "option5b", "option5c"] ); t( "Not - recursive", "#form option:not(:not(:selected))[id^='option3']", [ "option3b", "option3c"] ); t( ":not() failing interior", "#qunit-fixture p:not(.foo)", ["firstp","ap","sndp","en","sap","first"] ); t( ":not() failing interior", "#qunit-fixture p:not(div.foo)", ["firstp","ap","sndp","en","sap","first"] ); t( ":not() failing interior", "#qunit-fixture p:not(p.foo)", ["firstp","ap","sndp","en","sap","first"] ); t( ":not() failing interior", "#qunit-fixture p:not(#blargh)", ["firstp","ap","sndp","en","sap","first"] ); t( ":not() failing interior", "#qunit-fixture p:not(div#blargh)", ["firstp","ap","sndp","en","sap","first"] ); t( ":not() failing interior", "#qunit-fixture p:not(p#blargh)", ["firstp","ap","sndp","en","sap","first"] ); t( ":not Multiple", "#qunit-fixture p:not(a)", ["firstp","ap","sndp","en","sap","first"] ); t( ":not Multiple", "#qunit-fixture p:not( a )", ["firstp","ap","sndp","en","sap","first"] ); t( ":not Multiple", "#qunit-fixture p:not( p )", [] ); t( ":not Multiple", "#qunit-fixture p:not(a, b)", ["firstp","ap","sndp","en","sap","first"] ); t( ":not Multiple", "#qunit-fixture p:not(a, b, div)", ["firstp","ap","sndp","en","sap","first"] ); t( ":not Multiple", "p:not(p)", [] ); t( ":not Multiple", "p:not(a,p)", [] ); t( ":not Multiple", "p:not(p,a)", [] ); t( ":not Multiple", "p:not(a,p,b)", [] ); t( ":not Multiple", ":input:not(:image,:input,:submit)", [] ); t( ":not Multiple", "#qunit-fixture p:not(:has(a), :nth-child(1))", ["first"] ); t( "No element not selector", ".container div:not(.excluded) div", [] ); t( ":not() Existing attribute", "#form select:not([multiple])", ["select1", "select2", "select5"]); t( ":not() Equals attribute", "#form select:not([name=select1])", ["select2", "select3", "select4","select5"]); t( ":not() Equals quoted attribute", "#form select:not([name='select1'])", ["select2", "select3", "select4", "select5"]); t( ":not() Multiple Class", "#foo a:not(.blog)", ["yahoo", "anchor2"] ); t( ":not() Multiple Class", "#foo a:not(.link)", ["yahoo", "anchor2"] ); t( ":not() Multiple Class", "#foo a:not(.blog.link)", ["yahoo", "anchor2"] ); t( ":not chaining (compound)", "#qunit-fixture div[id]:not(:has(div, span)):not(:has(*))", ["nothiddendivchild", "divWithNoTabIndex"] ); t( ":not chaining (with attribute)", "#qunit-fixture form[id]:not([action$='formaction']):not(:button)", ["lengthtest", "name-tests", "testForm"] ); t( ":not chaining (colon in attribute)", "#qunit-fixture form[id]:not([action='form:action']):not(:button)", ["form", "lengthtest", "name-tests", "testForm"] ); t( ":not chaining (colon in attribute and nested chaining)", "#qunit-fixture form[id]:not([action='form:action']:button):not(:input)", ["form", "lengthtest", "name-tests", "testForm"] ); t( ":not chaining", "#form select:not(.select1):contains(Nothing) > option:not(option)", [] ); t( "positional :not()", "#foo p:not(:last)", ["sndp", "en"] ); t( "positional :not() prefix", "#foo p:not(:last) a", ["yahoo"] ); t( "compound positional :not()", "#foo p:not(:first, :last)", ["en"] ); t( "compound positional :not()", "#foo p:not(:first, :even)", ["en"] ); t( "compound positional :not()", "#foo p:not(:first, :odd)", ["sap"] ); t( "reordered compound positional :not()", "#foo p:not(:odd, :first)", ["sap"] ); t( "positional :not() with pre-filter", "#foo p:not([id]:first)", ["en", "sap"] ); t( "positional :not() with post-filter", "#foo p:not(:first[id])", ["en", "sap"] ); t( "positional :not() with pre-filter", "#foo p:not([lang]:first)", ["sndp", "sap"] ); t( "positional :not() with post-filter", "#foo p:not(:first[lang])", ["sndp", "en", "sap"] ); }); test("pseudo - position", function() { expect( 34 ); t( "First element", "div:first", ["qunit"] ); t( "First element(case-insensitive)", "div:fiRst", ["qunit"] ); t( "nth Element", "#qunit-fixture p:nth(1)", ["ap"] ); t( "First Element", "#qunit-fixture p:first", ["firstp"] ); t( "Last Element", "p:last", ["first"] ); t( "Even Elements", "#qunit-fixture p:even", ["firstp","sndp","sap"] ); t( "Odd Elements", "#qunit-fixture p:odd", ["ap","en","first"] ); t( "Position Equals", "#qunit-fixture p:eq(1)", ["ap"] ); t( "Position Equals (negative)", "#qunit-fixture p:eq(-1)", ["first"] ); t( "Position Greater Than", "#qunit-fixture p:gt(0)", ["ap","sndp","en","sap","first"] ); t( "Position Less Than", "#qunit-fixture p:lt(3)", ["firstp","ap","sndp"] ); t( "Check position filtering", "div#nothiddendiv:eq(0)", ["nothiddendiv"] ); t( "Check position filtering", "div#nothiddendiv:last", ["nothiddendiv"] ); t( "Check position filtering", "div#nothiddendiv:not(:gt(0))", ["nothiddendiv"] ); t( "Check position filtering", "#foo > :not(:first)", ["en", "sap"] ); t( "Check position filtering", "#qunit-fixture select > :not(:gt(2))", ["option1a", "option1b", "option1c"] ); t( "Check position filtering", "#qunit-fixture select:lt(2) :not(:first)", ["option1b", "option1c", "option1d", "option2a", "option2b", "option2c", "option2d"] ); t( "Check position filtering", "div.nothiddendiv:eq(0)", ["nothiddendiv"] ); t( "Check position filtering", "div.nothiddendiv:last", ["nothiddendiv"] ); t( "Check position filtering", "div.nothiddendiv:not(:lt(0))", ["nothiddendiv"] ); t( "Check element position", "#qunit-fixture div div:eq(0)", ["nothiddendivchild"] ); t( "Check element position", "#select1 option:eq(3)", ["option1d"] ); t( "Check element position", "#qunit-fixture div div:eq(10)", ["names-group"] ); t( "Check element position", "#qunit-fixture div div:first", ["nothiddendivchild"] ); t( "Check element position", "#qunit-fixture div > div:first", ["nothiddendivchild"] ); t( "Check element position", "#dl div:first div:first", ["foo"] ); t( "Check element position", "#dl div:first > div:first", ["foo"] ); t( "Check element position", "div#nothiddendiv:first > div:first", ["nothiddendivchild"] ); t( "Chained pseudo after a pos pseudo", "#listWithTabIndex li:eq(0):contains(Rice)", ["foodWithNegativeTabIndex"] ); t( "Check sort order with POS and comma", "#qunit-fixture em>em>em>em:first-child,div>em:first", ["siblingfirst", "siblinggreatgrandchild"] ); t( "Isolated position", ":last", ["last"] ); deepEqual( Sizzle( "*:lt(2) + *", null, [], Sizzle("#qunit-fixture > p") ), q("ap"), "Seeded pos with trailing relative" ); // jQuery #12526 var context = jQuery("#qunit-fixture").append("<div id='jquery12526'></div>")[0]; deepEqual( Sizzle( ":last", context ), q("jquery12526"), "Post-manipulation positional" ); QUnit.reset(); // Sizzle extension Sizzle.selectors.setFilters["primary"] = Sizzle.selectors.setFilters["first"]; t( "Extend Sizzle's POS selectors to rename first to primary", "div:primary", ["qunit"] ); // Reset delete Sizzle.selectors.setFilters["primary"]; }); test("pseudo - form", function() { expect( 10 ); var extraTexts = jQuery("<input id=\"impliedText\"/><input id=\"capitalText\" type=\"TEXT\">").appendTo("#form"); t( "Form element :input", "#form :input", ["text1", "text2", "radio1", "radio2", "check1", "check2", "hidden1", "hidden2", "name", "search", "button", "area1", "select1", "select2", "select3", "select4", "select5", "impliedText", "capitalText"] ); t( "Form element :radio", "#form :radio", ["radio1", "radio2"] ); t( "Form element :checkbox", "#form :checkbox", ["check1", "check2"] ); t( "Form element :text", "#form :text", ["text1", "text2", "hidden2", "name", "impliedText", "capitalText"] ); t( "Form element :radio:checked", "#form :radio:checked", ["radio2"] ); t( "Form element :checkbox:checked", "#form :checkbox:checked", ["check1"] ); t( "Form element :radio:checked, :checkbox:checked", "#form :radio:checked, #form :checkbox:checked", ["radio2", "check1"] ); t( "Selected Option Element", "#form option:selected", ["option1a","option2d","option3b","option3c","option4b","option4c","option4d","option5a"] ); t( "Selected Option Element are also :checked", "#form option:checked", ["option1a","option2d","option3b","option3c","option4b","option4c","option4d","option5a"] ); t( "Hidden inputs should be treated as enabled. See QSA test.", "#hidden1:enabled", ["hidden1"] ); extraTexts.remove(); }); test("caching", function() { expect( 1 ); Sizzle( ":not(code)", document.getElementById("ap") ); deepEqual( Sizzle( ":not(code)", document.getElementById("foo") ), q("sndp", "en", "yahoo", "sap", "anchor2", "simon"), "Reusing selector with new context" ); });
test/unit/selector.js
/*global QUnit: true, q: true, t: true, url: true, createWithFriesXML: true, Sizzle: true, module: true, test: true, asyncTest: true, expect: true, stop: true, start: true, ok: true, equal: true, notEqual: true, deepEqual: true, notDeepEqual: true, strictEqual: true, notStrictEqual: true, raises: true, moduleTeardown: true */ module("selector", { teardown: moduleTeardown }); // #### NOTE: #### // jQuery should not be used in this module // except for DOM manipulation // If jQuery is mandatory for the selection, move the test to jquery/test/unit/selector.js // Use t() or Sizzle() // ############### /* ======== QUnit Reference ======== http://docs.jquery.com/QUnit Test methods: expect(numAssertions) stop() start() note: QUnit's eventual addition of an argument to stop/start is ignored in this test suite so that start and stop can be passed as callbacks without worrying about their parameters Test assertions: ok(value, [message]) equal(actual, expected, [message]) notEqual(actual, expected, [message]) deepEqual(actual, expected, [message]) notDeepEqual(actual, expected, [message]) strictEqual(actual, expected, [message]) notStrictEqual(actual, expected, [message]) raises(block, [expected], [message]) ======== testinit.js reference ======== See data/testinit.js q(...); Returns an array of elements with the given IDs @example q("main", "foo", "bar") => [<div id="main">, <span id="foo">, <input id="bar">] t( testName, selector, [ "array", "of", "ids" ] ); Asserts that a select matches the given IDs @example t("Check for something", "//[a]", ["foo", "baar"]); url( "some/url.php" ); Add random number to url to stop caching @example url("data/test.html") => "data/test.html?10538358428943" @example url("data/test.php?foo=bar") => "data/test.php?foo=bar&10538358345554" */ test("element", function() { expect( 37 ); equal( Sizzle("").length, 0, "Empty selector returns an empty array" ); equal( Sizzle(" ").length, 0, "Empty selector returns an empty array" ); equal( Sizzle("\t").length, 0, "Empty selector returns an empty array" ); var form = document.getElementById("form"); ok( !Sizzle.matchesSelector( form, "" ), "Empty string passed to matchesSelector does not match" ); ok( Sizzle("*").length >= 30, "Select all" ); var all = Sizzle("*"), good = true; for ( var i = 0; i < all.length; i++ ) { if ( all[i].nodeType == 8 ) { good = false; } } ok( good, "Select all elements, no comment nodes" ); t( "Element Selector", "html", ["html"] ); t( "Element Selector", "body", ["body"] ); t( "Element Selector", "#qunit-fixture p", ["firstp","ap","sndp","en","sap","first"] ); t( "Leading space", " #qunit-fixture p", ["firstp","ap","sndp","en","sap","first"] ); t( "Leading tab", "\t#qunit-fixture p", ["firstp","ap","sndp","en","sap","first"] ); t( "Leading carriage return", "\r#qunit-fixture p", ["firstp","ap","sndp","en","sap","first"] ); t( "Leading line feed", "\n#qunit-fixture p", ["firstp","ap","sndp","en","sap","first"] ); t( "Leading form feed", "\f#qunit-fixture p", ["firstp","ap","sndp","en","sap","first"] ); t( "Trailing space", "#qunit-fixture p ", ["firstp","ap","sndp","en","sap","first"] ); t( "Trailing tab", "#qunit-fixture p\t", ["firstp","ap","sndp","en","sap","first"] ); t( "Trailing carriage return", "#qunit-fixture p\r", ["firstp","ap","sndp","en","sap","first"] ); t( "Trailing line feed", "#qunit-fixture p\n", ["firstp","ap","sndp","en","sap","first"] ); t( "Trailing form feed", "#qunit-fixture p\f", ["firstp","ap","sndp","en","sap","first"] ); t( "Parent Element", "dl ol", ["empty", "listWithTabIndex"] ); t( "Parent Element (non-space descendant combinator)", "dl\tol", ["empty", "listWithTabIndex"] ); var obj1 = document.getElementById("object1"); equal( Sizzle("param", obj1).length, 2, "Object/param as context" ); deepEqual( Sizzle("select", form), q("select1","select2","select3","select4","select5"), "Finding selects with a context." ); // Check for unique-ness and sort order deepEqual( Sizzle("p, div p"), Sizzle("p"), "Check for duplicates: p, div p" ); t( "Checking sort order", "h2, h1", ["qunit-header", "qunit-banner", "qunit-userAgent"] ); t( "Checking sort order", "h2:first, h1:first", ["qunit-header", "qunit-banner"] ); t( "Checking sort order", "#qunit-fixture p, #qunit-fixture p a", ["firstp", "simon1", "ap", "google", "groups", "anchor1", "mark", "sndp", "en", "yahoo", "sap", "anchor2", "simon", "first"] ); // Test Conflict ID var lengthtest = document.getElementById("lengthtest"); deepEqual( Sizzle("#idTest", lengthtest), q("idTest"), "Finding element with id of ID." ); deepEqual( Sizzle("[name='id']", lengthtest), q("idTest"), "Finding element with id of ID." ); deepEqual( Sizzle("input[id='idTest']", lengthtest), q("idTest"), "Finding elements with id of ID." ); var siblingTest = document.getElementById("siblingTest"); deepEqual( Sizzle("div em", siblingTest), [], "Element-rooted QSA does not select based on document context" ); deepEqual( Sizzle("div em, div em, div em:not(div em)", siblingTest), [], "Element-rooted QSA does not select based on document context" ); deepEqual( Sizzle("div em, em\\,", siblingTest), [], "Escaped commas do not get treated with an id in element-rooted QSA" ); var iframe = document.getElementById("iframe"), iframeDoc = iframe.contentDocument || iframe.contentWindow.document; iframeDoc.open(); iframeDoc.write("<body><p id='foo'>bar</p></body>"); iframeDoc.close(); deepEqual( Sizzle( "p:contains(bar)", iframeDoc ), [ iframeDoc.getElementById("foo") ], "Other document as context" ); var html = ""; for ( i = 0; i < 100; i++ ) { html = "<div>" + html + "</div>"; } html = jQuery( html ).appendTo( document.body ); ok( !!Sizzle("body div div div").length, "No stack or performance problems with large amounts of descendents" ); ok( !!Sizzle("body>div div div").length, "No stack or performance problems with large amounts of descendents" ); html.remove(); // Real use case would be using .watch in browsers with window.watch (see Issue #157) q("qunit-fixture")[0].appendChild( document.createElement("toString") ).id = "toString"; t( "Element name matches Object.prototype property", "toString#toString", ["toString"] ); }); test("XML Document Selectors", function() { var xml = createWithFriesXML(); expect( 10 ); equal( Sizzle("foo_bar", xml).length, 1, "Element Selector with underscore" ); equal( Sizzle(".component", xml).length, 1, "Class selector" ); equal( Sizzle("[class*=component]", xml).length, 1, "Attribute selector for class" ); equal( Sizzle("property[name=prop2]", xml).length, 1, "Attribute selector with name" ); equal( Sizzle("[name=prop2]", xml).length, 1, "Attribute selector with name" ); equal( Sizzle("#seite1", xml).length, 1, "Attribute selector with ID" ); equal( Sizzle("component#seite1", xml).length, 1, "Attribute selector with ID" ); equal( Sizzle.matches( "#seite1", Sizzle("component", xml) ).length, 1, "Attribute selector filter with ID" ); equal( Sizzle("meta property thing", xml).length, 2, "Descendent selector and dir caching" ); ok( Sizzle.matchesSelector( xml.lastChild, "soap\\:Envelope" ), "Check for namespaced element" ); }); test("broken", function() { expect( 26 ); function broken( name, selector ) { raises(function() { Sizzle.call( null, selector ); }, function( e ) { return e.message.indexOf("Syntax error") >= 0; }, name + ": " + selector ); } broken( "Broken Selector", "[" ); broken( "Broken Selector", "(" ); broken( "Broken Selector", "{" ); broken( "Broken Selector", "<" ); broken( "Broken Selector", "()" ); broken( "Broken Selector", "<>" ); broken( "Broken Selector", "{}" ); broken( "Broken Selector", "," ); broken( "Broken Selector", ",a" ); broken( "Broken Selector", "a," ); // Hangs on IE 9 if regular expression is inefficient broken( "Broken Selector", "[id=012345678901234567890123456789"); broken( "Doesn't exist", ":visble" ); broken( "Nth-child", ":nth-child" ); // Sigh again. IE 9 thinks this is also a real selector // not super critical that we fix this case //broken( "Nth-child", ":nth-child(-)" ); // Sigh. WebKit thinks this is a real selector in qSA // They've already fixed this and it'll be coming into // current browsers soon. Currently, Safari 5.0 still has this problem // broken( "Nth-child", ":nth-child(asdf)", [] ); broken( "Nth-child", ":nth-child(2n+-0)" ); broken( "Nth-child", ":nth-child(2+0)" ); broken( "Nth-child", ":nth-child(- 1n)" ); broken( "Nth-child", ":nth-child(-1 n)" ); broken( "First-child", ":first-child(n)" ); broken( "Last-child", ":last-child(n)" ); broken( "Only-child", ":only-child(n)" ); broken( "Nth-last-last-child", ":nth-last-last-child(1)" ); broken( "First-last-child", ":first-last-child" ); broken( "Last-last-child", ":last-last-child" ); broken( "Only-last-child", ":only-last-child" ); // Make sure attribute value quoting works correctly. See: #6093 var attrbad = jQuery('<input type="hidden" value="2" name="foo.baz" id="attrbad1"/><input type="hidden" value="2" name="foo[baz]" id="attrbad2"/>').appendTo("body"); broken( "Attribute not escaped", "input[name=foo.baz]", [] ); // Shouldn't be matching those inner brackets broken( "Attribute not escaped", "input[name=foo[baz]]", [] ); attrbad.remove(); }); test("id", function() { expect( 31 ); t( "ID Selector", "#body", ["body"] ); t( "ID Selector w/ Element", "body#body", ["body"] ); t( "ID Selector w/ Element", "ul#first", [] ); t( "ID selector with existing ID descendant", "#firstp #simon1", ["simon1"] ); t( "ID selector with non-existant descendant", "#firstp #foobar", [] ); t( "ID selector using UTF8", "#台北Táiběi", ["台北Táiběi"] ); t( "Multiple ID selectors using UTF8", "#台北Táiběi, #台北", ["台北Táiběi","台北"] ); t( "Descendant ID selector using UTF8", "div #台北", ["台北"] ); t( "Child ID selector using UTF8", "form > #台北", ["台北"] ); t( "Escaped ID", "#foo\\:bar", ["foo:bar"] ); t( "Escaped ID with descendent", "#foo\\:bar span:not(:input)", ["foo_descendent"] ); t( "Escaped ID", "#test\\.foo\\[5\\]bar", ["test.foo[5]bar"] ); t( "Descendant escaped ID", "div #foo\\:bar", ["foo:bar"] ); t( "Descendant escaped ID", "div #test\\.foo\\[5\\]bar", ["test.foo[5]bar"] ); t( "Child escaped ID", "form > #foo\\:bar", ["foo:bar"] ); t( "Child escaped ID", "form > #test\\.foo\\[5\\]bar", ["test.foo[5]bar"] ); var fiddle = jQuery("<div id='fiddle\\Foo'><span id='fiddleSpan'></span></div>").appendTo("#qunit-fixture"); deepEqual( Sizzle( "> span", Sizzle("#fiddle\\\\Foo")[0] ), q([ "fiddleSpan" ]), "Escaped ID as context" ); fiddle.remove(); t( "ID Selector, child ID present", "#form > #radio1", ["radio1"] ); // bug #267 t( "ID Selector, not an ancestor ID", "#form #first", [] ); t( "ID Selector, not a child ID", "#form > #option1a", [] ); t( "All Children of ID", "#foo > *", ["sndp", "en", "sap"] ); t( "All Children of ID with no children", "#firstUL > *", [] ); var a = jQuery("<div><a name=\"tName1\">tName1 A</a><a name=\"tName2\">tName2 A</a><div id=\"tName1\">tName1 Div</div></div>").appendTo("#qunit-fixture"); equal( Sizzle("#tName1")[0].id, 'tName1', "ID selector with same value for a name attribute" ); equal( Sizzle("#tName2").length, 0, "ID selector non-existing but name attribute on an A tag" ); a.remove(); a = jQuery("<a id='backslash\\foo'></a>").appendTo("#qunit-fixture"); t( "ID Selector contains backslash", "#backslash\\\\foo", ["backslash\\foo"] ); t( "ID Selector on Form with an input that has a name of 'id'", "#lengthtest", ["lengthtest"] ); t( "ID selector with non-existant ancestor", "#asdfasdf #foobar", [] ); // bug #986 deepEqual( Sizzle("div#form", document.body), [], "ID selector within the context of another element" ); t( "Underscore ID", "#types_all", ["types_all"] ); t( "Dash ID", "#qunit-fixture", ["qunit-fixture"] ); t( "ID with weird characters in it", "#name\\+value", ["name+value"] ); }); test("class", function() { expect( 25 ); t( "Class Selector", ".blog", ["mark","simon"] ); t( "Class Selector", ".GROUPS", ["groups"] ); t( "Class Selector", ".blog.link", ["simon"] ); t( "Class Selector w/ Element", "a.blog", ["mark","simon"] ); t( "Parent Class Selector", "p .blog", ["mark","simon"] ); t( "Class selector using UTF8", ".台北Táiběi", ["utf8class1"] ); //t( "Class selector using UTF8", ".台北", ["utf8class1","utf8class2"] ); t( "Class selector using UTF8", ".台北Táiběi.台北", ["utf8class1"] ); t( "Class selector using UTF8", ".台北Táiběi, .台北", ["utf8class1","utf8class2"] ); t( "Descendant class selector using UTF8", "div .台北Táiběi", ["utf8class1"] ); t( "Child class selector using UTF8", "form > .台北Táiběi", ["utf8class1"] ); t( "Escaped Class", ".foo\\:bar", ["foo:bar"] ); t( "Escaped Class", ".test\\.foo\\[5\\]bar", ["test.foo[5]bar"] ); t( "Descendant escaped Class", "div .foo\\:bar", ["foo:bar"] ); t( "Descendant escaped Class", "div .test\\.foo\\[5\\]bar", ["test.foo[5]bar"] ); t( "Child escaped Class", "form > .foo\\:bar", ["foo:bar"] ); t( "Child escaped Class", "form > .test\\.foo\\[5\\]bar", ["test.foo[5]bar"] ); var div = document.createElement("div"); div.innerHTML = "<div class='test e'></div><div class='test'></div>"; deepEqual( Sizzle(".e", div), [ div.firstChild ], "Finding a second class." ); div.lastChild.className = "e"; deepEqual( Sizzle(".e", div), [ div.firstChild, div.lastChild ], "Finding a modified class." ); ok( !Sizzle.matchesSelector( div, ".null"), ".null does not match an element with no class" ); ok( !Sizzle.matchesSelector( div.firstChild, ".null div"), ".null does not match an element with no class" ); div.className = "null"; ok( Sizzle.matchesSelector( div, ".null"), ".null matches element with class 'null'" ); ok( Sizzle.matchesSelector( div.firstChild, ".null div"), "caching system respects DOM changes" ); ok( !Sizzle.matchesSelector( document, ".foo" ), "testing class on document doesn't error" ); ok( !Sizzle.matchesSelector( window, ".foo" ), "testing class on window doesn't error" ); div.lastChild.className += " hasOwnProperty toString"; deepEqual( Sizzle(".e.hasOwnProperty.toString", div), [ div.lastChild ], "Classes match Object.prototype properties" ); }); test("name", function() { expect( 15 ); t( "Name selector", "input[name=action]", ["text1"] ); t( "Name selector with single quotes", "input[name='action']", ["text1"] ); t( "Name selector with double quotes", 'input[name="action"]', ["text1"] ); t( "Name selector non-input", "[name=example]", ["name-is-example"] ); t( "Name selector non-input", "[name=div]", ["name-is-div"] ); t( "Name selector non-input", "*[name=iframe]", ["iframe"] ); t( "Name selector for grouped input", "input[name='types[]']", ["types_all", "types_anime", "types_movie"] ); var form = document.getElementById("form"); deepEqual( Sizzle("input[name=action]", form), q("text1"), "Name selector within the context of another element" ); deepEqual( Sizzle("input[name='foo[bar]']", form), q("hidden2"), "Name selector for grouped form element within the context of another element" ); form = jQuery("<form><input name='id'/></form>").appendTo("body"); equal( Sizzle("input", form[0]).length, 1, "Make sure that rooted queries on forms (with possible expandos) work." ); form.remove(); var a = jQuery("<div><a id=\"tName1ID\" name=\"tName1\">tName1 A</a><a id=\"tName2ID\" name=\"tName2\">tName2 A</a><div id=\"tName1\">tName1 Div</div></div>") .appendTo("#qunit-fixture").children(); equal( a.length, 3, "Make sure the right number of elements were inserted." ); equal( a[1].id, "tName2ID", "Make sure the right number of elements were inserted." ); equal( Sizzle("[name=tName1]")[0], a[0], "Find elements that have similar IDs" ); equal( Sizzle("[name=tName2]")[0], a[1], "Find elements that have similar IDs" ); t( "Find elements that have similar IDs", "#tName2ID", ["tName2ID"] ); a.parent().remove(); }); test("multiple", function() { expect(6); t( "Comma Support", "h2, #qunit-fixture p", ["qunit-banner","qunit-userAgent","firstp","ap","sndp","en","sap","first"]); t( "Comma Support", "h2 , #qunit-fixture p", ["qunit-banner","qunit-userAgent","firstp","ap","sndp","en","sap","first"]); t( "Comma Support", "h2 , #qunit-fixture p", ["qunit-banner","qunit-userAgent","firstp","ap","sndp","en","sap","first"]); t( "Comma Support", "h2,#qunit-fixture p", ["qunit-banner","qunit-userAgent","firstp","ap","sndp","en","sap","first"]); t( "Comma Support", "h2,#qunit-fixture p ", ["qunit-banner","qunit-userAgent","firstp","ap","sndp","en","sap","first"]); t( "Comma Support", "h2\t,\r#qunit-fixture p\n", ["qunit-banner","qunit-userAgent","firstp","ap","sndp","en","sap","first"]); }); test("child and adjacent", function() { expect( 42 ); t( "Child", "p > a", ["simon1","google","groups","mark","yahoo","simon"] ); t( "Child", "p> a", ["simon1","google","groups","mark","yahoo","simon"] ); t( "Child", "p >a", ["simon1","google","groups","mark","yahoo","simon"] ); t( "Child", "p>a", ["simon1","google","groups","mark","yahoo","simon"] ); t( "Child w/ Class", "p > a.blog", ["mark","simon"] ); t( "All Children", "code > *", ["anchor1","anchor2"] ); t( "All Grandchildren", "p > * > *", ["anchor1","anchor2"] ); t( "Adjacent", "#qunit-fixture a + a", ["groups"] ); t( "Adjacent", "#qunit-fixture a +a", ["groups"] ); t( "Adjacent", "#qunit-fixture a+ a", ["groups"] ); t( "Adjacent", "#qunit-fixture a+a", ["groups"] ); t( "Adjacent", "p + p", ["ap","en","sap"] ); t( "Adjacent", "p#firstp + p", ["ap"] ); t( "Adjacent", "p[lang=en] + p", ["sap"] ); t( "Adjacent", "a.GROUPS + code + a", ["mark"] ); t( "Comma, Child, and Adjacent", "#qunit-fixture a + a, code > a", ["groups","anchor1","anchor2"] ); t( "Element Preceded By", "#qunit-fixture p ~ div", ["foo", "nothiddendiv", "moretests","tabindex-tests", "liveHandlerOrder", "siblingTest"] ); t( "Element Preceded By", "#first ~ div", ["moretests","tabindex-tests", "liveHandlerOrder", "siblingTest"] ); t( "Element Preceded By", "#groups ~ a", ["mark"] ); t( "Element Preceded By", "#length ~ input", ["idTest"] ); t( "Element Preceded By", "#siblingfirst ~ em", ["siblingnext", "siblingthird"] ); t( "Element Preceded By (multiple)", "#siblingTest em ~ em ~ em ~ span", ["siblingspan"] ); t( "Element Preceded By, Containing", "#liveHandlerOrder ~ div em:contains('1')", ["siblingfirst"] ); var siblingFirst = document.getElementById("siblingfirst"); deepEqual( Sizzle("~ em", siblingFirst), q("siblingnext", "siblingthird"), "Element Preceded By with a context." ); deepEqual( Sizzle("+ em", siblingFirst), q("siblingnext"), "Element Directly Preceded By with a context." ); deepEqual( Sizzle("~ em:first", siblingFirst), q("siblingnext"), "Element Preceded By positional with a context." ); var en = document.getElementById("en"); deepEqual( Sizzle("+ p, a", en), q("yahoo", "sap"), "Compound selector with context, beginning with sibling test." ); deepEqual( Sizzle("a, + p", en), q("yahoo", "sap"), "Compound selector with context, containing sibling test." ); t( "Multiple combinators selects all levels", "#siblingTest em *", ["siblingchild", "siblinggrandchild", "siblinggreatgrandchild"] ); t( "Multiple combinators selects all levels", "#siblingTest > em *", ["siblingchild", "siblinggrandchild", "siblinggreatgrandchild"] ); t( "Multiple sibling combinators doesn't miss general siblings", "#siblingTest > em:first-child + em ~ span", ["siblingspan"] ); t( "Combinators are not skipped when mixing general and specific", "#siblingTest > em:contains('x') + em ~ span", [] ); equal( Sizzle("#listWithTabIndex").length, 1, "Parent div for next test is found via ID (#8310)" ); equal( Sizzle("#listWithTabIndex li:eq(2) ~ li").length, 1, "Find by general sibling combinator (#8310)" ); equal( Sizzle("#__sizzle__").length, 0, "Make sure the temporary id assigned by sizzle is cleared out (#8310)" ); equal( Sizzle("#listWithTabIndex").length, 1, "Parent div for previous test is still found via ID (#8310)" ); t( "Verify deep class selector", "div.blah > p > a", [] ); t( "No element deep selector", "div.foo > span > a", [] ); var nothiddendiv = document.getElementById("nothiddendiv"); deepEqual( Sizzle("> :first", nothiddendiv), q("nothiddendivchild"), "Verify child context positional selector" ); deepEqual( Sizzle("> :eq(0)", nothiddendiv), q("nothiddendivchild"), "Verify child context positional selector" ); deepEqual( Sizzle("> *:first", nothiddendiv), q("nothiddendivchild"), "Verify child context positional selector" ); t( "Non-existant ancestors", ".fototab > .thumbnails > a", [] ); }); test("attributes", function() { expect( 62 ); t( "Attribute Exists", "#qunit-fixture a[title]", ["google"] ); t( "Attribute Exists (case-insensitive)", "#qunit-fixture a[TITLE]", ["google"] ); t( "Attribute Exists", "#qunit-fixture *[title]", ["google"] ); t( "Attribute Exists", "#qunit-fixture [title]", ["google"] ); t( "Attribute Exists", "#qunit-fixture a[ title ]", ["google"] ); t( "Boolean attribute exists", "#select2 option[selected]", ["option2d"]); t( "Boolean attribute equals", "#select2 option[selected='selected']", ["option2d"]); t( "Attribute Equals", "#qunit-fixture a[rel='bookmark']", ["simon1"] ); t( "Attribute Equals", "#qunit-fixture a[rel='bookmark']", ["simon1"] ); t( "Attribute Equals", "#qunit-fixture a[rel=bookmark]", ["simon1"] ); t( "Attribute Equals", "#qunit-fixture a[href='http://www.google.com/']", ["google"] ); t( "Attribute Equals", "#qunit-fixture a[ rel = 'bookmark' ]", ["simon1"] ); t( "Attribute Equals Number", "#qunit-fixture option[value=1]", ["option1b","option2b","option3b","option4b","option5c"] ); t( "Attribute Equals Number", "#qunit-fixture li[tabIndex=-1]", ["foodWithNegativeTabIndex"] ); document.getElementById("anchor2").href = "#2"; t( "href Attribute", "p a[href^=#]", ["anchor2"] ); t( "href Attribute", "p a[href*=#]", ["simon1", "anchor2"] ); t( "for Attribute", "form label[for]", ["label-for"] ); t( "for Attribute in form", "#form [for=action]", ["label-for"] ); t( "Attribute containing []", "input[name^='foo[']", ["hidden2"] ); t( "Attribute containing []", "input[name^='foo[bar]']", ["hidden2"] ); t( "Attribute containing []", "input[name*='[bar]']", ["hidden2"] ); t( "Attribute containing []", "input[name$='bar]']", ["hidden2"] ); t( "Attribute containing []", "input[name$='[bar]']", ["hidden2"] ); t( "Attribute containing []", "input[name$='foo[bar]']", ["hidden2"] ); t( "Attribute containing []", "input[name*='foo[bar]']", ["hidden2"] ); deepEqual( Sizzle( "input[data-comma='0,1']" ), [ document.getElementById("el12087") ], "Without context, single-quoted attribute containing ','" ); deepEqual( Sizzle( 'input[data-comma="0,1"]' ), [ document.getElementById("el12087") ], "Without context, double-quoted attribute containing ','" ); deepEqual( Sizzle( "input[data-comma='0,1']", document.getElementById("t12087") ), [ document.getElementById("el12087") ], "With context, single-quoted attribute containing ','" ); deepEqual( Sizzle( 'input[data-comma="0,1"]', document.getElementById("t12087") ), [ document.getElementById("el12087") ], "With context, double-quoted attribute containing ','" ); t( "Multiple Attribute Equals", "#form input[type='radio'], #form input[type='hidden']", ["radio1", "radio2", "hidden1"] ); t( "Multiple Attribute Equals", "#form input[type='radio'], #form input[type=\"hidden\"]", ["radio1", "radio2", "hidden1"] ); t( "Multiple Attribute Equals", "#form input[type='radio'], #form input[type=hidden]", ["radio1", "radio2", "hidden1"] ); t( "Attribute selector using UTF8", "span[lang=中文]", ["台北"] ); t( "Attribute Begins With", "a[href ^= 'http://www']", ["google","yahoo"] ); t( "Attribute Ends With", "a[href $= 'org/']", ["mark"] ); t( "Attribute Contains", "a[href *= 'google']", ["google","groups"] ); t( "Attribute Is Not Equal", "#ap a[hreflang!='en']", ["google","groups","anchor1"] ); var opt = document.getElementById("option1a"), match = Sizzle.matchesSelector; opt.setAttribute( "test", "" ); ok( match( opt, "[id*=option1][type!=checkbox]" ), "Attribute Is Not Equal Matches" ); ok( match( opt, "[id*=option1]" ), "Attribute With No Quotes Contains Matches" ); ok( match( opt, "[test=]" ), "Attribute With No Quotes No Content Matches" ); ok( !match( opt, "[test^='']" ), "Attribute with empty string value does not match startsWith selector (^=)" ); ok( match( opt, "[id=option1a]" ), "Attribute With No Quotes Equals Matches" ); ok( match( document.getElementById("simon1"), "a[href*=#]" ), "Attribute With No Quotes Href Contains Matches" ); t( "Empty values", "#select1 option[value='']", ["option1a"] ); t( "Empty values", "#select1 option[value!='']", ["option1b","option1c","option1d"] ); t( "Select options via :selected", "#select1 option:selected", ["option1a"] ); t( "Select options via :selected", "#select2 option:selected", ["option2d"] ); t( "Select options via :selected", "#select3 option:selected", ["option3b", "option3c"] ); t( "Select options via :selected", "select[name='select2'] option:selected", ["option2d"] ); t( "Grouped Form Elements", "input[name='foo[bar]']", ["hidden2"] ); var input = document.getElementById("text1"); input.title = "Don't click me"; ok( match( input, "input[title=\"Don't click me\"]" ), "Quote within attribute value does not mess up tokenizer" ); // Uncomment if the boolHook is removed // var check2 = document.getElementById("check2"); // check2.checked = true; // ok( !Sizzle.matches("[checked]", [ check2 ] ), "Dynamic boolean attributes match when they should with Sizzle.matches (#11115)" ); // jQuery #12303 input.setAttribute( "data-pos", ":first" ); ok( match( input, "input[data-pos=\\:first]"), "POS within attribute value is treated as an attribute value" ); ok( match( input, "input[data-pos=':first']"), "POS within attribute value is treated as an attribute value" ); ok( match( input, ":input[data-pos=':first']"), "POS within attribute value after pseudo is treated as an attribute value" ); input.removeAttribute("data-pos"); // Make sure attribute value quoting works correctly. See: #6093 var attrbad = jQuery("<input type=\"hidden\" value=\"2\" name=\"foo.baz\" id=\"attrbad1\"/><input type=\"hidden\" value=\"2\" name=\"foo[baz]\" id=\"attrbad2\"/><input type=\"hidden\" data-attr=\"foo_baz']\" id=\"attrbad3\"/>").appendTo("body"); t( "Underscores are valid unquoted", "input[id=types_all]", ["types_all"] ); t( "Find escaped attribute value", "input[name=foo\\.baz]", ["attrbad1"] ); t( "Find escaped attribute value", "input[name=foo\\[baz\\]]", ["attrbad2"] ); t( "Find escaped attribute value", "input[data-attr='foo_baz\\']']", ["attrbad3"] ); t( "input[type=text]", "#form input[type=text]", ["text1", "text2", "hidden2", "name"] ); t( "input[type=search]", "#form input[type=search]", ["search"] ); attrbad.remove(); // #6428 t( "Find escaped attribute value", "#form input[name=foo\\[bar\\]]", ["hidden2"] ); // #3279 var div = document.createElement("div"); div.innerHTML = "<div id='foo' xml:test='something'></div>"; deepEqual( Sizzle( "[xml\\:test]", div ), [ div.firstChild ], "Finding by attribute with escaped characters." ); div = null; }); test("pseudo - (parent|empty)", function() { expect( 3 ); t( "Empty", "ul:empty", ["firstUL"] ); t( "Empty with comment node", "ol:empty", ["empty"] ); t( "Is A Parent", "#qunit-fixture p:parent", ["firstp","ap","sndp","en","sap","first"] ); }); test("pseudo - (first|last|only)-(child|of-type)", function() { expect( 12 ); t( "First Child", "p:first-child", ["firstp","sndp"] ); t( "First Child (leading id)", "#qunit-fixture p:first-child", ["firstp","sndp"] ); t( "First Child (leading class)", ".nothiddendiv div:first-child", ["nothiddendivchild"] ); t( "First Child (case-insensitive)", "#qunit-fixture p:FIRST-CHILD", ["firstp","sndp"] ); t( "Last Child", "p:last-child", ["sap"] ); t( "Last Child (leading id)", "#qunit-fixture a:last-child", ["simon1","anchor1","mark","yahoo","anchor2","simon","liveLink1","liveLink2"] ); t( "Only Child", "#qunit-fixture a:only-child", ["simon1","anchor1","yahoo","anchor2","liveLink1","liveLink2"] ); t( "First-of-type", "#qunit-fixture > p:first-of-type", ["firstp"] ); t( "Last-of-type", "#qunit-fixture > p:last-of-type", ["first"] ); t( "Only-of-type", "#qunit-fixture > :only-of-type", ["name+value", "firstUL", "empty", "floatTest", "iframe", "table"] ); // Verify that the child position isn't being cached improperly var secondChildren = jQuery("p:nth-child(2)").before("<div></div>"); t( "No longer second child", "p:nth-child(2)", [] ); secondChildren.prev().remove(); t( "Restored second child", "p:nth-child(2)", ["ap","en"] ); }); test("pseudo - nth-child", function() { expect( 30 ); t( "Nth-child", "p:nth-child(1)", ["firstp","sndp"] ); t( "Nth-child (with whitespace)", "p:nth-child( 1 )", ["firstp","sndp"] ); t( "Nth-child (case-insensitive)", "#form select:first option:NTH-child(3)", ["option1c"] ); t( "Not nth-child", "#qunit-fixture p:not(:nth-child(1))", ["ap","en","sap","first"] ); t( "Nth-child(2)", "#qunit-fixture form#form > *:nth-child(2)", ["text1"] ); t( "Nth-child(2)", "#qunit-fixture form#form > :nth-child(2)", ["text1"] ); t( "Nth-child(-1)", "#form select:first option:nth-child(-1)", [] ); t( "Nth-child(3)", "#form select:first option:nth-child(3)", ["option1c"] ); t( "Nth-child(0n+3)", "#form select:first option:nth-child(0n+3)", ["option1c"] ); t( "Nth-child(1n+0)", "#form select:first option:nth-child(1n+0)", ["option1a", "option1b", "option1c", "option1d"] ); t( "Nth-child(1n)", "#form select:first option:nth-child(1n)", ["option1a", "option1b", "option1c", "option1d"] ); t( "Nth-child(n)", "#form select:first option:nth-child(n)", ["option1a", "option1b", "option1c", "option1d"] ); t( "Nth-child(even)", "#form select:first option:nth-child(even)", ["option1b", "option1d"] ); t( "Nth-child(odd)", "#form select:first option:nth-child(odd)", ["option1a", "option1c"] ); t( "Nth-child(2n)", "#form select:first option:nth-child(2n)", ["option1b", "option1d"] ); t( "Nth-child(2n+1)", "#form select:first option:nth-child(2n+1)", ["option1a", "option1c"] ); t( "Nth-child(2n + 1)", "#form select:first option:nth-child(2n + 1)", ["option1a", "option1c"] ); t( "Nth-child(+2n + 1)", "#form select:first option:nth-child(+2n + 1)", ["option1a", "option1c"] ); t( "Nth-child(3n)", "#form select:first option:nth-child(3n)", ["option1c"] ); t( "Nth-child(3n+1)", "#form select:first option:nth-child(3n+1)", ["option1a", "option1d"] ); t( "Nth-child(3n+2)", "#form select:first option:nth-child(3n+2)", ["option1b"] ); t( "Nth-child(3n+3)", "#form select:first option:nth-child(3n+3)", ["option1c"] ); t( "Nth-child(3n-1)", "#form select:first option:nth-child(3n-1)", ["option1b"] ); t( "Nth-child(3n-2)", "#form select:first option:nth-child(3n-2)", ["option1a", "option1d"] ); t( "Nth-child(3n-3)", "#form select:first option:nth-child(3n-3)", ["option1c"] ); t( "Nth-child(3n+0)", "#form select:first option:nth-child(3n+0)", ["option1c"] ); t( "Nth-child(-1n+3)", "#form select:first option:nth-child(-1n+3)", ["option1a", "option1b", "option1c"] ); t( "Nth-child(-n+3)", "#form select:first option:nth-child(-n+3)", ["option1a", "option1b", "option1c"] ); t( "Nth-child(-1n + 3)", "#form select:first option:nth-child(-1n + 3)", ["option1a", "option1b", "option1c"] ); deepEqual( Sizzle( ":nth-child(n)", null, null, [ document.createElement("a") ].concat( q("ap") ) ), q("ap"), "Seeded nth-child" ); }); test("pseudo - nth-last-child", function() { expect( 30 ); t( "Nth-last-child", "form:nth-last-child(5)", ["testForm"] ); t( "Nth-last-child (with whitespace)", "form:nth-last-child( 5 )", ["testForm"] ); t( "Nth-last-child (case-insensitive)", "#form select:first option:NTH-last-child(3)", ["option1b"] ); t( "Not nth-last-child", "#qunit-fixture p:not(:nth-last-child(1))", ["firstp", "ap", "sndp", "en", "first"] ); t( "Nth-last-child(-1)", "#form select:first option:nth-last-child(-1)", [] ); t( "Nth-last-child(3)", "#form select:first :nth-last-child(3)", ["option1b"] ); t( "Nth-last-child(3)", "#form select:first *:nth-last-child(3)", ["option1b"] ); t( "Nth-last-child(3)", "#form select:first option:nth-last-child(3)", ["option1b"] ); t( "Nth-last-child(0n+3)", "#form select:first option:nth-last-child(0n+3)", ["option1b"] ); t( "Nth-last-child(1n+0)", "#form select:first option:nth-last-child(1n+0)", ["option1a", "option1b", "option1c", "option1d"] ); t( "Nth-last-child(1n)", "#form select:first option:nth-last-child(1n)", ["option1a", "option1b", "option1c", "option1d"] ); t( "Nth-last-child(n)", "#form select:first option:nth-last-child(n)", ["option1a", "option1b", "option1c", "option1d"] ); t( "Nth-last-child(even)", "#form select:first option:nth-last-child(even)", ["option1a", "option1c"] ); t( "Nth-last-child(odd)", "#form select:first option:nth-last-child(odd)", ["option1b", "option1d"] ); t( "Nth-last-child(2n)", "#form select:first option:nth-last-child(2n)", ["option1a", "option1c"] ); t( "Nth-last-child(2n+1)", "#form select:first option:nth-last-child(2n+1)", ["option1b", "option1d"] ); t( "Nth-last-child(2n + 1)", "#form select:first option:nth-last-child(2n + 1)", ["option1b", "option1d"] ); t( "Nth-last-child(+2n + 1)", "#form select:first option:nth-last-child(+2n + 1)", ["option1b", "option1d"] ); t( "Nth-last-child(3n)", "#form select:first option:nth-last-child(3n)", ["option1b"] ); t( "Nth-last-child(3n+1)", "#form select:first option:nth-last-child(3n+1)", ["option1a", "option1d"] ); t( "Nth-last-child(3n+2)", "#form select:first option:nth-last-child(3n+2)", ["option1c"] ); t( "Nth-last-child(3n+3)", "#form select:first option:nth-last-child(3n+3)", ["option1b"] ); t( "Nth-last-child(3n-1)", "#form select:first option:nth-last-child(3n-1)", ["option1c"] ); t( "Nth-last-child(3n-2)", "#form select:first option:nth-last-child(3n-2)", ["option1a", "option1d"] ); t( "Nth-last-child(3n-3)", "#form select:first option:nth-last-child(3n-3)", ["option1b"] ); t( "Nth-last-child(3n+0)", "#form select:first option:nth-last-child(3n+0)", ["option1b"] ); t( "Nth-last-child(-1n+3)", "#form select:first option:nth-last-child(-1n+3)", ["option1b", "option1c", "option1d"] ); t( "Nth-last-child(-n+3)", "#form select:first option:nth-last-child(-n+3)", ["option1b", "option1c", "option1d"] ); t( "Nth-last-child(-1n + 3)", "#form select:first option:nth-last-child(-1n + 3)", ["option1b", "option1c", "option1d"] ); deepEqual( Sizzle( ":nth-last-child(n)", null, null, [ document.createElement("a") ].concat( q("ap") ) ), q("ap"), "Seeded nth-last-child" ); }); test("pseudo - nth-of-type", function() { expect( 9 ); t( "Nth-of-type(-1)", ":nth-of-type(-1)", [] ); t( "Nth-of-type(3)", "#ap :nth-of-type(3)", ["mark"] ); t( "Nth-of-type(n)", "#ap :nth-of-type(n)", ["google", "groups", "code1", "anchor1", "mark"] ); t( "Nth-of-type(0n+3)", "#ap :nth-of-type(0n+3)", ["mark"] ); t( "Nth-of-type(2n)", "#ap :nth-of-type(2n)", ["groups"] ); t( "Nth-of-type(even)", "#ap :nth-of-type(even)", ["groups"] ); t( "Nth-of-type(2n+1)", "#ap :nth-of-type(2n+1)", ["google", "code1", "anchor1", "mark"] ); t( "Nth-of-type(odd)", "#ap :nth-of-type(odd)", ["google", "code1", "anchor1", "mark"] ); t( "Nth-of-type(-n+2)", "#qunit-fixture > :nth-of-type(-n+2)", ["firstp", "ap", "foo", "nothiddendiv", "name+value", "firstUL", "empty", "form", "floatTest", "iframe", "lengthtest", "table"] ); }); test("pseudo - nth-last-of-type", function() { expect( 9 ); t( "Nth-last-of-type(-1)", ":nth-last-of-type(-1)", [] ); t( "Nth-last-of-type(3)", "#ap :nth-last-of-type(3)", ["google"] ); t( "Nth-last-of-type(n)", "#ap :nth-last-of-type(n)", ["google", "groups", "code1", "anchor1", "mark"] ); t( "Nth-last-of-type(0n+3)", "#ap :nth-last-of-type(0n+3)", ["google"] ); t( "Nth-last-of-type(2n)", "#ap :nth-last-of-type(2n)", ["groups"] ); t( "Nth-last-of-type(even)", "#ap :nth-last-of-type(even)", ["groups"] ); t( "Nth-last-of-type(2n+1)", "#ap :nth-last-of-type(2n+1)", ["google", "code1", "anchor1", "mark"] ); t( "Nth-last-of-type(odd)", "#ap :nth-last-of-type(odd)", ["google", "code1", "anchor1", "mark"] ); t( "Nth-last-of-type(-n+2)", "#qunit-fixture > :nth-last-of-type(-n+2)", ["ap", "name+value", "first", "firstUL", "empty", "floatTest", "iframe", "table", "name-tests", "testForm", "liveHandlerOrder", "siblingTest"] ); }); test("pseudo - misc", function() { expect( 45 ); t( "Headers", ":header", ["qunit-header", "qunit-banner", "qunit-userAgent"] ); t( "Headers(case-insensitive)", ":Header", ["qunit-header", "qunit-banner", "qunit-userAgent"] ); t( "Has Children - :has()", "p:has(a)", ["firstp","ap","en","sap"] ); t( "Has Children - :has()", "p:has( a )", ["firstp","ap","en","sap"] ); t( "Multiple matches with the same context (cache check)", "#form select:has(option:first-child:contains('o'))", ["select1", "select2", "select3", "select4"] ); ok( Sizzle("#qunit-fixture :not(:has(:has(*)))").length, "All not grandparents" ); var select = document.getElementById("select1"), match = Sizzle.matchesSelector; ok( match( select, ":has(option)" ), "Has Option Matches" ); t( "Text Contains", "a:contains(Google)", ["google","groups"] ); t( "Text Contains", "a:contains(Google Groups)", ["groups"] ); t( "Text Contains", "a:contains('Google Groups (Link)')", ["groups"] ); t( "Text Contains", "a:contains(\"(Link)\")", ["groups"] ); t( "Text Contains", "a:contains(Google Groups (Link))", ["groups"] ); t( "Text Contains", "a:contains((Link))", ["groups"] ); var tmp = document.createElement("div"); tmp.id = "tmp_input"; document.body.appendChild( tmp ); jQuery.each( [ "button", "submit", "reset" ], function( i, type ) { jQuery( tmp ).append( "<input id='input_T' type='T'/><button id='button_T' type='T'>test</button>".replace(/T/g, type) ); t( "Input Buttons :" + type, "#tmp_input :" + type, [ "input_" + type, "button_" + type ] ); ok( match( Sizzle("#input_" + type)[0], ":" + type ), "Input Matches :" + type ); ok( match( Sizzle("#button_" + type)[0], ":" + type ), "Button Matches :" + type ); }); document.body.removeChild( tmp ); // Recreate tmp tmp = document.createElement("div"); tmp.id = "tmp_input"; tmp.innerHTML = "<span>Hello I am focusable.</span>"; // Setting tabIndex should make the element focusable // http://dev.w3.org/html5/spec/single-page.html#focus-management document.body.appendChild( tmp ); tmp.tabIndex = 0; tmp.focus(); if ( document.activeElement !== tmp || (document.hasFocus && !document.hasFocus()) || (document.querySelectorAll && !document.querySelectorAll("div:focus").length) ) { ok( true, "The div was not focused. Skip checking the :focus match." ); ok( true, "The div was not focused. Skip checking the :focus match." ); } else { t( "tabIndex element focused", ":focus", [ "tmp_input" ] ); ok( match( tmp, ":focus" ), ":focus matches tabIndex div" ); } // Blur tmp tmp.blur(); document.body.focus(); ok( !match( tmp, ":focus" ), ":focus doesn't match tabIndex div" ); document.body.removeChild( tmp ); // Input focus/active var input = document.createElement("input"); input.type = "text"; input.id = "focus-input"; document.body.appendChild( input ); input.focus(); // Inputs can't be focused unless the document has focus if ( document.activeElement !== input || (document.hasFocus && !document.hasFocus()) || (document.querySelectorAll && !document.querySelectorAll("input:focus").length) ) { ok( true, "The input was not focused. Skip checking the :focus match." ); ok( true, "The input was not focused. Skip checking the :focus match." ); } else { t( "Element focused", "input:focus", [ "focus-input" ] ); ok( match( input, ":focus" ), ":focus matches" ); } // :active selector: this selector does not depend on document focus if ( document.activeElement === input ) { ok( match( input, ":active" ), ":active Matches" ); } else { ok( true, "The input did not become active. Skip checking the :active match." ); } input.blur(); // When IE is out of focus, blur does not work. Force it here. if ( document.activeElement === input ) { document.body.focus(); } ok( !match( input, ":focus" ), ":focus doesn't match" ); ok( !match( input, ":active" ), ":active doesn't match" ); document.body.removeChild( input ); deepEqual( Sizzle( "[id='select1'] *:not(:last-child), [id='select2'] *:not(:last-child)", q("qunit-fixture")[0] ), q( "option1a", "option1b", "option1c", "option2a", "option2b", "option2c" ), "caching system tolerates recursive selection" ); // Tokenization edge cases t( "Sequential pseudos", "#qunit-fixture p:has(:contains(mark)):has(code)", ["ap"] ); t( "Sequential pseudos", "#qunit-fixture p:has(:contains(mark)):has(code):contains(This link)", ["ap"] ); t( "Pseudo argument containing ')'", "p:has(>a.GROUPS[src!=')'])", ["ap"] ); t( "Pseudo argument containing ')'", "p:has(>a.GROUPS[src!=')'])", ["ap"] ); t( "Pseudo followed by token containing ')'", "p:contains(id=\"foo\")[id!=\\)]", ["sndp"] ); t( "Pseudo followed by token containing ')'", "p:contains(id=\"foo\")[id!=')']", ["sndp"] ); t( "Multi-pseudo", "#ap:has(*), #ap:has(*)", ["ap"] ); t( "Multi-positional", "#ap:gt(0), #ap:lt(1)", ["ap"] ); t( "Multi-pseudo with leading nonexistent id", "#nonexistent:has(*), #ap:has(*)", ["ap"] ); t( "Multi-positional with leading nonexistent id", "#nonexistent:gt(0), #ap:lt(1)", ["ap"] ); Sizzle.selectors.filters.icontains = function( elem, i, match ) { return Sizzle.getText( elem ).toLowerCase().indexOf( (match[3] || "").toLowerCase() ) > -1; }; Sizzle.selectors.setFilters.podium = function( elements, argument ) { var count = argument == null || argument === "" ? 3 : +argument; return elements.slice( 0, count ); }; t( "Backwards-compatible custom pseudos", "a:icontains(THIS BLOG ENTRY)", ["simon1"] ); t( "Backwards-compatible custom setFilters", "#form :PODIUM", ["label-for", "text1", "text2"] ); t( "Backwards-compatible custom setFilters with argument", "#form input:Podium(1)", ["text1"] ); delete Sizzle.selectors.filters.icontains; delete Sizzle.selectors.setFilters.podium; t( "Tokenization stressor", "a[class*=blog]:not(:has(*, :contains(!)), :contains(!)), br:contains(]), p:contains(]), :not(:empty):not(:parent)", ["ap", "mark","yahoo","simon"] ); }); test("pseudo - :not", function() { expect( 43 ); t( "Not", "a.blog:not(.link)", ["mark"] ); t( ":not() with :first", "#foo p:not(:first) .link", ["simon"] ); t( "Not - multiple", "#form option:not(:contains(Nothing),#option1b,:selected)", ["option1c", "option1d", "option2b", "option2c", "option3d", "option3e", "option4e", "option5b", "option5c"] ); t( "Not - recursive", "#form option:not(:not(:selected))[id^='option3']", [ "option3b", "option3c"] ); t( ":not() failing interior", "#qunit-fixture p:not(.foo)", ["firstp","ap","sndp","en","sap","first"] ); t( ":not() failing interior", "#qunit-fixture p:not(div.foo)", ["firstp","ap","sndp","en","sap","first"] ); t( ":not() failing interior", "#qunit-fixture p:not(p.foo)", ["firstp","ap","sndp","en","sap","first"] ); t( ":not() failing interior", "#qunit-fixture p:not(#blargh)", ["firstp","ap","sndp","en","sap","first"] ); t( ":not() failing interior", "#qunit-fixture p:not(div#blargh)", ["firstp","ap","sndp","en","sap","first"] ); t( ":not() failing interior", "#qunit-fixture p:not(p#blargh)", ["firstp","ap","sndp","en","sap","first"] ); t( ":not Multiple", "#qunit-fixture p:not(a)", ["firstp","ap","sndp","en","sap","first"] ); t( ":not Multiple", "#qunit-fixture p:not( a )", ["firstp","ap","sndp","en","sap","first"] ); t( ":not Multiple", "#qunit-fixture p:not( p )", [] ); t( ":not Multiple", "#qunit-fixture p:not(a, b)", ["firstp","ap","sndp","en","sap","first"] ); t( ":not Multiple", "#qunit-fixture p:not(a, b, div)", ["firstp","ap","sndp","en","sap","first"] ); t( ":not Multiple", "p:not(p)", [] ); t( ":not Multiple", "p:not(a,p)", [] ); t( ":not Multiple", "p:not(p,a)", [] ); t( ":not Multiple", "p:not(a,p,b)", [] ); t( ":not Multiple", ":input:not(:image,:input,:submit)", [] ); t( ":not Multiple", "#qunit-fixture p:not(:has(a), :nth-child(1))", ["first"] ); t( "No element not selector", ".container div:not(.excluded) div", [] ); t( ":not() Existing attribute", "#form select:not([multiple])", ["select1", "select2", "select5"]); t( ":not() Equals attribute", "#form select:not([name=select1])", ["select2", "select3", "select4","select5"]); t( ":not() Equals quoted attribute", "#form select:not([name='select1'])", ["select2", "select3", "select4", "select5"]); t( ":not() Multiple Class", "#foo a:not(.blog)", ["yahoo", "anchor2"] ); t( ":not() Multiple Class", "#foo a:not(.link)", ["yahoo", "anchor2"] ); t( ":not() Multiple Class", "#foo a:not(.blog.link)", ["yahoo", "anchor2"] ); t( ":not chaining (compound)", "#qunit-fixture div[id]:not(:has(div, span)):not(:has(*))", ["nothiddendivchild", "divWithNoTabIndex"] ); t( ":not chaining (with attribute)", "#qunit-fixture form[id]:not([action$='formaction']):not(:button)", ["lengthtest", "name-tests", "testForm"] ); t( ":not chaining (colon in attribute)", "#qunit-fixture form[id]:not([action='form:action']):not(:button)", ["form", "lengthtest", "name-tests", "testForm"] ); t( ":not chaining (colon in attribute and nested chaining)", "#qunit-fixture form[id]:not([action='form:action']:button):not(:input)", ["form", "lengthtest", "name-tests", "testForm"] ); t( ":not chaining", "#form select:not(.select1):contains(Nothing) > option:not(option)", [] ); t( "positional :not()", "#foo p:not(:last)", ["sndp", "en"] ); t( "positional :not() prefix", "#foo p:not(:last) a", ["yahoo"] ); t( "compound positional :not()", "#foo p:not(:first, :last)", ["en"] ); t( "compound positional :not()", "#foo p:not(:first, :even)", ["en"] ); t( "compound positional :not()", "#foo p:not(:first, :odd)", ["sap"] ); t( "reordered compound positional :not()", "#foo p:not(:odd, :first)", ["sap"] ); t( "positional :not() with pre-filter", "#foo p:not([id]:first)", ["en", "sap"] ); t( "positional :not() with post-filter", "#foo p:not(:first[id])", ["en", "sap"] ); t( "positional :not() with pre-filter", "#foo p:not([lang]:first)", ["sndp", "sap"] ); t( "positional :not() with post-filter", "#foo p:not(:first[lang])", ["sndp", "en", "sap"] ); }); test("pseudo - position", function() { expect( 34 ); t( "First element", "div:first", ["qunit"] ); t( "First element(case-insensitive)", "div:fiRst", ["qunit"] ); t( "nth Element", "#qunit-fixture p:nth(1)", ["ap"] ); t( "First Element", "#qunit-fixture p:first", ["firstp"] ); t( "Last Element", "p:last", ["first"] ); t( "Even Elements", "#qunit-fixture p:even", ["firstp","sndp","sap"] ); t( "Odd Elements", "#qunit-fixture p:odd", ["ap","en","first"] ); t( "Position Equals", "#qunit-fixture p:eq(1)", ["ap"] ); t( "Position Equals (negative)", "#qunit-fixture p:eq(-1)", ["first"] ); t( "Position Greater Than", "#qunit-fixture p:gt(0)", ["ap","sndp","en","sap","first"] ); t( "Position Less Than", "#qunit-fixture p:lt(3)", ["firstp","ap","sndp"] ); t( "Check position filtering", "div#nothiddendiv:eq(0)", ["nothiddendiv"] ); t( "Check position filtering", "div#nothiddendiv:last", ["nothiddendiv"] ); t( "Check position filtering", "div#nothiddendiv:not(:gt(0))", ["nothiddendiv"] ); t( "Check position filtering", "#foo > :not(:first)", ["en", "sap"] ); t( "Check position filtering", "#qunit-fixture select > :not(:gt(2))", ["option1a", "option1b", "option1c"] ); t( "Check position filtering", "#qunit-fixture select:lt(2) :not(:first)", ["option1b", "option1c", "option1d", "option2a", "option2b", "option2c", "option2d"] ); t( "Check position filtering", "div.nothiddendiv:eq(0)", ["nothiddendiv"] ); t( "Check position filtering", "div.nothiddendiv:last", ["nothiddendiv"] ); t( "Check position filtering", "div.nothiddendiv:not(:lt(0))", ["nothiddendiv"] ); t( "Check element position", "#qunit-fixture div div:eq(0)", ["nothiddendivchild"] ); t( "Check element position", "#select1 option:eq(3)", ["option1d"] ); t( "Check element position", "#qunit-fixture div div:eq(10)", ["names-group"] ); t( "Check element position", "#qunit-fixture div div:first", ["nothiddendivchild"] ); t( "Check element position", "#qunit-fixture div > div:first", ["nothiddendivchild"] ); t( "Check element position", "#dl div:first div:first", ["foo"] ); t( "Check element position", "#dl div:first > div:first", ["foo"] ); t( "Check element position", "div#nothiddendiv:first > div:first", ["nothiddendivchild"] ); t( "Chained pseudo after a pos pseudo", "#listWithTabIndex li:eq(0):contains(Rice)", ["foodWithNegativeTabIndex"] ); t( "Check sort order with POS and comma", "#qunit-fixture em>em>em>em:first-child,div>em:first", ["siblingfirst", "siblinggreatgrandchild"] ); t( "Isolated position", ":last", ["last"] ); deepEqual( Sizzle( "*:lt(2) + *", null, [], Sizzle("#qunit-fixture > p") ), q("ap"), "Seeded pos with trailing relative" ); // jQuery #12526 var context = jQuery("#qunit-fixture").append("<div id='jquery12526'></div>")[0]; deepEqual( Sizzle( ":last", context ), q("jquery12526"), "Post-manipulation positional" ); QUnit.reset(); // Sizzle extension Sizzle.selectors.setFilters["primary"] = Sizzle.selectors.setFilters["first"]; t( "Extend Sizzle's POS selectors to rename first to primary", "div:primary", ["qunit"] ); // Reset delete Sizzle.selectors.setFilters["primary"]; }); test("pseudo - form", function() { expect( 10 ); var extraTexts = jQuery("<input id=\"impliedText\"/><input id=\"capitalText\" type=\"TEXT\">").appendTo("#form"); t( "Form element :input", "#form :input", ["text1", "text2", "radio1", "radio2", "check1", "check2", "hidden1", "hidden2", "name", "search", "button", "area1", "select1", "select2", "select3", "select4", "select5", "impliedText", "capitalText"] ); t( "Form element :radio", "#form :radio", ["radio1", "radio2"] ); t( "Form element :checkbox", "#form :checkbox", ["check1", "check2"] ); t( "Form element :text", "#form :text", ["text1", "text2", "hidden2", "name", "impliedText", "capitalText"] ); t( "Form element :radio:checked", "#form :radio:checked", ["radio2"] ); t( "Form element :checkbox:checked", "#form :checkbox:checked", ["check1"] ); t( "Form element :radio:checked, :checkbox:checked", "#form :radio:checked, #form :checkbox:checked", ["radio2", "check1"] ); t( "Selected Option Element", "#form option:selected", ["option1a","option2d","option3b","option3c","option4b","option4c","option4d","option5a"] ); t( "Selected Option Element are also :checked", "#form option:checked", ["option1a","option2d","option3b","option3c","option4b","option4c","option4d","option5a"] ); t( "Hidden inputs should be treated as enabled. See QSA test.", "#hidden1:enabled", ["hidden1"] ); extraTexts.remove(); }); test("caching", function() { expect( 1 ); Sizzle( ":not(code)", document.getElementById("ap") ); deepEqual( Sizzle( ":not(code)", document.getElementById("foo") ), q("sndp", "en", "yahoo", "sap", "anchor2", "simon"), "Reusing selector with new context" ); });
Add comment about bypassing QUnit's window.error in 'broken' tests
test/unit/selector.js
Add comment about bypassing QUnit's window.error in 'broken' tests
<ide><path>est/unit/selector.js <ide> <ide> function broken( name, selector ) { <ide> raises(function() { <add> // Setting context to null here somehow avoids QUnit's window.error handling <add> // making the e & e.message correct <add> // For whatever reason, without this, <add> // Sizzle.error will be called but no error will be seen in oldIE <ide> Sizzle.call( null, selector ); <ide> }, function( e ) { <ide> return e.message.indexOf("Syntax error") >= 0;
Java
mit
1d956cb46abd8fed5a1a643c182ac89ea3627168
0
xiwan/xlsEditor,xiwan/xlsEditor
package Composites; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.Vector; import javax.swing.table.DefaultTableModel; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.TableEditor; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Text; import jxl.Cell; import jxl.CellType; import jxl.Sheet; import jxl.Workbook; import jxl.WorkbookSettings; import jxl.read.biff.BiffException; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import jxl.write.WriteException; import jxl.write.biff.RowsExceededException; public class XlsTable { private Vector headers = new Vector(); private Vector data = new Vector(); public Vector getHeaders() { return headers; } // public void setHeaders(Vector headers) { // this.headers = headers; // } public Vector getData(int row) { return (Vector) this.data.get(row); } public void setData(int row, Vector dd) { this.data.set(row, dd); } public void setData(int row, int col, String update) { //this.data = data; Vector dd = (Vector) this.data.get(row); dd.set(col, update); this.data.set(row, dd); } public void importContents(String fileSelectedPath, final Table table) { try { File inputWorkbook = new File(fileSelectedPath); Workbook w = Workbook.getWorkbook(inputWorkbook); Sheet sheet = w.getSheet(0); int rows = sheet.getRows(); int cols = sheet.getColumns(); headers.clear(); data.clear(); for (int i = 0; i < rows; i++) { Vector d = new Vector(); for (int j = 0; j < cols; j++) { Cell cell = sheet.getCell(j, i); CellType type = cell.getType(); if (type == CellType.LABEL) { d.add(cell.getContents().toString()); } if (type == CellType.NUMBER) { d.add(cell.getContents().toString()); } if (i == 3) { headers.add(cell.getContents()); } } data.add(d); } // fill the headers and data for (int i = 0; i < headers.size(); i++) { TableColumn column = new TableColumn(table, SWT.NONE, i); column.setText(headers.get(i).toString()); table.getColumn(i).pack(); } for (int i = 0; i < sheet.getRows(); i++) { TableItem item = new TableItem(table, SWT.NONE, i); for (int j = 0; j < sheet.getColumns(); j++) { Cell cell = sheet.getCell(j, i); item.setText(j, cell.getContents()); //item.addListener(eventType, listener); } } final TableEditor editor = new TableEditor(table); editor.horizontalAlignment = SWT.LEFT; editor.grabHorizontal = true; table.addListener(SWT.MouseDoubleClick, new Listener(){ @Override public void handleEvent(Event event) { // TODO Auto-generated method stub Rectangle clientArea = table.getClientArea(); Point pt = new Point(event.x, event.y); int index = table.getTopIndex(); while (index < table.getItemCount()) { boolean visible = false; final int row = index; final TableItem item = table.getItem(index); for (int i = 0; i < table.getColumnCount(); i++) { Rectangle rect = item.getBounds(i); if (rect.contains(pt)) { final int column = i; final Text text = new Text(table, SWT.NONE); Listener textListener = new Listener() { @Override public void handleEvent(Event evt) { // TODO Auto-generated method stub switch (evt.type) { case SWT.FocusOut: item.setText(column, text.getText()); XlsTable.this.setData(row, column, text.getText());; // Vector dd = (Vector) data.get(row); // dd.set(column, text.getText()); // data.set(row, dd); //System.out.println(column + " "+ row + " = " + dd.get(column)); text.dispose(); break; case SWT.Traverse: switch (evt.detail) { case SWT.TRAVERSE_RETURN: item.setText(column, text.getText()); // FALL THROUGH case SWT.TRAVERSE_ESCAPE: text.dispose(); evt.doit = false; } break; } } }; text.addListener(SWT.FocusOut, textListener); text.addListener(SWT.Traverse, textListener); editor.setEditor(text, item, i); text.setText(item.getText(i)); text.selectAll(); text.setFocus(); return; } if (!visible && rect.intersects(clientArea)) { visible = true; } } if (!visible) return; index++; } } }); } catch (BiffException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void exportContents(String outputPath){ try { DefaultTableModel model = new DefaultTableModel(data, headers); WritableWorkbook workbook = Workbook.createWorkbook(new File(outputPath)); WritableSheet sheet = workbook.createSheet("First Sheet", 0); for (int i=0; i < model.getRowCount(); i++) { for (int j=0; j < model.getColumnCount(); j++) { if (model.getValueAt(i, j) != null) { Label content = new Label(j, i, model.getValueAt(i, j).toString()); sheet.addCell(content); } } } // JTable table = new JTable(); // table.setModel(model); // table.setAutoCreateRowSorter(true); // model = new DefaultTableModel(data, headers); // table.setModel(model); // JScrollPane scroll = new JScrollPane(table); // JFrame f = new JFrame(); // f.getContentPane().add(scroll); // f.setSize(400, 200); // f.setResizable(true); // f.setVisible(true); workbook.write(); workbook.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RowsExceededException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (WriteException e) { // TODO Auto-generated catch block e.printStackTrace(); } }; }
src/Composites/XlsTable.java
package Composites; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.Vector; import javax.swing.table.DefaultTableModel; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.TableEditor; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Text; import jxl.Cell; import jxl.CellType; import jxl.Sheet; import jxl.Workbook; import jxl.WorkbookSettings; import jxl.read.biff.BiffException; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import jxl.write.WriteException; import jxl.write.biff.RowsExceededException; public class XlsTable { private Vector headers = new Vector(); private Vector data = new Vector(); public Vector getHeaders() { return headers; } // public void setHeaders(Vector headers) { // this.headers = headers; // } public Vector getData(int row) { return (Vector) this.data.get(row); } public void setData(int row, int col, String update) { //this.data = data; Vector dd = (Vector) this.data.get(row); dd.set(col, update); this.data.set(row, dd); } public void importContents(String fileSelectedPath, final Table table) { try { File inputWorkbook = new File(fileSelectedPath); Workbook w = Workbook.getWorkbook(inputWorkbook); Sheet sheet = w.getSheet(0); int rows = sheet.getRows(); int cols = sheet.getColumns(); headers.clear(); data.clear(); for (int i = 0; i < rows; i++) { Vector d = new Vector(); for (int j = 0; j < cols; j++) { Cell cell = sheet.getCell(j, i); CellType type = cell.getType(); if (type == CellType.LABEL) { d.add(cell.getContents().toString()); } if (type == CellType.NUMBER) { d.add(cell.getContents().toString()); } if (i == 3) { headers.add(cell.getContents()); } } data.add(d); } // fill the headers and data for (int i = 0; i < headers.size(); i++) { TableColumn column = new TableColumn(table, SWT.NONE, i); column.setText(headers.get(i).toString()); table.getColumn(i).pack(); } for (int i = 0; i < sheet.getRows(); i++) { TableItem item = new TableItem(table, SWT.NONE, i); for (int j = 0; j < sheet.getColumns(); j++) { Cell cell = sheet.getCell(j, i); item.setText(j, cell.getContents()); //item.addListener(eventType, listener); } } final TableEditor editor = new TableEditor(table); editor.horizontalAlignment = SWT.LEFT; editor.grabHorizontal = true; table.addListener(SWT.MouseDoubleClick, new Listener(){ @Override public void handleEvent(Event event) { // TODO Auto-generated method stub Rectangle clientArea = table.getClientArea(); Point pt = new Point(event.x, event.y); int index = table.getTopIndex(); while (index < table.getItemCount()) { boolean visible = false; final int row = index; final TableItem item = table.getItem(index); for (int i = 0; i < table.getColumnCount(); i++) { Rectangle rect = item.getBounds(i); if (rect.contains(pt)) { final int column = i; final Text text = new Text(table, SWT.NONE); Listener textListener = new Listener() { @Override public void handleEvent(Event evt) { // TODO Auto-generated method stub switch (evt.type) { case SWT.FocusOut: item.setText(column, text.getText()); XlsTable.this.setData(row, column, text.getText());; // Vector dd = (Vector) data.get(row); // dd.set(column, text.getText()); // data.set(row, dd); //System.out.println(column + " "+ row + " = " + dd.get(column)); text.dispose(); break; case SWT.Traverse: switch (evt.detail) { case SWT.TRAVERSE_RETURN: item.setText(column, text.getText()); // FALL THROUGH case SWT.TRAVERSE_ESCAPE: text.dispose(); evt.doit = false; } break; } } }; text.addListener(SWT.FocusOut, textListener); text.addListener(SWT.Traverse, textListener); editor.setEditor(text, item, i); text.setText(item.getText(i)); text.selectAll(); text.setFocus(); return; } if (!visible && rect.intersects(clientArea)) { visible = true; } } if (!visible) return; index++; } } }); } catch (BiffException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void exportContents(String outputPath){ try { DefaultTableModel model = new DefaultTableModel(data, headers); WritableWorkbook workbook = Workbook.createWorkbook(new File(outputPath)); WritableSheet sheet = workbook.createSheet("First Sheet", 0); for (int i=0; i < model.getRowCount(); i++) { for (int j=0; j < model.getColumnCount(); j++) { if (model.getValueAt(i, j) != null) { Label content = new Label(j, i, model.getValueAt(i, j).toString()); sheet.addCell(content); } } } // JTable table = new JTable(); // table.setModel(model); // table.setAutoCreateRowSorter(true); // model = new DefaultTableModel(data, headers); // table.setModel(model); // JScrollPane scroll = new JScrollPane(table); // JFrame f = new JFrame(); // f.getContentPane().add(scroll); // f.setSize(400, 200); // f.setResizable(true); // f.setVisible(true); workbook.write(); workbook.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RowsExceededException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (WriteException e) { // TODO Auto-generated catch block e.printStackTrace(); } }; }
update a row
src/Composites/XlsTable.java
update a row
<ide><path>rc/Composites/XlsTable.java <ide> return (Vector) this.data.get(row); <ide> } <ide> <add> public void setData(int row, Vector dd) { <add> this.data.set(row, dd); <add> } <ide> <ide> public void setData(int row, int col, String update) { <ide> //this.data = data;
JavaScript
mit
29e37eeefd097254cea34ea67338f44be5846970
0
dbaldon/toolkit-for-ynab,dbaldon/toolkit-for-ynab,boxfoot/toolkit-for-ynab,boxfoot/toolkit-for-ynab,Niictar/toolkit-for-ynab,Niictar/toolkit-for-ynab,mhum/ynab-enhanced,blargity/toolkit-for-ynab,dbaldon/toolkit-for-ynab,johde/toolkit-for-ynab,boxfoot/toolkit-for-ynab,mhum/ynab-enhanced,gpeden/ynab-enhanced,toolkit-for-ynab/toolkit-for-ynab,johde/toolkit-for-ynab,johde/toolkit-for-ynab,mhum/ynab-enhanced,dbaldon/toolkit-for-ynab,joshmadewell/toolkit-for-ynab,egens/toolkit-for-ynab,egens/toolkit-for-ynab,toolkit-for-ynab/toolkit-for-ynab,blargity/toolkit-for-ynab,toolkit-for-ynab/toolkit-for-ynab,egens/toolkit-for-ynab,toolkit-for-ynab/toolkit-for-ynab,falkencreative/toolkit-for-ynab,gpeden/ynab-enhanced,joshmadewell/toolkit-for-ynab,egens/toolkit-for-ynab,Niictar/toolkit-for-ynab,johde/toolkit-for-ynab,Niictar/toolkit-for-ynab,gpeden/ynab-enhanced,boxfoot/toolkit-for-ynab,ahatzz11/toolkit-for-ynab,ahatzz11/toolkit-for-ynab,falkencreative/toolkit-for-ynab,ahatzz11/toolkit-for-ynab,falkencreative/toolkit-for-ynab,falkencreative/toolkit-for-ynab,joshmadewell/toolkit-for-ynab,mhum/ynab-enhanced,blargity/toolkit-for-ynab,blargity/toolkit-for-ynab,joshmadewell/toolkit-for-ynab,ahatzz11/toolkit-for-ynab,gpeden/ynab-enhanced
function injectCollapseInitializer() { if (typeof Em !== 'undefined' && typeof Ember !== 'undefined') { (function($){ $.event.special.destroyed = { remove: function(o) { if (o.handler) { o.handler() } } } })(jQuery) // Wait for loading thingy to go away $(".init-loading").bind('destroyed', function() { // Check if the sidebar exists if ($(".nav-main").length){ setupBtns(); } else { setTimeout(watchSidebar, 250); } }); } else { setTimeout(injectCollapseInitializer, 250); } } setTimeout(injectCollapseInitializer, 250); // Watch for the budget grid function watchBudgetGrid() { exists = false; if ($(".budget-toolbar").length) { exists = true; } if (exists) { setCollapsedSizes(); setActiveButton(); } else { setTimeout(watchBudgetGrid, 250); } } // Watch for the account grid function watchAccountGrid() { exists = false; if ($(".accounts-toolbar").length) { exists = true; } if (exists) { setCollapsedSizes(); setActiveButton(); } else { setTimeout(watchAccountGrid, 250); } } // Watch that the button is still there function watchButton() { exists = false; if ($(".navlink-collapse").length) { exists = true; } if (!exists) { watchSidebar(); } else { setTimeout(watchButton, 1000); } } // Watch for the sidebar on screens where it doesn't exist function watchSidebar() { exists = false; if ($(".nav-main").length) { exists = true; } if (exists) { setupBtns(); } else { setTimeout(watchSidebar, 250); } } // Add buttons and handlers to screen function setupBtns() { var collapseBtn = '<li> \ <li class="ember-view navlink-collapse"> \ <a href="#"> \ <span class="ember-view flaticon stroke left-circle-4"></span>Collapse \ </a> \ </li> \ </li>' var budgetAction = $('.nav-main').find(".mail-1").closest("a").data('ember-action'); var accountAction = $('.nav-main').find(".government-1").closest("a").data('ember-action'); var expandBtns = '\ <div class=collapsed-buttons> \ <a href="#" data-ember-action="'+budgetAction+'" onClick="watchBudgetGrid()"> \ <button class="button button-prefs flaticon stroke mail-1 collapsed-budget"></button> \ </a> \ <a href="#" data-ember-action="'+accountAction+'" onClick="watchAccountGrid()"> \ <button class="button button-prefs flaticon stroke government-1 collapsed-account"></button> \ </a> \ <button class="button button-prefs flaticon stroke right-circle-4 navbar-expand"></button> \ <div>'; var originalSizes = { sidebarWidth: $(".sidebar").width(), contentLeft: $(".content").css("left"), headerLeft: $(".budget-header").css("left"), contentWidth: $(".budget-content").css("width"), inspectorWidth: $(".budget-inspector").css("width") } if (!$(".collapsed-buttons").length) { $(".sidebar").prepend(expandBtns); } else { $(".collapsed-buttons").remove(); $(".sidebar").prepend(expandBtns); } $(".nav-main").append(collapseBtn); $(".collapsed-buttons").hide(); $(".navlink-collapse").on("click", collapseMenu); $(".navbar-expand").on("click", function() { expandMenu(originalSizes) }); // Monitor our button and set up watcher in case we change screens watchButton(); } // Handle clicking expand button. Puts things back to original sizes function expandMenu(originalSizes) { $(".sidebar > .ember-view").show(); $(".sidebar").width(originalSizes.sidebarWidth); $(".content").css("left", originalSizes.contentLeft); $(".budget-header").css("left", originalSizes.headerLeft); $(".budget-content").css("width", originalSizes.contentWidth); $(".budget-inspector").css("width", originalSizes.inspectorWidth); $(".collapsed-buttons").hide(); } // Handle clicking the collapse button function collapseMenu() { setActiveButton(); $(".sidebar > .ember-view").hide(); $(".collapsed-buttons").show(); setCollapsedSizes(); } // Set collapsed sizes function setCollapsedSizes() { $(".sidebar").width("40px"); $(".content").css("left", "40px"); $(".budget-header").css("left", "40px"); $(".budget-content").css("width", "73%"); $(".budget-inspector").css("width", "27%"); $(".ynab-grid-header").removeAttr("style"); } // Add the active style to correct button function setActiveButton() { deactivateCollapsedActive(); if ($(".accounts-toolbar").length) { $(".collapsed-account").addClass('collapsed-active'); } if ($(".budget-toolbar").length) { $(".collapsed-budget").addClass('collapsed-active'); } } // Deactivate collapsed buttons function deactivateCollapsedActive() { $(".collapsed-account").removeClass('collapsed-active'); $(".collapsed-budget").removeClass('collapsed-active'); }
src/features/collapse-side-menu/main.js
function injectInitializer() { if (typeof Em !== 'undefined' && typeof Ember !== 'undefined') { (function($){ $.event.special.destroyed = { remove: function(o) { if (o.handler) { o.handler() } } } })(jQuery) // Wait for loading thingy to go away $(".init-loading").bind('destroyed', function() { // Check if the sidebar exists if ($(".nav-main").length){ setupBtns(); } else { setTimeout(watchSidebar, 250); } }); } else { setTimeout(injectInitializer, 250); } } setTimeout(injectInitializer, 250); // Watch for the budget grid function watchBudgetGrid() { exists = false; if ($(".budget-toolbar").length) { exists = true; } if (exists) { setCollapsedSizes(); setActiveButton(); } else { setTimeout(watchBudgetGrid, 250); } } // Watch for the account grid function watchAccountGrid() { exists = false; if ($(".accounts-toolbar").length) { exists = true; } if (exists) { setCollapsedSizes(); setActiveButton(); } else { setTimeout(watchAccountGrid, 250); } } // Watch that the button is still there function watchButton() { exists = false; if ($(".navlink-collapse").length) { exists = true; } if (!exists) { watchSidebar(); } else { setTimeout(watchButton, 1000); } } // Watch for the sidebar on screens where it doesn't exist function watchSidebar() { exists = false; if ($(".nav-main").length) { exists = true; } if (exists) { setupBtns(); } else { setTimeout(watchSidebar, 250); } } // Add buttons and handlers to screen function setupBtns() { var collapseBtn = '<li> \ <li class="ember-view navlink-collapse"> \ <a href="#"> \ <span class="ember-view flaticon stroke left-circle-4"></span>Collapse \ </a> \ </li> \ </li>' var budgetAction = $('.nav-main').find(".mail-1").closest("a").data('ember-action'); var accountAction = $('.nav-main').find(".government-1").closest("a").data('ember-action'); var expandBtns = '\ <div class=collapsed-buttons> \ <a href="#" data-ember-action="'+budgetAction+'" onClick="watchBudgetGrid()"> \ <button class="button button-prefs flaticon stroke mail-1 collapsed-budget"></button> \ </a> \ <a href="#" data-ember-action="'+accountAction+'" onClick="watchAccountGrid()"> \ <button class="button button-prefs flaticon stroke government-1 collapsed-account"></button> \ </a> \ <button class="button button-prefs flaticon stroke right-circle-4 navbar-expand"></button> \ <div>'; var originalSizes = { sidebarWidth: $(".sidebar").width(), contentLeft: $(".content").css("left"), headerLeft: $(".budget-header").css("left"), contentWidth: $(".budget-content").css("width"), inspectorWidth: $(".budget-inspector").css("width") } if (!$(".collapsed-buttons").length) { $(".sidebar").prepend(expandBtns); } else { $(".collapsed-buttons").remove(); $(".sidebar").prepend(expandBtns); } $(".nav-main").append(collapseBtn); $(".collapsed-buttons").hide(); $(".navlink-collapse").on("click", collapseMenu); $(".navbar-expand").on("click", function() { expandMenu(originalSizes) }); // Monitor our button and set up watcher in case we change screens watchButton(); } // Handle clicking expand button. Puts things back to original sizes function expandMenu(originalSizes) { $(".sidebar > .ember-view").show(); $(".sidebar").width(originalSizes.sidebarWidth); $(".content").css("left", originalSizes.contentLeft); $(".budget-header").css("left", originalSizes.headerLeft); $(".budget-content").css("width", originalSizes.contentWidth); $(".budget-inspector").css("width", originalSizes.inspectorWidth); $(".collapsed-buttons").hide(); } // Handle clicking the collapse button function collapseMenu() { setActiveButton(); $(".sidebar > .ember-view").hide(); $(".collapsed-buttons").show(); setCollapsedSizes(); } // Set collapsed sizes function setCollapsedSizes() { $(".sidebar").width("40px"); $(".content").css("left", "40px"); $(".budget-header").css("left", "40px"); $(".budget-content").css("width", "73%"); $(".budget-inspector").css("width", "27%"); $(".ynab-grid-header").removeAttr("style"); } // Add the active style to correct button function setActiveButton() { deactivateCollapsedActive(); if ($(".accounts-toolbar").length) { $(".collapsed-account").addClass('collapsed-active'); } if ($(".budget-toolbar").length) { $(".collapsed-budget").addClass('collapsed-active'); } } // Deactivate collapsed buttons function deactivateCollapsedActive() { $(".collapsed-account").removeClass('collapsed-active'); $(".collapsed-budget").removeClass('collapsed-active'); }
Change function name to avoid conflict
src/features/collapse-side-menu/main.js
Change function name to avoid conflict
<ide><path>rc/features/collapse-side-menu/main.js <del>function injectInitializer() { <add>function injectCollapseInitializer() { <ide> if (typeof Em !== 'undefined' && typeof Ember !== 'undefined') { <ide> (function($){ <ide> $.event.special.destroyed = { <ide> } <ide> }); <ide> } else { <del> setTimeout(injectInitializer, 250); <add> setTimeout(injectCollapseInitializer, 250); <ide> } <ide> } <ide> <del>setTimeout(injectInitializer, 250); <add>setTimeout(injectCollapseInitializer, 250); <ide> <ide> // Watch for the budget grid <ide> function watchBudgetGrid() {
JavaScript
bsd-2-clause
f28eacffc3c7092c337e0622196ea1df1cda84c5
0
macbre/phantomas,macbre/phantomas,macbre/phantomas
/** * phantomas CommonJS module */ "use strict"; const Browser = require("./browser"), EventEmitter = require("./AwaitEventEmitter"), debug = require("debug")("phantomas:core"), loader = require("./loader"), puppeteer = require("puppeteer"), path = require("path"), Results = require("../core/results"), VERSION = require("./../package").version; /** * Main CommonJS module entry point * * @param {string} url * @param {Object} opts * @returns {browser} */ function phantomas(url, opts) { var events = new EventEmitter(), browser, options; debug("OS: %s %s", process.platform, process.arch); debug("Node.js: %s", process.version); debug("phantomas: %s", VERSION); debug( "Puppeteer: preferred revision r%s", puppeteer._launcher._preferredRevision ); debug("URL: <%s>", url); // options handling options = Object.assign({}, opts || {}); // avoid #563 options.url = options.url || url || false; debug("Options: %s", JSON.stringify(options)); events.setMaxListeners(100); // MaxListenersExceededWarning: Possible EventEmitter memory leak detected. var results = new Results(); results.setUrl(url); results.setGenerator("phantomas v" + VERSION); // set up and run Puppeteer browser = new Browser(); browser.bind(events); var promise = new Promise(async (resolve, reject) => { try { if (typeof options.url !== "string") { return reject(Error("URL must be a string")); } const page = await browser.init(options), debugScope = require("debug")("phantomas:scope:log"); // prepare a small instance object that will be passed to modules and extensions on init const scope = { getParam: (param, _default) => { return options[param] || _default; }, getVersion: () => VERSION, emit: events.emit.bind(events), on: events.on.bind(events), once: events.once.bind(events), log: debugScope.bind(debug), addOffender: results.addOffender.bind(results), incrMetric: results.incrMetric.bind(results), setMetric: results.setMetric, addToAvgMetric: results.addToAvgMetric, getMetric: results.getMetric, // @see https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#pageevaluatepagefunction-args evaluate: page.evaluate.bind(page), // @see https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#pageselector-1 /* istanbul ignore next */ querySelectorAll: async (selector) => { debug('querySelectorAll("%s")', selector); return page.$$(selector); }, // @see https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#pageevaluateonnewdocumentpagefunction-args injectJs: async (script) => { const debug = require("debug")("phantomas:injectJs"); // Make sure we're on an HTML document, not an XML document for example const prefix = "if (document.constructor.name === 'HTMLDocument') {", suffix = "}"; const preloadFile = prefix + require("fs").readFileSync(script, "utf8") + suffix; await page.evaluateOnNewDocument(preloadFile); debug(script + " JavaScript file has been injected into page scope"); }, }; // pass phantomas options to page scope // https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#pageevaluateonnewdocumentpagefunction-args /* istanbul ignore next */ await page.evaluateOnNewDocument((options) => { window.__phantomas_options = options; }, options); // expose the function that will pass events from page scope code into Node.js layer // @see https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#pageexposefunctionname-puppeteerfunction await page.exposeFunction("__phantomas_emit", scope.emit); // Inject helper code into the browser's scope events.on("init", () => { scope.injectJs(__dirname + "/../core/scope.js"); }); // bind to sendMsg calls from page scope code events.on("scopeMessage", (type, args) => { const debug = require("debug")("phantomas:core:scopeEvents"); // debug(type + ' [' + args + ']'); switch (type) { case "addOffender": case "incrMetric": case "log": case "setMetric": scope[type].apply(scope, args); break; /* istanbul ignore next */ default: debug("Unrecognized event type: " + type); } }); // bind to a first response // and reject a promise if the first response is 4xx / 5xx HTTP error var firstResponseReceived = false; events.once("recv", async (entry) => { if (!firstResponseReceived && entry.status >= 400) { debug( "<%s> response code is HTTP %d %s", entry.url, entry.status, entry.statusText ); // close the browser before leaving here, otherwise subsequent instances will have problems await browser.close(); reject( new Error( "HTTP response code from <" + entry.url + "> is " + entry.status ) ); } firstResponseReceived = true; }); // load modules and extensions debug("Loading core modules..."); loader.loadCoreModules(scope); debug("Loading extensions..."); loader.loadExtensions(scope); debug("Loading modules..."); loader.loadModules(scope); await events.emit("init", page, browser.getPuppeteerBrowser()); // @desc Browser's scope and modules are set up, the page is about to be loaded // https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#pagegotourl-options const waitUntil = options["wait-for-network-idle"] ? "networkidle0" : undefined, timeout = options.timeout; await browser.visit(url, waitUntil, timeout); // resolve our run // https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#browserclose await events.emit("beforeClose", page); // @desc Called before the Chromium (and all of its pages) is closed await browser.close(); // your last chance to add metrics await events.emit("report"); // @desc Called just before the phantomas results are returned to the caller resolve(results); } catch (ex) { debug("Exception caught: " + ex); debug(ex); // close the browser before leaving here, otherwise subsequent instances will have problems await browser.close(); reject(ex); } }); promise.on = events.on.bind(events); promise.once = events.once.bind(events); return promise; } phantomas.metadata = require(__dirname + "/metadata/metadata.json"); phantomas.path = path.normalize(__dirname + "/.."); phantomas.version = VERSION; module.exports = phantomas;
lib/index.js
/** * phantomas CommonJS module */ "use strict"; const Browser = require("./browser"), EventEmitter = require("./AwaitEventEmitter"), debug = require("debug")("phantomas:core"), loader = require("./loader"), puppeteer = require("puppeteer"), path = require("path"), Results = require("../core/results"), VERSION = require("./../package").version; /** * Main CommonJS module entry point * * @param {string} url * @param {Object} opts * @returns {browser} */ function phantomas(url, opts) { var events = new EventEmitter(), browser, options; debug("OS: %s %s", process.platform, process.arch); debug("Node.js: %s", process.version); debug("phantomas: %s", VERSION); debug( "Puppeteer: preferred revision r%s", puppeteer._launcher._preferredRevision ); debug("URL: <%s>", url); // options handling options = Object.assign({}, opts || {}); // avoid #563 options.url = options.url || url || false; debug("Options: %s", JSON.stringify(options)); events.setMaxListeners(100); // MaxListenersExceededWarning: Possible EventEmitter memory leak detected. var results = new Results(); results.setUrl(url); results.setGenerator("phantomas v" + VERSION); // set up and run Puppeteer browser = new Browser(); browser.bind(events); var promise = new Promise(async (resolve, reject) => { try { if (typeof options.url !== "string") { return reject(Error("URL must be a string")); } const page = await browser.init(options), debugScope = require("debug")("phantomas:scope:log"); // prepare a small instance object that will be passed to modules and extensions on init const scope = { getParam: (param, _default) => { return options[param] || _default; }, getVersion: () => VERSION, emit: events.emit.bind(events), on: events.on.bind(events), once: events.once.bind(events), log: debugScope.bind(debug), addOffender: results.addOffender.bind(results), incrMetric: results.incrMetric.bind(results), setMetric: results.setMetric, addToAvgMetric: results.addToAvgMetric, getMetric: results.getMetric, // @see https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#pageevaluatepagefunction-args evaluate: page.evaluate.bind(page), // @see https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#pageselector-1 querySelectorAll: async (selector) => { debug('querySelectorAll("%s")', selector); return page.$$(selector); }, // @see https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#pageevaluateonnewdocumentpagefunction-args injectJs: async (script) => { const debug = require("debug")("phantomas:injectJs"); // Make sure we're on an HTML document, not an XML document for example const prefix = "if (document.constructor.name === 'HTMLDocument') {", suffix = "}"; const preloadFile = prefix + require("fs").readFileSync(script, "utf8") + suffix; await page.evaluateOnNewDocument(preloadFile); debug(script + " JavaScript file has been injected into page scope"); }, }; // pass phantomas options to page scope // https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#pageevaluateonnewdocumentpagefunction-args /* istanbul ignore next */ await page.evaluateOnNewDocument((options) => { window.__phantomas_options = options; }, options); // expose the function that will pass events from page scope code into Node.js layer // @see https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#pageexposefunctionname-puppeteerfunction await page.exposeFunction("__phantomas_emit", scope.emit); // Inject helper code into the browser's scope events.on("init", () => { scope.injectJs(__dirname + "/../core/scope.js"); }); // bind to sendMsg calls from page scope code events.on("scopeMessage", (type, args) => { const debug = require("debug")("phantomas:core:scopeEvents"); // debug(type + ' [' + args + ']'); switch (type) { case "addOffender": case "incrMetric": case "log": case "setMetric": scope[type].apply(scope, args); break; default: debug("Unrecognized event type: " + type); } }); // bind to a first response // and reject a promise if the first response is 4xx / 5xx HTTP error var firstResponseReceived = false; events.once("recv", async (entry) => { if (!firstResponseReceived && entry.status >= 400) { debug( "<%s> response code is HTTP %d %s", entry.url, entry.status, entry.statusText ); // close the browser before leaving here, otherwise subsequent instances will have problems await browser.close(); reject( new Error( "HTTP response code from <" + entry.url + "> is " + entry.status ) ); } firstResponseReceived = true; }); // load modules and extensions debug("Loading core modules..."); loader.loadCoreModules(scope); debug("Loading extensions..."); loader.loadExtensions(scope); debug("Loading modules..."); loader.loadModules(scope); await events.emit("init", page, browser.getPuppeteerBrowser()); // @desc Browser's scope and modules are set up, the page is about to be loaded // https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#pagegotourl-options const waitUntil = options["wait-for-network-idle"] ? "networkidle0" : undefined, timeout = options.timeout; await browser.visit(url, waitUntil, timeout); // resolve our run // https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#browserclose await events.emit("beforeClose", page); // @desc Called before the Chromium (and all of its pages) is closed await browser.close(); // your last chance to add metrics await events.emit("report"); // @desc Called just before the phantomas results are returned to the caller resolve(results); } catch (ex) { debug("Exception caught: " + ex); debug(ex); // close the browser before leaving here, otherwise subsequent instances will have problems await browser.close(); reject(ex); } }); promise.on = events.on.bind(events); promise.once = events.once.bind(events); return promise; } phantomas.metadata = require(__dirname + "/metadata/metadata.json"); phantomas.path = path.normalize(__dirname + "/.."); phantomas.version = VERSION; module.exports = phantomas;
lib/index.js: skip coverage for two code branches
lib/index.js
lib/index.js: skip coverage for two code branches
<ide><path>ib/index.js <ide> evaluate: page.evaluate.bind(page), <ide> <ide> // @see https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#pageselector-1 <add> /* istanbul ignore next */ <ide> querySelectorAll: async (selector) => { <ide> debug('querySelectorAll("%s")', selector); <ide> return page.$$(selector); <ide> scope[type].apply(scope, args); <ide> break; <ide> <add> /* istanbul ignore next */ <ide> default: <ide> debug("Unrecognized event type: " + type); <ide> }
Java
apache-2.0
29b2d19e511c8a264d6688eaedd6fbb57c99506e
0
pinotlytics/pinot,linkedin/pinot,fx19880617/pinot-1,Hanmourang/Pinot,izzizz/pinot,fx19880617/pinot-1,Hanmourang/Pinot,linkedin/pinot,fx19880617/pinot-1,pinotlytics/pinot,izzizz/pinot,Hanmourang/Pinot,sajavadi/pinot,apucher/pinot,slietz/pinot,apucher/pinot,izzizz/pinot,tkao1000/pinot,apucher/pinot,fx19880617/pinot-1,pinotlytics/pinot,slietz/pinot,tkao1000/pinot,slietz/pinot,tkao1000/pinot,Hanmourang/Pinot,Hanmourang/Pinot,apucher/pinot,tkao1000/pinot,izzizz/pinot,tkao1000/pinot,izzizz/pinot,apucher/pinot,pinotlytics/pinot,Hanmourang/Pinot,slietz/pinot,slietz/pinot,linkedin/pinot,slietz/pinot,pinotlytics/pinot,pinotlytics/pinot,linkedin/pinot,izzizz/pinot,fx19880617/pinot-1,sajavadi/pinot,sajavadi/pinot,linkedin/pinot,sajavadi/pinot,sajavadi/pinot
/** * Copyright (C) 2014-2015 LinkedIn Corp. ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.linkedin.pinot.common.utils; import java.io.File; import java.lang.reflect.Method; import java.nio.ByteBuffer; import java.util.Collections; import java.util.Map; import java.util.WeakHashMap; import java.util.concurrent.atomic.AtomicLong; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Utilities to deal with memory mapped buffers, which may not be portable. * */ public class MmapUtils { private static final Logger LOGGER = LoggerFactory.getLogger(MmapUtils.class); private static final AtomicLong DIRECT_BYTE_BUFFER_USAGE = new AtomicLong(0L); private static final long BYTES_IN_MEGABYTE = 1024L * 1024L; private static final Map<ByteBuffer, String> BUFFER_TO_CONTEXT_MAP = Collections.synchronizedMap(new WeakHashMap<>()); /** * Unloads a byte buffer from memory * @param buffer The buffer to unload */ public static void unloadByteBuffer(ByteBuffer buffer) { if (null == buffer) return; // Non direct byte buffers do not require any special handling, since they're on heap if (!buffer.isDirect()) return; // Remove usage from direct byte buffer usage final int bufferSize = buffer.capacity(); DIRECT_BYTE_BUFFER_USAGE.addAndGet(-bufferSize); LOGGER.info("Releasing byte buffer of size {} with context {}, currently allocated {} MB", bufferSize, BUFFER_TO_CONTEXT_MAP.get(buffer), DIRECT_BYTE_BUFFER_USAGE.get() / BYTES_IN_MEGABYTE); // A DirectByteBuffer can be cleaned up by doing buffer.cleaner().clean(), but this is not a public API. This is // probably not portable between JVMs. try { Method cleanerMethod = buffer.getClass().getMethod("cleaner"); Method cleanMethod = Class.forName("sun.misc.Cleaner").getMethod("clean"); cleanerMethod.setAccessible(true); cleanMethod.setAccessible(true); // buffer.cleaner().clean() Object cleaner = cleanerMethod.invoke(buffer); if (cleaner != null) { cleanMethod.invoke(cleaner); } } catch (Exception e) { LOGGER.warn("Caught (ignored) exception while unloading byte buffer", e); } } /** * Allocates a direct byte buffer, tracking usage information. * * @param capacity The capacity to allocate. * @param allocationContext The file that this byte buffer refers to * @param details Further details about the allocation * @return A new allocated byte buffer with the requested capacity */ public static ByteBuffer allocateDirectByteBuffer(int capacity, File allocationContext, String details) { String context; if (allocationContext != null) { context = allocationContext.getAbsolutePath() + " (" + details + ")"; } else { context = "no file (" + details + ")"; } DIRECT_BYTE_BUFFER_USAGE.addAndGet(capacity); LOGGER.info("Allocating byte buffer of size {} with context {}, currently allocated {} MB", capacity, context, DIRECT_BYTE_BUFFER_USAGE.get() / BYTES_IN_MEGABYTE); final ByteBuffer byteBuffer = ByteBuffer.allocateDirect(capacity); BUFFER_TO_CONTEXT_MAP.put(byteBuffer, context); return byteBuffer; } }
pinot-common/src/main/java/com/linkedin/pinot/common/utils/MmapUtils.java
/** * Copyright (C) 2014-2015 LinkedIn Corp. ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.linkedin.pinot.common.utils; import java.io.File; import java.lang.reflect.Method; import java.nio.ByteBuffer; import java.util.WeakHashMap; import java.util.concurrent.atomic.AtomicLong; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Utilities to deal with memory mapped buffers, which may not be portable. * */ public class MmapUtils { private static final Logger LOGGER = LoggerFactory.getLogger(MmapUtils.class); private static final AtomicLong DIRECT_BYTE_BUFFER_USAGE = new AtomicLong(0L); private static final long BYTES_IN_MEGABYTE = 1024L * 1024L; private static final WeakHashMap<ByteBuffer, String> BUFFER_TO_CONTEXT_MAP = new WeakHashMap<>(); /** * Unloads a byte buffer from memory * @param buffer The buffer to unload */ public static void unloadByteBuffer(ByteBuffer buffer) { if (null == buffer) return; // Non direct byte buffers do not require any special handling, since they're on heap if (!buffer.isDirect()) return; // Remove usage from direct byte buffer usage final int bufferSize = buffer.capacity(); DIRECT_BYTE_BUFFER_USAGE.addAndGet(-bufferSize); LOGGER.info("Releasing byte buffer of size {} with context {}, currently allocated {} MB", bufferSize, BUFFER_TO_CONTEXT_MAP.get(buffer), DIRECT_BYTE_BUFFER_USAGE.get() / BYTES_IN_MEGABYTE); // A DirectByteBuffer can be cleaned up by doing buffer.cleaner().clean(), but this is not a public API. This is // probably not portable between JVMs. try { Method cleanerMethod = buffer.getClass().getMethod("cleaner"); Method cleanMethod = Class.forName("sun.misc.Cleaner").getMethod("clean"); cleanerMethod.setAccessible(true); cleanMethod.setAccessible(true); // buffer.cleaner().clean() Object cleaner = cleanerMethod.invoke(buffer); if (cleaner != null) { cleanMethod.invoke(cleaner); } } catch (Exception e) { LOGGER.warn("Caught (ignored) exception while unloading byte buffer", e); } } /** * Allocates a direct byte buffer, tracking usage information. * * @param capacity The capacity to allocate. * @param allocationContext The file that this byte buffer refers to * @param details Further details about the allocation * @return A new allocated byte buffer with the requested capacity */ public static ByteBuffer allocateDirectByteBuffer(int capacity, File allocationContext, String details) { String context; if (allocationContext != null) { context = allocationContext.getAbsolutePath() + " (" + details + ")"; } else { context = "no file (" + details + ")"; } DIRECT_BYTE_BUFFER_USAGE.addAndGet(capacity); LOGGER.info("Allocating byte buffer of size {} with context {}, currently allocated {} MB", capacity, context, DIRECT_BYTE_BUFFER_USAGE.get() / BYTES_IN_MEGABYTE); final ByteBuffer byteBuffer = ByteBuffer.allocateDirect(capacity); BUFFER_TO_CONTEXT_MAP.put(byteBuffer, context); return byteBuffer; } }
[PINOT 2094] Fix MmapUtils to use thread-safe map Fixed MmapUtils to use Collections.synchronizedMap instead of the thread-unsafe version. All integration tests pass reliably on the local machine now. RB=575684 G=pinot-dev-reviewers R=kgopalak,jfim,ssubrama,dpatel,mshrivas A=kgopalak
pinot-common/src/main/java/com/linkedin/pinot/common/utils/MmapUtils.java
[PINOT 2094] Fix MmapUtils to use thread-safe map
<ide><path>inot-common/src/main/java/com/linkedin/pinot/common/utils/MmapUtils.java <ide> import java.io.File; <ide> import java.lang.reflect.Method; <ide> import java.nio.ByteBuffer; <add>import java.util.Collections; <add>import java.util.Map; <ide> import java.util.WeakHashMap; <ide> import java.util.concurrent.atomic.AtomicLong; <ide> import org.slf4j.Logger; <ide> private static final Logger LOGGER = LoggerFactory.getLogger(MmapUtils.class); <ide> private static final AtomicLong DIRECT_BYTE_BUFFER_USAGE = new AtomicLong(0L); <ide> private static final long BYTES_IN_MEGABYTE = 1024L * 1024L; <del> private static final WeakHashMap<ByteBuffer, String> BUFFER_TO_CONTEXT_MAP = new WeakHashMap<>(); <add> private static final Map<ByteBuffer, String> BUFFER_TO_CONTEXT_MAP = Collections.synchronizedMap(new WeakHashMap<>()); <ide> <ide> /** <ide> * Unloads a byte buffer from memory
Java
apache-2.0
0f191731a2aeccb5baf7f19b743e71e4cb3c7413
0
protyposis/Spectaculum,protyposis/Spectaculum
/* * Copyright (c) 2014 Mario Guggenberger <[email protected]> * * This file is part of MediaPlayer-Extended. * * MediaPlayer-Extended is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MediaPlayer-Extended is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MediaPlayer-Extended. If not, see <http://www.gnu.org/licenses/>. */ package net.protyposis.android.spectaculumdemo; import android.app.Activity; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.SeekBar; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import net.protyposis.android.spectaculum.SpectaculumView; import net.protyposis.android.spectaculum.effects.EnumParameter; import net.protyposis.android.spectaculum.effects.FloatParameter; import net.protyposis.android.spectaculum.effects.IntegerParameter; import net.protyposis.android.spectaculum.effects.Parameter; /** * Created by Mario on 06.09.2014. */ public class ParameterListAdapter extends BaseAdapter { private Activity mActivity; private SpectaculumView mTextureView; public List<Parameter> mParameters; public ParameterListAdapter(Activity activity, SpectaculumView textureView, List<Parameter> parameters) { mActivity = activity; mTextureView = textureView; mParameters = new ArrayList<Parameter>(parameters); } @Override public int getCount() { return mParameters.size(); } @Override public Parameter getItem(int position) { return mParameters.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { final Parameter parameter = getItem(position); View view = convertView; if(convertView == null || convertView.getTag() != parameter.getType()) { if(parameter.getType() == Parameter.Type.ENUM) { view = mActivity.getLayoutInflater().inflate(R.layout.list_item_parameter_spinner, parent, false); } else { view = mActivity.getLayoutInflater().inflate(R.layout.list_item_parameter_seekbar, parent, false); } view.setTag(parameter.getType()); } ((TextView) view.findViewById(R.id.name)).setText(parameter.getName()); final SeekBar seekBar = (SeekBar) view.findViewById(R.id.seekBar); final Spinner spinner = (Spinner) view.findViewById(R.id.spinner); final TextView valueView = (TextView) view.findViewById(R.id.value); final Button resetButton = (Button) view.findViewById(R.id.reset); if (parameter.getType() == Parameter.Type.INTEGER) { final IntegerParameter p = (IntegerParameter) parameter; int interval = p.getMax() - p.getMin(); seekBar.setMax(interval); seekBar.setProgress(p.getValue() - p.getMin()); SeekBar.OnSeekBarChangeListener changeListener = new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { final int value = progress + p.getMin(); mTextureView.queueEvent(new Runnable() { @Override public void run() { p.setValue(value); } }); valueView.setText(String.format("%d", value)); } @Override public void onStartTrackingTouch(SeekBar seekBar) { if(p.getDescription() != null) { Toast.makeText(mActivity, p.getDescription(), Toast.LENGTH_SHORT).show(); } } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }; seekBar.setOnSeekBarChangeListener(changeListener); changeListener.onProgressChanged(seekBar, seekBar.getProgress(), false); // init value label resetButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { seekBar.setProgress(p.getDefault() - p.getMin()); } }); } else if (parameter.getType() == Parameter.Type.FLOAT) { final int precision = 100; // 2 digits after comma final FloatParameter p = (FloatParameter) parameter; float interval = p.getMax() - p.getMin(); seekBar.setMax((int) (interval * precision)); seekBar.setProgress((int) ((p.getValue() - p.getMin()) * precision)); SeekBar.OnSeekBarChangeListener changeListener = new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, final int progress, boolean fromUser) { final float value = (progress / (float) precision) + p.getMin(); mTextureView.queueEvent(new Runnable() { @Override public void run() { p.setValue(value); } }); valueView.setText(String.format("%.2f", value)); } @Override public void onStartTrackingTouch(SeekBar seekBar) { if(p.getDescription() != null) { Toast.makeText(mActivity, p.getDescription(), Toast.LENGTH_SHORT).show(); } } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }; seekBar.setOnSeekBarChangeListener(changeListener); changeListener.onProgressChanged(seekBar, seekBar.getProgress(), false); // init value label resetButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { seekBar.setProgress((int) ((p.getDefault() - p.getMin()) * precision)); } }); } else if (parameter.getType() == Parameter.Type.ENUM) { final EnumParameter p = (EnumParameter) parameter; final ArrayAdapter<Enum> adapter = new ArrayAdapter<>(mActivity, android.R.layout.simple_spinner_item, p.getEnumValues()); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); spinner.setSelection(adapter.getPosition(p.getValue())); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, final int position, long id) { Toast.makeText(mActivity, p.getDescription(), Toast.LENGTH_SHORT).show(); mTextureView.queueEvent(new Runnable() { @Override public void run() { p.setValue(p.getEnumValues()[position]); } }); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); resetButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { spinner.setSelection(adapter.getPosition(p.getDefault())); } }); } return view; } public void clear() { mParameters.clear(); notifyDataSetChanged(); } }
Spectaculum-Demo/src/main/java/net/protyposis/android/spectaculumdemo/ParameterListAdapter.java
/* * Copyright (c) 2014 Mario Guggenberger <[email protected]> * * This file is part of MediaPlayer-Extended. * * MediaPlayer-Extended is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MediaPlayer-Extended is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MediaPlayer-Extended. If not, see <http://www.gnu.org/licenses/>. */ package net.protyposis.android.spectaculumdemo; import android.app.Activity; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.SeekBar; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import net.protyposis.android.spectaculum.SpectaculumView; import net.protyposis.android.spectaculum.effects.EnumParameter; import net.protyposis.android.spectaculum.effects.FloatParameter; import net.protyposis.android.spectaculum.effects.IntegerParameter; import net.protyposis.android.spectaculum.effects.Parameter; /** * Created by Mario on 06.09.2014. */ public class ParameterListAdapter extends BaseAdapter { private Activity mActivity; private SpectaculumView mTextureView; public List<Parameter> mParameters; public ParameterListAdapter(Activity activity, SpectaculumView textureView, List<Parameter> parameters) { mActivity = activity; mTextureView = textureView; mParameters = new ArrayList<Parameter>(parameters); } @Override public int getCount() { return mParameters.size(); } @Override public Parameter getItem(int position) { return mParameters.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { final Parameter parameter = getItem(position); View view = convertView; if(convertView == null || convertView.getTag() != parameter.getType()) { if(parameter.getType() == Parameter.Type.ENUM) { view = mActivity.getLayoutInflater().inflate(R.layout.list_item_parameter_spinner, parent, false); } else { view = mActivity.getLayoutInflater().inflate(R.layout.list_item_parameter_seekbar, parent, false); } view.setTag(parameter.getType()); } ((TextView) view.findViewById(R.id.name)).setText(parameter.getName()); final SeekBar seekBar = (SeekBar) view.findViewById(R.id.seekBar); final Spinner spinner = (Spinner) view.findViewById(R.id.spinner); final TextView valueView = (TextView) view.findViewById(R.id.value); final Button resetButton = (Button) view.findViewById(R.id.reset); if (parameter.getType() == Parameter.Type.INTEGER) { final IntegerParameter p = (IntegerParameter) parameter; int interval = p.getMax() - p.getMin(); seekBar.setMax(interval); seekBar.setProgress(p.getValue() - p.getMin()); SeekBar.OnSeekBarChangeListener changeListener = new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { final int value = progress + p.getMin(); mTextureView.queueEvent(new Runnable() { @Override public void run() { p.setValue(value); } }); valueView.setText(String.format("%d", value)); } @Override public void onStartTrackingTouch(SeekBar seekBar) { if(p.getDescription() != null) { Toast.makeText(mActivity, p.getDescription(), Toast.LENGTH_SHORT).show(); } } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }; seekBar.setOnSeekBarChangeListener(changeListener); changeListener.onProgressChanged(seekBar, seekBar.getProgress(), false); // init value label resetButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { seekBar.setProgress(p.getDefault() - p.getMin()); } }); } else if (parameter.getType() == Parameter.Type.FLOAT) { final int precision = 100; // 2 digits after comma final FloatParameter p = (FloatParameter) parameter; float interval = p.getMax() - p.getMin(); seekBar.setMax((int) (interval * precision)); seekBar.setProgress((int) ((p.getValue() - p.getMin()) * precision)); SeekBar.OnSeekBarChangeListener changeListener = new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, final int progress, boolean fromUser) { final float value = (progress / (float) precision) + p.getMin(); mTextureView.queueEvent(new Runnable() { @Override public void run() { p.setValue(value); } }); valueView.setText(String.format("%.2f", value)); } @Override public void onStartTrackingTouch(SeekBar seekBar) { if(p.getDescription() != null) { Toast.makeText(mActivity, p.getDescription(), Toast.LENGTH_SHORT).show(); } } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }; seekBar.setOnSeekBarChangeListener(changeListener); changeListener.onProgressChanged(seekBar, seekBar.getProgress(), false); // init value label resetButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { seekBar.setProgress((int) ((p.getDefault() - p.getMin()) * precision)); } }); } else if (parameter.getType() == Parameter.Type.ENUM) { final EnumParameter p = (EnumParameter) parameter; final ArrayAdapter<Enum> adapter = new ArrayAdapter<>(mActivity, android.R.layout.simple_spinner_item, p.getEnumValues()); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, final int position, long id) { Toast.makeText(mActivity, p.getDescription(), Toast.LENGTH_SHORT).show(); mTextureView.queueEvent(new Runnable() { @Override public void run() { p.setValue(p.getEnumValues()[position]); } }); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); resetButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { spinner.setSelection(adapter.getPosition(p.getDefault())); } }); } return view; } public void clear() { mParameters.clear(); notifyDataSetChanged(); } }
Init spinner with current value
Spectaculum-Demo/src/main/java/net/protyposis/android/spectaculumdemo/ParameterListAdapter.java
Init spinner with current value
<ide><path>pectaculum-Demo/src/main/java/net/protyposis/android/spectaculumdemo/ParameterListAdapter.java <ide> final ArrayAdapter<Enum> adapter = new ArrayAdapter<>(mActivity, android.R.layout.simple_spinner_item, p.getEnumValues()); <ide> adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); <ide> spinner.setAdapter(adapter); <del> <add> spinner.setSelection(adapter.getPosition(p.getValue())); <ide> spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { <ide> @Override <ide> public void onItemSelected(AdapterView<?> parent, View view, final int position, long id) {
Java
lgpl-2.1
55aa99926ee7323bb6a101d7a31e3b5671d283f7
0
certusoft/swingx,certusoft/swingx
/* * $Id$ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx; import java.awt.Point; import java.awt.event.MouseEvent; import javax.swing.JTable; import javax.swing.SwingUtilities; import javax.swing.table.TableModel; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import org.jdesktop.swingx.table.TableColumnExt; import org.jdesktop.swingx.treetable.AbstractTreeTableModel; import org.jdesktop.swingx.treetable.DefaultTreeTableModel; import org.jdesktop.swingx.treetable.FileSystemModel; import org.jdesktop.swingx.treetable.TreeTableModel; import org.jdesktop.swingx.util.ComponentTreeTableModel; import org.jdesktop.swingx.util.PropertyChangeReport; import org.jdesktop.swingx.util.TreeSelectionReport; public class JXTreeTableUnitTest extends InteractiveTestCase { protected TreeTableModel treeTableModel; protected TreeTableModel simpleTreeTableModel; public JXTreeTableUnitTest() { super("JXTreeTable Unit Test"); } /** * Issue #270-swingx: NPE in some contexts when accessing the * TreeTableModelAdapter. * */ public void testConservativeRowForNodeInAdapter() { // for testing we need a model which relies on // node != null TreeTableModel model = new DefaultTreeTableModel((TreeNode) simpleTreeTableModel.getRoot()) { @Override public Object getValueAt(Object node, int column) { // access node node.toString(); return super.getValueAt(node, column); } @Override public void setValueAt(Object value, Object node, int column) { // access node node.toString(); super.setValueAt(value, node, column); } @Override public boolean isCellEditable(Object node, int column) { // access node node.toString(); return super.isCellEditable(node, column); } }; // can't use ComponentTreeTableModel in headless environment // JXTreeTable treeTable = new JXTreeTable(new ComponentTreeTableModel(new JXFrame())); JXTreeTable treeTable = new JXTreeTable(model); treeTable.setRootVisible(true); TableModel adapter = treeTable.getModel(); treeTable.collapseAll(); assertEquals(1, treeTable.getRowCount()); // simulate contexts where the accessed row isn't currently visible adapter.getValueAt(treeTable.getRowCount(), 0); adapter.isCellEditable(treeTable.getRowCount(), 0); adapter.setValueAt("somename", treeTable.getRowCount(), 0); } /** * test if table and tree rowHeights are the same. * */ public void testAdjustedRowHeights() { JXTreeTable treeTable = new JXTreeTable(simpleTreeTableModel); JXTree tree = (JXTree) treeTable.getCellRenderer(0, 0); // sanity: same initially assertEquals("table and tree rowHeights must be equal", treeTable.getRowHeight(), tree.getRowHeight()); // change treeTable height treeTable.setRowHeight(treeTable.getRowHeight() * 2); assertEquals("table and tree rowHeights must be equal", treeTable.getRowHeight(), tree.getRowHeight()); // change treeTable height tree.setRowHeight(tree.getRowHeight() * 2); assertEquals("table and tree rowHeights must be equal", treeTable.getRowHeight(), tree.getRowHeight()); } /** * #321-swingx: missing tree property toggleClickCount, largeModel. * */ public void testToggleClickCount() { JXTreeTable treeTable = new JXTreeTable(simpleTreeTableModel); int clickCount = treeTable.getToggleClickCount(); // asserting documented default clickCount == 2 assertEquals("default clickCount", 2, clickCount); int newClickCount = clickCount + 1; treeTable.setToggleClickCount(newClickCount); assertEquals("toggleClickCount must be changed", newClickCount, treeTable.getToggleClickCount()); boolean largeModel = treeTable.isLargeModel(); assertFalse("initial largeModel", largeModel); treeTable.setLargeModel(!largeModel); assertTrue("largeModel property must be toggled", treeTable.isLargeModel()); } /** * Issue #168-jdnc: dnd enabled breaks node collapse/expand. * testing auto-detection of dragHackEnabled. * */ public void testDragHackFlagOn() { JXTreeTable treeTable = new JXTreeTable(simpleTreeTableModel); assertNull(treeTable.getClientProperty(JXTreeTable.DRAG_HACK_FLAG_KEY)); treeTable.getTreeTableHacker().expandOrCollapseNode(0, new MouseEvent(treeTable, 0, 0, 0, 0, 0, 1, false)); Boolean dragHackFlag = (Boolean) treeTable.getClientProperty(JXTreeTable.DRAG_HACK_FLAG_KEY); assertNotNull(dragHackFlag); assertTrue(dragHackFlag); } /** * Issue #168-jdnc: dnd enabled breaks node collapse/expand. * testing auto-detection of dragHackEnabled. * */ public void testDragHackFlagOff() { System.setProperty("sun.swing.enableImprovedDragGesture", "true"); JXTreeTable treeTable = new JXTreeTable(simpleTreeTableModel); assertNull(treeTable.getClientProperty(JXTreeTable.DRAG_HACK_FLAG_KEY)); treeTable.getTreeTableHacker().expandOrCollapseNode(0, new MouseEvent(treeTable, 0, 0, 0, 0, 0, 1, false)); Boolean dragHackFlag = (Boolean) treeTable.getClientProperty(JXTreeTable.DRAG_HACK_FLAG_KEY); assertNotNull(dragHackFlag); assertFalse(dragHackFlag); System.getProperties().remove("sun.swing.enableImprovedDragGesture"); } /** * loosely related to Issue #248-swingx: setRootVisible (true) after * initial rootInvisible didn't show the root. * * this here is a sanity test that there is exactly one row, the problem * is a missing visual update of the table. * */ public void testEmptyModelInitiallyInvisibleRoot() { final DefaultMutableTreeNode root = new DefaultMutableTreeNode(); final InsertTreeTableModel model = new InsertTreeTableModel(root); final JXTreeTable treeTable = new JXTreeTable(model); // sanity... assertFalse(treeTable.isRootVisible()); assertEquals("no rows with invisible root", 0, treeTable.getRowCount()); treeTable.setRootVisible(true); // sanity... assertTrue(treeTable.isRootVisible()); assertEquals("one row with visible root", 1, treeTable.getRowCount()); } /** * Issue #247-swingx: update probs with insert node. * The insert under a collapsed node fires a dataChanged on the table * which results in the usual total "memory" loss (f.i. selection) * * The tree model is after setup is (see the bug report as well): * root * childA * childB * * In the view childA is collapsed: * root * childA * */ public void testInsertUnderCollapsedNode() { final DefaultMutableTreeNode root = new DefaultMutableTreeNode(); final InsertTreeTableModel model = new InsertTreeTableModel(root); DefaultMutableTreeNode childA = model.addChild(root); final DefaultMutableTreeNode childB = model.addChild(childA); final JXTreeTable treeTable = new JXTreeTable(model); treeTable.setRootVisible(true); // sanity... assertEquals(2, treeTable.getRowCount()); final int selected = 1; // select childA treeTable.setRowSelectionInterval(selected, selected); model.addChild(childB); // need to invoke - the tableEvent is fired delayed as well // Note: doing so will make the test _appear_ to pass, the // assertion failure can be seen as an output only! // any idea how to make the test fail? SwingUtilities.invokeLater(new Runnable() { public void run() { int selectedAfterInsert = treeTable.getSelectedRow(); assertEquals(selected, selectedAfterInsert); } }); } /** * Model used to show insert update issue. */ public static class InsertTreeTableModel extends DefaultTreeTableModel { private boolean rootIsFolder; public InsertTreeTableModel(TreeNode root) { super(root); } public InsertTreeTableModel(TreeNode root, boolean rootIsFolder) { super(root); this.rootIsFolder = rootIsFolder; } @Override public boolean isLeaf(Object node) { if (rootIsFolder && (node == getRoot())) { return false; } return super.isLeaf(node); } public int getColumnCount() { return 2; } public DefaultMutableTreeNode addChild(DefaultMutableTreeNode parent) { DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("Child"); parent.add(newNode); nodesWereInserted(parent, new int[] {parent.getIndex(newNode) }); // fireTreeNodesInserted(this, getPathToRoot(parent), // new int[] { parent.getIndex(newNode) }, // new Object[] { newNode }); return newNode; } } /** * Issue #230-swingx: * JXTreeTable should fire property change on setTreeTableModel. * * * */ public void testTreeTableModelIsBoundProperty() { JXTreeTable treeTable = new JXTreeTable(); PropertyChangeReport report = new PropertyChangeReport(); treeTable.addPropertyChangeListener(report); treeTable.setTreeTableModel(simpleTreeTableModel); int allPropertyCount = report.getEventCount(); int treeTMPropertyCount = report.getEventCount("treeTableModel"); assertEquals("treeTable must have fired exactly one event for property treeTableModel", 1, treeTMPropertyCount); assertEquals("treeTable must have fired event for property treeTableModel only", allPropertyCount, treeTMPropertyCount); // sanity: must not fire when setting to same report.clear(); treeTable.setTreeTableModel(simpleTreeTableModel); assertEquals("treeTable must not have fired", 0, report.getEventCount()); } /** * Issue #54: hidden columns not removed on setModel. * sanity test (make sure nothing evil introduced in treeTable as * compared to table) */ public void testRemoveAllColumsAfterModelChanged() { JXTreeTable table = new JXTreeTable(new FileSystemModel()); TableColumnExt columnX = table.getColumnExt(1); columnX.setVisible(false); int columnCount = table.getColumnCount(true); assertEquals("total column count must be same as model", table.getModel().getColumnCount(), columnCount); assertEquals("visible column count must one less as total", columnCount - 1, table.getColumnCount()); table.setTreeTableModel(new FileSystemModel()); assertEquals("visible columns must be same as total", table.getColumnCount(), table.getColumnCount(true)); } /** * Issue #241: treeModelListeners not removed. * */ public void testRemoveListeners() { JXTreeTable treeTable = new JXTreeTable(treeTableModel); treeTable.setTreeTableModel(new FileSystemModel()); assertEquals(0, ((AbstractTreeTableModel) treeTableModel).getTreeModelListeners().length); } public void testRowForPath() { JXTreeTable treeTable = new JXTreeTable(simpleTreeTableModel); // @todo - make sure we find an expandible row instead of hardcoding int rowCount = treeTable.getRowCount(); int row = 2; TreePath path = treeTable.getPathForRow(row); assertEquals("original row must be retrieved", row, treeTable.getRowForPath(path)); treeTable.expandRow(row - 1); // sanity assert assertTrue("really expanded", treeTable.getRowCount() > rowCount); TreePath expanded = treeTable.getPathForRow(row); assertNotSame("path at original row must be different when expanded", path, expanded); assertEquals("original row must be retrieved", row, treeTable.getRowForPath(expanded)); } public void testPathForRowContract() { JXTreeTable treeTable = new JXTreeTable(treeTableModel); assertNull("row < 0 must return null path", treeTable.getPathForRow(-1)); assertNull("row >= getRowCount must return null path", treeTable.getPathForRow(treeTable.getRowCount())); } public void testTableRowAtNegativePoint() { JXTable treeTable = new JXTable(1, 4); int negativeYRowHeight = - treeTable.getRowHeight(); int negativeYRowHeightPlusOne = negativeYRowHeight + 1; int negativeYMinimal = -1; assertEquals("negative y location rowheight " + negativeYRowHeight + " must return row -1", -1, treeTable.rowAtPoint(new Point(-1, negativeYRowHeight))); assertEquals("negative y location " + negativeYRowHeightPlusOne +" must return row -1", -1, treeTable.rowAtPoint(new Point(-1, negativeYRowHeightPlusOne))); assertEquals("minimal negative y location must return row -1", -1, treeTable.rowAtPoint(new Point(-1, negativeYMinimal))); } public void testTableRowAtOutsidePoint() { JTable treeTable = new JTable(2, 4); int negativeYRowHeight = (treeTable.getRowHeight()+ treeTable.getRowMargin()) * treeTable.getRowCount() ; int negativeYRowHeightPlusOne = negativeYRowHeight - 1; int negativeYMinimal = -1; assertEquals("negative y location rowheight " + negativeYRowHeight + " must return row -1", -1, treeTable.rowAtPoint(new Point(-1, negativeYRowHeight))); assertEquals("negative y location " + negativeYRowHeightPlusOne +" must return row -1", -1, treeTable.rowAtPoint(new Point(-1, negativeYRowHeightPlusOne))); // assertEquals("minimal negative y location must return row -1", // -1, treeTable.rowAtPoint(new Point(-1, negativeYMinimal))); } public void testPathForLocationContract() { JXTreeTable treeTable = new JXTreeTable(treeTableModel); // this is actually a JTable rowAtPoint bug: falsely calculates // row == 0 if - 1 >= y > - getRowHeight() //assertEquals("location outside must return null path", null, treeTable.getPathForLocation(-1, -(treeTable.getRowHeight() - 1))); int negativeYRowHeight = - treeTable.getRowHeight(); int negativeYRowHeightPlusOne = negativeYRowHeight + 1; int negativeYMinimal = -1; assertEquals("negative y location rowheight " + negativeYRowHeight + " must return row -1", -1, treeTable.rowAtPoint(new Point(-1, negativeYRowHeight))); assertEquals("negative y location " + negativeYRowHeightPlusOne +" must return row -1", -1, treeTable.rowAtPoint(new Point(-1, negativeYRowHeightPlusOne))); assertEquals("minimal negative y location must return row -1", -1, treeTable.rowAtPoint(new Point(-1, negativeYMinimal))); } /** * Issue #151: renderer properties ignored after setting treeTableModel. * */ public void testRendererProperties() { JXTreeTable treeTable = new JXTreeTable(treeTableModel); // storing negates of properties boolean expandsSelected = !treeTable.getExpandsSelectedPaths(); boolean scrollsOnExpand = !treeTable.getScrollsOnExpand(); boolean showRootHandles = !treeTable.getShowsRootHandles(); boolean rootVisible = !treeTable.isRootVisible(); // setting negates properties treeTable.setExpandsSelectedPaths(expandsSelected); treeTable.setScrollsOnExpand(scrollsOnExpand); treeTable.setShowsRootHandles(showRootHandles); treeTable.setRootVisible(rootVisible); // assert negates are set - sanity assert assertEquals("expand selected", expandsSelected, treeTable .getExpandsSelectedPaths()); assertEquals("scrolls expand", scrollsOnExpand, treeTable .getScrollsOnExpand()); assertEquals("shows handles", showRootHandles, treeTable .getShowsRootHandles()); assertEquals("root visible", rootVisible, treeTable.isRootVisible()); // setting a new model treeTable.setTreeTableModel(new DefaultTreeTableModel()); // assert negates are set assertEquals("expand selected", expandsSelected, treeTable .getExpandsSelectedPaths()); assertEquals("scrolls expand", scrollsOnExpand, treeTable .getScrollsOnExpand()); assertEquals("shows handles", showRootHandles, treeTable .getShowsRootHandles()); assertEquals("root visible", rootVisible, treeTable.isRootVisible()); } /** * Issue #148: line style client property not respected by renderer. * */ public void testLineStyle() { JXTreeTable treeTable = new JXTreeTable(treeTableModel); String propertyName = "JTree.lineStyle"; treeTable.putClientProperty(propertyName, "Horizontal"); JXTree renderer = (JXTree) treeTable.getCellRenderer(0, 0); assertEquals(propertyName + " set on renderer", "Horizontal", renderer .getClientProperty(propertyName)); } /** * sanity test: arbitrary client properties not passed to renderer. * */ public void testArbitraryClientProperty() { JXTreeTable treeTable = new JXTreeTable(treeTableModel); String propertyName = "someproperty"; treeTable.putClientProperty(propertyName, "Horizontal"); JXTree renderer = (JXTree) treeTable.getCellRenderer(0, 0); assertNull(propertyName + " not set on renderer", renderer .getClientProperty(propertyName)); } // ------------------ init protected void setUp() throws Exception { super.setUp(); JXTree tree = new JXTree(); DefaultTreeModel treeModel = (DefaultTreeModel) tree.getModel(); simpleTreeTableModel = new DefaultTreeTableModel((TreeNode) treeModel.getRoot()); treeTableModel = new FileSystemModel(); } }
src/test/org/jdesktop/swingx/JXTreeTableUnitTest.java
/* * $Id$ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx; import java.awt.Point; import java.awt.event.MouseEvent; import javax.swing.JTable; import javax.swing.SwingUtilities; import javax.swing.table.TableModel; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import org.jdesktop.swingx.table.TableColumnExt; import org.jdesktop.swingx.treetable.AbstractTreeTableModel; import org.jdesktop.swingx.treetable.DefaultTreeTableModel; import org.jdesktop.swingx.treetable.FileSystemModel; import org.jdesktop.swingx.treetable.TreeTableModel; import org.jdesktop.swingx.util.ComponentTreeTableModel; import org.jdesktop.swingx.util.PropertyChangeReport; public class JXTreeTableUnitTest extends InteractiveTestCase { protected TreeTableModel treeTableModel; protected TreeTableModel simpleTreeTableModel; public JXTreeTableUnitTest() { super("JXTreeTable Unit Test"); } /** * Issue #270-swingx: NPE in some contexts when accessing the * TreeTableModelAdapter. * */ public void testConservativeRowForNodeInAdapter() { JXTreeTable treeTable = new JXTreeTable(new ComponentTreeTableModel(new JXFrame())); treeTable.setRootVisible(true); TableModel adapter = treeTable.getModel(); treeTable.collapseAll(); assertEquals(1, treeTable.getRowCount()); // simulate contexts where the accessed row isn't currently visible adapter.getValueAt(treeTable.getRowCount(), 0); adapter.isCellEditable(treeTable.getRowCount(), 0); adapter.setValueAt("somename", treeTable.getRowCount(), 0); } /** * test if table and tree rowHeights are the same. * */ public void testAdjustedRowHeights() { JXTreeTable treeTable = new JXTreeTable(simpleTreeTableModel); JXTree tree = (JXTree) treeTable.getCellRenderer(0, 0); // sanity: same initially assertEquals("table and tree rowHeights must be equal", treeTable.getRowHeight(), tree.getRowHeight()); // change treeTable height treeTable.setRowHeight(treeTable.getRowHeight() * 2); assertEquals("table and tree rowHeights must be equal", treeTable.getRowHeight(), tree.getRowHeight()); // change treeTable height tree.setRowHeight(tree.getRowHeight() * 2); assertEquals("table and tree rowHeights must be equal", treeTable.getRowHeight(), tree.getRowHeight()); } /** * #321-swingx: missing tree property toggleClickCount, largeModel. * */ public void testToggleClickCount() { JXTreeTable treeTable = new JXTreeTable(simpleTreeTableModel); int clickCount = treeTable.getToggleClickCount(); // asserting documented default clickCount == 2 assertEquals("default clickCount", 2, clickCount); int newClickCount = clickCount + 1; treeTable.setToggleClickCount(newClickCount); assertEquals("toggleClickCount must be changed", newClickCount, treeTable.getToggleClickCount()); boolean largeModel = treeTable.isLargeModel(); assertFalse("initial largeModel", largeModel); treeTable.setLargeModel(!largeModel); assertTrue("largeModel property must be toggled", treeTable.isLargeModel()); } /** * Issue #168-jdnc: dnd enabled breaks node collapse/expand. * testing auto-detection of dragHackEnabled. * */ public void testDragHackFlagOn() { JXTreeTable treeTable = new JXTreeTable(simpleTreeTableModel); assertNull(treeTable.getClientProperty(JXTreeTable.DRAG_HACK_FLAG_KEY)); treeTable.getTreeTableHacker().expandOrCollapseNode(0, new MouseEvent(treeTable, 0, 0, 0, 0, 0, 1, false)); Boolean dragHackFlag = (Boolean) treeTable.getClientProperty(JXTreeTable.DRAG_HACK_FLAG_KEY); assertNotNull(dragHackFlag); assertTrue(dragHackFlag); } /** * Issue #168-jdnc: dnd enabled breaks node collapse/expand. * testing auto-detection of dragHackEnabled. * */ public void testDragHackFlagOff() { System.setProperty("sun.swing.enableImprovedDragGesture", "true"); JXTreeTable treeTable = new JXTreeTable(simpleTreeTableModel); assertNull(treeTable.getClientProperty(JXTreeTable.DRAG_HACK_FLAG_KEY)); treeTable.getTreeTableHacker().expandOrCollapseNode(0, new MouseEvent(treeTable, 0, 0, 0, 0, 0, 1, false)); Boolean dragHackFlag = (Boolean) treeTable.getClientProperty(JXTreeTable.DRAG_HACK_FLAG_KEY); assertNotNull(dragHackFlag); assertFalse(dragHackFlag); System.getProperties().remove("sun.swing.enableImprovedDragGesture"); } /** * loosely related to Issue #248-swingx: setRootVisible (true) after * initial rootInvisible didn't show the root. * * this here is a sanity test that there is exactly one row, the problem * is a missing visual update of the table. * */ public void testEmptyModelInitiallyInvisibleRoot() { final DefaultMutableTreeNode root = new DefaultMutableTreeNode(); final InsertTreeTableModel model = new InsertTreeTableModel(root); final JXTreeTable treeTable = new JXTreeTable(model); // sanity... assertFalse(treeTable.isRootVisible()); assertEquals("no rows with invisible root", 0, treeTable.getRowCount()); treeTable.setRootVisible(true); // sanity... assertTrue(treeTable.isRootVisible()); assertEquals("one row with visible root", 1, treeTable.getRowCount()); } /** * Issue #247-swingx: update probs with insert node. * The insert under a collapsed node fires a dataChanged on the table * which results in the usual total "memory" loss (f.i. selection) * * The tree model is after setup is (see the bug report as well): * root * childA * childB * * In the view childA is collapsed: * root * childA * */ public void testInsertUnderCollapsedNode() { final DefaultMutableTreeNode root = new DefaultMutableTreeNode(); final InsertTreeTableModel model = new InsertTreeTableModel(root); DefaultMutableTreeNode childA = model.addChild(root); final DefaultMutableTreeNode childB = model.addChild(childA); final JXTreeTable treeTable = new JXTreeTable(model); treeTable.setRootVisible(true); // sanity... assertEquals(2, treeTable.getRowCount()); final int selected = 1; // select childA treeTable.setRowSelectionInterval(selected, selected); model.addChild(childB); // need to invoke - the tableEvent is fired delayed as well // Note: doing so will make the test _appear_ to pass, the // assertion failure can be seen as an output only! // any idea how to make the test fail? SwingUtilities.invokeLater(new Runnable() { public void run() { int selectedAfterInsert = treeTable.getSelectedRow(); assertEquals(selected, selectedAfterInsert); } }); } /** * Model used to show insert update issue. */ public static class InsertTreeTableModel extends DefaultTreeTableModel { private boolean rootIsFolder; public InsertTreeTableModel(TreeNode root) { super(root); } public InsertTreeTableModel(TreeNode root, boolean rootIsFolder) { super(root); this.rootIsFolder = rootIsFolder; } @Override public boolean isLeaf(Object node) { if (rootIsFolder && (node == getRoot())) { return false; } return super.isLeaf(node); } public int getColumnCount() { return 2; } public DefaultMutableTreeNode addChild(DefaultMutableTreeNode parent) { DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("Child"); parent.add(newNode); nodesWereInserted(parent, new int[] {parent.getIndex(newNode) }); // fireTreeNodesInserted(this, getPathToRoot(parent), // new int[] { parent.getIndex(newNode) }, // new Object[] { newNode }); return newNode; } } /** * Issue #230-swingx: * JXTreeTable should fire property change on setTreeTableModel. * * * */ public void testTreeTableModelIsBoundProperty() { JXTreeTable treeTable = new JXTreeTable(); PropertyChangeReport report = new PropertyChangeReport(); treeTable.addPropertyChangeListener(report); treeTable.setTreeTableModel(simpleTreeTableModel); int allPropertyCount = report.getEventCount(); int treeTMPropertyCount = report.getEventCount("treeTableModel"); assertEquals("treeTable must have fired exactly one event for property treeTableModel", 1, treeTMPropertyCount); assertEquals("treeTable must have fired event for property treeTableModel only", allPropertyCount, treeTMPropertyCount); // sanity: must not fire when setting to same report.clear(); treeTable.setTreeTableModel(simpleTreeTableModel); assertEquals("treeTable must not have fired", 0, report.getEventCount()); } /** * Issue #54: hidden columns not removed on setModel. * sanity test (make sure nothing evil introduced in treeTable as * compared to table) */ public void testRemoveAllColumsAfterModelChanged() { JXTreeTable table = new JXTreeTable(new FileSystemModel()); TableColumnExt columnX = table.getColumnExt(1); columnX.setVisible(false); int columnCount = table.getColumnCount(true); assertEquals("total column count must be same as model", table.getModel().getColumnCount(), columnCount); assertEquals("visible column count must one less as total", columnCount - 1, table.getColumnCount()); table.setTreeTableModel(new FileSystemModel()); assertEquals("visible columns must be same as total", table.getColumnCount(), table.getColumnCount(true)); } /** * Issue #241: treeModelListeners not removed. * */ public void testRemoveListeners() { JXTreeTable treeTable = new JXTreeTable(treeTableModel); treeTable.setTreeTableModel(new FileSystemModel()); assertEquals(0, ((AbstractTreeTableModel) treeTableModel).getTreeModelListeners().length); } public void testRowForPath() { JXTreeTable treeTable = new JXTreeTable(simpleTreeTableModel); // @todo - make sure we find an expandible row instead of hardcoding int rowCount = treeTable.getRowCount(); int row = 2; TreePath path = treeTable.getPathForRow(row); assertEquals("original row must be retrieved", row, treeTable.getRowForPath(path)); treeTable.expandRow(row - 1); // sanity assert assertTrue("really expanded", treeTable.getRowCount() > rowCount); TreePath expanded = treeTable.getPathForRow(row); assertNotSame("path at original row must be different when expanded", path, expanded); assertEquals("original row must be retrieved", row, treeTable.getRowForPath(expanded)); } public void testPathForRowContract() { JXTreeTable treeTable = new JXTreeTable(treeTableModel); assertNull("row < 0 must return null path", treeTable.getPathForRow(-1)); assertNull("row >= getRowCount must return null path", treeTable.getPathForRow(treeTable.getRowCount())); } public void testTableRowAtNegativePoint() { JXTable treeTable = new JXTable(1, 4); int negativeYRowHeight = - treeTable.getRowHeight(); int negativeYRowHeightPlusOne = negativeYRowHeight + 1; int negativeYMinimal = -1; assertEquals("negative y location rowheight " + negativeYRowHeight + " must return row -1", -1, treeTable.rowAtPoint(new Point(-1, negativeYRowHeight))); assertEquals("negative y location " + negativeYRowHeightPlusOne +" must return row -1", -1, treeTable.rowAtPoint(new Point(-1, negativeYRowHeightPlusOne))); assertEquals("minimal negative y location must return row -1", -1, treeTable.rowAtPoint(new Point(-1, negativeYMinimal))); } public void testTableRowAtOutsidePoint() { JTable treeTable = new JTable(2, 4); int negativeYRowHeight = (treeTable.getRowHeight()+ treeTable.getRowMargin()) * treeTable.getRowCount() ; int negativeYRowHeightPlusOne = negativeYRowHeight - 1; int negativeYMinimal = -1; assertEquals("negative y location rowheight " + negativeYRowHeight + " must return row -1", -1, treeTable.rowAtPoint(new Point(-1, negativeYRowHeight))); assertEquals("negative y location " + negativeYRowHeightPlusOne +" must return row -1", -1, treeTable.rowAtPoint(new Point(-1, negativeYRowHeightPlusOne))); // assertEquals("minimal negative y location must return row -1", // -1, treeTable.rowAtPoint(new Point(-1, negativeYMinimal))); } public void testPathForLocationContract() { JXTreeTable treeTable = new JXTreeTable(treeTableModel); // this is actually a JTable rowAtPoint bug: falsely calculates // row == 0 if - 1 >= y > - getRowHeight() //assertEquals("location outside must return null path", null, treeTable.getPathForLocation(-1, -(treeTable.getRowHeight() - 1))); int negativeYRowHeight = - treeTable.getRowHeight(); int negativeYRowHeightPlusOne = negativeYRowHeight + 1; int negativeYMinimal = -1; assertEquals("negative y location rowheight " + negativeYRowHeight + " must return row -1", -1, treeTable.rowAtPoint(new Point(-1, negativeYRowHeight))); assertEquals("negative y location " + negativeYRowHeightPlusOne +" must return row -1", -1, treeTable.rowAtPoint(new Point(-1, negativeYRowHeightPlusOne))); assertEquals("minimal negative y location must return row -1", -1, treeTable.rowAtPoint(new Point(-1, negativeYMinimal))); } /** * Issue #151: renderer properties ignored after setting treeTableModel. * */ public void testRendererProperties() { JXTreeTable treeTable = new JXTreeTable(treeTableModel); // storing negates of properties boolean expandsSelected = !treeTable.getExpandsSelectedPaths(); boolean scrollsOnExpand = !treeTable.getScrollsOnExpand(); boolean showRootHandles = !treeTable.getShowsRootHandles(); boolean rootVisible = !treeTable.isRootVisible(); // setting negates properties treeTable.setExpandsSelectedPaths(expandsSelected); treeTable.setScrollsOnExpand(scrollsOnExpand); treeTable.setShowsRootHandles(showRootHandles); treeTable.setRootVisible(rootVisible); // assert negates are set - sanity assert assertEquals("expand selected", expandsSelected, treeTable .getExpandsSelectedPaths()); assertEquals("scrolls expand", scrollsOnExpand, treeTable .getScrollsOnExpand()); assertEquals("shows handles", showRootHandles, treeTable .getShowsRootHandles()); assertEquals("root visible", rootVisible, treeTable.isRootVisible()); // setting a new model treeTable.setTreeTableModel(new DefaultTreeTableModel()); // assert negates are set assertEquals("expand selected", expandsSelected, treeTable .getExpandsSelectedPaths()); assertEquals("scrolls expand", scrollsOnExpand, treeTable .getScrollsOnExpand()); assertEquals("shows handles", showRootHandles, treeTable .getShowsRootHandles()); assertEquals("root visible", rootVisible, treeTable.isRootVisible()); } /** * Issue #148: line style client property not respected by renderer. * */ public void testLineStyle() { JXTreeTable treeTable = new JXTreeTable(treeTableModel); String propertyName = "JTree.lineStyle"; treeTable.putClientProperty(propertyName, "Horizontal"); JXTree renderer = (JXTree) treeTable.getCellRenderer(0, 0); assertEquals(propertyName + " set on renderer", "Horizontal", renderer .getClientProperty(propertyName)); } /** * sanity test: arbitrary client properties not passed to renderer. * */ public void testArbitraryClientProperty() { JXTreeTable treeTable = new JXTreeTable(treeTableModel); String propertyName = "someproperty"; treeTable.putClientProperty(propertyName, "Horizontal"); JXTree renderer = (JXTree) treeTable.getCellRenderer(0, 0); assertNull(propertyName + " not set on renderer", renderer .getClientProperty(propertyName)); } // ------------------ init protected void setUp() throws Exception { super.setUp(); JXTree tree = new JXTree(); DefaultTreeModel treeModel = (DefaultTreeModel) tree.getModel(); simpleTreeTableModel = new DefaultTreeTableModel((TreeNode) treeModel.getRoot()); treeTableModel = new FileSystemModel(); } }
fixed headlessException in test
src/test/org/jdesktop/swingx/JXTreeTableUnitTest.java
fixed headlessException in test
<ide><path>rc/test/org/jdesktop/swingx/JXTreeTableUnitTest.java <ide> import org.jdesktop.swingx.treetable.TreeTableModel; <ide> import org.jdesktop.swingx.util.ComponentTreeTableModel; <ide> import org.jdesktop.swingx.util.PropertyChangeReport; <add>import org.jdesktop.swingx.util.TreeSelectionReport; <ide> <ide> <ide> public class JXTreeTableUnitTest extends InteractiveTestCase { <ide> * <ide> */ <ide> public void testConservativeRowForNodeInAdapter() { <del> JXTreeTable treeTable = new JXTreeTable(new ComponentTreeTableModel(new JXFrame())); <add> // for testing we need a model which relies on <add> // node != null <add> TreeTableModel model = new DefaultTreeTableModel((TreeNode) simpleTreeTableModel.getRoot()) { <add> <add> @Override <add> public Object getValueAt(Object node, int column) { <add> // access node <add> node.toString(); <add> return super.getValueAt(node, column); <add> } <add> <add> @Override <add> public void setValueAt(Object value, Object node, int column) { <add> // access node <add> node.toString(); <add> super.setValueAt(value, node, column); <add> } <add> <add> @Override <add> public boolean isCellEditable(Object node, int column) { <add> // access node <add> node.toString(); <add> return super.isCellEditable(node, column); <add> } <add> <add> }; <add> // can't use ComponentTreeTableModel in headless environment <add>// JXTreeTable treeTable = new JXTreeTable(new ComponentTreeTableModel(new JXFrame())); <add> JXTreeTable treeTable = new JXTreeTable(model); <ide> treeTable.setRootVisible(true); <ide> TableModel adapter = treeTable.getModel(); <ide> treeTable.collapseAll();
Java
apache-2.0
bfa79a5638c09131693eb3b902bd8d9f8a204858
0
metaborg/spoofax,metaborg/spoofax,metaborg/spoofax,metaborg/spoofax-eclipse,metaborg/spoofax
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.strategoxt.imp.runtime.services.outline; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.PopupDialog; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseMoveListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.FontMetrics; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeItem; import org.eclipse.ui.internal.misc.StringMatcher; /** * Abstract class for showing a filtered tree in a lightweight popup dialog. */ public abstract class FilteringInfoPopup extends PopupDialog implements DisposeListener { /** * The NamePatternFilter selects the elements which * match the given string patterns. */ protected class NamePatternFilter extends ViewerFilter { public NamePatternFilter() { } /* (non-Javadoc) * Method declared on ViewerFilter. */ public boolean select(Viewer viewer, Object parentElement, Object element) { if(matcher==null) { return true; } TreeViewer treeViewer= (TreeViewer) viewer; String matchName = getMatchName(element); if (matchName != null && matcher.match(matchName)) return true; return hasUnfilteredChild(treeViewer, element); } private boolean hasUnfilteredChild(TreeViewer viewer, Object element) { Object[] children = ((ITreeContentProvider) viewer .getContentProvider()).getChildren(element); for (int i = 0; i < children.length; i++) if (select(viewer, element, children[i])) return true; return false; } } /** The control's text widget */ private Text filterText; /** The control's tree widget */ private TreeViewer treeViewer; /** * Fields that support the dialog menu */ private Composite viewMenuButtonComposite; /** * Field for tree style since it must be remembered by the instance. */ private int treeStyle; private StringMatcher matcher; /** * Creates a tree information control with the given shell as parent. The given * styles are applied to the shell and the tree widget. * * @param parent the parent shell * @param shellStyle the additional styles for the shell * @param treeStyle the additional styles for the tree widget * @param showStatusField <code>true</code> iff the control has a status field at the bottom */ public FilteringInfoPopup(Shell parent, int shellStyle, int treeStyle, boolean showStatusField) { super(parent, shellStyle, true, true, true, true, null, null); this.treeStyle= treeStyle; // Title and status text must be set to get the title label created, so force empty values here. if (hasHeader()) setTitleText(""); //$NON-NLS-1$ setInfoText(""); // //$NON-NLS-1$ // Status field text can only be computed after widgets are created. setInfoText(getStatusFieldText()); } /** * Create the main content for this information control. * * @param parent The parent composite * @return The control representing the main content. */ protected Control createDialogArea(Composite parent) { treeViewer= createTreeViewer(parent, treeStyle); final Tree tree= treeViewer.getTree(); tree.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { if (e.character == SWT.ESC) dispose(); } public void keyReleased(KeyEvent e) { // do nothing } }); tree.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { // do nothing } public void widgetDefaultSelected(SelectionEvent e) { Object selectedElement = getSelectedElement(); close(); handleElementSelected(selectedElement); } }); tree.addMouseMoveListener(new MouseMoveListener() { public void mouseMove(MouseEvent e) { TreeItem[] selectedItems = tree.getSelection(); TreeItem selectedItem = selectedItems.length == 0 ? null : selectedItems[0]; TreeItem itemUnderPointer = tree.getItem(new Point(e.x, e.y)); if (itemUnderPointer != null) { if (itemUnderPointer != selectedItem) { select(itemUnderPointer); } else if (e.y < tree.getItemHeight() / 4) { // Scroll up Point p= tree.toDisplay(e.x, e.y); TreeItem item= (TreeItem) treeViewer.scrollUp(p.x, p.y); if (item != null) { select(item); } } else if (e.y > tree.getBounds().height - tree.getItemHeight() / 4) { // Scroll down Point p= tree.toDisplay(e.x, e.y); TreeItem item= (TreeItem) treeViewer.scrollDown(p.x, p.y); if (item != null) { select(item); } } } } private void select(TreeItem item) { // set selection on viewer instead of directly on tree so that // selection listeners are notified Object element = item.getData(); if (element != null) { treeViewer.setSelection(new StructuredSelection(element)); } } }); tree.addMouseListener(new MouseAdapter() { public void mouseUp(MouseEvent e) { if (tree.getSelectionCount() < 1) return; if (e.button != 1) return; if (tree.equals(e.getSource())) { Object o= tree.getItem(new Point(e.x, e.y)); TreeItem selection= tree.getSelection()[0]; if (selection.equals(o)) { Object selectedElement = getSelectedElement(); close(); handleElementSelected(selectedElement); } } } }); installFilter(); addDisposeListener(this); return treeViewer.getControl(); } /** * Creates a tree information control with the given shell as parent. The given * styles are applied to the shell and the tree widget. * * @param parent the parent shell * @param shellStyle the additional styles for the shell * @param treeStyle the additional styles for the tree widget */ public FilteringInfoPopup(Shell parent, int shellStyle, int treeStyle) { this(parent, shellStyle, treeStyle, false); } protected abstract TreeViewer createTreeViewer(Composite parent, int style); /** * Returns the name of the dialog settings section. * * @return the name of the dialog settings section */ protected abstract String getId(); /* (non-Javadoc) * @see org.eclipse.jface.dialogs.PopupDialog#getFocusControl() */ protected Control getFocusControl() { return filterText; } protected TreeViewer getTreeViewer() { return treeViewer; } /** * Returns <code>true</code> if the control has a header, <code>false</code> otherwise. * <p> * The default is to return <code>false</code>. * </p> * * @return <code>true</code> if the control has a header */ protected boolean hasHeader() { // default is to have no header return false; } protected Text getFilterText() { return filterText; } protected Text createFilterText(Composite parent) { filterText= new Text(parent, SWT.NONE); GridData data= new GridData(GridData.FILL_HORIZONTAL); GC gc= new GC(parent); gc.setFont(parent.getFont()); FontMetrics fontMetrics= gc.getFontMetrics(); gc.dispose(); data.heightHint= Dialog.convertHeightInCharsToPixels(fontMetrics, 1); data.horizontalAlignment= GridData.FILL; data.verticalAlignment= GridData.CENTER; filterText.setLayoutData(data); filterText.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { if (e.keyCode == 0x0D) { // return Object selectedElement = getSelectedElement(); close(); handleElementSelected(selectedElement); } if (e.keyCode == SWT.ARROW_DOWN) treeViewer.getTree().setFocus(); if (e.keyCode == SWT.ARROW_UP) treeViewer.getTree().setFocus(); if (e.character == 0x1B) // ESC dispose(); } public void keyReleased(KeyEvent e) { // do nothing } }); return filterText; } protected void createHorizontalSeparator(Composite parent) { Label separator= new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL | SWT.LINE_DOT); separator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); } protected void updateStatusFieldText() { setInfoText(getStatusFieldText()); } /** * Handles click in status field. * <p> * Default does nothing. * </p> */ protected void handleStatusFieldClicked() { } protected String getStatusFieldText() { return ""; //$NON-NLS-1$ } private void installFilter() { filterText.setText(""); //$NON-NLS-1$ filterText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { String text= ((Text) e.widget).getText(); int length= text.length(); if (length > 0 && text.charAt(length -1 ) != '*') { text= text + '*'; } setMatcherString(text, true); } }); getTreeViewer().addFilter(new NamePatternFilter()); } /** * The string matcher has been modified. The default implementation * refreshes the view and selects the first matched element */ protected void stringMatcherUpdated() { // refresh viewer to re-filter treeViewer.getControl().setRedraw(false); treeViewer.refresh(); treeViewer.expandAll(); selectFirstMatch(); treeViewer.getControl().setRedraw(true); } /** * Sets the patterns to filter out for the receiver. * <p> * The following characters have special meaning: * ? => any character * * => any string * </p> * * @param pattern the pattern * @param update <code>true</code> if the viewer should be updated */ protected void setMatcherString(String pattern, boolean update) { if (pattern.length() == 0) { matcher= null; } else { boolean ignoreCase= pattern.toLowerCase().equals(pattern); matcher= new StringMatcher(pattern, ignoreCase, false); } if (update) stringMatcherUpdated(); } protected StringMatcher getMatcher() { return matcher; } /** * Implementers can modify * * @return the selected element */ protected Object getSelectedElement() { if (treeViewer == null) return null; return ((IStructuredSelection) treeViewer.getSelection()).getFirstElement(); } abstract protected void handleElementSelected(Object selectedElement); /** * Selects the first element in the tree which * matches the current filter pattern. */ protected void selectFirstMatch() { Tree tree= treeViewer.getTree(); Object element= findElement(tree.getItems()); if (element != null) treeViewer.setSelection(new StructuredSelection(element), true); else treeViewer.setSelection(StructuredSelection.EMPTY); } private Object findElement(TreeItem[] items) { for (int i= 0; i < items.length; i++) { Object element= items[i].getData(); if (matcher == null) return element; if (element != null) { String label= getMatchName(element); if (matcher.match(label)) return element; } element= findElement(items[i].getItems()); if (element != null) return element; } return null; } /** * {@inheritDoc} */ public void setInformation(String information) { // this method is ignored, see IInformationControlExtension2 } /** * {@inheritDoc} */ public abstract void setInput(Object information); protected void inputChanged(Object newInput, Object newSelection) { filterText.setText(""); //$NON-NLS-1$ treeViewer.setInput(newInput); if (newSelection != null) { treeViewer.setSelection(new StructuredSelection(newSelection)); } } /** * {@inheritDoc} */ public void setVisible(boolean visible) { if (visible) { open(); } else { saveDialogBounds(getShell()); getShell().setVisible(false); } } /** * {@inheritDoc} */ public final void dispose() { close(); } /** * {@inheritDoc} * @param event can be null * <p> * Subclasses may extend. * </p> */ public void widgetDisposed(DisposeEvent event) { treeViewer= null; filterText= null; } /** * {@inheritDoc} */ public boolean hasContents() { return treeViewer != null && treeViewer.getInput() != null; } /** * {@inheritDoc} */ public void setSizeConstraints(int maxWidth, int maxHeight) { // ignore } /** * {@inheritDoc} */ public Point computeSizeHint() { // return the shell's size - note that it already has the persisted size if persisting // is enabled. return getShell().getSize(); } /** * {@inheritDoc} */ public void setLocation(Point location) { /* * If the location is persisted, it gets managed by PopupDialog - fine. Otherwise, the location is * computed in Window#getInitialLocation, which will center it in the parent shell / main * monitor, which is wrong for two reasons: * - we want to center over the editor / subject control, not the parent shell * - the center is computed via the initalSize, which may be also wrong since the size may * have been updated since via min/max sizing of AbstractInformationControlManager. * In that case, override the location with the one computed by the manager. Note that * the call to constrainShellSize in PopupDialog.open will still ensure that the shell is * entirely visible. */ if (!getPersistBounds() || getDialogSettings() == null) getShell().setLocation(location); } /** * {@inheritDoc} */ public void setSize(int width, int height) { getShell().setSize(width, height); } /** * {@inheritDoc} */ public void addDisposeListener(DisposeListener listener) { getShell().addDisposeListener(listener); } /** * {@inheritDoc} */ public void removeDisposeListener(DisposeListener listener) { getShell().removeDisposeListener(listener); } /** * {@inheritDoc} */ public void setForegroundColor(Color foreground) { applyForegroundColor(foreground, getContents()); } /** * {@inheritDoc} */ public void setBackgroundColor(Color background) { applyBackgroundColor(background, getContents()); } /** * {@inheritDoc} */ public boolean isFocusControl() { return treeViewer.getControl().isFocusControl() || filterText.isFocusControl(); } /** * {@inheritDoc} */ public void setFocus() { getShell().forceFocus(); filterText.setFocus(); } /** * {@inheritDoc} */ public void addFocusListener(FocusListener listener) { getShell().addFocusListener(listener); } /** * {@inheritDoc} */ public void removeFocusListener(FocusListener listener) { getShell().removeFocusListener(listener); } /* * Overridden to insert the filter text into the title and menu area. * * @since 3.2 */ protected Control createTitleMenuArea(Composite parent) { viewMenuButtonComposite= (Composite) super.createTitleMenuArea(parent); // If there is a header, then the filter text must be created // underneath the title and menu area. if (hasHeader()) { filterText= createFilterText(parent); } return viewMenuButtonComposite; } /* * Overridden to insert the filter text into the title control * if there is no header specified. * @since 3.2 */ protected Control createTitleControl(Composite parent) { if (hasHeader()) { return super.createTitleControl(parent); } filterText= createFilterText(parent); return filterText; } /* * @see org.eclipse.jface.dialogs.PopupDialog#setTabOrder(org.eclipse.swt.widgets.Composite) */ protected void setTabOrder(Composite composite) { if (hasHeader()) { composite.setTabList(new Control[] { filterText, treeViewer.getTree() }); } else { viewMenuButtonComposite.setTabList(new Control[] { filterText }); composite.setTabList(new Control[] { viewMenuButtonComposite, treeViewer.getTree() }); } } /** * Returns the name of the given element used for matching. The default * implementation gets the name from the tree viewer's label provider. * Subclasses may override. * * @param element the element * @return the name to be used for matching */ protected String getMatchName(Object element) { return ((ILabelProvider) getTreeViewer().getLabelProvider()).getText(element); } }
org.strategoxt.imp.runtime/src/org/strategoxt/imp/runtime/services/outline/FilteringInfoPopup.java
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.strategoxt.imp.runtime.services.outline; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.PopupDialog; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseMoveListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.FontMetrics; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeItem; import org.eclipse.ui.internal.misc.StringMatcher; /** * Abstract class for showing a filtered tree in a lightweight popup dialog. */ public abstract class FilteringInfoPopup extends PopupDialog implements DisposeListener { /** * The NamePatternFilter selects the elements which * match the given string patterns. */ protected class NamePatternFilter extends ViewerFilter { public NamePatternFilter() { } /* (non-Javadoc) * Method declared on ViewerFilter. */ public boolean select(Viewer viewer, Object parentElement, Object element) { if(matcher==null) { return true; } TreeViewer treeViewer= (TreeViewer) viewer; String matchName = getMatchName(element); if (matchName != null && matcher.match(matchName)) return true; return hasUnfilteredChild(treeViewer, element); } private boolean hasUnfilteredChild(TreeViewer viewer, Object element) { Object[] children = ((ITreeContentProvider) viewer .getContentProvider()).getChildren(element); for (int i = 0; i < children.length; i++) if (select(viewer, element, children[i])) return true; return false; } } /** The control's text widget */ private Text filterText; /** The control's tree widget */ private TreeViewer treeViewer; /** * Fields that support the dialog menu */ private Composite viewMenuButtonComposite; /** * Field for tree style since it must be remembered by the instance. */ private int treeStyle; private StringMatcher matcher; /** * Creates a tree information control with the given shell as parent. The given * styles are applied to the shell and the tree widget. * * @param parent the parent shell * @param shellStyle the additional styles for the shell * @param treeStyle the additional styles for the tree widget * @param showStatusField <code>true</code> iff the control has a status field at the bottom */ public FilteringInfoPopup(Shell parent, int shellStyle, int treeStyle, boolean showStatusField) { super(parent, shellStyle, true, true, true, true, null, null); this.treeStyle= treeStyle; // Title and status text must be set to get the title label created, so force empty values here. if (hasHeader()) setTitleText(""); //$NON-NLS-1$ setInfoText(""); // //$NON-NLS-1$ // Create all controls early to preserve the life cycle of the original implementation. create(); // Status field text can only be computed after widgets are created. setInfoText(getStatusFieldText()); } /** * Create the main content for this information control. * * @param parent The parent composite * @return The control representing the main content. */ protected Control createDialogArea(Composite parent) { treeViewer= createTreeViewer(parent, treeStyle); final Tree tree= treeViewer.getTree(); tree.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { if (e.character == SWT.ESC) dispose(); } public void keyReleased(KeyEvent e) { // do nothing } }); tree.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { // do nothing } public void widgetDefaultSelected(SelectionEvent e) { Object selectedElement = getSelectedElement(); close(); handleElementSelected(selectedElement); } }); tree.addMouseMoveListener(new MouseMoveListener() { public void mouseMove(MouseEvent e) { TreeItem[] selectedItems = tree.getSelection(); TreeItem selectedItem = selectedItems.length == 0 ? null : selectedItems[0]; TreeItem itemUnderPointer = tree.getItem(new Point(e.x, e.y)); if (itemUnderPointer != null) { if (itemUnderPointer != selectedItem) { select(itemUnderPointer); } else if (e.y < tree.getItemHeight() / 4) { // Scroll up Point p= tree.toDisplay(e.x, e.y); TreeItem item= (TreeItem) treeViewer.scrollUp(p.x, p.y); if (item != null) { select(item); } } else if (e.y > tree.getBounds().height - tree.getItemHeight() / 4) { // Scroll down Point p= tree.toDisplay(e.x, e.y); TreeItem item= (TreeItem) treeViewer.scrollDown(p.x, p.y); if (item != null) { select(item); } } } } private void select(TreeItem item) { // set selection on viewer instead of directly on tree so that // selection listeners are notified Object element = item.getData(); if (element != null) { treeViewer.setSelection(new StructuredSelection(element)); } } }); tree.addMouseListener(new MouseAdapter() { public void mouseUp(MouseEvent e) { if (tree.getSelectionCount() < 1) return; if (e.button != 1) return; if (tree.equals(e.getSource())) { Object o= tree.getItem(new Point(e.x, e.y)); TreeItem selection= tree.getSelection()[0]; if (selection.equals(o)) { Object selectedElement = getSelectedElement(); close(); handleElementSelected(selectedElement); } } } }); installFilter(); addDisposeListener(this); return treeViewer.getControl(); } /** * Creates a tree information control with the given shell as parent. The given * styles are applied to the shell and the tree widget. * * @param parent the parent shell * @param shellStyle the additional styles for the shell * @param treeStyle the additional styles for the tree widget */ public FilteringInfoPopup(Shell parent, int shellStyle, int treeStyle) { this(parent, shellStyle, treeStyle, false); } protected abstract TreeViewer createTreeViewer(Composite parent, int style); /** * Returns the name of the dialog settings section. * * @return the name of the dialog settings section */ protected abstract String getId(); /* (non-Javadoc) * @see org.eclipse.jface.dialogs.PopupDialog#getFocusControl() */ protected Control getFocusControl() { return filterText; } protected TreeViewer getTreeViewer() { return treeViewer; } /** * Returns <code>true</code> if the control has a header, <code>false</code> otherwise. * <p> * The default is to return <code>false</code>. * </p> * * @return <code>true</code> if the control has a header */ protected boolean hasHeader() { // default is to have no header return false; } protected Text getFilterText() { return filterText; } protected Text createFilterText(Composite parent) { filterText= new Text(parent, SWT.NONE); GridData data= new GridData(GridData.FILL_HORIZONTAL); GC gc= new GC(parent); gc.setFont(parent.getFont()); FontMetrics fontMetrics= gc.getFontMetrics(); gc.dispose(); data.heightHint= Dialog.convertHeightInCharsToPixels(fontMetrics, 1); data.horizontalAlignment= GridData.FILL; data.verticalAlignment= GridData.CENTER; filterText.setLayoutData(data); filterText.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { if (e.keyCode == 0x0D) { // return Object selectedElement = getSelectedElement(); close(); handleElementSelected(selectedElement); } if (e.keyCode == SWT.ARROW_DOWN) treeViewer.getTree().setFocus(); if (e.keyCode == SWT.ARROW_UP) treeViewer.getTree().setFocus(); if (e.character == 0x1B) // ESC dispose(); } public void keyReleased(KeyEvent e) { // do nothing } }); return filterText; } protected void createHorizontalSeparator(Composite parent) { Label separator= new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL | SWT.LINE_DOT); separator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); } protected void updateStatusFieldText() { setInfoText(getStatusFieldText()); } /** * Handles click in status field. * <p> * Default does nothing. * </p> */ protected void handleStatusFieldClicked() { } protected String getStatusFieldText() { return ""; //$NON-NLS-1$ } private void installFilter() { filterText.setText(""); //$NON-NLS-1$ filterText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { String text= ((Text) e.widget).getText(); int length= text.length(); if (length > 0 && text.charAt(length -1 ) != '*') { text= text + '*'; } setMatcherString(text, true); } }); getTreeViewer().addFilter(new NamePatternFilter()); } /** * The string matcher has been modified. The default implementation * refreshes the view and selects the first matched element */ protected void stringMatcherUpdated() { // refresh viewer to re-filter treeViewer.getControl().setRedraw(false); treeViewer.refresh(); treeViewer.expandAll(); selectFirstMatch(); treeViewer.getControl().setRedraw(true); } /** * Sets the patterns to filter out for the receiver. * <p> * The following characters have special meaning: * ? => any character * * => any string * </p> * * @param pattern the pattern * @param update <code>true</code> if the viewer should be updated */ protected void setMatcherString(String pattern, boolean update) { if (pattern.length() == 0) { matcher= null; } else { boolean ignoreCase= pattern.toLowerCase().equals(pattern); matcher= new StringMatcher(pattern, ignoreCase, false); } if (update) stringMatcherUpdated(); } protected StringMatcher getMatcher() { return matcher; } /** * Implementers can modify * * @return the selected element */ protected Object getSelectedElement() { if (treeViewer == null) return null; return ((IStructuredSelection) treeViewer.getSelection()).getFirstElement(); } abstract protected void handleElementSelected(Object selectedElement); /** * Selects the first element in the tree which * matches the current filter pattern. */ protected void selectFirstMatch() { Tree tree= treeViewer.getTree(); Object element= findElement(tree.getItems()); if (element != null) treeViewer.setSelection(new StructuredSelection(element), true); else treeViewer.setSelection(StructuredSelection.EMPTY); } private Object findElement(TreeItem[] items) { for (int i= 0; i < items.length; i++) { Object element= items[i].getData(); if (matcher == null) return element; if (element != null) { String label= getMatchName(element); if (matcher.match(label)) return element; } element= findElement(items[i].getItems()); if (element != null) return element; } return null; } /** * {@inheritDoc} */ public void setInformation(String information) { // this method is ignored, see IInformationControlExtension2 } /** * {@inheritDoc} */ public abstract void setInput(Object information); protected void inputChanged(Object newInput, Object newSelection) { filterText.setText(""); //$NON-NLS-1$ treeViewer.setInput(newInput); if (newSelection != null) { treeViewer.setSelection(new StructuredSelection(newSelection)); } } /** * {@inheritDoc} */ public void setVisible(boolean visible) { if (visible) { open(); } else { saveDialogBounds(getShell()); getShell().setVisible(false); } } /** * {@inheritDoc} */ public final void dispose() { close(); } /** * {@inheritDoc} * @param event can be null * <p> * Subclasses may extend. * </p> */ public void widgetDisposed(DisposeEvent event) { treeViewer= null; filterText= null; } /** * {@inheritDoc} */ public boolean hasContents() { return treeViewer != null && treeViewer.getInput() != null; } /** * {@inheritDoc} */ public void setSizeConstraints(int maxWidth, int maxHeight) { // ignore } /** * {@inheritDoc} */ public Point computeSizeHint() { // return the shell's size - note that it already has the persisted size if persisting // is enabled. return getShell().getSize(); } /** * {@inheritDoc} */ public void setLocation(Point location) { /* * If the location is persisted, it gets managed by PopupDialog - fine. Otherwise, the location is * computed in Window#getInitialLocation, which will center it in the parent shell / main * monitor, which is wrong for two reasons: * - we want to center over the editor / subject control, not the parent shell * - the center is computed via the initalSize, which may be also wrong since the size may * have been updated since via min/max sizing of AbstractInformationControlManager. * In that case, override the location with the one computed by the manager. Note that * the call to constrainShellSize in PopupDialog.open will still ensure that the shell is * entirely visible. */ if (!getPersistBounds() || getDialogSettings() == null) getShell().setLocation(location); } /** * {@inheritDoc} */ public void setSize(int width, int height) { getShell().setSize(width, height); } /** * {@inheritDoc} */ public void addDisposeListener(DisposeListener listener) { getShell().addDisposeListener(listener); } /** * {@inheritDoc} */ public void removeDisposeListener(DisposeListener listener) { getShell().removeDisposeListener(listener); } /** * {@inheritDoc} */ public void setForegroundColor(Color foreground) { applyForegroundColor(foreground, getContents()); } /** * {@inheritDoc} */ public void setBackgroundColor(Color background) { applyBackgroundColor(background, getContents()); } /** * {@inheritDoc} */ public boolean isFocusControl() { return treeViewer.getControl().isFocusControl() || filterText.isFocusControl(); } /** * {@inheritDoc} */ public void setFocus() { getShell().forceFocus(); filterText.setFocus(); } /** * {@inheritDoc} */ public void addFocusListener(FocusListener listener) { getShell().addFocusListener(listener); } /** * {@inheritDoc} */ public void removeFocusListener(FocusListener listener) { getShell().removeFocusListener(listener); } /* * Overridden to insert the filter text into the title and menu area. * * @since 3.2 */ protected Control createTitleMenuArea(Composite parent) { viewMenuButtonComposite= (Composite) super.createTitleMenuArea(parent); // If there is a header, then the filter text must be created // underneath the title and menu area. if (hasHeader()) { filterText= createFilterText(parent); } return viewMenuButtonComposite; } /* * Overridden to insert the filter text into the title control * if there is no header specified. * @since 3.2 */ protected Control createTitleControl(Composite parent) { if (hasHeader()) { return super.createTitleControl(parent); } filterText= createFilterText(parent); return filterText; } /* * @see org.eclipse.jface.dialogs.PopupDialog#setTabOrder(org.eclipse.swt.widgets.Composite) */ protected void setTabOrder(Composite composite) { if (hasHeader()) { composite.setTabList(new Control[] { filterText, treeViewer.getTree() }); } else { viewMenuButtonComposite.setTabList(new Control[] { filterText }); composite.setTabList(new Control[] { viewMenuButtonComposite, treeViewer.getTree() }); } } /** * Returns the name of the given element used for matching. The default * implementation gets the name from the tree viewer's label provider. * Subclasses may override. * * @param element the element * @return the name to be used for matching */ protected String getMatchName(Object element) { return ((ILabelProvider) getTreeViewer().getLabelProvider()).getText(element); } }
I assume this is a bug. Creating controls before the statements in subclass constructors have been executed is likely to result in nullpointers.
org.strategoxt.imp.runtime/src/org/strategoxt/imp/runtime/services/outline/FilteringInfoPopup.java
I assume this is a bug. Creating controls before the statements in subclass constructors have been executed is likely to result in nullpointers.
<ide><path>rg.strategoxt.imp.runtime/src/org/strategoxt/imp/runtime/services/outline/FilteringInfoPopup.java <ide> setTitleText(""); //$NON-NLS-1$ <ide> setInfoText(""); // //$NON-NLS-1$ <ide> <del> // Create all controls early to preserve the life cycle of the original implementation. <del> create(); <del> <ide> // Status field text can only be computed after widgets are created. <ide> setInfoText(getStatusFieldText()); <ide> }
Java
agpl-3.0
a7a89a7bf110cb38542626f1d6561aed9f7d51bd
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
0d97ee18-2e62-11e5-9284-b827eb9e62be
hello.java
0d9243a0-2e62-11e5-9284-b827eb9e62be
0d97ee18-2e62-11e5-9284-b827eb9e62be
hello.java
0d97ee18-2e62-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>0d9243a0-2e62-11e5-9284-b827eb9e62be <add>0d97ee18-2e62-11e5-9284-b827eb9e62be
JavaScript
mit
b243052a20279509b4b6566bbe44e58daf2b9d42
0
tolmasky/language,tolmasky/language
var hasOwnProperty = Object.prototype.hasOwnProperty; // start = (("a" "a") "a") "b") / // (("a" "a") "a") !"d" "c") // A? // R = A / "" // A* // U = A / "" // R = U / R // A+ // var CHARACTER = 0, CHOICE = 1, SEQUENCE = 2, NOT = 3, AND = 4, NAME = 5, DOT = -1; var FAIL = 0, SUCCESS = 2, INCOMPLETE = 3; var EOF = { }, PLACEHOLDER = { }, FAILURE_NODE = { state:FAIL }; function Context(aContext, rules) { this.rules = rules; this.incomplete = { }; this.cache = { }; this.recursive = { }; this.index = -1; this.placeholderParents = { }; if (aContext) { this.rules = aContext.rules; this.index = aContext.index + 1; } } /* // r = (bcc / b) cd var rules = { 0: { UID:0, type:SEQUENCE, children:[2, 1] }, 1: { UID:1, type:SEQUENCE, children:["c", "d"] }, 2: { UID:2, type:CHOICE, children:[3, "b"] }, 3: { UID:3, type:SEQUENCE, children:["b", 4] }, 4: { UID:4, type:SEQUENCE, children:["c", "c"] } }; var source = "bcd"; // r = (bc / b) d var rules = { 0: { UID:0, type:SEQUENCE, children:[1 ,"d"] }, 1: { UID:1, type:CHOICE, children:[2, "b"] }, 2: { UID:2, type:SEQUENCE, children:["b", "c"] } }; var source = "bcd"; */ // A = A a / a var rules = { 0: { UID:0, type:NAME, children:[1], name:"start" }, 1: { UID:1, type:CHOICE, children:[2, "a"] }, 2: { UID:2, type:SEQUENCE, children:[1, "a"] } }; var source = "aaaa"; /* var rules = { 0: { UID:0, type:CHOICE, children:[1, 2] }, 1: { UID:1, type:SEQUENCE, children:[3, "b"] }, 2: { UID:2, type:SEQUENCE, children:[3, 5] }, 3: { UID:3, type:SEQUENCE, children:[4, "a"] }, 4: { UID:4, type:SEQUENCE, children:["a", "a"] }, 5: { UID:5, type:AND, children:[6, -1] }, 6: { UID:6, type:NOT, children:["d"] } }; var source = "aaac"; */ var context = new Context(null, rules); var start = fall(null, 0, context); var index = 0, count = source.length; print_node(start); for (; index < count; ++index) { console.log("+++++DOING " + source[index]); context = parse(context, source[index]); //console.log(context); print_node(start); } console.log("+++++DOING EOF"); context = parse(context, EOF); print_node(start); function print_node(node, indentation, prints) { indentation = indentation || ""; prints = prints || { }; if (node === PLACEHOLDER) return console.log(indentation + " PLACEHOLDER"); if (prints[node.UID] === 2) return; else if (prints[node.UID] === 1) prints[node.UID] += 1; else prints[node.UID] = 1; var rule = node.rule; if (typeof rule === "string") console.log(indentation + rule + " [" + node.state + "]"); else if (rule === -1) console.log(indentation + "DOT " + node.UID); else if (rule.type === CHOICE) console.log(indentation + "CHOICE " + node.UID + " [" + node.state + "]"); else if (rule.type === SEQUENCE) console.log(indentation + "SEQUENCE " + node.UID + " [" + node.state + "]"); else if (rule.type === NOT) console.log(indentation + "NOT " + node.UID); else if (rule.type === AND) console.log(indentation + "AND " + node.UID); else if (rule.type === NAME) console.log(indentation + "NAME " + node.UID + " " + node.name); for (var index = 0, count = node.children.length; index < count; ++index) print_node(node.children[index], indentation + " ", prints); prints[node.UID]--; } function fall(parent, ruleUID, context) { var UID = ruleUID + " " + context.index, recursive = context.recursive; if (recursive[UID]) { context.placeholderParents[parent.UID] = parent; return PLACEHOLDER; } var rule = context.rules[ruleUID] || ruleUID, cache = context.cache, node = cache[UID] || { UID:UID, state:INCOMPLETE, rule:rule, parents:{ }, children:[] }; // Only add this parent if we haven't already accounted for it. // This accounts for the user doing something silly like A / A if (parent && !hasOwnProperty.call(node.parents, parent.UID)) node.parents[parent.UID] = parent; // If it's cached, we've already worked this one out. if (cache[UID]) return node; // Add this to the cache. cache[UID] = node; // If this is a character, there is nothing we can do during the fall stage. // Simply store it in the incomplete hash and return. if (typeof rule === "string" || rule === -1) { // The empty string always trivially succeeds, and consumes no input. if (rule === "") climb(node, context); else context.incomplete[UID] = node; return node; } if (rule.type === NAME) node.name = rule.name; // Before handling our children, make sure we register ourselves so we don't get handled again. recursive[UID] = node; if (rule.type === SEQUENCE) node.children[0] = fall(node, rule.children[0], context); else node.children = rule.children.map(function (child) { return fall(node, child, context); }); // Now unregister ourselves. delete recursive[UID]; return node; } function climbAllParents(node, context) { var parents = node.parents; for (UID in parents) if (hasOwnProperty.call(parents, UID)) climb(parents[UID], context); } function climb(node, context) { if (node.state !== INCOMPLETE) return; var children = node.children, rule = node.rule; if (rule.type === CHOICE) { var lhs = children[0]; // No matter what, if the first one is incomplete, we can't make a decision. if (lhs.state === INCOMPLETE) return; // If not, and this was our ONLY child, or it was successful, // then our state is now it's state and we can keep climbing. if (children.length === 1 || lhs.state === SUCCESS) { children.length = 1; node.state = lhs.state; return climbAllParents(node, context); } // Now we know for sure that we have 2 children AND the first was a failure, // so its all on rhs. var rhs = children[1]; // Same as before, keep waiting. if (rhs.state === INCOMPLETE) return; // From now on, we know we have a result, either success of fail. node.state = rhs.state; // If we succeeded, do a little accounting to make rhs our only child. if (rhs.state === SUCCESS) { children[0] = rhs; children.length = 1; } else children.length = 0; return climbAllParents(node, context); } else if (rule.type === AND) { var lhs = children[0], rhs = children[1]; // We have to know the result of both to continue. if (lhs.state === INCOMPLETE || rhs.state === INCOMPLETE) return; // If our first child (the "predicate") fails, then we fail. // Both must succeed to succeed as a whole. node.state = (lhs.state === SUCCESS && rhs.state === SUCCESS) ? SUCCESS : FAIL; children[0] = rhs; children.length = 1; return climbAllParents(node, context); } else if (rule.type === SEQUENCE) { if (children[0].state === INCOMPLETE) return; // If we have two children, there is no more advancing left to do. // We simply have to decide if we succeeded or failed. if (children.length === 2) { node.state = children[1].state; return climbAllParents(node, context); } // If not, then see whether the first one failed... if (children[0].state === FAIL) { node.state = FAIL; return climbAllParents(node, context); } // If it succeeded, then fall down again... children[1] = fall(node, node.rule.children[1], context); } else if (rule.type === NOT) { var child = children[0]; if (child.state === INCOMPLETE) return; node.state = (child.state === FAIL ? SUCCESS : FAIL); return climbAllParents(node, context); } else if (rule.type === NAME) { var child = children[0]; if (child.state === INCOMPLETE) return; node.state = child.state; return climbAllParents(node, context); } } function parse(context, character) { var incomplete = context.incomplete; var placeholderParents = context.placeholderParents; var newContext = new Context(context); var UID; for (UID in placeholderParents) if (hasOwnProperty.call(placeholderParents, UID)) { var parent = placeholderParents[UID], children = parent.children, index = 0, count = children.length; for (; index < count; ++index) if (children[index] === PLACEHOLDER) if (character === EOF) children[index] = FAILURE_NODE; else children[index] = fall(parent, parent.rule.children[index], newContext); climb(parent, newContext); } for (UID in incomplete) if (hasOwnProperty.call(incomplete, UID)) { var node = incomplete[UID]; node.state = node.rule === -1 || character === node.rule ? SUCCESS : FAIL; climbAllParents(node, newContext); } return newContext; } /* // ADOPTION // gotta get up and try and try and try //carry onnnn the sound may your touch the ground // r = (bc / b) d // r = (bc d / b d) // r = (;_set) - (choice(bc) d) // = - (choice(b) d) // algo: // (not? pred?) // climb to seq take remaining, append. // r = choice hold(bc) -> seq _next_ // hold(b) -> seq _next_ // a (c / d) b // a ((c) b / (d) b) /* if (rule.type === CHOICE) { var index = 0, count = children.length; for (; index < count; ++index) { var child = children[index]; // Can't know yet. if (child.state === INCOMPLETE) return; if (child.state === SUCCESS) { node.state = SUCCESS; children[0] = child; children.length = 1; return climbAllParents(node, context); } // By this point, there can only be FAILUREs behind us... if (child.state === FAILURE && index === count - 1) { node.state = FAILURE; children.length = 0; return climbAllParents(node, context); } } return; } if (rule.type === CHOICE) { var index = 0, count = children.length; for (; index < count; ++index) { var child = children[index]; // Can't know yet. if (child.state === INCOMPLETE) return; if (child.state === SUCCESS) { node.state = SUCCESS; children[0] = child; children.length = 1; return climbAllParents(node, context); } // By this point, there can only be FAILUREs behind us... if (child.state === FAILURE && index === count - 1) { node.state = FAILURE; children.length = 0; return climbAllParents(node, context); } } return; } if (rule.type === SEQUENCE) { var index = 0, count = children.length; for (; index < count; ++index) { var child = children[index]; // Can't know yet. if (child.state === INCOMPLETE) return; if (child.state === FAILURE) { node.state = FAILURE; children.length = 0; return climbAllParents(node, context); } } node.state = SUCCESS; children[0] = children[children.length - 1]; return climbAllParents(node, context); } { node.state = SUCCESS; children[0] = child; children.length = 1; return climbAllParents(node, context); } // By this point, there can only be FAILUREs behind us... if (child.state === FAILURE && index === count - 1) { node.state = FAILURE; children.length = 0; return climbAllParents(node, context); } } } */
languages/Objective-J/stab.js
var hasOwnProperty = Object.prototype.hasOwnProperty; // start = (("a" "a") "a") "b") / // (("a" "a") "a") !"d" "c") // A? // R = A / "" // A* // U = A / "" // R = U / R // A+ // var CHARACTER = 0, CHOICE = 1, SEQUENCE = 2, NOT = 3, AND = 4, DOT = -1; var FAIL = 0, SUCCESS = 2, INCOMPLETE = 3; var EOF = { }, PLACEHOLDER = { }, FAILURE_NODE = { state:FAIL }; /* function Context(aContext) { if (aC }*/ var context = { rules : { 0: { UID:0, type:CHOICE, children:["a", 1] }, 1: { UID:1, type:SEQUENCE, children:[0, "a"] } }, incomplete: { }, cache: { }, recursive: { }, index: -1, placeholderParents: { } }; /* var context = { rules : { 0: { UID:0, type:CHOICE, children:[1, 2] }, 1: { UID:1, type:SEQUENCE, children:[3, "b"] }, 2: { UID:2, type:SEQUENCE, children:[3, 5] }, 3: { UID:3, type:SEQUENCE, children:[4, "a"] }, 4: { UID:4, type:SEQUENCE, children:["a", "a"] }, 5: { UID:5, type:AND, children:[6, -1] }, 6: { UID:6, type:NOT, children:["d"] } }, incomplete: { }, cache: { } };*/ var start = fall(null, 0, context); var source = "aaaa", index = 0, count = source.length; print_node(start); for (; index < count; ++index) { console.log("+++++DOING " + source[index]); context = parse(context, source[index]); //console.log(context); print_node(start); } console.log("+++++DOING EOF"); context = parse(context, EOF); print_node(start); function print_node(node, indentation, prints) { indentation = indentation || ""; prints = prints || { }; if (node === PLACEHOLDER) return console.log(indentation + " PLACEHOLDER"); if (prints[node.UID] === 2) return; else if (prints[node.UID] === 1) prints[node.UID] += 1; else prints[node.UID] = 1; var rule = node.rule; if (typeof rule === "string") console.log(indentation + rule + " [" + node.state + "]"); else if (rule === -1) console.log(indentation + "DOT " + node.UID); else if (rule.type === CHOICE) console.log(indentation + "CHOICE " + node.UID + " [" + node.state + "]"); else if (rule.type === SEQUENCE) console.log(indentation + "SEQUENCE " + node.UID + " [" + node.state + "]"); else if (rule.type === NOT) console.log(indentation + "NOT " + node.UID); else if (rule.type === AND) console.log(indentation + "AND " + node.UID); for (var index = 0, count = node.children.length; index < count; ++index) print_node(node.children[index], indentation + " ", prints); prints[node.UID]--; } function fall(parent, ruleUID, context) { var UID = ruleUID + " " + context.index, recursive = context.recursive; if (recursive[UID]) {console.log("did it..."); context.placeholderParents[parent.UID] = parent; return PLACEHOLDER; } var rule = context.rules[ruleUID] || ruleUID, cache = context.cache, node = cache[UID] || { UID:UID, state:INCOMPLETE, rule:rule, parents:{ }, children:[] }; // Only add this parent if we haven't already accounted for it. // This accounts for the user doing something silly like A / A if (parent && !hasOwnProperty.call(node.parents, parent.UID)) node.parents[parent.UID] = parent; // If it's cached, we've already worked this one out. if (cache[UID]) return node; // Add this to the cache. cache[UID] = node; // If this is a character, there is nothing we can do during the fall stage. // Simply store it in the incomplete hash and return. if (typeof rule === "string" || rule === -1) { // The empty string always trivially succeeds, and consumes no input. if (rule === "") climb(node, context); else context.incomplete[UID] = node; return node; } // Before handling our children, make sure we register ourselves so we don't get handled again. recursive[UID] = node; // We always want to fill in the first child. node.children[0] = fall(node, node.rule.children[0], context); // But only the second if this is a CHOICE or and AND. if (rule.type === CHOICE || rule.type === AND) node.children[1] = fall(node, node.rule.children[1], context); // Now unregister ourselves. delete recursive[UID]; return node; } function climbAllParents(node, context) { var parents = node.parents; for (UID in parents) if (hasOwnProperty.call(parents, UID)) climb(parents[UID], context); } function climb(node, context) { if (node.state !== INCOMPLETE) return; var children = node.children, rule = node.rule; if (rule.type === CHOICE) { var lhs = children[0]; // No matter what, if the first one is incomplete, we can't make a decision. if (lhs.state === INCOMPLETE) return; // If not, and this was our ONLY child, or it was successful, // then our state is now it's state and we can keep climbing. if (children.length === 1 || lhs.state === SUCCESS) { children.length = 1; node.state = lhs.state; return climbAllParents(node, context); } // Now we know for sure that we have 2 children AND the first was a failure, // so its all on rhs. var rhs = children[1]; // Same as before, keep waiting. if (rhs.state === INCOMPLETE) return; // From now on, we know we have a result, either success of fail. node.state = rhs.state; // If we succeeded, do a little accounting to make rhs our only child. if (rhs.state === SUCCESS) { children[0] = rhs; children.length = 1; } else children.length = 0; return climbAllParents(node, context); } else if (rule.type === AND) { var lhs = children[0], rhs = children[1]; // We have to know the result of both to continue. if (lhs.state === INCOMPLETE || rhs.state === INCOMPLETE) return; // If our first child (the "predicate") fails, then we fail. // Both must succeed to succeed as a whole. node.state = (lhs.state === SUCCESS && rhs.state === SUCCESS) ? SUCCESS : FAIL; children[0] = rhs; children.length = 1; return climbAllParents(node, context); } else if (rule.type === SEQUENCE) { if (children[0].state === INCOMPLETE) return; // If we have two children, there is no more advancing left to do. // We simply have to decide if we succeeded or failed. if (children.length === 2) { node.state = children[1].state; return climbAllParents(node, context); } // If not, then see whether the first one failed... if (children[0].state === FAIL) { node.state = FAIL; return climbAllParents(node, context); } // If it succeeded, then fall down again... children[1] = fall(node, node.rule.children[1], context); } else if (rule.type === NOT) { var child = children[0]; if (child.state === INCOMPLETE) return; node.state = (child.state === FAIL ? SUCCESS : FAIL); return climbAllParents(node, context); } } function parse(context, character) { var incomplete = context.incomplete; var newContext = { rules:context.rules, incomplete:{ }, cache:{ }, index:context.index + 1, recursive:{ }, placeholderParents:{ } }; var placeholderParents = context.placeholderParents; var UID; for (UID in placeholderParents) if (hasOwnProperty.call(placeholderParents, UID)) { var parent = placeholderParents[UID], children = parent.children, index = 0, count = children.length; for (; index < count; ++index) if (children[index] === PLACEHOLDER) if (character === EOF) children[index] = FAILURE_NODE; else children[index] = fall(parent, parent.rule.children[index], newContext); climb(parent, newContext); } for (UID in incomplete) if (hasOwnProperty.call(incomplete, UID)) { var node = incomplete[UID]; node.state = node.rule === -1 || character === node.rule ? SUCCESS : FAIL; climbAllParents(node, newContext); } return newContext; }
Some cleanup in preparation for more than 2 sequences/choices. Reviewed by @tolmasky.
languages/Objective-J/stab.js
Some cleanup in preparation for more than 2 sequences/choices.
<ide><path>anguages/Objective-J/stab.js <ide> // U = A / "" <ide> // R = U / R <ide> // A+ <del>// <add>// <ide> <ide> var CHARACTER = 0, <ide> CHOICE = 1, <ide> SEQUENCE = 2, <ide> NOT = 3, <ide> AND = 4, <add> NAME = 5, <ide> DOT = -1; <ide> <ide> var FAIL = 0, <ide> var EOF = { }, <ide> PLACEHOLDER = { }, <ide> FAILURE_NODE = { state:FAIL }; <add> <add>function Context(aContext, rules) <add>{ <add> this.rules = rules; <add> this.incomplete = { }; <add> this.cache = { }; <add> this.recursive = { }; <add> this.index = -1; <add> this.placeholderParents = { }; <add> <add> if (aContext) <add> { <add> this.rules = aContext.rules; <add> this.index = aContext.index + 1; <add> } <add>} <add> <ide> /* <del>function Context(aContext) <del>{ <del> if (aC <del>}*/ <del> <del>var context = <del>{ <del> rules : { <del> 0: { UID:0, type:CHOICE, children:["a", 1] }, <del> 1: { UID:1, type:SEQUENCE, children:[0, "a"] } <del> }, <del> incomplete: { }, <del> cache: { }, <del> recursive: { }, <del> index: -1, <del> placeholderParents: { } <del>}; <add>// r = (bcc / b) cd <add>var rules = { <add> 0: { UID:0, type:SEQUENCE, children:[2, 1] }, <add> 1: { UID:1, type:SEQUENCE, children:["c", "d"] }, <add> 2: { UID:2, type:CHOICE, children:[3, "b"] }, <add> 3: { UID:3, type:SEQUENCE, children:["b", 4] }, <add> 4: { UID:4, type:SEQUENCE, children:["c", "c"] } <add> }; <add>var source = "bcd"; <add> <add>// r = (bc / b) d <add>var rules = { <add> 0: { UID:0, type:SEQUENCE, children:[1 ,"d"] }, <add> 1: { UID:1, type:CHOICE, children:[2, "b"] }, <add> 2: { UID:2, type:SEQUENCE, children:["b", "c"] } <add> }; <add>var source = "bcd"; <add>*/ <add>// A = A a / a <add>var rules = { <add> 0: { UID:0, type:NAME, children:[1], name:"start" }, <add> 1: { UID:1, type:CHOICE, children:[2, "a"] }, <add> 2: { UID:2, type:SEQUENCE, children:[1, "a"] } <add> }; <add>var source = "aaaa"; <add> <ide> /* <del>var context = <del>{ <del> rules : { <add>var rules = { <ide> 0: { UID:0, type:CHOICE, children:[1, 2] }, <ide> 1: { UID:1, type:SEQUENCE, children:[3, "b"] }, <ide> 2: { UID:2, type:SEQUENCE, children:[3, 5] }, <ide> 4: { UID:4, type:SEQUENCE, children:["a", "a"] }, <ide> 5: { UID:5, type:AND, children:[6, -1] }, <ide> 6: { UID:6, type:NOT, children:["d"] } <del> }, <del> incomplete: { }, <del> cache: { } <del>};*/ <del> <add> }; <add>var source = "aaac"; <add>*/ <add> <add>var context = new Context(null, rules); <ide> var start = fall(null, 0, context); <ide> <del>var source = "aaaa", <del> index = 0, <add>var index = 0, <ide> count = source.length; <ide> <ide> print_node(start); <ide> else if (rule.type === AND) <ide> console.log(indentation + "AND " + node.UID); <ide> <add> else if (rule.type === NAME) <add> console.log(indentation + "NAME " + node.UID + " " + node.name); <add> <ide> for (var index = 0, count = node.children.length; index < count; ++index) <ide> print_node(node.children[index], indentation + " ", prints); <ide> <ide> recursive = context.recursive; <ide> <ide> if (recursive[UID]) <del> {console.log("did it..."); <add> { <ide> context.placeholderParents[parent.UID] = parent; <ide> <ide> return PLACEHOLDER; <ide> return node; <ide> } <ide> <add> if (rule.type === NAME) <add> node.name = rule.name; <add> <ide> // Before handling our children, make sure we register ourselves so we don't get handled again. <ide> recursive[UID] = node; <ide> <del> // We always want to fill in the first child. <del> node.children[0] = fall(node, node.rule.children[0], context); <del> <del> // But only the second if this is a CHOICE or and AND. <del> if (rule.type === CHOICE || rule.type === AND) <del> node.children[1] = fall(node, node.rule.children[1], context); <add> if (rule.type === SEQUENCE) <add> node.children[0] = fall(node, rule.children[0], context); <add> else <add> node.children = rule.children.map(function (child) { return fall(node, child, context); }); <ide> <ide> // Now unregister ourselves. <ide> delete recursive[UID]; <ide> } <ide> <ide> // If it succeeded, then fall down again... <del> children[1] = fall(node, node.rule.children[1], context); <add> children[1] = fall(node, node.rule.children[1], context); <ide> } <ide> <ide> else if (rule.type === NOT) <ide> <ide> return climbAllParents(node, context); <ide> } <add> <add> else if (rule.type === NAME) <add> { <add> var child = children[0]; <add> <add> if (child.state === INCOMPLETE) <add> return; <add> <add> node.state = child.state; <add> <add> return climbAllParents(node, context); <add> } <ide> } <ide> <ide> function parse(context, character) <ide> { <ide> var incomplete = context.incomplete; <del> var newContext = { rules:context.rules, incomplete:{ }, cache:{ }, index:context.index + 1, recursive:{ }, placeholderParents:{ } }; <ide> var placeholderParents = context.placeholderParents; <add> var newContext = new Context(context); <ide> var UID; <ide> <ide> for (UID in placeholderParents) <ide> return newContext; <ide> } <ide> <add>/* <add>// ADOPTION <add>// gotta get up and try and try and try <add>//carry onnnn the sound may your touch the ground <add>// r = (bc / b) d <add>// r = (bc d / b d) <add>// r = (;_set) - (choice(bc) d) <add>// = - (choice(b) d) <add>// algo: <add>// (not? pred?) <add>// climb to seq take remaining, append. <add>// r = choice hold(bc) -> seq _next_ <add>// hold(b) -> seq _next_ <add>// a (c / d) b <add>// a ((c) b / (d) b) <add>/* <add> if (rule.type === CHOICE) <add> { <add> var index = 0, <add> count = children.length; <add> <add> for (; index < count; ++index) <add> { <add> var child = children[index]; <add> <add> // Can't know yet. <add> if (child.state === INCOMPLETE) <add> return; <add> <add> if (child.state === SUCCESS) <add> { <add> node.state = SUCCESS; <add> <add> children[0] = child; <add> children.length = 1; <add> <add> return climbAllParents(node, context); <add> } <add> <add> // By this point, there can only be FAILUREs behind us... <add> if (child.state === FAILURE && index === count - 1) <add> { <add> node.state = FAILURE; <add> <add> children.length = 0; <add> <add> return climbAllParents(node, context); <add> } <add> } <add> <add> return; <add> } <add> <add> if (rule.type === CHOICE) <add> { <add> var index = 0, <add> count = children.length; <add> <add> for (; index < count; ++index) <add> { <add> var child = children[index]; <add> <add> // Can't know yet. <add> if (child.state === INCOMPLETE) <add> return; <add> <add> if (child.state === SUCCESS) <add> { <add> node.state = SUCCESS; <add> <add> children[0] = child; <add> children.length = 1; <add> <add> return climbAllParents(node, context); <add> } <add> <add> // By this point, there can only be FAILUREs behind us... <add> if (child.state === FAILURE && index === count - 1) <add> { <add> node.state = FAILURE; <add> <add> children.length = 0; <add> <add> return climbAllParents(node, context); <add> } <add> } <add> <add> return; <add> } <add> <add> if (rule.type === SEQUENCE) <add> { <add> var index = 0, <add> count = children.length; <add> <add> for (; index < count; ++index) <add> { <add> var child = children[index]; <add> <add> // Can't know yet. <add> if (child.state === INCOMPLETE) <add> return; <add> <add> if (child.state === FAILURE) <add> { <add> node.state = FAILURE; <add> children.length = 0; <add> <add> return climbAllParents(node, context); <add> } <add> } <add> <add> node.state = SUCCESS; <add> children[0] = children[children.length - 1]; <add> <add> return climbAllParents(node, context); <add> } <add> <add> { <add> node.state = SUCCESS; <add> children[0] = child; <add> children.length = 1; <add> <add> return climbAllParents(node, context); <add> } <add> <add> // By this point, there can only be FAILUREs behind us... <add> if (child.state === FAILURE && index === count - 1) <add> { <add> node.state = FAILURE; <add> children.length = 0; <add> <add> return climbAllParents(node, context); <add> } <add> } <add> } <add> <add>*/
Java
apache-2.0
570c57d8237dcad73bcccae3716016b2f47b21dc
0
vector-im/vector-android,vector-im/riot-android,noepitome/neon-android,floviolleau/vector-android,vector-im/vector-android,vector-im/riot-android,noepitome/neon-android,riot-spanish/riot-android,floviolleau/vector-android,noepitome/neon-android,riot-spanish/riot-android,vector-im/vector-android,vt0r/vector-android,vector-im/riot-android,vector-im/vector-android,vector-im/riot-android,riot-spanish/riot-android,vt0r/vector-android,vector-im/riot-android,noepitome/neon-android,vt0r/vector-android,riot-spanish/riot-android,floviolleau/vector-android
/* * Copyright 2015 OpenMarket Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.activity; import android.annotation.SuppressLint; import android.app.FragmentManager; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.text.TextUtils; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBar.TabListener; import android.widget.Toast; import org.matrix.androidsdk.MXSession; import org.matrix.androidsdk.fragments.MatrixMessageListFragment; import im.vector.Matrix; import im.vector.R; import im.vector.fragments.VectorMessagesSearchResultsListFragment; import im.vector.fragments.VectorRoomsSearchResultsListFragment; /** * Displays a generic activity search method */ public class VectorUnifiedSearchActivity extends MXCActionBarActivity implements TabListener { private static final String LOG_TAG = "VectorUniSrchActivity"; public static final CharSequence NOT_IMPLEMENTED = "Not yet implemented"; // tab related items private static final String TAG_FRAGMENT_SEARCH_IN_MESSAGE = "im.vector.activity.TAG_FRAGMENT_SEARCH_IN_MESSAGE"; private static final String TAG_FRAGMENT_SEARCH_IN_ROOM_NAMES = "im.vector.activity.TAG_FRAGMENT_SEARCH_IN_ROOM_NAMES"; private static final String TAG_FRAGMENT_SEARCH_PEOPLE = "im.vector.activity.TAG_FRAGMENT_SEARCH_PEOPLE"; private static final String TAG_FRAGMENT_SEARCH_IN_FILES = "im.vector.activity.TAG_FRAGMENT_SEARCH_IN_FILES"; private int mSearchInRoomNamesTabIndex = -1; private int mSearchInMessagesTabIndex = -1; private int mSearchInPeopleTabIndex = -1; private int mSearchInFilesTabIndex = -1; private int mCurrentTabIndex = -1; ActionBar mActionBar; // activity life cycle management: // - Bundle keys private static final String KEY_STATE_CURRENT_TAB_INDEX = "CURRENT_SELECTED_TAB"; private static final String KEY_STATE_IS_BACKGROUND_ROOMS_TAB = "IS_BACKGROUND_ROOMS_TAB"; private static final String KEY_STATE_IS_BACKGROUND_MESSAGES_TAB = "IS_BACKGROUND_MESSAGES_TAB"; private static final String KEY_STATE_IS_BACKGROUND_PEOPLE_TAB = "IS_BACKGROUND_PEOPLE_TAB"; private static final String KEY_STATE_IS_BACKGROUND_FILES_TAB = "IS_BACKGROUND_FILES_TAB"; private static final String KEY_STATE_SEARCH_PATTERN_MESSAGES_TAB = "SEARCH_PATTERN_MESSAGES"; private static final String KEY_STATE_SEARCH_PATTERN_ROOMS_TAB = "SEARCH_PATTERN_ROOMS"; private static final String KEY_STATE_SEARCH_PATTERN_PEOPLE_TAB = "SEARCH_PATTERN_PEOPLE"; private static final String KEY_STATE_SEARCH_PATTERN_FILES_TAB = "SEARCH_PATTERN_FILES"; // search fragments private VectorMessagesSearchResultsListFragment mSearchInMessagesFragment; private VectorRoomsSearchResultsListFragment mSearchInRoomNamesFragment; private VectorMessagesSearchResultsListFragment mSearchInFilesFragment; private VectorMessagesSearchResultsListFragment mSearchInPeopleFragment; private MXSession mSession; // UI items private ImageView mBackgroundImageView; private TextView mNoResultsTxtView; private View mWaitWhileSearchInProgressView; private EditText mPatternToSearchEditText; private static class TabListenerHolder { public final String mFragmentTag; //public final int mContainerId; public Fragment mTabFragment; public int mBackgroundVisibility; public int mNoResultsTxtViewVisibility; public String mSearchedPattern; public TabListenerHolder(String aTabTag, int aBackgroundVisibility, int aNoResultsVisibility, String aSearchPattern) { mFragmentTag = aTabTag; mNoResultsTxtViewVisibility = aNoResultsVisibility; mBackgroundVisibility = aBackgroundVisibility; mSearchedPattern = aSearchPattern; } } @Override protected void onCreate(Bundle savedInstanceState) { if (CommonActivityUtils.shouldRestartApp()) { Log.e(LOG_TAG, "Restart the application."); CommonActivityUtils.restartApp(this); } super.onCreate(savedInstanceState); setContentView(R.layout.activity_vector_unified_search); // the session should be passed in parameter // but the current design does not describe how the multi accounts will be managed. mSession = Matrix.getInstance(this).getDefaultSession(); if (mSession == null) { Log.e(LOG_TAG, "No MXSession."); finish(); return; } // UI widgets binding & init fields mBackgroundImageView = (ImageView)findViewById(R.id.search_background_imageview); mNoResultsTxtView = (TextView)findViewById(R.id.search_no_result_textview); mWaitWhileSearchInProgressView = findViewById(R.id.search_in_progress_view); mActionBar = getSupportActionBar(); // customize the action bar with a custom view to contain the search input text View actionBarView = customizeActionBar(); // add the search logic based on the text search input listener mPatternToSearchEditText = (EditText) actionBarView.findViewById(R.id.room_action_bar_edit_text); actionBarView.postDelayed(new Runnable() { @Override public void run() { mPatternToSearchEditText.requestFocus(); InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); im.showSoftInput(mPatternToSearchEditText, 0); } }, 100); mPatternToSearchEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEARCH) { // start the search according to the current selected tab searchAccordingToTabHandler(); return true; } return false; } }); // tab creation and restore tabs UI context createNavigationTabs(savedInstanceState); } @Override public void onDestroy() { super.onDestroy(); Log.d(LOG_TAG, "## onDestroy(): "); } @Override protected void onResume() { super.onResume(); Log.d(LOG_TAG, "## onResume(): "); searchAccordingToTabHandler(); } /** * Reset the UI to its init state: * - "waiting while searching" screen disabled * - background image visible * - no results message disabled */ private void resetUi() { // stop "wait while searching" screen if (null != mWaitWhileSearchInProgressView) { mWaitWhileSearchInProgressView.setVisibility(View.GONE); } // display the background if (null != mBackgroundImageView) { mBackgroundImageView.setVisibility(View.VISIBLE); } if (null != mNoResultsTxtView) { mNoResultsTxtView.setVisibility(View.GONE); } } /** * The search is done. * @param tabIndex the tab index * @param nbrMessages the number of found messages. */ private void onSearchEnd(int tabIndex, int nbrMessages) { if (mCurrentTabIndex == tabIndex) { Log.d(LOG_TAG, "## onSearchEnd() nbrMsg=" + nbrMessages); // stop "wait while searching" screen mWaitWhileSearchInProgressView.setVisibility(View.GONE); // display the background only if there is no result if (0 == nbrMessages) { mBackgroundImageView.setVisibility(View.VISIBLE); } else { mBackgroundImageView.setVisibility(View.GONE); } // display the "no result" text only if the researched text is not empty mNoResultsTxtView.setVisibility(((0 == nbrMessages) && !TextUtils.isEmpty(mPatternToSearchEditText.getText().toString())) ? View.VISIBLE : View.GONE); } } /** * Called by the fragments when they are resumed. * It is used to refresh the search while playing with the tab. */ public void onSearchFragmentResume() { searchAccordingToTabHandler(); } /** * Update the tag of the current tab with its UI values */ private void saveCurrentUiTabContext() { if(-1 != mCurrentTabIndex) { ActionBar.Tab currentTab = mActionBar.getTabAt(mCurrentTabIndex); TabListenerHolder tabTag = (TabListenerHolder) currentTab.getTag(); tabTag.mBackgroundVisibility = mBackgroundImageView.getVisibility(); tabTag.mNoResultsTxtViewVisibility = mNoResultsTxtView.getVisibility(); tabTag.mSearchedPattern = mPatternToSearchEditText.getText().toString(); currentTab.setTag(tabTag); } } /** * Update the tag of the tab with its the UI values * @param aTabToUpdate the tab to be updated */ private void saveUiTabContext(ActionBar.Tab aTabToUpdate) { TabListenerHolder tabTag = (TabListenerHolder) aTabToUpdate.getTag(); tabTag.mBackgroundVisibility = mBackgroundImageView.getVisibility(); tabTag.mNoResultsTxtViewVisibility = mNoResultsTxtView.getVisibility(); tabTag.mSearchedPattern = mPatternToSearchEditText.getText().toString(); aTabToUpdate.setTag(tabTag); } /** * Restore the UI context associated with the tab * @param aTabToRestore the tab to be restored */ private void restoreUiTabContext(ActionBar.Tab aTabToRestore) { TabListenerHolder tabTag = (TabListenerHolder) aTabToRestore.getTag(); mBackgroundImageView.setVisibility(tabTag.mBackgroundVisibility); mNoResultsTxtView.setVisibility(tabTag.mNoResultsTxtViewVisibility); mPatternToSearchEditText.setText(tabTag.mSearchedPattern); } private void searchAccordingToTabHandler() { int currentIndex = mActionBar.getSelectedNavigationIndex(); resetUi(); String pattern = mPatternToSearchEditText.getText().toString(); if((currentIndex == mSearchInRoomNamesTabIndex) && (null != mSearchInRoomNamesFragment)) { if (mSearchInRoomNamesFragment.isAdded()) { // display the "wait while searching" screen (progress bar) mWaitWhileSearchInProgressView.setVisibility(View.VISIBLE); mSearchInRoomNamesFragment.searchPattern(pattern, new MatrixMessageListFragment.OnSearchResultListener() { @Override public void onSearchSucceed(int nbrMessages) { onSearchEnd(mSearchInRoomNamesTabIndex, nbrMessages); } @Override public void onSearchFailed() { onSearchEnd(mSearchInRoomNamesTabIndex, 0); } }); } } else if((currentIndex == mSearchInMessagesTabIndex) && (null != mSearchInMessagesFragment)) { if (mSearchInMessagesFragment.isAdded()) { // display the "wait while searching" screen (progress bar) mWaitWhileSearchInProgressView.setVisibility(View.VISIBLE); mSearchInMessagesFragment.searchPattern(pattern, new MatrixMessageListFragment.OnSearchResultListener() { @Override public void onSearchSucceed(int nbrMessages) { onSearchEnd(mSearchInMessagesTabIndex, nbrMessages); } @Override public void onSearchFailed() { onSearchEnd(mSearchInMessagesTabIndex, 0); } }); } else { mWaitWhileSearchInProgressView.setVisibility(View.GONE); } } else { onSearchEnd(currentIndex, 0); Toast.makeText(VectorUnifiedSearchActivity.this, NOT_IMPLEMENTED, Toast.LENGTH_SHORT).show(); } } /** * Add a custom action bar with a view * @return the action bar inflated view */ private View customizeActionBar() { mActionBar.setDisplayShowCustomEnabled(true); mActionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_HOME_AS_UP); // add a custom action bar view containing an EditText to input the search text ActionBar.LayoutParams layout = new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT); View actionBarLayout = getLayoutInflater().inflate(R.layout.vector_search_action_bar, null); mActionBar.setCustomView(actionBarLayout, layout); return actionBarLayout; } //============================================================================================================== // Tabs logic implementation //============================================================================================================== /** * Create the search fragment instances from the saved instance; * @param aSavedInstanceState the saved instance. */ private void createNavigationTabs(Bundle aSavedInstanceState) { int tabIndex = 0; int tabIndexToRestore; int isBackroundDisplayed; String searchPattern; // Set the tabs navigation mode mActionBar.setNavigationMode(android.support.v7.app.ActionBar.NAVIGATION_MODE_TABS); // ROOMS names search tab creation android.support.v7.app.ActionBar.Tab tabToBeadded = mActionBar.newTab(); String tabTitle = getResources().getString(R.string.tab_title_search_rooms); tabToBeadded.setText(tabTitle); tabToBeadded.setTabListener(this); isBackroundDisplayed = (null != aSavedInstanceState)?aSavedInstanceState.getInt(KEY_STATE_IS_BACKGROUND_ROOMS_TAB, View.VISIBLE):View.VISIBLE; searchPattern = (null != aSavedInstanceState)?aSavedInstanceState.getString(KEY_STATE_SEARCH_PATTERN_ROOMS_TAB,""):""; tabToBeadded.setTag(new TabListenerHolder(TAG_FRAGMENT_SEARCH_IN_ROOM_NAMES, isBackroundDisplayed, View.GONE, searchPattern)); mActionBar.addTab(tabToBeadded); mSearchInRoomNamesTabIndex = tabIndex++; // MESSAGES search tab creation tabToBeadded = mActionBar.newTab(); tabTitle = getResources().getString(R.string.tab_title_search_messages); tabToBeadded.setText(tabTitle); tabToBeadded.setTabListener(this); isBackroundDisplayed = (null != aSavedInstanceState)?aSavedInstanceState.getInt(KEY_STATE_IS_BACKGROUND_MESSAGES_TAB, View.VISIBLE):View.VISIBLE; searchPattern = (null != aSavedInstanceState)?aSavedInstanceState.getString(KEY_STATE_SEARCH_PATTERN_MESSAGES_TAB,""):""; tabToBeadded.setTag(new TabListenerHolder(TAG_FRAGMENT_SEARCH_IN_MESSAGE, isBackroundDisplayed, View.GONE, searchPattern)); mActionBar.addTab(tabToBeadded); mSearchInMessagesTabIndex = tabIndex++; // PEOPLE search tab creation tabToBeadded = mActionBar.newTab(); tabTitle = getResources().getString(R.string.tab_title_search_people); tabToBeadded.setText(tabTitle); tabToBeadded.setTabListener(this); isBackroundDisplayed = (null != aSavedInstanceState)?aSavedInstanceState.getInt(KEY_STATE_IS_BACKGROUND_PEOPLE_TAB, View.VISIBLE):View.VISIBLE; searchPattern = (null != aSavedInstanceState)?aSavedInstanceState.getString(KEY_STATE_SEARCH_PATTERN_PEOPLE_TAB,""):""; tabToBeadded.setTag(new TabListenerHolder(TAG_FRAGMENT_SEARCH_PEOPLE, isBackroundDisplayed, View.GONE, searchPattern)); mActionBar.addTab(tabToBeadded); mSearchInPeopleTabIndex = tabIndex++; // FILES search tab creation tabToBeadded = mActionBar.newTab(); tabTitle = getResources().getString(R.string.tab_title_search_files); tabToBeadded.setText(tabTitle); tabToBeadded.setTabListener(this); isBackroundDisplayed = (null != aSavedInstanceState)?aSavedInstanceState.getInt(KEY_STATE_IS_BACKGROUND_FILES_TAB, View.VISIBLE):View.VISIBLE; searchPattern = (null != aSavedInstanceState)?aSavedInstanceState.getString(KEY_STATE_SEARCH_PATTERN_FILES_TAB,""):""; tabToBeadded.setTag(new TabListenerHolder(TAG_FRAGMENT_SEARCH_IN_FILES, isBackroundDisplayed, View.GONE, searchPattern)); mActionBar.addTab(tabToBeadded); mSearchInFilesTabIndex = tabIndex++; // set the default tab to be displayed tabIndexToRestore = (null != aSavedInstanceState)?aSavedInstanceState.getInt(KEY_STATE_CURRENT_TAB_INDEX, 0) : 0; if(-1 == tabIndexToRestore) { // default value: display the search in rooms tab tabIndexToRestore = mSearchInRoomNamesTabIndex; } mCurrentTabIndex = tabIndexToRestore; // set the tab to display mActionBar.setSelectedNavigationItem(tabIndexToRestore); } @Override public void onTabSelected(android.support.v7.app.ActionBar.Tab tab, android.support.v4.app.FragmentTransaction ft) { TabListenerHolder tabListenerHolder = (TabListenerHolder) tab.getTag(); Log.d(LOG_TAG, "## onTabSelected() FragTag=" + tabListenerHolder.mFragmentTag); // clear any displayed windows resetUi(); // inter tab selection life cycle: restore tab UI restoreUiTabContext(tab); if (tabListenerHolder.mFragmentTag.equals(TAG_FRAGMENT_SEARCH_IN_ROOM_NAMES)) { if (null == mSearchInRoomNamesFragment) { mSearchInRoomNamesFragment = VectorRoomsSearchResultsListFragment.newInstance(mSession.getMyUser().userId, R.layout.fragment_vector_recents_list); ft.replace(R.id.search_fragment_container, mSearchInRoomNamesFragment, tabListenerHolder.mFragmentTag); Log.d(LOG_TAG, "## onTabSelected() SearchInRoomNames frag added"); } else { ft.attach(mSearchInRoomNamesFragment); Log.d(LOG_TAG, "## onTabSelected() SearchInRoomNames frag attach"); } mCurrentTabIndex = mSearchInRoomNamesTabIndex; } else if (tabListenerHolder.mFragmentTag.equals(TAG_FRAGMENT_SEARCH_IN_MESSAGE)) { if (null == mSearchInMessagesFragment) { mSearchInMessagesFragment = VectorMessagesSearchResultsListFragment.newInstance(mSession.getMyUser().userId, org.matrix.androidsdk.R.layout.fragment_matrix_message_list_fragment); ft.replace(R.id.search_fragment_container, mSearchInMessagesFragment, tabListenerHolder.mFragmentTag); Log.d(LOG_TAG, "## onTabSelected() SearchInMessages frag added"); } else { ft.attach(mSearchInMessagesFragment); Log.d(LOG_TAG, "## onTabSelected() SearchInMessages frag added"); } mCurrentTabIndex = mSearchInMessagesTabIndex; } else if (tabListenerHolder.mFragmentTag.equals(TAG_FRAGMENT_SEARCH_PEOPLE)) { mCurrentTabIndex = mSearchInPeopleTabIndex; } else if (tabListenerHolder.mFragmentTag.equals(TAG_FRAGMENT_SEARCH_IN_FILES)) { mCurrentTabIndex = mSearchInFilesTabIndex; } if (-1 != mCurrentTabIndex) { searchAccordingToTabHandler(); } } @Override public void onTabUnselected(android.support.v7.app.ActionBar.Tab tab, android.support.v4.app.FragmentTransaction ft) { TabListenerHolder tabListenerHolder = (TabListenerHolder) tab.getTag(); Log.d(LOG_TAG, "## onTabUnselected() FragTag=" + tabListenerHolder.mFragmentTag); // save tab UI context before leaving the tab... saveUiTabContext(tab); if(tabListenerHolder.mFragmentTag.equals(TAG_FRAGMENT_SEARCH_IN_MESSAGE)) { if(null != mSearchInMessagesFragment) { ft.detach(mSearchInMessagesFragment); } } else if(tabListenerHolder.mFragmentTag.equals(TAG_FRAGMENT_SEARCH_IN_ROOM_NAMES) ){ if(null != mSearchInRoomNamesFragment) { ft.detach(mSearchInRoomNamesFragment); } } } @Override public void onTabReselected(android.support.v7.app.ActionBar.Tab tab, FragmentTransaction ft) { } //============================================================================================================== // Life cycle Activity methods //============================================================================================================== @SuppressLint("LongLogTag") @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); Log.d(LOG_TAG, "## onSaveInstanceState(): "); // save current tab int currentIndex = mActionBar.getSelectedNavigationIndex(); outState.putInt(KEY_STATE_CURRENT_TAB_INDEX, currentIndex); // save background visibility for each tab (could be optimized) int visibility = ((TabListenerHolder)mActionBar.getTabAt(mSearchInRoomNamesTabIndex).getTag()).mBackgroundVisibility; outState.putInt(KEY_STATE_IS_BACKGROUND_ROOMS_TAB, visibility); visibility = ((TabListenerHolder)mActionBar.getTabAt(mSearchInMessagesTabIndex).getTag()).mBackgroundVisibility; outState.putInt(KEY_STATE_IS_BACKGROUND_MESSAGES_TAB, visibility); visibility = ((TabListenerHolder)mActionBar.getTabAt(mSearchInPeopleTabIndex).getTag()).mBackgroundVisibility; outState.putInt(KEY_STATE_IS_BACKGROUND_PEOPLE_TAB, visibility); visibility = ((TabListenerHolder)mActionBar.getTabAt(mSearchInFilesTabIndex).getTag()).mBackgroundVisibility; outState.putInt(KEY_STATE_IS_BACKGROUND_FILES_TAB, visibility); // save search pattern for each tab (could be optimized) String searchedPattern = ((TabListenerHolder)mActionBar.getTabAt(mSearchInRoomNamesTabIndex).getTag()).mSearchedPattern; outState.putString(KEY_STATE_SEARCH_PATTERN_ROOMS_TAB, searchedPattern); searchedPattern = ((TabListenerHolder)mActionBar.getTabAt(mSearchInMessagesTabIndex).getTag()).mSearchedPattern; outState.putString(KEY_STATE_SEARCH_PATTERN_MESSAGES_TAB, searchedPattern); searchedPattern = ((TabListenerHolder)mActionBar.getTabAt(mSearchInPeopleTabIndex).getTag()).mSearchedPattern; outState.putString(KEY_STATE_SEARCH_PATTERN_PEOPLE_TAB, searchedPattern); searchedPattern = ((TabListenerHolder)mActionBar.getTabAt(mSearchInFilesTabIndex).getTag()).mSearchedPattern; outState.putString(KEY_STATE_SEARCH_PATTERN_FILES_TAB, searchedPattern); } }
console/src/main/java/im/vector/activity/VectorUnifiedSearchActivity.java
/* * Copyright 2015 OpenMarket Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.activity; import android.annotation.SuppressLint; import android.app.FragmentManager; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.text.TextUtils; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBar.TabListener; import android.widget.Toast; import org.matrix.androidsdk.MXSession; import org.matrix.androidsdk.fragments.MatrixMessageListFragment; import im.vector.Matrix; import im.vector.R; import im.vector.fragments.VectorMessagesSearchResultsListFragment; import im.vector.fragments.VectorRoomsSearchResultsListFragment; /** * Displays a generic activity search method */ public class VectorUnifiedSearchActivity extends MXCActionBarActivity implements TabListener { private static final String LOG_TAG = "VectorUniSrchActivity"; public static final CharSequence NOT_IMPLEMENTED = "Not yet implemented"; // tab related items private static final String TAG_FRAGMENT_SEARCH_IN_MESSAGE = "im.vector.activity.TAG_FRAGMENT_SEARCH_IN_MESSAGE"; private static final String TAG_FRAGMENT_SEARCH_IN_ROOM_NAMES = "im.vector.activity.TAG_FRAGMENT_SEARCH_IN_ROOM_NAMES"; private static final String TAG_FRAGMENT_SEARCH_PEOPLE = "im.vector.activity.TAG_FRAGMENT_SEARCH_PEOPLE"; private static final String TAG_FRAGMENT_SEARCH_IN_FILES = "im.vector.activity.TAG_FRAGMENT_SEARCH_IN_FILES"; private int mSearchInRoomNamesTabIndex = -1; private int mSearchInMessagesTabIndex = -1; private int mSearchInPeopleTabIndex = -1; private int mSearchInFilesTabIndex = -1; private int mCurrentTabIndex = -1; ActionBar mActionBar; // activity life cycle management: // - Bundle keys private static final String KEY_STATE_CURRENT_TAB_INDEX = "CURRENT_SELECTED_TAB"; private static final String KEY_STATE_IS_BACKGROUND_ROOMS_TAB = "IS_BACKGROUND_ROOMS_TAB"; private static final String KEY_STATE_IS_BACKGROUND_MESSAGES_TAB = "IS_BACKGROUND_MESSAGES_TAB"; private static final String KEY_STATE_IS_BACKGROUND_PEOPLE_TAB = "IS_BACKGROUND_PEOPLE_TAB"; private static final String KEY_STATE_IS_BACKGROUND_FILES_TAB = "IS_BACKGROUND_FILES_TAB"; private static final String KEY_STATE_SEARCH_PATTERN_MESSAGES_TAB = "SEARCH_PATTERN_MESSAGES"; private static final String KEY_STATE_SEARCH_PATTERN_ROOMS_TAB = "SEARCH_PATTERN_ROOMS"; private static final String KEY_STATE_SEARCH_PATTERN_PEOPLE_TAB = "SEARCH_PATTERN_PEOPLE"; private static final String KEY_STATE_SEARCH_PATTERN_FILES_TAB = "SEARCH_PATTERN_FILES"; // search fragments private VectorMessagesSearchResultsListFragment mSearchInMessagesFragment; private VectorRoomsSearchResultsListFragment mSearchInRoomNamesFragment; private VectorMessagesSearchResultsListFragment mSearchInFilesFragment; private VectorMessagesSearchResultsListFragment mSearchInPeopleFragment; private MXSession mSession; // UI items private ImageView mBackgroundImageView; private TextView mNoResultsTxtView; private View mWaitWhileSearchInProgressView; private EditText mPatternToSearchEditText; private static class TabListenerHolder { public final String mFragmentTag; //public final int mContainerId; public Fragment mTabFragment; public int mBackgroundVisibility; public int mNoResultsTxtViewVisibility; public String mSearchedPattern; public TabListenerHolder(String aTabTag, int aBackgroundVisibility, int aNoResultsVisibility, String aSearchPattern) { mFragmentTag = aTabTag; mNoResultsTxtViewVisibility = aNoResultsVisibility; mBackgroundVisibility = aBackgroundVisibility; mSearchedPattern = aSearchPattern; } } @Override protected void onCreate(Bundle savedInstanceState) { if (CommonActivityUtils.shouldRestartApp()) { Log.e(LOG_TAG, "Restart the application."); CommonActivityUtils.restartApp(this); } super.onCreate(savedInstanceState); setContentView(R.layout.activity_vector_unified_search); // the session should be passed in parameter // but the current design does not describe how the multi accounts will be managed. mSession = Matrix.getInstance(this).getDefaultSession(); if (mSession == null) { Log.e(LOG_TAG, "No MXSession."); finish(); return; } // UI widgets binding & init fields mBackgroundImageView = (ImageView)findViewById(R.id.search_background_imageview); mNoResultsTxtView = (TextView)findViewById(R.id.search_no_result_textview); mWaitWhileSearchInProgressView = findViewById(R.id.search_in_progress_view); mActionBar = getSupportActionBar(); // customize the action bar with a custom view to contain the search input text View actionBarView = customizeActionBar(); // add the search logic based on the text search input listener mPatternToSearchEditText = (EditText) actionBarView.findViewById(R.id.room_action_bar_edit_text); actionBarView.postDelayed(new Runnable() { @Override public void run() { mPatternToSearchEditText.requestFocus(); InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); im.showSoftInput(mPatternToSearchEditText, 0); } }, 100); mPatternToSearchEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEARCH) { // start the search according to the current selected tab searchAccordingToTabHandler(); return true; } return false; } }); // tab creation and restore tabs UI context createNavigationTabs(savedInstanceState); } @Override public void onDestroy() { super.onDestroy(); Log.d(LOG_TAG, "## onDestroy(): "); } @Override protected void onResume() { super.onResume(); Log.d(LOG_TAG, "## onResume(): "); searchAccordingToTabHandler(); } /** * Reset the UI to its init state: * - "waiting while searching" screen disabled * - background image visible * - no results message disabled */ private void resetUi() { // stop "wait while searching" screen if (null != mWaitWhileSearchInProgressView) { mWaitWhileSearchInProgressView.setVisibility(View.GONE); } // display the background if (null != mBackgroundImageView) { mBackgroundImageView.setVisibility(View.VISIBLE); } if (null != mNoResultsTxtView) { mNoResultsTxtView.setVisibility(View.GONE); } } /** * The search is done. * @param nbrMessages the number of found messages. */ private void onSearchEnd(int nbrMessages) { Log.d(LOG_TAG,"## onSearchEnd() nbrMsg="+nbrMessages); // stop "wait while searching" screen mWaitWhileSearchInProgressView.setVisibility(View.GONE); // display the background only if there is no result if(0 == nbrMessages) { mBackgroundImageView.setVisibility(View.VISIBLE); } else { mBackgroundImageView.setVisibility(View.GONE); } // display the "no result" text only if the researched text is not empty mNoResultsTxtView.setVisibility(((0 == nbrMessages) && !TextUtils.isEmpty(mPatternToSearchEditText.getText().toString())) ? View.VISIBLE : View.GONE); } /** * Called by the fragements when they are resumed. * It is used to refresh the search while playing with the tab. */ public void onSearchFragmentResume() { searchAccordingToTabHandler(); } /** * Update the tag of the current tab with its UI values */ private void saveCurrentUiTabContext() { if(-1 != mCurrentTabIndex) { ActionBar.Tab currentTab = mActionBar.getTabAt(mCurrentTabIndex); TabListenerHolder tabTag = (TabListenerHolder) currentTab.getTag(); tabTag.mBackgroundVisibility = mBackgroundImageView.getVisibility(); tabTag.mNoResultsTxtViewVisibility = mNoResultsTxtView.getVisibility(); tabTag.mSearchedPattern = mPatternToSearchEditText.getText().toString(); currentTab.setTag(tabTag); } } /** * Update the tag of the tab with its the UI values * @param aTabToUpdate the tab to be updated */ private void saveUiTabContext(ActionBar.Tab aTabToUpdate) { TabListenerHolder tabTag = (TabListenerHolder) aTabToUpdate.getTag(); tabTag.mBackgroundVisibility = mBackgroundImageView.getVisibility(); tabTag.mNoResultsTxtViewVisibility = mNoResultsTxtView.getVisibility(); tabTag.mSearchedPattern = mPatternToSearchEditText.getText().toString(); aTabToUpdate.setTag(tabTag); } /** * Restore the UI context associated with the tab * @param aTabToRestore the tab to be restored */ private void restoreUiTabContext(ActionBar.Tab aTabToRestore) { TabListenerHolder tabTag = (TabListenerHolder) aTabToRestore.getTag(); mBackgroundImageView.setVisibility(tabTag.mBackgroundVisibility); mNoResultsTxtView.setVisibility(tabTag.mNoResultsTxtViewVisibility); mPatternToSearchEditText.setText(tabTag.mSearchedPattern); } private void searchAccordingToTabHandler() { int currentIndex = mActionBar.getSelectedNavigationIndex(); resetUi(); String pattern = mPatternToSearchEditText.getText().toString(); if((currentIndex == mSearchInRoomNamesTabIndex) && (null != mSearchInRoomNamesFragment)) { if (mSearchInRoomNamesFragment.isAdded()) { // display the "wait while searching" screen (progress bar) mWaitWhileSearchInProgressView.setVisibility(View.VISIBLE); mSearchInRoomNamesFragment.searchPattern(pattern, new MatrixMessageListFragment.OnSearchResultListener() { @Override public void onSearchSucceed(int nbrMessages) { onSearchEnd(nbrMessages); } @Override public void onSearchFailed() { onSearchEnd(0); } }); } } else if((currentIndex == mSearchInMessagesTabIndex) && (null != mSearchInMessagesFragment)) { if (mSearchInMessagesFragment.isAdded()) { // display the "wait while searching" screen (progress bar) mWaitWhileSearchInProgressView.setVisibility(View.VISIBLE); mSearchInMessagesFragment.searchPattern(pattern, new MatrixMessageListFragment.OnSearchResultListener() { @Override public void onSearchSucceed(int nbrMessages) { onSearchEnd(nbrMessages); } @Override public void onSearchFailed() { onSearchEnd(0); } }); } else { mWaitWhileSearchInProgressView.setVisibility(View.GONE); } } else { onSearchEnd(0); Toast.makeText(VectorUnifiedSearchActivity.this, NOT_IMPLEMENTED, Toast.LENGTH_SHORT).show(); } } /** * Add a custom action bar with a view * @return the action bar inflated view */ private View customizeActionBar() { mActionBar.setDisplayShowCustomEnabled(true); mActionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_HOME_AS_UP); // add a custom action bar view containing an EditText to input the search text ActionBar.LayoutParams layout = new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT); View actionBarLayout = getLayoutInflater().inflate(R.layout.vector_search_action_bar, null); mActionBar.setCustomView(actionBarLayout, layout); return actionBarLayout; } //============================================================================================================== // Tabs logic implementation //============================================================================================================== /** * Create the search fragment instances from the saved instance; * @param aSavedInstanceState the saved instance. */ private void createNavigationTabs(Bundle aSavedInstanceState) { int tabIndex = 0; int tabIndexToRestore; int isBackroundDisplayed; String searchPattern; // Set the tabs navigation mode mActionBar.setNavigationMode(android.support.v7.app.ActionBar.NAVIGATION_MODE_TABS); // ROOMS names search tab creation android.support.v7.app.ActionBar.Tab tabToBeadded = mActionBar.newTab(); String tabTitle = getResources().getString(R.string.tab_title_search_rooms); tabToBeadded.setText(tabTitle); tabToBeadded.setTabListener(this); isBackroundDisplayed = (null != aSavedInstanceState)?aSavedInstanceState.getInt(KEY_STATE_IS_BACKGROUND_ROOMS_TAB, View.VISIBLE):View.VISIBLE; searchPattern = (null != aSavedInstanceState)?aSavedInstanceState.getString(KEY_STATE_SEARCH_PATTERN_ROOMS_TAB,""):""; tabToBeadded.setTag(new TabListenerHolder(TAG_FRAGMENT_SEARCH_IN_ROOM_NAMES, isBackroundDisplayed, View.GONE, searchPattern)); mActionBar.addTab(tabToBeadded); mSearchInRoomNamesTabIndex = tabIndex++; // MESSAGES search tab creation tabToBeadded = mActionBar.newTab(); tabTitle = getResources().getString(R.string.tab_title_search_messages); tabToBeadded.setText(tabTitle); tabToBeadded.setTabListener(this); isBackroundDisplayed = (null != aSavedInstanceState)?aSavedInstanceState.getInt(KEY_STATE_IS_BACKGROUND_MESSAGES_TAB, View.VISIBLE):View.VISIBLE; searchPattern = (null != aSavedInstanceState)?aSavedInstanceState.getString(KEY_STATE_SEARCH_PATTERN_MESSAGES_TAB,""):""; tabToBeadded.setTag(new TabListenerHolder(TAG_FRAGMENT_SEARCH_IN_MESSAGE, isBackroundDisplayed, View.GONE, searchPattern)); mActionBar.addTab(tabToBeadded); mSearchInMessagesTabIndex = tabIndex++; // PEOPLE search tab creation tabToBeadded = mActionBar.newTab(); tabTitle = getResources().getString(R.string.tab_title_search_people); tabToBeadded.setText(tabTitle); tabToBeadded.setTabListener(this); isBackroundDisplayed = (null != aSavedInstanceState)?aSavedInstanceState.getInt(KEY_STATE_IS_BACKGROUND_PEOPLE_TAB, View.VISIBLE):View.VISIBLE; searchPattern = (null != aSavedInstanceState)?aSavedInstanceState.getString(KEY_STATE_SEARCH_PATTERN_PEOPLE_TAB,""):""; tabToBeadded.setTag(new TabListenerHolder(TAG_FRAGMENT_SEARCH_PEOPLE, isBackroundDisplayed, View.GONE, searchPattern)); mActionBar.addTab(tabToBeadded); mSearchInPeopleTabIndex = tabIndex++; // FILES search tab creation tabToBeadded = mActionBar.newTab(); tabTitle = getResources().getString(R.string.tab_title_search_files); tabToBeadded.setText(tabTitle); tabToBeadded.setTabListener(this); isBackroundDisplayed = (null != aSavedInstanceState)?aSavedInstanceState.getInt(KEY_STATE_IS_BACKGROUND_FILES_TAB, View.VISIBLE):View.VISIBLE; searchPattern = (null != aSavedInstanceState)?aSavedInstanceState.getString(KEY_STATE_SEARCH_PATTERN_FILES_TAB,""):""; tabToBeadded.setTag(new TabListenerHolder(TAG_FRAGMENT_SEARCH_IN_FILES, isBackroundDisplayed, View.GONE, searchPattern)); mActionBar.addTab(tabToBeadded); mSearchInFilesTabIndex = tabIndex++; // set the default tab to be displayed tabIndexToRestore = (null != aSavedInstanceState)?aSavedInstanceState.getInt(KEY_STATE_CURRENT_TAB_INDEX, 0) : 0; if(-1 == tabIndexToRestore) { // default value: display the search in rooms tab tabIndexToRestore = mSearchInRoomNamesTabIndex; } mCurrentTabIndex = tabIndexToRestore; // set the tab to display mActionBar.setSelectedNavigationItem(tabIndexToRestore); } @Override public void onTabSelected(android.support.v7.app.ActionBar.Tab tab, android.support.v4.app.FragmentTransaction ft) { TabListenerHolder tabListenerHolder = (TabListenerHolder) tab.getTag(); Log.d(LOG_TAG, "## onTabSelected() FragTag=" + tabListenerHolder.mFragmentTag); // clear any displayed windows resetUi(); // inter tab selection life cycle: restore tab UI restoreUiTabContext(tab); if (tabListenerHolder.mFragmentTag.equals(TAG_FRAGMENT_SEARCH_IN_ROOM_NAMES)) { if (null == mSearchInRoomNamesFragment) { mSearchInRoomNamesFragment = VectorRoomsSearchResultsListFragment.newInstance(mSession.getMyUser().userId, R.layout.fragment_vector_recents_list); ft.replace(R.id.search_fragment_container, mSearchInRoomNamesFragment, tabListenerHolder.mFragmentTag); Log.d(LOG_TAG, "## onTabSelected() SearchInRoomNames frag added"); } else { ft.attach(mSearchInRoomNamesFragment); Log.d(LOG_TAG, "## onTabSelected() SearchInRoomNames frag attach"); } mCurrentTabIndex = mSearchInRoomNamesTabIndex; } else if (tabListenerHolder.mFragmentTag.equals(TAG_FRAGMENT_SEARCH_IN_MESSAGE)) { if (null == mSearchInMessagesFragment) { mSearchInMessagesFragment = VectorMessagesSearchResultsListFragment.newInstance(mSession.getMyUser().userId, org.matrix.androidsdk.R.layout.fragment_matrix_message_list_fragment); ft.replace(R.id.search_fragment_container, mSearchInMessagesFragment, tabListenerHolder.mFragmentTag); Log.d(LOG_TAG, "## onTabSelected() SearchInMessages frag added"); } else { ft.attach(mSearchInMessagesFragment); Log.d(LOG_TAG, "## onTabSelected() SearchInMessages frag added"); } mCurrentTabIndex = mSearchInMessagesTabIndex; } else if (tabListenerHolder.mFragmentTag.equals(TAG_FRAGMENT_SEARCH_PEOPLE)) { mCurrentTabIndex = mSearchInPeopleTabIndex; } else if (tabListenerHolder.mFragmentTag.equals(TAG_FRAGMENT_SEARCH_IN_FILES)) { mCurrentTabIndex = mSearchInFilesTabIndex; } if (-1 != mCurrentTabIndex) { searchAccordingToTabHandler(); } } @Override public void onTabUnselected(android.support.v7.app.ActionBar.Tab tab, android.support.v4.app.FragmentTransaction ft) { TabListenerHolder tabListenerHolder = (TabListenerHolder) tab.getTag(); Log.d(LOG_TAG, "## onTabUnselected() FragTag=" + tabListenerHolder.mFragmentTag); // save tab UI context before leaving the tab... saveUiTabContext(tab); if(tabListenerHolder.mFragmentTag.equals(TAG_FRAGMENT_SEARCH_IN_MESSAGE)) { if(null != mSearchInMessagesFragment) { ft.detach(mSearchInMessagesFragment); } } else if(tabListenerHolder.mFragmentTag.equals(TAG_FRAGMENT_SEARCH_IN_ROOM_NAMES) ){ if(null != mSearchInRoomNamesFragment) { ft.detach(mSearchInRoomNamesFragment); } } } @Override public void onTabReselected(android.support.v7.app.ActionBar.Tab tab, FragmentTransaction ft) { } //============================================================================================================== // Life cycle Activity methods //============================================================================================================== @SuppressLint("LongLogTag") @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); Log.d(LOG_TAG, "## onSaveInstanceState(): "); // save current tab int currentIndex = mActionBar.getSelectedNavigationIndex(); outState.putInt(KEY_STATE_CURRENT_TAB_INDEX, currentIndex); // save background visibility for each tab (could be optimized) int visibility = ((TabListenerHolder)mActionBar.getTabAt(mSearchInRoomNamesTabIndex).getTag()).mBackgroundVisibility; outState.putInt(KEY_STATE_IS_BACKGROUND_ROOMS_TAB, visibility); visibility = ((TabListenerHolder)mActionBar.getTabAt(mSearchInMessagesTabIndex).getTag()).mBackgroundVisibility; outState.putInt(KEY_STATE_IS_BACKGROUND_MESSAGES_TAB, visibility); visibility = ((TabListenerHolder)mActionBar.getTabAt(mSearchInPeopleTabIndex).getTag()).mBackgroundVisibility; outState.putInt(KEY_STATE_IS_BACKGROUND_PEOPLE_TAB, visibility); visibility = ((TabListenerHolder)mActionBar.getTabAt(mSearchInFilesTabIndex).getTag()).mBackgroundVisibility; outState.putInt(KEY_STATE_IS_BACKGROUND_FILES_TAB, visibility); // save search pattern for each tab (could be optimized) String searchedPattern = ((TabListenerHolder)mActionBar.getTabAt(mSearchInRoomNamesTabIndex).getTag()).mSearchedPattern; outState.putString(KEY_STATE_SEARCH_PATTERN_ROOMS_TAB, searchedPattern); searchedPattern = ((TabListenerHolder)mActionBar.getTabAt(mSearchInMessagesTabIndex).getTag()).mSearchedPattern; outState.putString(KEY_STATE_SEARCH_PATTERN_MESSAGES_TAB, searchedPattern); searchedPattern = ((TabListenerHolder)mActionBar.getTabAt(mSearchInPeopleTabIndex).getTag()).mSearchedPattern; outState.putString(KEY_STATE_SEARCH_PATTERN_PEOPLE_TAB, searchedPattern); searchedPattern = ((TabListenerHolder)mActionBar.getTabAt(mSearchInFilesTabIndex).getTag()).mSearchedPattern; outState.putString(KEY_STATE_SEARCH_PATTERN_FILES_TAB, searchedPattern); } }
add_login_splash_activity "no results" was displayed with results.
console/src/main/java/im/vector/activity/VectorUnifiedSearchActivity.java
add_login_splash_activity
<ide><path>onsole/src/main/java/im/vector/activity/VectorUnifiedSearchActivity.java <ide> <ide> /** <ide> * The search is done. <add> * @param tabIndex the tab index <ide> * @param nbrMessages the number of found messages. <ide> */ <del> private void onSearchEnd(int nbrMessages) { <del> Log.d(LOG_TAG,"## onSearchEnd() nbrMsg="+nbrMessages); <del> // stop "wait while searching" screen <del> mWaitWhileSearchInProgressView.setVisibility(View.GONE); <del> <del> // display the background only if there is no result <del> if(0 == nbrMessages) { <del> mBackgroundImageView.setVisibility(View.VISIBLE); <del> } <del> else { <del> mBackgroundImageView.setVisibility(View.GONE); <del> } <del> <del> // display the "no result" text only if the researched text is not empty <del> mNoResultsTxtView.setVisibility(((0 == nbrMessages) && !TextUtils.isEmpty(mPatternToSearchEditText.getText().toString())) ? View.VISIBLE : View.GONE); <del> } <del> <del> /** <del> * Called by the fragements when they are resumed. <add> private void onSearchEnd(int tabIndex, int nbrMessages) { <add> if (mCurrentTabIndex == tabIndex) { <add> Log.d(LOG_TAG, "## onSearchEnd() nbrMsg=" + nbrMessages); <add> // stop "wait while searching" screen <add> mWaitWhileSearchInProgressView.setVisibility(View.GONE); <add> <add> // display the background only if there is no result <add> if (0 == nbrMessages) { <add> mBackgroundImageView.setVisibility(View.VISIBLE); <add> } else { <add> mBackgroundImageView.setVisibility(View.GONE); <add> } <add> <add> // display the "no result" text only if the researched text is not empty <add> mNoResultsTxtView.setVisibility(((0 == nbrMessages) && !TextUtils.isEmpty(mPatternToSearchEditText.getText().toString())) ? View.VISIBLE : View.GONE); <add> } <add> } <add> <add> /** <add> * Called by the fragments when they are resumed. <ide> * It is used to refresh the search while playing with the tab. <ide> */ <ide> public void onSearchFragmentResume() { <ide> mSearchInRoomNamesFragment.searchPattern(pattern, new MatrixMessageListFragment.OnSearchResultListener() { <ide> @Override <ide> public void onSearchSucceed(int nbrMessages) { <del> onSearchEnd(nbrMessages); <add> onSearchEnd(mSearchInRoomNamesTabIndex, nbrMessages); <ide> } <ide> <ide> @Override <ide> public void onSearchFailed() { <del> onSearchEnd(0); <add> onSearchEnd(mSearchInRoomNamesTabIndex, 0); <ide> } <ide> }); <ide> } <ide> mSearchInMessagesFragment.searchPattern(pattern, new MatrixMessageListFragment.OnSearchResultListener() { <ide> @Override <ide> public void onSearchSucceed(int nbrMessages) { <del> onSearchEnd(nbrMessages); <add> onSearchEnd(mSearchInMessagesTabIndex, nbrMessages); <ide> } <ide> <ide> @Override <ide> public void onSearchFailed() { <del> onSearchEnd(0); <add> onSearchEnd(mSearchInMessagesTabIndex, 0); <ide> } <ide> }); <ide> } else { <ide> } <ide> } <ide> else { <del> onSearchEnd(0); <add> onSearchEnd(currentIndex, 0); <ide> Toast.makeText(VectorUnifiedSearchActivity.this, NOT_IMPLEMENTED, Toast.LENGTH_SHORT).show(); <ide> } <ide> }
Java
unlicense
b030b89196cadaea49c6ad0572ac219344855a0f
0
ferran294/HundirLaFlota
package tablero; import java.awt.BorderLayout; import java.awt.Color; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class Juego { /** * Implementa el juego 'Hundir la flota' mediante una interfaz grafica (GUI) */ /** Estados posibles de las casillas del tablero */ private static final int AGUA = -1, TOCADO = -2, HUNDIDO = -3; /** Parametros por defecto de una partida */ private static final int NUMFILAS=8, NUMCOLUMNAS=8, NUMBARCOS=6; private Partida partida = null; // Objeto con los datos de la partida en juego private JFrame frame = null; // Tablero de juego private JLabel estado = null; // Texto en el panel de estado private JButton buttons[][] = null; // Botones asociados a las casillas de la partida /** Atributos de la partida en juego */ private int numFilas, numColumnas, numBarcos, quedan, disparos; /** * Programa principal. Crea y lanza un nuevo juego * @param args no se utiliza */ public static void main(String[] args) { Juego juego = new Juego(); juego.ejecuta(); } // end main /** * Lanza una nueva hebra que establece los atributos del juego y dibuja la interfaz grafica: tablero */ private void ejecuta() { // POR IMPLEMENTAR frame = new JFrame(); frame.setVisible(true); anyadeMenu(); } // end ejecuta /** * Dibuja el tablero de juego y crea la partida inicial */ private void dibujaTablero() { // PUTA } // end dibujaTablero /** * Anyade el menu de opciones del juego */ private void anyadeMenu() { MenuListener e = new MenuListener(); JMenuBar mb = new JMenuBar(); frame.setJMenuBar(mb); JMenu menu = new JMenu("Opciones"); mb.add(menu); JMenuItem salir = new JMenuItem("Salir"); salir.addActionListener(e); menu.add(salir); JMenuItem nuevaPartida = new JMenuItem("Nueva partida"); nuevaPartida.addActionListener(e); menu.add(nuevaPartida); JMenuItem solucion = new JMenuItem("Mostrar solución"); solucion.addActionListener(e); menu.add(solucion); } // end anyadeMenu /** * Anyade el panel con las casillas del mar y sus etiquetas. * Cada casilla sera un boton con su correspondiente escuchador * @param nf numero de filas * @param nc numero de columnas */ private void anyadeGrid(int nf, int nc) { // POR IMPLEMENTAR } // end anyadeGrid /** * Anyade el panel de estado al tablero * @param cadena cadena inicial del panel de estado */ private void anyadePanelEstado(String cadena) { // POR IMPLEMENTAR } // end anyadePanel Estado /** * Cambia la cadena mostrada en el panel de estado * @param cadenaEstado nuevo estado */ private void cambiaEstado(String cadenaEstado) { // POR IMPLEMENTAR } // end cambiaEstado /** * Muestra la solucion de la partida y marca la partida como finalizada */ private void muestraSolucion() { // POR IMPLEMENTAR } // end muestraSolucion /** * Limpia las casillas del tablero */ private void limpiaTablero() { // POR IMPLEMENTAR } // end limpiaTablero /******************************************************************************************/ /********************* CLASE INTERNA MenuListener ****************************************/ /******************************************************************************************/ /** * Clase interna que escucha el menu de Opciones del tablero * */ private class MenuListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { // POR IMPLEMENTAR } // end actionPerformed } // end class MenuListener /******************************************************************************************/ /********************* CLASE INTERNA ButtonListener **************************************/ /******************************************************************************************/ /** * Clase interna que escucha cada uno de los botones del tablero * Para poder identificar el boton que ha generado el evento se pueden usar las propiedades * de los componentes, apoyandose en los metodos putClientProperty y getClientProperty */ private class ButtonListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { // POR IMPLEMENTAR } // end actionPerformed } // end class ButtonListener } // end class Juego
HundirLaFlota/src/tablero/Juego.java
package tablero; import java.awt.BorderLayout; import java.awt.Color; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class Juego { /** * Implementa el juego 'Hundir la flota' mediante una interfaz grafica (GUI) */ /** Estados posibles de las casillas del tablero */ private static final int AGUA = -1, TOCADO = -2, HUNDIDO = -3; /** Parametros por defecto de una partida */ private static final int NUMFILAS=8, NUMCOLUMNAS=8, NUMBARCOS=6; private Partida partida = null; // Objeto con los datos de la partida en juego private JFrame frame = null; // Tablero de juego private JLabel estado = null; // Texto en el panel de estado private JButton buttons[][] = null; // Botones asociados a las casillas de la partida /** Atributos de la partida en juego */ private int numFilas, numColumnas, numBarcos, quedan, disparos; /** * Programa principal. Crea y lanza un nuevo juego * @param args no se utiliza */ public static void main(String[] args) { Juego juego = new Juego(); juego.ejecuta(); } // end main /** * Lanza una nueva hebra que establece los atributos del juego y dibuja la interfaz grafica: tablero */ private void ejecuta() { // POR IMPLEMENTAR } // end ejecuta /** * Dibuja el tablero de juego y crea la partida inicial */ private void dibujaTablero() { // POR IMPLEMENTAR } // end dibujaTablero /** * Anyade el menu de opciones del juego */ private void anyadeMenu() { // POR IMPLEMENTAR } // end anyadeMenu /** * Anyade el panel con las casillas del mar y sus etiquetas. * Cada casilla sera un boton con su correspondiente escuchador * @param nf numero de filas * @param nc numero de columnas */ private void anyadeGrid(int nf, int nc) { // POR IMPLEMENTAR } // end anyadeGrid /** * Anyade el panel de estado al tablero * @param cadena cadena inicial del panel de estado */ private void anyadePanelEstado(String cadena) { // POR IMPLEMENTAR } // end anyadePanel Estado /** * Cambia la cadena mostrada en el panel de estado * @param cadenaEstado nuevo estado */ private void cambiaEstado(String cadenaEstado) { // POR IMPLEMENTAR } // end cambiaEstado /** * Muestra la solucion de la partida y marca la partida como finalizada */ private void muestraSolucion() { // POR IMPLEMENTAR } // end muestraSolucion /** * Limpia las casillas del tablero */ private void limpiaTablero() { // POR IMPLEMENTAR } // end limpiaTablero /******************************************************************************************/ /********************* CLASE INTERNA MenuListener ****************************************/ /******************************************************************************************/ /** * Clase interna que escucha el menu de Opciones del tablero * */ private class MenuListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { // POR IMPLEMENTAR } // end actionPerformed } // end class MenuListener /******************************************************************************************/ /********************* CLASE INTERNA ButtonListener **************************************/ /******************************************************************************************/ /** * Clase interna que escucha cada uno de los botones del tablero * Para poder identificar el boton que ha generado el evento se pueden usar las propiedades * de los componentes, apoyandose en los metodos putClientProperty y getClientProperty */ private class ButtonListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { // POR IMPLEMENTAR } // end actionPerformed } // end class ButtonListener } // end class Juego
Método anyadeMenu implementado.
HundirLaFlota/src/tablero/Juego.java
Método anyadeMenu implementado.
<ide><path>undirLaFlota/src/tablero/Juego.java <ide> */ <ide> private void ejecuta() { <ide> // POR IMPLEMENTAR <add> frame = new JFrame(); <add> frame.setVisible(true); <add> anyadeMenu(); <ide> } // end ejecuta <ide> <ide> /** <ide> * Dibuja el tablero de juego y crea la partida inicial <ide> */ <ide> private void dibujaTablero() { <del> // POR IMPLEMENTAR <add> // PUTA <ide> } // end dibujaTablero <ide> <ide> /** <ide> * Anyade el menu de opciones del juego <ide> */ <ide> private void anyadeMenu() { <del> // POR IMPLEMENTAR <add> MenuListener e = new MenuListener(); <add> <add> JMenuBar mb = new JMenuBar(); <add> frame.setJMenuBar(mb); <add> <add> JMenu menu = new JMenu("Opciones"); <add> mb.add(menu); <add> <add> JMenuItem salir = new JMenuItem("Salir"); <add> salir.addActionListener(e); <add> menu.add(salir); <add> <add> JMenuItem nuevaPartida = new JMenuItem("Nueva partida"); <add> nuevaPartida.addActionListener(e); <add> menu.add(nuevaPartida); <add> <add> JMenuItem solucion = new JMenuItem("Mostrar solución"); <add> solucion.addActionListener(e); <add> menu.add(solucion); <add> <ide> } // end anyadeMenu <ide> <ide> /**
Java
apache-2.0
e2819768868aba80971ba5787f54129cd7c9110a
0
WestCoastInformatics/UMLS-Terminology-Server,WestCoastInformatics/UMLS-Terminology-Server,WestCoastInformatics/UMLS-Terminology-Server,WestCoastInformatics/UMLS-Terminology-Server,WestCoastInformatics/UMLS-Terminology-Server
/* * Copyright 2015 West Coast Informatics, LLC */ package com.wci.umls.server.jpa.algo; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import org.hibernate.ScrollMode; import org.hibernate.ScrollableResults; import org.hibernate.Session; import com.wci.umls.server.ReleaseInfo; import com.wci.umls.server.algo.Algorithm; import com.wci.umls.server.helpers.Branch; import com.wci.umls.server.helpers.ConfigUtility; import com.wci.umls.server.helpers.FieldedStringTokenizer; import com.wci.umls.server.jpa.ReleaseInfoJpa; import com.wci.umls.server.jpa.content.AtomJpa; import com.wci.umls.server.jpa.content.AtomSubsetJpa; import com.wci.umls.server.jpa.content.AtomSubsetMemberJpa; import com.wci.umls.server.jpa.content.AttributeJpa; import com.wci.umls.server.jpa.content.ConceptJpa; import com.wci.umls.server.jpa.content.ConceptRelationshipJpa; import com.wci.umls.server.jpa.content.ConceptSubsetJpa; import com.wci.umls.server.jpa.content.ConceptSubsetMemberJpa; import com.wci.umls.server.jpa.meta.AdditionalRelationshipTypeJpa; import com.wci.umls.server.jpa.meta.AttributeNameJpa; import com.wci.umls.server.jpa.meta.GeneralMetadataEntryJpa; import com.wci.umls.server.jpa.meta.LanguageJpa; import com.wci.umls.server.jpa.meta.PropertyChainJpa; import com.wci.umls.server.jpa.meta.RelationshipTypeJpa; import com.wci.umls.server.jpa.meta.RootTerminologyJpa; import com.wci.umls.server.jpa.meta.TermTypeJpa; import com.wci.umls.server.jpa.meta.TerminologyJpa; import com.wci.umls.server.jpa.services.HistoryServiceJpa; import com.wci.umls.server.model.content.Atom; import com.wci.umls.server.model.content.AtomSubset; import com.wci.umls.server.model.content.AtomSubsetMember; import com.wci.umls.server.model.content.Attribute; import com.wci.umls.server.model.content.Component; import com.wci.umls.server.model.content.ComponentHasAttributesAndName; import com.wci.umls.server.model.content.Concept; import com.wci.umls.server.model.content.ConceptRelationship; import com.wci.umls.server.model.content.ConceptSubset; import com.wci.umls.server.model.content.ConceptSubsetMember; import com.wci.umls.server.model.content.Subset; import com.wci.umls.server.model.content.SubsetMember; import com.wci.umls.server.model.meta.AdditionalRelationshipType; import com.wci.umls.server.model.meta.AttributeName; import com.wci.umls.server.model.meta.CodeVariantType; import com.wci.umls.server.model.meta.GeneralMetadataEntry; import com.wci.umls.server.model.meta.IdType; import com.wci.umls.server.model.meta.Language; import com.wci.umls.server.model.meta.NameVariantType; import com.wci.umls.server.model.meta.PropertyChain; import com.wci.umls.server.model.meta.RelationshipType; import com.wci.umls.server.model.meta.RootTerminology; import com.wci.umls.server.model.meta.TermType; import com.wci.umls.server.model.meta.Terminology; import com.wci.umls.server.model.meta.UsageType; import com.wci.umls.server.services.RootService; import com.wci.umls.server.services.helpers.ProgressEvent; import com.wci.umls.server.services.helpers.ProgressListener; import com.wci.umls.server.services.helpers.PushBackReader; /** * Implementation of an algorithm to import RF2 snapshot data. */ public class Rf2SnapshotLoaderAlgorithm extends HistoryServiceJpa implements Algorithm { /** Listeners. */ private List<ProgressListener> listeners = new ArrayList<>(); /** The isa type rel. */ private final static String isaTypeRel = "116680003"; /** The root concept id. */ private final static String rootConceptId = "138875005"; /** The Constant coreModuleId. */ private final static String coreModuleId = "900000000000207008"; /** The Constant metadataModuleId. */ private final static String metadataModuleId = "900000000000012004"; /** The dpn ref set id. */ private Set<String> dpnRefSetIds = new HashSet<>(); { // US English Language dpnRefSetIds.add("900000000000509007"); // VET extension dpnRefSetIds.add("332501000009101"); } /** The dpn acceptability id. */ private String dpnAcceptabilityId = "900000000000548007"; /** The dpn type id. */ private String dpnTypeId = "900000000000013009"; /** The preferred atoms set. */ private Set<String> prefAtoms = new HashSet<>(); /** The terminology. */ private String terminology; /** The terminology version. */ private String version; /** The release version. */ private String releaseVersion; /** The release version date. */ private Date releaseVersionDate; /** The readers. */ private Rf2Readers readers; /** The definition map. */ private Map<String, Set<Long>> definitionMap = new HashMap<>(); /** The atom id map. */ private Map<String, Long> atomIdMap = new HashMap<>(); /** The module ids. */ private Set<String> moduleIds = new HashSet<>(); /** non-core modules map. */ private Map<String, Set<String>> moduleConceptIdMap = new HashMap<>(); /** The concept id map. */ private Map<String, Long> conceptIdMap = new HashMap<>(); /** The atom subset map. */ private Map<String, AtomSubset> atomSubsetMap = new HashMap<>(); /** The concept subset map. */ private Map<String, ConceptSubset> conceptSubsetMap = new HashMap<>(); /** The term types. */ private Set<String> termTypes = new HashSet<>(); /** The additional rel types. */ private Set<String> additionalRelTypes = new HashSet<>(); /** The languages. */ private Set<String> languages = new HashSet<>(); /** The attribute names. */ private Set<String> attributeNames = new HashSet<>(); /** The concept attribute values. */ private Set<String> generalEntryValues = new HashSet<>(); /** counter for objects created, reset in each load section. */ int objectCt; // /** The init pref name. */ final String initPrefName = "No default preferred name found"; /** The loader. */ final String loader = "loader"; /** The id. */ final String id = "id"; /** The published. */ final String published = "PUBLISHED"; /** * Instantiates an empty {@link Rf2SnapshotLoaderAlgorithm}. * @throws Exception if anything goes wrong */ public Rf2SnapshotLoaderAlgorithm() throws Exception { super(); } /** * Sets the terminology. * * @param terminology the terminology */ public void setTerminology(String terminology) { this.terminology = terminology; } /** * Sets the terminology version. * * @param version the terminology version */ public void setVersion(String version) { this.version = version; } /** * Sets the release version. * * @param releaseVersion the rlease version */ public void setReleaseVersion(String releaseVersion) { this.releaseVersion = releaseVersion; } /** * Sets the readers. * * @param readers the readers */ public void setReaders(Rf2Readers readers) { this.readers = readers; } /* see superclass */ @Override public void compute() throws Exception { try { Logger.getLogger(getClass()).info("Start loading snapshot"); Logger.getLogger(getClass()).info(" terminology = " + terminology); Logger.getLogger(getClass()).info(" version = " + version); Logger.getLogger(getClass()).info(" releaseVersion = " + releaseVersion); releaseVersionDate = ConfigUtility.DATE_FORMAT.parse(releaseVersion); // control transaction scope setTransactionPerOperation(false); // Turn of ID computation when loading a terminology setAssignIdentifiersFlag(false); // Let loader set last modified flags. setLastModifiedFlag(false); // faster performance. beginTransaction(); // // Load concepts // Logger.getLogger(getClass()).info(" Loading Concepts..."); loadConcepts(); // // Load descriptions and language refsets // Logger.getLogger(getClass()).info(" Loading Atoms..."); loadAtoms(); loadDefinitions(); Logger.getLogger(getClass()).info(" Loading Language Ref Sets..."); loadLanguageRefSetMembers(); Logger.getLogger(getClass()) .info(" Connecting atoms/concepts and computing preferred names..."); connectAtomsAndConcepts(); // // Load relationships // Logger.getLogger(getClass()).info(" Loading Relationships..."); loadRelationships(); // // load AssocationReference RefSets (Content) // Logger.getLogger(getClass()) .info(" Loading Association Reference Ref Sets..."); loadAssociationReferenceRefSets(); commitClearBegin(); // // Load AttributeValue RefSets (Content) // Logger.getLogger(getClass()) .info(" Loading Attribute Value Ref Sets..."); loadAttributeValueRefSets(); commitClearBegin(); // // Load Simple RefSets (Content) // Logger.getLogger(getClass()).info(" Loading Simple Ref Sets..."); loadSimpleRefSets(); // // Load SimpleMapRefSets // Logger.getLogger(getClass()).info(" Loading Simple Map Ref Sets..."); loadSimpleMapRefSets(); commitClearBegin(); // // Load ComplexMapRefSets // Logger.getLogger(getClass()).info(" Loading Complex Map Ref Sets..."); loadComplexMapRefSets(); // // Load ExtendedMapRefSets // Logger.getLogger(getClass()).info(" Loading Extended Map Ref Sets..."); loadExtendedMapRefSets(); commitClearBegin(); // load RefsetDescriptor RefSets (Content) // Logger.getLogger(getClass()) .info(" Loading Refset Descriptor Ref Sets..."); loadRefsetDescriptorRefSets(); // // load ModuleDependency RefSets (Content) // Logger.getLogger(getClass()) .info(" Loading Module Dependency Ref Sets..."); loadModuleDependencyRefSets(); // // load AtomType RefSets (Content) // Logger.getLogger(getClass()).info(" Loading Atom Type Ref Sets..."); loadAtomTypeRefSets(); // Load metadata loadMetadata(); // Make subsets and label sets loadExtensionLabelSets(); // // Create ReleaseInfo for this release if it does not already exist // ReleaseInfo info = getReleaseInfo(terminology, releaseVersion); if (info == null) { info = new ReleaseInfoJpa(); info.setName(releaseVersion); info.setDescription(terminology + " " + releaseVersion + " release"); info.setPlanned(false); info.setPublished(true); info.setReleaseBeginDate(releaseVersionDate); info.setReleaseFinishDate(releaseVersionDate); info.setTerminology(terminology); info.setVersion(version); info.setLastModified(releaseVersionDate); info.setLastModifiedBy(loader); addReleaseInfo(info); } // Clear concept cache // clear and commit commitClearBegin(); Logger.getLogger(getClass()) .info(getComponentStats(terminology, version, Branch.ROOT)); Logger.getLogger(getClass()).info("Done ..."); } catch (Exception e) { throw e; } } /* see superclass */ @Override public void reset() throws Exception { // do nothing } /** * Fires a {@link ProgressEvent}. * @param pct percent done * @param note progress note */ public void fireProgressEvent(int pct, String note) { ProgressEvent pe = new ProgressEvent(this, pct, pct, note); for (int i = 0; i < listeners.size(); i++) { listeners.get(i).updateProgress(pe); } Logger.getLogger(getClass()).info(" " + pct + "% " + note); } /* see superclass */ @Override public void addProgressListener(ProgressListener l) { listeners.add(l); } /* see superclass */ @Override public void removeProgressListener(ProgressListener l) { listeners.remove(l); } /* see superclass */ @Override public void cancel() { throw new UnsupportedOperationException("cannot cancel."); } /** * Load concepts. * * @throws Exception the exception */ private void loadConcepts() throws Exception { String line = ""; objectCt = 0; PushBackReader reader = readers.getReader(Rf2Readers.Keys.CONCEPT); while ((line = reader.readLine()) != null) { final String fields[] = FieldedStringTokenizer.split(line, "\t"); final Concept concept = new ConceptJpa(); if (!fields[0].equals(id)) { // header // Stop if the effective time is past the release version if (fields[1].compareTo(releaseVersion) > 0) { reader.push(line); break; } final Date date = ConfigUtility.DATE_FORMAT.parse(fields[1]); concept.setTerminologyId(fields[0]); concept.setTimestamp(date); concept.setObsolete(fields[2].equals("0")); concept.setSuppressible(concept.isObsolete()); concept.setFullyDefined(fields[4].equals("900000000000073002")); concept.setTerminology(terminology); concept.setVersion(version); concept.setName(initPrefName); concept.setLastModified(date); concept.setLastModifiedBy(loader); concept.setPublished(true); concept.setPublishable(true); concept.setUsesRelationshipUnion(true); concept.setWorkflowStatus(published); // Attributes final Attribute attribute = new AttributeJpa(); setCommonFields(attribute, date); attribute.setName("moduleId"); attribute.setValue(fields[3].intern()); cacheAttributeMetadata(attribute); concept.addAttribute(attribute); addAttribute(attribute, concept); final Attribute attribute2 = new AttributeJpa(); setCommonFields(attribute2, date); attribute2.setName("definitionStatusId"); attribute2.setValue(fields[4].intern()); cacheAttributeMetadata(attribute2); concept.addAttribute(attribute2); addAttribute(attribute2, concept); // copy concept to shed any hibernate stuff addConcept(concept); conceptIdMap.put(concept.getTerminologyId(), concept.getId()); // Save extension module info if (isExtensionModule(fields[3])) { moduleIds.add(fields[3]); if (!moduleConceptIdMap.containsKey(fields[3])) { moduleConceptIdMap.put(fields[3], new HashSet<String>()); } moduleConceptIdMap.get(fields[3]).add(concept.getTerminologyId()); } logAndCommit(++objectCt, RootService.logCt, RootService.commitCt); } } commitClearBegin(); } /** * Load relationships. * * @throws Exception the exception */ private void loadRelationships() throws Exception { String line = ""; objectCt = 0; PushBackReader reader = readers.getReader(Rf2Readers.Keys.RELATIONSHIP); // Iterate over relationships while ((line = reader.readLine()) != null) { // Split line final String fields[] = FieldedStringTokenizer.split(line, "\t"); // Skip header if (!fields[0].equals(id)) { // Stop if the effective time is past the release version if (fields[1].compareTo(releaseVersion) > 0) { reader.push(line); break; } // Configure relationship final ConceptRelationship relationship = new ConceptRelationshipJpa(); final Date date = ConfigUtility.DATE_FORMAT.parse(fields[1]); relationship.setTerminologyId(fields[0]); relationship.setTimestamp(date); relationship.setLastModified(date); relationship.setObsolete(fields[2].equals("0")); // active relationship.setSuppressible(relationship.isObsolete()); relationship.setGroup(fields[6].intern()); // relationshipGroup relationship.setRelationshipType( fields[7].equals(isaTypeRel) ? "Is a" : "other"); // typeId relationship.setAdditionalRelationshipType(fields[7]); // typeId relationship .setHierarchical(relationship.getRelationshipType().equals("Is a")); generalEntryValues.add(relationship.getAdditionalRelationshipType()); additionalRelTypes.add(relationship.getAdditionalRelationshipType()); relationship.setStated(fields[8].equals("900000000000010007")); relationship.setInferred(fields[8].equals("900000000000011006")); relationship.setTerminology(terminology); relationship.setVersion(version); relationship.setLastModified(releaseVersionDate); relationship.setLastModifiedBy(loader); relationship.setPublished(true); relationship.setPublishable(true); relationship.setAssertedDirection(true); // Attributes Attribute attribute = new AttributeJpa(); setCommonFields(attribute, date); attribute.setName("moduleId"); attribute.setValue(fields[3].intern()); relationship.addAttribute(attribute); addAttribute(attribute, relationship); Attribute attribute2 = new AttributeJpa(); setCommonFields(attribute2, date); attribute2.setName("characteristicTypeId"); attribute2.setValue(fields[8].intern()); cacheAttributeMetadata(attribute2); relationship.addAttribute(attribute2); addAttribute(attribute2, relationship); Attribute attribute3 = new AttributeJpa(); setCommonFields(attribute3, date); attribute3.setName("modifierId"); attribute3.setValue(fields[9].intern()); cacheAttributeMetadata(attribute3); relationship.addAttribute(attribute3); addAttribute(attribute3, relationship); // get concepts from cache, they just need to have ids final Concept fromConcept = getConcept(conceptIdMap.get(fields[4])); final Concept toConcept = getConcept(conceptIdMap.get(fields[5])); if (fromConcept != null && toConcept != null) { relationship.setFrom(fromConcept); relationship.setTo(toConcept); // unnecessary // sourceConcept.addRelationship(relationship); addRelationship(relationship); } else { if (fromConcept == null) { throw new Exception( "Relationship " + relationship.getTerminologyId() + " -existent source concept " + fields[4]); } if (toConcept == null) { throw new Exception("Relationship" + relationship.getTerminologyId() + " references non-existent destination concept " + fields[5]); } } logAndCommit(++objectCt, RootService.logCt, RootService.commitCt); } } // Final commit commitClearBegin(); } /** * Load descriptions. * * @throws Exception the exception */ private void loadAtoms() throws Exception { String line = ""; objectCt = 0; PushBackReader reader = readers.getReader(Rf2Readers.Keys.DESCRIPTION); while ((line = reader.readLine()) != null) { final String fields[] = FieldedStringTokenizer.split(line, "\t"); if (!fields[0].equals(id)) { // Stop if the effective time is past the release version if (fields[1].compareTo(releaseVersion) > 0) { reader.push(line); break; } final Atom atom = new AtomJpa(); final Date date = ConfigUtility.DATE_FORMAT.parse(fields[1]); atom.setTerminologyId(fields[0]); atom.setTimestamp(date); atom.setLastModified(date); atom.setLastModifiedBy(loader); atom.setObsolete(fields[2].equals("0")); atom.setSuppressible(atom.isObsolete()); atom.setConceptId(fields[4]); atom.setDescriptorId(""); atom.setCodeId(""); atom.setLexicalClassId(""); atom.setStringClassId(""); atom.setLanguage(fields[5].intern()); languages.add(atom.getLanguage()); atom.setTermType(fields[6].intern()); generalEntryValues.add(atom.getTermType()); termTypes.add(atom.getTermType()); atom.setName(fields[7]); atom.setTerminology(terminology); atom.setVersion(version); atom.setPublished(true); atom.setPublishable(true); atom.setWorkflowStatus(published); // Attributes final Attribute attribute = new AttributeJpa(); setCommonFields(attribute, date); attribute.setName("moduleId"); attribute.setValue(fields[3].intern()); atom.addAttribute(attribute); addAttribute(attribute, atom); final Attribute attribute2 = new AttributeJpa(); setCommonFields(attribute2, date); attribute2.setName("caseSignificanceId"); attribute2.setValue(fields[8].intern()); cacheAttributeMetadata(attribute2); atom.addAttribute(attribute2); addAttribute(attribute2, atom); // set concept from cache and set initial prev concept final Long conceptId = conceptIdMap.get(fields[4]); if (conceptId == null) { throw new Exception( "Descriptions file references nonexistent concept: " + fields[4]); } final Concept concept = getConcept(conceptIdMap.get(fields[4])); if (concept != null) { // this also adds language refset entries addAtom(atom); atomIdMap.put(atom.getTerminologyId(), atom.getId()); } else { throw new Exception("Atom " + atom.getTerminologyId() + " references non-existent concept " + fields[4]); } logAndCommit(++objectCt, RootService.logCt, RootService.commitCt); } } commitClearBegin(); } /** * Load definitions. Treat exactly like descriptions. * * @throws Exception the exception */ private void loadDefinitions() throws Exception { String line = ""; objectCt = 0; PushBackReader reader = readers.getReader(Rf2Readers.Keys.DEFINITION); while ((line = reader.readLine()) != null) { final String fields[] = FieldedStringTokenizer.split(line, "\t"); if (!fields[0].equals(id)) { // Stop if the effective time is past the release version if (fields[1].compareTo(releaseVersion) > 0) { reader.push(line); break; } final Atom def = new AtomJpa(); final Date date = ConfigUtility.DATE_FORMAT.parse(fields[1]); def.setTerminologyId(fields[0]); def.setTimestamp(date); def.setLastModified(date); def.setLastModifiedBy(loader); def.setObsolete(fields[2].equals("0")); def.setSuppressible(def.isObsolete()); def.setConceptId(fields[4]); def.setDescriptorId(""); def.setCodeId(""); def.setLexicalClassId(""); def.setStringClassId(""); def.setLanguage(fields[5].intern()); languages.add(def.getLanguage()); def.setTermType(fields[6].intern()); generalEntryValues.add(def.getTermType()); termTypes.add(def.getTermType()); def.setName(fields[7]); def.setTerminology(terminology); def.setVersion(version); def.setPublished(true); def.setPublishable(true); def.setWorkflowStatus(published); // Attributes final Attribute attribute = new AttributeJpa(); setCommonFields(attribute, date); attribute.setName("moduleId"); attribute.setValue(fields[3].intern()); def.addAttribute(attribute); addAttribute(attribute, def); final Attribute attribute2 = new AttributeJpa(); setCommonFields(attribute2, date); attribute2.setName("caseSignificanceId"); attribute2.setValue(fields[8].intern()); cacheAttributeMetadata(attribute2); def.addAttribute(attribute2); addAttribute(attribute2, def); // set concept from cache and set initial prev concept final Concept concept = getConcept(conceptIdMap.get(fields[4])); if (concept != null) { // this also adds language refset entries addAtom(def); atomIdMap.put(def.getTerminologyId(), def.getId()); } else { throw new Exception("Atom " + def.getTerminologyId() + " references non-existent concept " + fields[4]); } logAndCommit(++objectCt, RootService.logCt, RootService.commitCt); } } commitClearBegin(); } /** * Connect atoms and concepts. * * @throws Exception the exception */ private void connectAtomsAndConcepts() throws Exception { // Connect concepts and atoms and compute preferred names Logger.getLogger(getClass()).info(" Connect atoms and concepts"); objectCt = 0; // NOTE: Hibernate-specific to support iterating Session session = manager.unwrap(Session.class); org.hibernate.Query hQuery = session .createQuery("select a from AtomJpa a " + "where conceptId is not null " + "and conceptId != '' and terminology = :terminology " + "order by terminology, conceptId") .setParameter("terminology", terminology).setReadOnly(true) .setFetchSize(1000); ScrollableResults results = hQuery.scroll(ScrollMode.FORWARD_ONLY); String prevCui = null; String prefName = null; String altPrefName = null; Concept concept = null; while (results.next()) { final Atom atom = (Atom) results.get()[0]; if (atom.getConceptId() == null || atom.getConceptId().isEmpty()) { continue; } if (prevCui == null || !prevCui.equals(atom.getConceptId())) { if (concept != null) { // compute preferred name if (prefName == null) { prefName = altPrefName; Logger.getLogger(getClass()) .error("Unable to determine preferred name for " + concept.getTerminologyId()); if (altPrefName == null) { throw new Exception( "Unable to determine preferred name (or alt pref name) for " + concept.getTerminologyId()); } } concept.setName(prefName); prefName = null; // Add definitions if (definitionMap.containsKey(concept.getTerminologyId())) { for (Long id : definitionMap.get(concept.getTerminologyId())) { concept.addDefinition(getDefinition(id)); } } updateConcept(concept); // Set atom subset names if (atomSubsetMap.containsKey(concept.getTerminologyId())) { AtomSubset subset = atomSubsetMap.get(concept.getTerminologyId()); subset.setName(concept.getName()); subset.setDescription(concept.getName()); updateSubset(subset); } logAndCommit(++objectCt, RootService.logCt, RootService.commitCt); } concept = getConcept(conceptIdMap.get(atom.getConceptId())); } concept.addAtom(atom); // Active atoms with pref typeId that are preferred from language refset // perspective is the pref name. This bypasses the pref name computer // but is way faster. if (!atom.isObsolete() && atom.getTermType().equals(dpnTypeId) && prefAtoms.contains(atom.getTerminologyId())) { prefName = atom.getName(); } // Pick an alternative preferred name in case a true pref can't be found // this at least lets us choose something to move on. if (prefName == null && altPrefName == null) { if (!atom.isObsolete() && atom.getTermType().equals(dpnTypeId)) { altPrefName = atom.getName(); } } // If pref name is null, pick the first non-obsolete atom with the correct // term type // this guarantees that SOMETHING is picked prevCui = atom.getConceptId(); } if (concept != null) { if (prefName == null) { throw new Exception("Unable to determine preferred name for " + concept.getTerminologyId()); } concept.setName(prefName); updateConcept(concept); commitClearBegin(); } results.close(); commitClearBegin(); } /** * Load and cache all language refset members. * @throws Exception the exception */ private void loadLanguageRefSetMembers() throws Exception { objectCt = 0; PushBackReader reader = readers.getReader(Rf2Readers.Keys.LANGUAGE); String line; while ((line = reader.readLine()) != null) { final String fields[] = FieldedStringTokenizer.split(line, "\t"); if (!fields[0].equals(id)) { // header // Stop if the effective time is past the release version if (fields[1].compareTo(releaseVersion) > 0) { reader.push(line); return; } final AtomSubsetMember member = new AtomSubsetMemberJpa(); final Date date = ConfigUtility.DATE_FORMAT.parse(fields[1]); refsetHelper(member, fields); // Attributes final Attribute attribute = new AttributeJpa(); setCommonFields(attribute, date); attribute.setName("acceptabilityId"); attribute.setValue(fields[6].intern()); cacheAttributeMetadata(attribute); member.addAttribute(attribute); addAttribute(attribute, member); addSubsetMember(member); // Save preferred atom id info if (!member.isObsolete() && dpnAcceptabilityId.equals(fields[6]) && dpnRefSetIds.contains(fields[4])) { prefAtoms.add(member.getMember().getTerminologyId()); } logAndCommit(++objectCt, RootService.logCt, RootService.commitCt); } } commitClearBegin(); } /** * Load AttributeRefSets (Content). * * @throws Exception the exception */ private void loadAttributeValueRefSets() throws Exception { String line = ""; objectCt = 0; // Iterate through attribute value entries PushBackReader reader = readers.getReader(Rf2Readers.Keys.ATTRIBUTE_VALUE); while ((line = reader.readLine()) != null) { line = line.replace("\r", ""); final String fields[] = FieldedStringTokenizer.split(line, "\t"); if (!fields[0].equals(id)) { // header // Stop if the effective time is past the release version if (fields[1].compareTo(releaseVersion) > 0) { reader.push(line); break; } final Date date = ConfigUtility.DATE_FORMAT.parse(fields[1]); SubsetMember<? extends ComponentHasAttributesAndName, ? extends Subset> member = null; if (conceptIdMap.get(fields[5]) != null) { member = new ConceptSubsetMemberJpa(); } else if (atomIdMap.get(fields[5]) != null) { member = new AtomSubsetMemberJpa(); } else { throw new Exception( "Attribute value member connected to nonexistent object"); } refsetHelper(member, fields); // Attributes final Attribute attribute = new AttributeJpa(); setCommonFields(attribute, date); attribute.setName("valueId"); attribute.setValue(fields[6].intern()); attributeNames.add(attribute.getName()); cacheAttributeMetadata(attribute); member.addAttribute(attribute); addAttribute(attribute, member); // Add member addSubsetMember(member); logAndCommit(++objectCt, RootService.logCt, RootService.commitCt); } } } /** * Load Association Reference Refset (Content). * * @throws Exception the exception */ private void loadAssociationReferenceRefSets() throws Exception { String line = ""; objectCt = 0; // Iterate through attribute value entries PushBackReader reader = readers.getReader(Rf2Readers.Keys.ASSOCIATION_REFERENCE); while ((line = reader.readLine()) != null) { line = line.replace("\r", ""); final String fields[] = FieldedStringTokenizer.split(line, "\t"); if (!fields[0].equals(id)) { // header // Stop if the effective time is past the release version if (fields[1].compareTo(releaseVersion) > 0) { reader.push(line); break; } ConceptRelationship relationship = null; if (conceptIdMap.get(fields[5]) != null) { relationship = new ConceptRelationshipJpa(); } else { throw new Exception( "Association reference member connected to nonexistent object"); } final Date date = ConfigUtility.DATE_FORMAT.parse(fields[1]); // set the fields // id effectiveTime active moduleId refsetId referencedComponentId // targetComponentId relationship.setTerminologyId(fields[0]); relationship.setTimestamp(date); relationship.setLastModified(date); relationship.setObsolete(fields[2].equals("0")); // active relationship.setSuppressible(relationship.isObsolete()); relationship.setRelationshipType("RO"); relationship.setHierarchical(false); relationship.setAdditionalRelationshipType(fields[4]); relationship.setStated(false); relationship.setInferred(false); relationship.setTerminology(terminology); relationship.setVersion(version); relationship.setLastModified(releaseVersionDate); relationship.setLastModifiedBy(loader); relationship.setPublished(true); relationship.setPublishable(true); relationship.setAssertedDirection(true); // ensure additional relationship type has been added additionalRelTypes.add(relationship.getAdditionalRelationshipType()); // Module Id Attribute Attribute attribute = new AttributeJpa(); setCommonFields(attribute, date); attribute.setName("moduleId"); attribute.setValue(fields[3].intern()); relationship.addAttribute(attribute); addAttribute(attribute, relationship); // get concepts from cache, they just need to have ids final Concept fromConcept = getConcept(conceptIdMap.get(fields[4])); final Concept toConcept = getConcept(conceptIdMap.get(fields[5])); if (fromConcept != null && toConcept != null) { relationship.setFrom(fromConcept); relationship.setTo(toConcept); addRelationship(relationship); } else { if (fromConcept == null) { throw new Exception( "Relationship " + relationship.getTerminologyId() + " -existent source concept " + fields[4]); } if (toConcept == null) { throw new Exception("Relationship" + relationship.getTerminologyId() + " references non-existent destination concept " + fields[5]); } } logAndCommit(++objectCt, RootService.logCt, RootService.commitCt); } /** * Make a ConceptRelationshipJpa id = terminologyId timestamp/lastModified * = effectiveTime !active = obsolete published = true, publishable = * true, ... moduleId = becomes an attribute, see how it works in * loadRelationships referencedComponentId, look up the concept -> setFrom * targetComponentId, look up the concept -> setTo relationshipType = "RO" * additionalRelationshipType = refsetId Need to make sure a metadata * additionalRelationshipType gets added abbreviation = refsetId, * expandedForm = name of that concept (e.g. the part in capitals at the * beginning, "POSSIBLY EQUIVALENT TO") make sure to not add it more than * once. */ /* * SubsetMember<? extends ComponentHasAttributesAndName, ? extends Subset> * member = null; if (conceptIdMap.get(fields[5]) != null) { member = new * ConceptSubsetMemberJpa(); } else if (atomIdMap.get(fields[5]) != null) * { member = new AtomSubsetMemberJpa(); } else { throw new Exception( * "Attribute value member connected to nonexistent object"); } * refsetHelper(member, fields); * * // Attributes final Attribute attribute = new AttributeJpa(); * setCommonFields(attribute, date); * attribute.setName("targetComponentId"); * attribute.setValue(fields[6].intern()); * attributeNames.add(attribute.getName()); * member.addAttribute(attribute); addAttribute(attribute, member); * * // Add member addSubsetMember(member); */ logAndCommit(++objectCt, RootService.logCt, RootService.commitCt); } } /** * Load SimpleRefSets (Content). * * @throws Exception the exception */ private void loadSimpleRefSets() throws Exception { String line = ""; objectCt = 0; PushBackReader reader = readers.getReader(Rf2Readers.Keys.SIMPLE); while ((line = reader.readLine()) != null) { line = line.replace("\r", ""); final String fields[] = FieldedStringTokenizer.split(line, "\t"); if (!fields[0].equals(id)) { // header // Stop if the effective time is past the release version if (fields[1].compareTo(releaseVersion) > 0) { reader.push(line); break; } ConceptSubsetMember member = new ConceptSubsetMemberJpa(); refsetHelper(member, fields); // Add member addSubsetMember(member); logAndCommit(++objectCt, RootService.logCt, RootService.commitCt); } } } /** * Load SimpleMapRefSets (Crossmap). * * @throws Exception the exception */ private void loadSimpleMapRefSets() throws Exception { String line = ""; objectCt = 0; PushBackReader reader = readers.getReader(Rf2Readers.Keys.SIMPLE_MAP); while ((line = reader.readLine()) != null) { line = line.replace("\r", ""); final String fields[] = FieldedStringTokenizer.split(line, "\t"); if (!fields[0].equals(id)) { // header // Stop if the effective time is past the release version if (fields[1].compareTo(releaseVersion) > 0) { reader.push(line); break; } final Date date = ConfigUtility.DATE_FORMAT.parse(fields[1]); ConceptSubsetMember member = new ConceptSubsetMemberJpa(); refsetHelper(member, fields); // Attributes Attribute attribute = new AttributeJpa(); setCommonFields(attribute, date); attribute.setName("mapTarget"); attribute.setValue(fields[6].intern()); attributeNames.add(attribute.getName()); member.addAttribute(attribute); addAttribute(attribute, member); // Add member addSubsetMember(member); logAndCommit(++objectCt, RootService.logCt, RootService.commitCt); } } } /** * Load ComplexMapRefSets (Crossmap). * * @throws Exception the exception */ private void loadComplexMapRefSets() throws Exception { // TODO: for now terminology server doesn't load mappings. // later development of mapping objects is needed } /** * Load extended map ref sets. * * @throws Exception the exception */ private void loadExtendedMapRefSets() throws Exception { // TODO: for now terminology server doesn't load mappings. // later development of mapping objects is needed } /** * Load refset descriptor ref sets. * * @throws Exception the exception */ private void loadRefsetDescriptorRefSets() throws Exception { String line = ""; objectCt = 0; PushBackReader reader = readers.getReader(Rf2Readers.Keys.REFSET_DESCRIPTOR); while ((line = reader.readLine()) != null) { line = line.replace("\r", ""); final String fields[] = FieldedStringTokenizer.split(line, "\t"); if (!fields[0].equals(id)) { // header // Stop if the effective time is past the release version if (fields[1].compareTo(releaseVersion) > 0) { reader.push(line); break; } final Date date = ConfigUtility.DATE_FORMAT.parse(fields[1]); ConceptSubsetMember member = new ConceptSubsetMemberJpa(); refsetHelper(member, fields); // Attributes Attribute attribute = new AttributeJpa(); setCommonFields(attribute, date); attribute.setName("attributeDescription"); attribute.setValue(fields[6].intern()); cacheAttributeMetadata(attribute); member.addAttribute(attribute); addAttribute(attribute, member); Attribute attribute2 = new AttributeJpa(); setCommonFields(attribute2, date); attribute2.setName("attributeType"); attribute2.setValue(fields[7].intern()); cacheAttributeMetadata(attribute2); member.addAttribute(attribute2); addAttribute(attribute2, member); Attribute attribute3 = new AttributeJpa(); setCommonFields(attribute3, date); attribute3.setName("attributeOrder"); attribute3.setValue(fields[8].intern()); cacheAttributeMetadata(attribute3); member.addAttribute(attribute3); addAttribute(attribute3, member); // Add member addSubsetMember(member); logAndCommit(++objectCt, RootService.logCt, RootService.commitCt); } } } /** * Load module dependency refset members. * * @throws Exception the exception */ private void loadModuleDependencyRefSets() throws Exception { String line = ""; objectCt = 0; PushBackReader reader = readers.getReader(Rf2Readers.Keys.MODULE_DEPENDENCY); while ((line = reader.readLine()) != null) { line = line.replace("\r", ""); final String fields[] = FieldedStringTokenizer.split(line, "\t"); if (!fields[0].equals(id)) { // header // Stop if the effective time is past the release version if (fields[1].compareTo(releaseVersion) > 0) { reader.push(line); break; } final Date date = ConfigUtility.DATE_FORMAT.parse(fields[1]); ConceptSubsetMember member = new ConceptSubsetMemberJpa(); refsetHelper(member, fields); // Attributes Attribute attribute = new AttributeJpa(); setCommonFields(attribute, date); attribute.setName("sourceEffectiveTime"); attribute.setValue(fields[6].intern()); attributeNames.add(attribute.getName()); member.addAttribute(attribute); addAttribute(attribute, member); Attribute attribute2 = new AttributeJpa(); setCommonFields(attribute2, date); attribute2.setName("targetEffectiveTime"); attribute2.setValue(fields[7].intern()); attributeNames.add(attribute2.getName()); member.addAttribute(attribute2); addAttribute(attribute2, member); addSubsetMember(member); logAndCommit(++objectCt, RootService.logCt, RootService.commitCt); } } } /** * Load description type refset members. * * @throws Exception the exception */ private void loadAtomTypeRefSets() throws Exception { String line = ""; objectCt = 0; PushBackReader reader = readers.getReader(Rf2Readers.Keys.DESCRIPTION_TYPE); while ((line = reader.readLine()) != null) { line = line.replace("\r", ""); final String fields[] = FieldedStringTokenizer.split(line, "\t"); if (!fields[0].equals(id)) { // header // Stop if the effective time is past the release version if (fields[1].compareTo(releaseVersion) > 0) { reader.push(line); break; } final Date date = ConfigUtility.DATE_FORMAT.parse(fields[1]); ConceptSubsetMember member = new ConceptSubsetMemberJpa(); refsetHelper(member, fields); // Attributes Attribute attribute = new AttributeJpa(); setCommonFields(attribute, date); attribute.setName("descriptionFormat"); attribute.setValue(fields[6].intern()); cacheAttributeMetadata(attribute); member.addAttribute(attribute); addAttribute(attribute, member); Attribute attribute2 = new AttributeJpa(); setCommonFields(attribute2, date); attribute2.setName("descriptionLength"); attribute2.setValue(fields[7].intern()); attributeNames.add(attribute2.getName()); member.addAttribute(attribute2); addAttribute(attribute2, member); addSubsetMember(member); logAndCommit(++objectCt, RootService.logCt, RootService.commitCt); } } } /** * Refset helper. * * @param member the member * @param fields the fields * @throws Exception the exception */ private void refsetHelper( SubsetMember<? extends ComponentHasAttributesAndName, ? extends Subset> member, String[] fields) throws Exception { if (conceptIdMap.get(fields[5]) != null) { // Retrieve concept -- firstToken is referencedComponentId final Concept concept = getConcept(conceptIdMap.get(fields[5])); ((ConceptSubsetMember) member).setMember(concept); } else if (atomIdMap.get(fields[5]) != null) { final Atom description = getAtom(atomIdMap.get(fields[5])); ((AtomSubsetMember) member).setMember(description); } else { throw new Exception( "Attribute value member connected to nonexistent object"); } // Universal RefSet attributes final Date date = ConfigUtility.DATE_FORMAT.parse(fields[1]); member.setTerminology(terminology); member.setVersion(version); member.setTerminologyId(fields[0]); member.setTimestamp(date); member.setLastModified(date); member.setLastModifiedBy(loader); member.setObsolete(fields[2].equals("0")); member.setSuppressible(member.isObsolete()); member.setPublished(true); member.setPublishable(true); if (atomSubsetMap.containsKey(fields[4])) { final AtomSubset subset = atomSubsetMap.get(fields[4]); ((AtomSubsetMember) member).setSubset(subset); } else if (conceptSubsetMap.containsKey(fields[4])) { final ConceptSubset subset = conceptSubsetMap.get(fields[4]); ((ConceptSubsetMember) member).setSubset(subset); } else if (member instanceof AtomSubsetMember && !atomSubsetMap.containsKey(fields[4])) { final AtomSubset subset = new AtomSubsetJpa(); setCommonFields(subset, date); subset.setTerminologyId(fields[4].intern()); subset.setName(getConcept(conceptIdMap.get(fields[4])).getName()); subset.setDescription(subset.getName()); final Attribute attribute2 = new AttributeJpa(); setCommonFields(attribute2, date); attribute2.setName("moduleId"); attribute2.setValue(fields[3].intern()); subset.addAttribute(attribute2); addAttribute(attribute2, member); addSubset(subset); atomSubsetMap.put(fields[4], subset); commitClearBegin(); ((AtomSubsetMember) member).setSubset(subset); } else if (member instanceof ConceptSubsetMember && !conceptSubsetMap.containsKey(fields[4])) { final ConceptSubset subset = new ConceptSubsetJpa(); setCommonFields(subset, date); subset.setTerminologyId(fields[4].intern()); subset.setName(getConcept(conceptIdMap.get(fields[4])).getName()); subset.setDescription(subset.getName()); subset.setDisjointSubset(false); final Attribute attribute2 = new AttributeJpa(); setCommonFields(attribute2, date); attribute2.setName("moduleId"); attribute2.setValue(fields[3].intern()); subset.addAttribute(attribute2); addAttribute(attribute2, member); addSubset(subset); conceptSubsetMap.put(fields[4], subset); commitClearBegin(); ((ConceptSubsetMember) member).setSubset(subset); } else { throw new Exception("Unable to determine refset type."); } // Add moduleId attribute final Attribute attribute = new AttributeJpa(); setCommonFields(attribute, date); attribute.setName("moduleId"); attribute.setValue(fields[3].intern()); cacheAttributeMetadata(attribute); member.addAttribute(attribute); addAttribute(attribute, member); } /** * Load metadata. * * @throws Exception the exception */ private void loadMetadata() throws Exception { // Term types - each description type for (String tty : termTypes) { TermType termType = new TermTypeJpa(); termType.setTerminology(terminology); termType.setVersion(version); termType.setAbbreviation(tty); termType.setCodeVariantType(CodeVariantType.SY); termType.setExpandedForm(getConcept(conceptIdMap.get(tty)).getName()); termType.setHierarchicalType(false); termType.setTimestamp(releaseVersionDate); termType.setLastModified(releaseVersionDate); termType.setLastModifiedBy(loader); termType.setNameVariantType(NameVariantType.UNDEFINED); termType.setObsolete(false); termType.setSuppressible(false); termType.setPublishable(true); termType.setPublished(true); termType.setUsageType(UsageType.UNDEFINED); addTermType(termType); } // Languages - each language value Language rootLanguage = null; for (String lat : languages) { Language language = new LanguageJpa(); language.setTerminology(terminology); language.setVersion(version); language.setTimestamp(releaseVersionDate); language.setLastModified(releaseVersionDate); language.setLastModifiedBy(loader); language.setPublishable(true); language.setPublished(true); language.setExpandedForm(lat); language.setAbbreviation(lat); language.setISO3Code("???"); language.setISOCode(lat.substring(0, 2)); addLanguage(language); if (rootLanguage == null) { rootLanguage = language; } } // attribute name for (String atn : attributeNames) { AttributeName name = new AttributeNameJpa(); name.setTerminology(terminology); name.setVersion(version); name.setLastModified(releaseVersionDate); name.setLastModifiedBy(loader); name.setPublishable(true); name.setPublished(true); name.setExpandedForm(atn); name.setAbbreviation(atn); addAttributeName(name); } // relationship types - subClassOf, superClassOf String[] relTypes = new String[] { "other", "Inverse is a", "Is a" }; RelationshipType chd = null; RelationshipType par = null; RelationshipType ro = null; for (String rel : relTypes) { RelationshipType type = new RelationshipTypeJpa(); type.setTerminology(terminology); type.setVersion(version); type.setLastModified(releaseVersionDate); type.setLastModifiedBy(loader); type.setPublishable(true); type.setPublished(true); type.setAbbreviation(rel); if (rel.equals("Is a")) { chd = type; type.setExpandedForm("Is a (has parent)"); } else if (rel.equals("Inverse is a")) { par = type; type.setExpandedForm("Inverse is a (has child)"); } else if (rel.equals("other")) { ro = type; type.setExpandedForm("Other"); } else { throw new Exception("Unhandled type"); } addRelationshipType(type); } chd.setInverse(par); par.setInverse(chd); ro.setInverse(ro); updateRelationshipType(chd); updateRelationshipType(par); updateRelationshipType(ro); // additional relationship types (including grouping type, hierarchical // type) AdditionalRelationshipType directSubstance = null; AdditionalRelationshipType hasActiveIngredient = null; Map<AdditionalRelationshipType, AdditionalRelationshipType> inverses = new HashMap<>(); for (String rela : additionalRelTypes) { AdditionalRelationshipType type = new AdditionalRelationshipTypeJpa(); type.setTerminology(terminology); type.setVersion(version); type.setLastModified(releaseVersionDate); type.setLastModifiedBy(loader); type.setPublishable(true); type.setPublished(true); type.setExpandedForm(getConcept(conceptIdMap.get(rela)).getName()); type.setAbbreviation(rela); // $nevergrouped{"123005000"} = "T"; # part-of is never grouped // $nevergrouped{"272741003"} = "T"; # laterality is never grouped // $nevergrouped{"127489000"} = "T"; # has-active-ingredient is never // grouped // $nevergrouped{"411116001"} = "T"; # has-dose-form is never grouped if (rela.equals("123005000") || rela.equals("272741003") || rela.equals("127489000") || rela.equals("411116001")) { type.setGroupingType(false); } else { type.setGroupingType(true); } addAdditionalRelationshipType(type); if (rela.equals("363701004")) { hasActiveIngredient = type; } else if (rela.equals("127489000")) { directSubstance = type; } AdditionalRelationshipType inverseType = new AdditionalRelationshipTypeJpa(type); inverseType.setId(null); inverseType.setAbbreviation("inverse_" + type.getAbbreviation()); inverseType.setExpandedForm("inverse_" + type.getAbbreviation()); inverses.put(type, inverseType); addAdditionalRelationshipType(inverseType); } // handle inverses for (AdditionalRelationshipType type : inverses.keySet()) { AdditionalRelationshipType inverseType = inverses.get(type); type.setInverse(inverseType); inverseType.setInverse(type); updateAdditionalRelationshipType(type); updateAdditionalRelationshipType(inverseType); } // property chains (see Owl) // $rightid{"363701004"} = "127489000"; # direct-substance o // has-active-ingredient -> direct-substance PropertyChain chain = new PropertyChainJpa(); chain.setTerminology(terminology); chain.setVersion(version); chain.setLastModified(releaseVersionDate); chain.setLastModifiedBy(loader); chain.setPublishable(true); chain.setPublished(true); chain.setAbbreviation( "direct-substance o has-active-ingredient -> direct-substance"); chain.setExpandedForm(chain.getAbbreviation()); List<AdditionalRelationshipType> list = new ArrayList<>(); list.add(directSubstance); list.add(hasActiveIngredient); chain.setChain(list); chain.setResult(directSubstance); // do this only when the available rels exist if (chain.getChain().size() > 0 && chain.getResult() != null) { addPropertyChain(chain); } // semantic types - n/a // Root Terminology RootTerminology root = new RootTerminologyJpa(); root.setFamily(terminology); root.setHierarchicalName( getConcept(conceptIdMap.get(rootConceptId)).getName()); root.setLanguage(rootLanguage); root.setTimestamp(releaseVersionDate); root.setLastModified(releaseVersionDate); root.setLastModifiedBy(loader); root.setPolyhierarchy(true); root.setPreferredName(root.getHierarchicalName()); root.setRestrictionLevel(-1); root.setTerminology(terminology); addRootTerminology(root); // Terminology Terminology term = new TerminologyJpa(); term.setTerminology(terminology); term.setVersion(version); term.setTimestamp(releaseVersionDate); term.setLastModified(releaseVersionDate); term.setLastModifiedBy(loader); term.setAssertsRelDirection(true); term.setCurrent(true); term.setDescriptionLogicTerminology(true); term.setOrganizingClassType(IdType.CONCEPT); term.setPreferredName(root.getPreferredName()); term.setRootTerminology(root); addTerminology(term); // Add general metadata entries for all the attribute values // that are concept ids. for (String conceptId : generalEntryValues) { // Skip if there is no concept for this thing if (!conceptIdMap.containsKey(conceptId)) { Logger.getLogger(getClass()) .info(" Skipping Genral Metadata Entry = " + conceptId); continue; } String name = getConcept(conceptIdMap.get(conceptId)).getName(); Logger.getLogger(getClass()) .info(" Genral Metadata Entry = " + conceptId + ", " + name); GeneralMetadataEntry entry = new GeneralMetadataEntryJpa(); entry.setTerminology(terminology); entry.setVersion(version); entry.setLastModified(releaseVersionDate); entry.setLastModifiedBy(loader); entry.setPublishable(true); entry.setPublished(true); entry.setAbbreviation(conceptId); entry.setExpandedForm(name); entry.setKey("concept_metadata"); entry.setType("concept_name"); addGeneralMetadataEntry(entry); } String[] labels = new String[] { "Atoms_Label", "Subsets_Label", "Attributes_Label", "Semantic_Types_Label", "Obsolete_Label", "Obsolete_Indicator", }; String[] labelValues = new String[] { "Descriptions", "Refsets", "Properties", "Semantic Tags", "Retired", "Retired" }; int i = 0; for (String label : labels) { GeneralMetadataEntry entry = new GeneralMetadataEntryJpa(); entry.setTerminology(terminology); entry.setVersion(version); entry.setLastModified(releaseVersionDate); entry.setLastModifiedBy(loader); entry.setPublishable(true); entry.setPublished(true); entry.setAbbreviation(label); entry.setExpandedForm(labelValues[i++]); entry.setKey("label_metadata"); entry.setType("label_values"); addGeneralMetadataEntry(entry); } commitClearBegin(); } /** * Load extension label sets. * * @throws Exception the exception */ private void loadExtensionLabelSets() throws Exception { // for each non core module, create a Subset object List<ConceptSubset> subsets = new ArrayList<>(); for (String moduleId : moduleIds) { Logger.getLogger(getClass()) .info(" Create subset for module = " + moduleId); Concept concept = getConcept(conceptIdMap.get(moduleId)); ConceptSubset subset = new ConceptSubsetJpa(); subset.setName(concept.getName()); subset.setDescription("Represents the members of module " + moduleId); subset.setDisjointSubset(false); subset.setLabelSubset(true); subset.setLastModified(releaseVersionDate); subset.setTimestamp(releaseVersionDate); subset.setLastModifiedBy(loader); subset.setObsolete(false); subset.setSuppressible(false); subset.setPublishable(false); subset.setPublished(false); subset.setTerminology(terminology); subset.setTerminologyId(moduleId); subset.setVersion(version); addSubset(subset); subsets.add(subset); commitClearBegin(); // Create members int objectCt = 0; Logger.getLogger(getClass()).info(" Add subset members"); for (String conceptId : moduleConceptIdMap.get(moduleId)) { final Concept memberConcept = getConcept(conceptIdMap.get(conceptId)); ConceptSubsetMember member = new ConceptSubsetMemberJpa(); member.setLastModified(releaseVersionDate); member.setTimestamp(releaseVersionDate); member.setLastModifiedBy(loader); member.setMember(memberConcept); member.setObsolete(false); member.setSuppressible(false); member.setPublishable(false); member.setPublishable(false); member.setTerminologyId(""); member.setTerminology(terminology); member.setVersion(version); member.setSubset(subset); addSubsetMember(member); logAndCommit(++objectCt, RootService.logCt, RootService.commitCt); } } Logger.getLogger(getClass()).info(" count = " + objectCt); } /** * xsets the common fields. * * @param component the common fields * @param date the date */ private void setCommonFields(Component component, Date date) { component.setTimestamp(date); component.setTerminologyId(""); component.setTerminology(terminology); component.setVersion(version); component.setLastModified(date); component.setLastModifiedBy(loader); component.setObsolete(false); component.setPublishable(true); component.setPublished(true); component.setSuppressible(false); } /** * Cache attribute value. * * @param attribute the attribute */ private void cacheAttributeMetadata(Attribute attribute) { attributeNames.add(attribute.getName()); if (attribute.getValue().matches("^\\d[\\d]{6,}$")) { generalEntryValues.add(attribute.getValue()); } } /** * Indicates whether or not extension module is the case. * * @param moduleId the module id * @return <code>true</code> if so, <code>false</code> otherwise */ @SuppressWarnings("static-method") private boolean isExtensionModule(String moduleId) { return !moduleId.equals(coreModuleId) && !moduleId.equals(metadataModuleId); } /* see superclass */ @Override public void close() throws Exception { super.close(); readers = null; } }
jpa-services/src/main/java/com/wci/umls/server/jpa/algo/Rf2SnapshotLoaderAlgorithm.java
/* * Copyright 2015 West Coast Informatics, LLC */ package com.wci.umls.server.jpa.algo; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import org.hibernate.ScrollMode; import org.hibernate.ScrollableResults; import org.hibernate.Session; import com.wci.umls.server.ReleaseInfo; import com.wci.umls.server.algo.Algorithm; import com.wci.umls.server.helpers.Branch; import com.wci.umls.server.helpers.ConfigUtility; import com.wci.umls.server.helpers.FieldedStringTokenizer; import com.wci.umls.server.jpa.ReleaseInfoJpa; import com.wci.umls.server.jpa.content.AtomJpa; import com.wci.umls.server.jpa.content.AtomSubsetJpa; import com.wci.umls.server.jpa.content.AtomSubsetMemberJpa; import com.wci.umls.server.jpa.content.AttributeJpa; import com.wci.umls.server.jpa.content.ConceptJpa; import com.wci.umls.server.jpa.content.ConceptRelationshipJpa; import com.wci.umls.server.jpa.content.ConceptSubsetJpa; import com.wci.umls.server.jpa.content.ConceptSubsetMemberJpa; import com.wci.umls.server.jpa.meta.AdditionalRelationshipTypeJpa; import com.wci.umls.server.jpa.meta.AttributeNameJpa; import com.wci.umls.server.jpa.meta.GeneralMetadataEntryJpa; import com.wci.umls.server.jpa.meta.LanguageJpa; import com.wci.umls.server.jpa.meta.PropertyChainJpa; import com.wci.umls.server.jpa.meta.RelationshipTypeJpa; import com.wci.umls.server.jpa.meta.RootTerminologyJpa; import com.wci.umls.server.jpa.meta.TermTypeJpa; import com.wci.umls.server.jpa.meta.TerminologyJpa; import com.wci.umls.server.jpa.services.HistoryServiceJpa; import com.wci.umls.server.model.content.Atom; import com.wci.umls.server.model.content.AtomSubset; import com.wci.umls.server.model.content.AtomSubsetMember; import com.wci.umls.server.model.content.Attribute; import com.wci.umls.server.model.content.Component; import com.wci.umls.server.model.content.ComponentHasAttributesAndName; import com.wci.umls.server.model.content.Concept; import com.wci.umls.server.model.content.ConceptRelationship; import com.wci.umls.server.model.content.ConceptSubset; import com.wci.umls.server.model.content.ConceptSubsetMember; import com.wci.umls.server.model.content.Subset; import com.wci.umls.server.model.content.SubsetMember; import com.wci.umls.server.model.meta.AdditionalRelationshipType; import com.wci.umls.server.model.meta.AttributeName; import com.wci.umls.server.model.meta.CodeVariantType; import com.wci.umls.server.model.meta.GeneralMetadataEntry; import com.wci.umls.server.model.meta.IdType; import com.wci.umls.server.model.meta.Language; import com.wci.umls.server.model.meta.NameVariantType; import com.wci.umls.server.model.meta.PropertyChain; import com.wci.umls.server.model.meta.RelationshipType; import com.wci.umls.server.model.meta.RootTerminology; import com.wci.umls.server.model.meta.TermType; import com.wci.umls.server.model.meta.Terminology; import com.wci.umls.server.model.meta.UsageType; import com.wci.umls.server.services.RootService; import com.wci.umls.server.services.helpers.ProgressEvent; import com.wci.umls.server.services.helpers.ProgressListener; import com.wci.umls.server.services.helpers.PushBackReader; /** * Implementation of an algorithm to import RF2 snapshot data. */ public class Rf2SnapshotLoaderAlgorithm extends HistoryServiceJpa implements Algorithm { /** Listeners. */ private List<ProgressListener> listeners = new ArrayList<>(); /** The isa type rel. */ private final static String isaTypeRel = "116680003"; /** The root concept id. */ private final static String rootConceptId = "138875005"; /** The Constant coreModuleId. */ private final static String coreModuleId = "900000000000207008"; /** The Constant metadataModuleId. */ private final static String metadataModuleId = "900000000000012004"; /** The dpn ref set id. */ private Set<String> dpnRefSetIds = new HashSet<>(); { // US English Language dpnRefSetIds.add("900000000000509007"); // VET extension dpnRefSetIds.add("332501000009101"); } /** The dpn acceptability id. */ private String dpnAcceptabilityId = "900000000000548007"; /** The dpn type id. */ private String dpnTypeId = "900000000000013009"; /** The preferred atoms set. */ private Set<String> prefAtoms = new HashSet<>(); /** The terminology. */ private String terminology; /** The terminology version. */ private String version; /** The release version. */ private String releaseVersion; /** The release version date. */ private Date releaseVersionDate; /** The readers. */ private Rf2Readers readers; /** The definition map. */ private Map<String, Set<Long>> definitionMap = new HashMap<>(); /** The atom id map. */ private Map<String, Long> atomIdMap = new HashMap<>(); /** The module ids. */ private Set<String> moduleIds = new HashSet<>(); /** non-core modules map. */ private Map<String, Set<String>> moduleConceptIdMap = new HashMap<>(); /** The concept id map. */ private Map<String, Long> conceptIdMap = new HashMap<>(); /** The atom subset map. */ private Map<String, AtomSubset> atomSubsetMap = new HashMap<>(); /** The concept subset map. */ private Map<String, ConceptSubset> conceptSubsetMap = new HashMap<>(); /** The term types. */ private Set<String> termTypes = new HashSet<>(); /** The additional rel types. */ private Set<String> additionalRelTypes = new HashSet<>(); /** The languages. */ private Set<String> languages = new HashSet<>(); /** The attribute names. */ private Set<String> attributeNames = new HashSet<>(); /** The concept attribute values. */ private Set<String> generalEntryValues = new HashSet<>(); /** counter for objects created, reset in each load section. */ int objectCt; // /** The init pref name. */ final String initPrefName = "No default preferred name found"; /** The loader. */ final String loader = "loader"; /** The id. */ final String id = "id"; /** The published. */ final String published = "PUBLISHED"; /** * Instantiates an empty {@link Rf2SnapshotLoaderAlgorithm}. * @throws Exception if anything goes wrong */ public Rf2SnapshotLoaderAlgorithm() throws Exception { super(); } /** * Sets the terminology. * * @param terminology the terminology */ public void setTerminology(String terminology) { this.terminology = terminology; } /** * Sets the terminology version. * * @param version the terminology version */ public void setVersion(String version) { this.version = version; } /** * Sets the release version. * * @param releaseVersion the rlease version */ public void setReleaseVersion(String releaseVersion) { this.releaseVersion = releaseVersion; } /** * Sets the readers. * * @param readers the readers */ public void setReaders(Rf2Readers readers) { this.readers = readers; } /* see superclass */ @Override public void compute() throws Exception { try { Logger.getLogger(getClass()).info("Start loading snapshot"); Logger.getLogger(getClass()).info(" terminology = " + terminology); Logger.getLogger(getClass()).info(" version = " + version); Logger.getLogger(getClass()).info(" releaseVersion = " + releaseVersion); releaseVersionDate = ConfigUtility.DATE_FORMAT.parse(releaseVersion); // control transaction scope setTransactionPerOperation(false); // Turn of ID computation when loading a terminology setAssignIdentifiersFlag(false); // Let loader set last modified flags. setLastModifiedFlag(false); // faster performance. beginTransaction(); // // Load concepts // Logger.getLogger(getClass()).info(" Loading Concepts..."); loadConcepts(); // // Load descriptions and language refsets // Logger.getLogger(getClass()).info(" Loading Atoms..."); loadAtoms(); loadDefinitions(); Logger.getLogger(getClass()).info(" Loading Language Ref Sets..."); loadLanguageRefSetMembers(); Logger.getLogger(getClass()).info( " Connecting atoms/concepts and computing preferred names..."); connectAtomsAndConcepts(); // // Load relationships // Logger.getLogger(getClass()).info(" Loading Relationships..."); loadRelationships(); // // load AssocationReference RefSets (Content) // Logger.getLogger(getClass()).info( " Loading Association Reference Ref Sets..."); loadAssociationReferenceRefSets(); commitClearBegin(); // // Load AttributeValue RefSets (Content) // Logger.getLogger(getClass()) .info(" Loading Attribute Value Ref Sets..."); loadAttributeValueRefSets(); commitClearBegin(); // // Load Simple RefSets (Content) // Logger.getLogger(getClass()).info(" Loading Simple Ref Sets..."); loadSimpleRefSets(); // // Load SimpleMapRefSets // Logger.getLogger(getClass()).info(" Loading Simple Map Ref Sets..."); loadSimpleMapRefSets(); commitClearBegin(); // // Load ComplexMapRefSets // Logger.getLogger(getClass()).info(" Loading Complex Map Ref Sets..."); loadComplexMapRefSets(); // // Load ExtendedMapRefSets // Logger.getLogger(getClass()).info(" Loading Extended Map Ref Sets..."); loadExtendedMapRefSets(); commitClearBegin(); // load RefsetDescriptor RefSets (Content) // Logger.getLogger(getClass()).info( " Loading Refset Descriptor Ref Sets..."); loadRefsetDescriptorRefSets(); // // load ModuleDependency RefSets (Content) // Logger.getLogger(getClass()).info( " Loading Module Dependency Ref Sets..."); loadModuleDependencyRefSets(); // // load AtomType RefSets (Content) // Logger.getLogger(getClass()).info(" Loading Atom Type Ref Sets..."); loadAtomTypeRefSets(); // Load metadata loadMetadata(); // Make subsets and label sets loadExtensionLabelSets(); // // Create ReleaseInfo for this release if it does not already exist // ReleaseInfo info = getReleaseInfo(terminology, releaseVersion); if (info == null) { info = new ReleaseInfoJpa(); info.setName(releaseVersion); info.setDescription(terminology + " " + releaseVersion + " release"); info.setPlanned(false); info.setPublished(true); info.setReleaseBeginDate(releaseVersionDate); info.setReleaseFinishDate(releaseVersionDate); info.setTerminology(terminology); info.setVersion(version); info.setLastModified(releaseVersionDate); info.setLastModifiedBy(loader); addReleaseInfo(info); } // Clear concept cache // clear and commit commitClearBegin(); Logger.getLogger(getClass()).info( getComponentStats(terminology, version, Branch.ROOT)); Logger.getLogger(getClass()).info("Done ..."); } catch (Exception e) { throw e; } } /* see superclass */ @Override public void reset() throws Exception { // do nothing } /** * Fires a {@link ProgressEvent}. * @param pct percent done * @param note progress note */ public void fireProgressEvent(int pct, String note) { ProgressEvent pe = new ProgressEvent(this, pct, pct, note); for (int i = 0; i < listeners.size(); i++) { listeners.get(i).updateProgress(pe); } Logger.getLogger(getClass()).info(" " + pct + "% " + note); } /* see superclass */ @Override public void addProgressListener(ProgressListener l) { listeners.add(l); } /* see superclass */ @Override public void removeProgressListener(ProgressListener l) { listeners.remove(l); } /* see superclass */ @Override public void cancel() { throw new UnsupportedOperationException("cannot cancel."); } /** * Load concepts. * * @throws Exception the exception */ private void loadConcepts() throws Exception { String line = ""; objectCt = 0; PushBackReader reader = readers.getReader(Rf2Readers.Keys.CONCEPT); while ((line = reader.readLine()) != null) { final String fields[] = FieldedStringTokenizer.split(line,"\t"); final Concept concept = new ConceptJpa(); if (!fields[0].equals(id)) { // header // Stop if the effective time is past the release version if (fields[1].compareTo(releaseVersion) > 0) { reader.push(line); break; } final Date date = ConfigUtility.DATE_FORMAT.parse(fields[1]); concept.setTerminologyId(fields[0]); concept.setTimestamp(date); concept.setObsolete(fields[2].equals("0")); concept.setSuppressible(concept.isObsolete()); concept.setFullyDefined(fields[4].equals("900000000000073002")); concept.setTerminology(terminology); concept.setVersion(version); concept.setName(initPrefName); concept.setLastModified(date); concept.setLastModifiedBy(loader); concept.setPublished(true); concept.setPublishable(true); concept.setUsesRelationshipUnion(true); concept.setWorkflowStatus(published); // Attributes final Attribute attribute = new AttributeJpa(); setCommonFields(attribute, date); attribute.setName("moduleId"); attribute.setValue(fields[3].intern()); cacheAttributeMetadata(attribute); concept.addAttribute(attribute); addAttribute(attribute, concept); final Attribute attribute2 = new AttributeJpa(); setCommonFields(attribute2, date); attribute2.setName("definitionStatusId"); attribute2.setValue(fields[4].intern()); cacheAttributeMetadata(attribute2); concept.addAttribute(attribute2); addAttribute(attribute2, concept); // copy concept to shed any hibernate stuff addConcept(concept); conceptIdMap.put(concept.getTerminologyId(), concept.getId()); // Save extension module info if (isExtensionModule(fields[3])) { moduleIds.add(fields[3]); if (!moduleConceptIdMap.containsKey(fields[3])) { moduleConceptIdMap.put(fields[3], new HashSet<String>()); } moduleConceptIdMap.get(fields[3]).add(concept.getTerminologyId()); } logAndCommit(++objectCt, RootService.logCt, RootService.commitCt); } } commitClearBegin(); } /** * Load relationships. * * @throws Exception the exception */ private void loadRelationships() throws Exception { String line = ""; objectCt = 0; PushBackReader reader = readers.getReader(Rf2Readers.Keys.RELATIONSHIP); // Iterate over relationships while ((line = reader.readLine()) != null) { // Split line final String fields[] = FieldedStringTokenizer.split(line,"\t"); // Skip header if (!fields[0].equals(id)) { // Stop if the effective time is past the release version if (fields[1].compareTo(releaseVersion) > 0) { reader.push(line); break; } // Configure relationship final ConceptRelationship relationship = new ConceptRelationshipJpa(); final Date date = ConfigUtility.DATE_FORMAT.parse(fields[1]); relationship.setTerminologyId(fields[0]); relationship.setTimestamp(date); relationship.setLastModified(date); relationship.setObsolete(fields[2].equals("0")); // active relationship.setSuppressible(relationship.isObsolete()); relationship.setGroup(fields[6].intern()); // relationshipGroup relationship.setRelationshipType(fields[7].equals(isaTypeRel) ? "Is a" : "other"); // typeId relationship.setAdditionalRelationshipType(fields[7]); // typeId relationship.setHierarchical(relationship.getRelationshipType().equals( "Is a")); generalEntryValues.add(relationship.getAdditionalRelationshipType()); additionalRelTypes.add(relationship.getAdditionalRelationshipType()); relationship.setStated(fields[8].equals("900000000000010007")); relationship.setInferred(fields[8].equals("900000000000011006")); relationship.setTerminology(terminology); relationship.setVersion(version); relationship.setLastModified(releaseVersionDate); relationship.setLastModifiedBy(loader); relationship.setPublished(true); relationship.setPublishable(true); relationship.setAssertedDirection(true); // Attributes Attribute attribute = new AttributeJpa(); setCommonFields(attribute, date); attribute.setName("moduleId"); attribute.setValue(fields[3].intern()); relationship.addAttribute(attribute); addAttribute(attribute, relationship); Attribute attribute2 = new AttributeJpa(); setCommonFields(attribute2, date); attribute2.setName("characteristicTypeId"); attribute2.setValue(fields[8].intern()); cacheAttributeMetadata(attribute2); relationship.addAttribute(attribute2); addAttribute(attribute2, relationship); Attribute attribute3 = new AttributeJpa(); setCommonFields(attribute3, date); attribute3.setName("modifierId"); attribute3.setValue(fields[9].intern()); cacheAttributeMetadata(attribute3); relationship.addAttribute(attribute3); addAttribute(attribute3, relationship); // get concepts from cache, they just need to have ids final Concept fromConcept = getConcept(conceptIdMap.get(fields[4])); final Concept toConcept = getConcept(conceptIdMap.get(fields[5])); if (fromConcept != null && toConcept != null) { relationship.setFrom(fromConcept); relationship.setTo(toConcept); // unnecessary // sourceConcept.addRelationship(relationship); addRelationship(relationship); } else { if (fromConcept == null) { throw new Exception("Relationship " + relationship.getTerminologyId() + " -existent source concept " + fields[4]); } if (toConcept == null) { throw new Exception("Relationship" + relationship.getTerminologyId() + " references non-existent destination concept " + fields[5]); } } logAndCommit(++objectCt, RootService.logCt, RootService.commitCt); } } // Final commit commitClearBegin(); } /** * Load descriptions. * * @throws Exception the exception */ private void loadAtoms() throws Exception { String line = ""; objectCt = 0; PushBackReader reader = readers.getReader(Rf2Readers.Keys.DESCRIPTION); while ((line = reader.readLine()) != null) { final String fields[] = FieldedStringTokenizer.split(line,"\t"); if (!fields[0].equals(id)) { // Stop if the effective time is past the release version if (fields[1].compareTo(releaseVersion) > 0) { reader.push(line); break; } final Atom atom = new AtomJpa(); final Date date = ConfigUtility.DATE_FORMAT.parse(fields[1]); atom.setTerminologyId(fields[0]); atom.setTimestamp(date); atom.setLastModified(date); atom.setLastModifiedBy(loader); atom.setObsolete(fields[2].equals("0")); atom.setSuppressible(atom.isObsolete()); atom.setConceptId(fields[4]); atom.setDescriptorId(""); atom.setCodeId(""); atom.setLexicalClassId(""); atom.setStringClassId(""); atom.setLanguage(fields[5].intern()); languages.add(atom.getLanguage()); atom.setTermType(fields[6].intern()); generalEntryValues.add(atom.getTermType()); termTypes.add(atom.getTermType()); atom.setName(fields[7]); atom.setTerminology(terminology); atom.setVersion(version); atom.setPublished(true); atom.setPublishable(true); atom.setWorkflowStatus(published); // Attributes final Attribute attribute = new AttributeJpa(); setCommonFields(attribute, date); attribute.setName("moduleId"); attribute.setValue(fields[3].intern()); atom.addAttribute(attribute); addAttribute(attribute, atom); final Attribute attribute2 = new AttributeJpa(); setCommonFields(attribute2, date); attribute2.setName("caseSignificanceId"); attribute2.setValue(fields[8].intern()); cacheAttributeMetadata(attribute2); atom.addAttribute(attribute2); addAttribute(attribute2, atom); // set concept from cache and set initial prev concept final Long conceptId = conceptIdMap.get(fields[4]); if (conceptId == null) { throw new Exception( "Descriptions file references nonexistent concept: " + fields[4]); } final Concept concept = getConcept(conceptIdMap.get(fields[4])); if (concept != null) { // this also adds language refset entries addAtom(atom); atomIdMap.put(atom.getTerminologyId(), atom.getId()); } else { throw new Exception("Atom " + atom.getTerminologyId() + " references non-existent concept " + fields[4]); } logAndCommit(++objectCt, RootService.logCt, RootService.commitCt); } } commitClearBegin(); } /** * Load definitions. Treat exactly like descriptions. * * @throws Exception the exception */ private void loadDefinitions() throws Exception { String line = ""; objectCt = 0; PushBackReader reader = readers.getReader(Rf2Readers.Keys.DEFINITION); while ((line = reader.readLine()) != null) { final String fields[] = FieldedStringTokenizer.split(line,"\t"); if (!fields[0].equals(id)) { // Stop if the effective time is past the release version if (fields[1].compareTo(releaseVersion) > 0) { reader.push(line); break; } final Atom def = new AtomJpa(); final Date date = ConfigUtility.DATE_FORMAT.parse(fields[1]); def.setTerminologyId(fields[0]); def.setTimestamp(date); def.setLastModified(date); def.setLastModifiedBy(loader); def.setObsolete(fields[2].equals("0")); def.setSuppressible(def.isObsolete()); def.setConceptId(fields[4]); def.setDescriptorId(""); def.setCodeId(""); def.setLexicalClassId(""); def.setStringClassId(""); def.setLanguage(fields[5].intern()); languages.add(def.getLanguage()); def.setTermType(fields[6].intern()); generalEntryValues.add(def.getTermType()); termTypes.add(def.getTermType()); def.setName(fields[7]); def.setTerminology(terminology); def.setVersion(version); def.setPublished(true); def.setPublishable(true); def.setWorkflowStatus(published); // Attributes final Attribute attribute = new AttributeJpa(); setCommonFields(attribute, date); attribute.setName("moduleId"); attribute.setValue(fields[3].intern()); def.addAttribute(attribute); addAttribute(attribute, def); final Attribute attribute2 = new AttributeJpa(); setCommonFields(attribute2, date); attribute2.setName("caseSignificanceId"); attribute2.setValue(fields[8].intern()); cacheAttributeMetadata(attribute2); def.addAttribute(attribute2); addAttribute(attribute2, def); // set concept from cache and set initial prev concept final Concept concept = getConcept(conceptIdMap.get(fields[4])); if (concept != null) { // this also adds language refset entries addAtom(def); atomIdMap.put(def.getTerminologyId(), def.getId()); } else { throw new Exception("Atom " + def.getTerminologyId() + " references non-existent concept " + fields[4]); } logAndCommit(++objectCt, RootService.logCt, RootService.commitCt); } } commitClearBegin(); } /** * Connect atoms and concepts. * * @throws Exception the exception */ private void connectAtomsAndConcepts() throws Exception { // Connect concepts and atoms and compute preferred names Logger.getLogger(getClass()).info(" Connect atoms and concepts"); objectCt = 0; // NOTE: Hibernate-specific to support iterating Session session = manager.unwrap(Session.class); org.hibernate.Query hQuery = session .createQuery( "select a from AtomJpa a " + "where conceptId is not null " + "and conceptId != '' and terminology = :terminology " + "order by terminology, conceptId") .setParameter("terminology", terminology) .setReadOnly(true).setFetchSize(1000); ScrollableResults results = hQuery.scroll(ScrollMode.FORWARD_ONLY); String prevCui = null; String prefName = null; String altPrefName = null; Concept concept = null; while (results.next()) { final Atom atom = (Atom) results.get()[0]; if (atom.getConceptId() == null || atom.getConceptId().isEmpty()) { continue; } if (prevCui == null || !prevCui.equals(atom.getConceptId())) { if (concept != null) { // compute preferred name if (prefName == null) { prefName = altPrefName; Logger.getLogger(getClass()).error( "Unable to determine preferred name for " + concept.getTerminologyId()); if (altPrefName == null) { throw new Exception( "Unable to determine preferred name (or alt pref name) for " + concept.getTerminologyId()); } } concept.setName(prefName); prefName = null; // Add definitions if (definitionMap.containsKey(concept.getTerminologyId())) { for (Long id : definitionMap.get(concept.getTerminologyId())) { concept.addDefinition(getDefinition(id)); } } updateConcept(concept); // Set atom subset names if (atomSubsetMap.containsKey(concept.getTerminologyId())) { AtomSubset subset = atomSubsetMap.get(concept.getTerminologyId()); subset.setName(concept.getName()); subset.setDescription(concept.getName()); updateSubset(subset); } logAndCommit(++objectCt, RootService.logCt, RootService.commitCt); } concept = getConcept(conceptIdMap.get(atom.getConceptId())); } concept.addAtom(atom); // Active atoms with pref typeId that are preferred from language refset // perspective is the pref name. This bypasses the pref name computer // but is way faster. if (!atom.isObsolete() && atom.getTermType().equals(dpnTypeId) && prefAtoms.contains(atom.getTerminologyId())) { prefName = atom.getName(); } // Pick an alternative preferred name in case a true pref can't be found // this at least lets us choose something to move on. if (prefName == null && altPrefName == null) { if (!atom.isObsolete() && atom.getTermType().equals(dpnTypeId)) { altPrefName = atom.getName(); } } // If pref name is null, pick the first non-obsolete atom with the correct // term type // this guarantees that SOMETHING is picked prevCui = atom.getConceptId(); } if (concept != null) { if (prefName == null) { throw new Exception("Unable to determine preferred name for " + concept.getTerminologyId()); } concept.setName(prefName); updateConcept(concept); commitClearBegin(); } results.close(); commitClearBegin(); } /** * Load and cache all language refset members. * @throws Exception the exception */ private void loadLanguageRefSetMembers() throws Exception { objectCt = 0; PushBackReader reader = readers.getReader(Rf2Readers.Keys.LANGUAGE); String line; while ((line = reader.readLine()) != null) { final String fields[] = FieldedStringTokenizer.split(line,"\t"); if (!fields[0].equals(id)) { // header // Stop if the effective time is past the release version if (fields[1].compareTo(releaseVersion) > 0) { reader.push(line); return; } final AtomSubsetMember member = new AtomSubsetMemberJpa(); final Date date = ConfigUtility.DATE_FORMAT.parse(fields[1]); refsetHelper(member, fields); // Attributes final Attribute attribute = new AttributeJpa(); setCommonFields(attribute, date); attribute.setName("acceptabilityId"); attribute.setValue(fields[6].intern()); cacheAttributeMetadata(attribute); member.addAttribute(attribute); addAttribute(attribute, member); addSubsetMember(member); // Save preferred atom id info if (!member.isObsolete() && dpnAcceptabilityId.equals(fields[6]) && dpnRefSetIds.contains(fields[4])) { prefAtoms.add(member.getMember().getTerminologyId()); } logAndCommit(++objectCt, RootService.logCt, RootService.commitCt); } } commitClearBegin(); } /** * Load AttributeRefSets (Content). * * @throws Exception the exception */ private void loadAttributeValueRefSets() throws Exception { String line = ""; objectCt = 0; // Iterate through attribute value entries PushBackReader reader = readers.getReader(Rf2Readers.Keys.ATTRIBUTE_VALUE); while ((line = reader.readLine()) != null) { line = line.replace("\r", ""); final String fields[] = FieldedStringTokenizer.split(line,"\t"); if (!fields[0].equals(id)) { // header // Stop if the effective time is past the release version if (fields[1].compareTo(releaseVersion) > 0) { reader.push(line); break; } final Date date = ConfigUtility.DATE_FORMAT.parse(fields[1]); SubsetMember<? extends ComponentHasAttributesAndName, ? extends Subset> member = null; if (conceptIdMap.get(fields[5]) != null) { member = new ConceptSubsetMemberJpa(); } else if (atomIdMap.get(fields[5]) != null) { member = new AtomSubsetMemberJpa(); } else { throw new Exception( "Attribute value member connected to nonexistent object"); } refsetHelper(member, fields); // Attributes final Attribute attribute = new AttributeJpa(); setCommonFields(attribute, date); attribute.setName("valueId"); attribute.setValue(fields[6].intern()); attributeNames.add(attribute.getName()); cacheAttributeMetadata(attribute); member.addAttribute(attribute); addAttribute(attribute, member); // Add member addSubsetMember(member); logAndCommit(++objectCt, RootService.logCt, RootService.commitCt); } } } /** * Load Association Reference Refset (Content). * * @throws Exception the exception */ private void loadAssociationReferenceRefSets() throws Exception { String line = ""; objectCt = 0; // Iterate through attribute value entries PushBackReader reader = readers.getReader(Rf2Readers.Keys.ASSOCIATION_REFERENCE); while ((line = reader.readLine()) != null) { line = line.replace("\r", ""); final String fields[] = FieldedStringTokenizer.split(line,"\t"); if (!fields[0].equals(id)) { // header // Stop if the effective time is past the release version if (fields[1].compareTo(releaseVersion) > 0) { reader.push(line); break; } final Date date = ConfigUtility.DATE_FORMAT.parse(fields[1]); SubsetMember<? extends ComponentHasAttributesAndName, ? extends Subset> member = null; if (conceptIdMap.get(fields[5]) != null) { member = new ConceptSubsetMemberJpa(); } else if (atomIdMap.get(fields[5]) != null) { member = new AtomSubsetMemberJpa(); } else { throw new Exception( "Attribute value member connected to nonexistent object"); } refsetHelper(member, fields); // Attributes final Attribute attribute = new AttributeJpa(); setCommonFields(attribute, date); attribute.setName("targetComponentId"); attribute.setValue(fields[6].intern()); attributeNames.add(attribute.getName()); member.addAttribute(attribute); addAttribute(attribute, member); // Add member addSubsetMember(member); logAndCommit(++objectCt, RootService.logCt, RootService.commitCt); } } } /** * Load SimpleRefSets (Content). * * @throws Exception the exception */ private void loadSimpleRefSets() throws Exception { String line = ""; objectCt = 0; PushBackReader reader = readers.getReader(Rf2Readers.Keys.SIMPLE); while ((line = reader.readLine()) != null) { line = line.replace("\r", ""); final String fields[] = FieldedStringTokenizer.split(line,"\t"); if (!fields[0].equals(id)) { // header // Stop if the effective time is past the release version if (fields[1].compareTo(releaseVersion) > 0) { reader.push(line); break; } ConceptSubsetMember member = new ConceptSubsetMemberJpa(); refsetHelper(member, fields); // Add member addSubsetMember(member); logAndCommit(++objectCt, RootService.logCt, RootService.commitCt); } } } /** * Load SimpleMapRefSets (Crossmap). * * @throws Exception the exception */ private void loadSimpleMapRefSets() throws Exception { String line = ""; objectCt = 0; PushBackReader reader = readers.getReader(Rf2Readers.Keys.SIMPLE_MAP); while ((line = reader.readLine()) != null) { line = line.replace("\r", ""); final String fields[] = FieldedStringTokenizer.split(line,"\t"); if (!fields[0].equals(id)) { // header // Stop if the effective time is past the release version if (fields[1].compareTo(releaseVersion) > 0) { reader.push(line); break; } final Date date = ConfigUtility.DATE_FORMAT.parse(fields[1]); ConceptSubsetMember member = new ConceptSubsetMemberJpa(); refsetHelper(member, fields); // Attributes Attribute attribute = new AttributeJpa(); setCommonFields(attribute, date); attribute.setName("mapTarget"); attribute.setValue(fields[6].intern()); attributeNames.add(attribute.getName()); member.addAttribute(attribute); addAttribute(attribute, member); // Add member addSubsetMember(member); logAndCommit(++objectCt, RootService.logCt, RootService.commitCt); } } } /** * Load ComplexMapRefSets (Crossmap). * * @throws Exception the exception */ private void loadComplexMapRefSets() throws Exception { // TODO: for now terminology server doesn't load mappings. // later development of mapping objects is needed } /** * Load extended map ref sets. * * @throws Exception the exception */ private void loadExtendedMapRefSets() throws Exception { // TODO: for now terminology server doesn't load mappings. // later development of mapping objects is needed } /** * Load refset descriptor ref sets. * * @throws Exception the exception */ private void loadRefsetDescriptorRefSets() throws Exception { String line = ""; objectCt = 0; PushBackReader reader = readers.getReader(Rf2Readers.Keys.REFSET_DESCRIPTOR); while ((line = reader.readLine()) != null) { line = line.replace("\r", ""); final String fields[] = FieldedStringTokenizer.split(line,"\t"); if (!fields[0].equals(id)) { // header // Stop if the effective time is past the release version if (fields[1].compareTo(releaseVersion) > 0) { reader.push(line); break; } final Date date = ConfigUtility.DATE_FORMAT.parse(fields[1]); ConceptSubsetMember member = new ConceptSubsetMemberJpa(); refsetHelper(member, fields); // Attributes Attribute attribute = new AttributeJpa(); setCommonFields(attribute, date); attribute.setName("attributeDescription"); attribute.setValue(fields[6].intern()); cacheAttributeMetadata(attribute); member.addAttribute(attribute); addAttribute(attribute, member); Attribute attribute2 = new AttributeJpa(); setCommonFields(attribute2, date); attribute2.setName("attributeType"); attribute2.setValue(fields[7].intern()); cacheAttributeMetadata(attribute2); member.addAttribute(attribute2); addAttribute(attribute2, member); Attribute attribute3 = new AttributeJpa(); setCommonFields(attribute3, date); attribute3.setName("attributeOrder"); attribute3.setValue(fields[8].intern()); cacheAttributeMetadata(attribute3); member.addAttribute(attribute3); addAttribute(attribute3, member); // Add member addSubsetMember(member); logAndCommit(++objectCt, RootService.logCt, RootService.commitCt); } } } /** * Load module dependency refset members. * * @throws Exception the exception */ private void loadModuleDependencyRefSets() throws Exception { String line = ""; objectCt = 0; PushBackReader reader = readers.getReader(Rf2Readers.Keys.MODULE_DEPENDENCY); while ((line = reader.readLine()) != null) { line = line.replace("\r", ""); final String fields[] = FieldedStringTokenizer.split(line,"\t"); if (!fields[0].equals(id)) { // header // Stop if the effective time is past the release version if (fields[1].compareTo(releaseVersion) > 0) { reader.push(line); break; } final Date date = ConfigUtility.DATE_FORMAT.parse(fields[1]); ConceptSubsetMember member = new ConceptSubsetMemberJpa(); refsetHelper(member, fields); // Attributes Attribute attribute = new AttributeJpa(); setCommonFields(attribute, date); attribute.setName("sourceEffectiveTime"); attribute.setValue(fields[6].intern()); attributeNames.add(attribute.getName()); member.addAttribute(attribute); addAttribute(attribute, member); Attribute attribute2 = new AttributeJpa(); setCommonFields(attribute2, date); attribute2.setName("targetEffectiveTime"); attribute2.setValue(fields[7].intern()); attributeNames.add(attribute2.getName()); member.addAttribute(attribute2); addAttribute(attribute2, member); addSubsetMember(member); logAndCommit(++objectCt, RootService.logCt, RootService.commitCt); } } } /** * Load description type refset members. * * @throws Exception the exception */ private void loadAtomTypeRefSets() throws Exception { String line = ""; objectCt = 0; PushBackReader reader = readers.getReader(Rf2Readers.Keys.DESCRIPTION_TYPE); while ((line = reader.readLine()) != null) { line = line.replace("\r", ""); final String fields[] = FieldedStringTokenizer.split(line,"\t"); if (!fields[0].equals(id)) { // header // Stop if the effective time is past the release version if (fields[1].compareTo(releaseVersion) > 0) { reader.push(line); break; } final Date date = ConfigUtility.DATE_FORMAT.parse(fields[1]); ConceptSubsetMember member = new ConceptSubsetMemberJpa(); refsetHelper(member, fields); // Attributes Attribute attribute = new AttributeJpa(); setCommonFields(attribute, date); attribute.setName("descriptionFormat"); attribute.setValue(fields[6].intern()); cacheAttributeMetadata(attribute); member.addAttribute(attribute); addAttribute(attribute, member); Attribute attribute2 = new AttributeJpa(); setCommonFields(attribute2, date); attribute2.setName("descriptionLength"); attribute2.setValue(fields[7].intern()); attributeNames.add(attribute2.getName()); member.addAttribute(attribute2); addAttribute(attribute2, member); addSubsetMember(member); logAndCommit(++objectCt, RootService.logCt, RootService.commitCt); } } } /** * Refset helper. * * @param member the member * @param fields the fields * @throws Exception the exception */ private void refsetHelper( SubsetMember<? extends ComponentHasAttributesAndName, ? extends Subset> member, String[] fields) throws Exception { if (conceptIdMap.get(fields[5]) != null) { // Retrieve concept -- firstToken is referencedComponentId final Concept concept = getConcept(conceptIdMap.get(fields[5])); ((ConceptSubsetMember) member).setMember(concept); } else if (atomIdMap.get(fields[5]) != null) { final Atom description = getAtom(atomIdMap.get(fields[5])); ((AtomSubsetMember) member).setMember(description); } else { throw new Exception( "Attribute value member connected to nonexistent object"); } // Universal RefSet attributes final Date date = ConfigUtility.DATE_FORMAT.parse(fields[1]); member.setTerminology(terminology); member.setVersion(version); member.setTerminologyId(fields[0]); member.setTimestamp(date); member.setLastModified(date); member.setLastModifiedBy(loader); member.setObsolete(fields[2].equals("0")); member.setSuppressible(member.isObsolete()); member.setPublished(true); member.setPublishable(true); if (atomSubsetMap.containsKey(fields[4])) { final AtomSubset subset = atomSubsetMap.get(fields[4]); ((AtomSubsetMember) member).setSubset(subset); } else if (conceptSubsetMap.containsKey(fields[4])) { final ConceptSubset subset = conceptSubsetMap.get(fields[4]); ((ConceptSubsetMember) member).setSubset(subset); } else if (member instanceof AtomSubsetMember && !atomSubsetMap.containsKey(fields[4])) { final AtomSubset subset = new AtomSubsetJpa(); setCommonFields(subset, date); subset.setTerminologyId(fields[4].intern()); subset.setName(getConcept(conceptIdMap.get(fields[4])).getName()); subset.setDescription(subset.getName()); final Attribute attribute2 = new AttributeJpa(); setCommonFields(attribute2, date); attribute2.setName("moduleId"); attribute2.setValue(fields[3].intern()); subset.addAttribute(attribute2); addAttribute(attribute2, member); addSubset(subset); atomSubsetMap.put(fields[4], subset); commitClearBegin(); ((AtomSubsetMember) member).setSubset(subset); } else if (member instanceof ConceptSubsetMember && !conceptSubsetMap.containsKey(fields[4])) { final ConceptSubset subset = new ConceptSubsetJpa(); setCommonFields(subset, date); subset.setTerminologyId(fields[4].intern()); subset.setName(getConcept(conceptIdMap.get(fields[4])).getName()); subset.setDescription(subset.getName()); subset.setDisjointSubset(false); final Attribute attribute2 = new AttributeJpa(); setCommonFields(attribute2, date); attribute2.setName("moduleId"); attribute2.setValue(fields[3].intern()); subset.addAttribute(attribute2); addAttribute(attribute2, member); addSubset(subset); conceptSubsetMap.put(fields[4], subset); commitClearBegin(); ((ConceptSubsetMember) member).setSubset(subset); } else { throw new Exception("Unable to determine refset type."); } // Add moduleId attribute final Attribute attribute = new AttributeJpa(); setCommonFields(attribute, date); attribute.setName("moduleId"); attribute.setValue(fields[3].intern()); cacheAttributeMetadata(attribute); member.addAttribute(attribute); addAttribute(attribute, member); } /** * Load metadata. * * @throws Exception the exception */ private void loadMetadata() throws Exception { // Term types - each description type for (String tty : termTypes) { TermType termType = new TermTypeJpa(); termType.setTerminology(terminology); termType.setVersion(version); termType.setAbbreviation(tty); termType.setCodeVariantType(CodeVariantType.SY); termType.setExpandedForm(getConcept(conceptIdMap.get(tty)).getName()); termType.setHierarchicalType(false); termType.setTimestamp(releaseVersionDate); termType.setLastModified(releaseVersionDate); termType.setLastModifiedBy(loader); termType.setNameVariantType(NameVariantType.UNDEFINED); termType.setObsolete(false); termType.setSuppressible(false); termType.setPublishable(true); termType.setPublished(true); termType.setUsageType(UsageType.UNDEFINED); addTermType(termType); } // Languages - each language value Language rootLanguage = null; for (String lat : languages) { Language language = new LanguageJpa(); language.setTerminology(terminology); language.setVersion(version); language.setTimestamp(releaseVersionDate); language.setLastModified(releaseVersionDate); language.setLastModifiedBy(loader); language.setPublishable(true); language.setPublished(true); language.setExpandedForm(lat); language.setAbbreviation(lat); language.setISO3Code("???"); language.setISOCode(lat.substring(0, 2)); addLanguage(language); if (rootLanguage == null) { rootLanguage = language; } } // attribute name for (String atn : attributeNames) { AttributeName name = new AttributeNameJpa(); name.setTerminology(terminology); name.setVersion(version); name.setLastModified(releaseVersionDate); name.setLastModifiedBy(loader); name.setPublishable(true); name.setPublished(true); name.setExpandedForm(atn); name.setAbbreviation(atn); addAttributeName(name); } // relationship types - subClassOf, superClassOf String[] relTypes = new String[] { "other", "Inverse is a", "Is a" }; RelationshipType chd = null; RelationshipType par = null; RelationshipType ro = null; for (String rel : relTypes) { RelationshipType type = new RelationshipTypeJpa(); type.setTerminology(terminology); type.setVersion(version); type.setLastModified(releaseVersionDate); type.setLastModifiedBy(loader); type.setPublishable(true); type.setPublished(true); type.setAbbreviation(rel); if (rel.equals("Is a")) { chd = type; type.setExpandedForm("Is a (has parent)"); } else if (rel.equals("Inverse is a")) { par = type; type.setExpandedForm("Inverse is a (has child)"); } else if (rel.equals("other")) { ro = type; type.setExpandedForm("Other"); } else { throw new Exception("Unhandled type"); } addRelationshipType(type); } chd.setInverse(par); par.setInverse(chd); ro.setInverse(ro); updateRelationshipType(chd); updateRelationshipType(par); updateRelationshipType(ro); // additional relationship types (including grouping type, hierarchical // type) AdditionalRelationshipType directSubstance = null; AdditionalRelationshipType hasActiveIngredient = null; Map<AdditionalRelationshipType, AdditionalRelationshipType> inverses = new HashMap<>(); for (String rela : additionalRelTypes) { AdditionalRelationshipType type = new AdditionalRelationshipTypeJpa(); type.setTerminology(terminology); type.setVersion(version); type.setLastModified(releaseVersionDate); type.setLastModifiedBy(loader); type.setPublishable(true); type.setPublished(true); type.setExpandedForm(getConcept(conceptIdMap.get(rela)).getName()); type.setAbbreviation(rela); // $nevergrouped{"123005000"} = "T"; # part-of is never grouped // $nevergrouped{"272741003"} = "T"; # laterality is never grouped // $nevergrouped{"127489000"} = "T"; # has-active-ingredient is never // grouped // $nevergrouped{"411116001"} = "T"; # has-dose-form is never grouped if (rela.equals("123005000") || rela.equals("272741003") || rela.equals("127489000") || rela.equals("411116001")) { type.setGroupingType(false); } else { type.setGroupingType(true); } addAdditionalRelationshipType(type); if (rela.equals("363701004")) { hasActiveIngredient = type; } else if (rela.equals("127489000")) { directSubstance = type; } AdditionalRelationshipType inverseType = new AdditionalRelationshipTypeJpa(type); inverseType.setId(null); inverseType.setAbbreviation("inverse_" + type.getAbbreviation()); inverseType.setExpandedForm("inverse_" + type.getAbbreviation()); inverses.put(type, inverseType); addAdditionalRelationshipType(inverseType); } // handle inverses for (AdditionalRelationshipType type : inverses.keySet()) { AdditionalRelationshipType inverseType = inverses.get(type); type.setInverse(inverseType); inverseType.setInverse(type); updateAdditionalRelationshipType(type); updateAdditionalRelationshipType(inverseType); } // property chains (see Owl) // $rightid{"363701004"} = "127489000"; # direct-substance o // has-active-ingredient -> direct-substance PropertyChain chain = new PropertyChainJpa(); chain.setTerminology(terminology); chain.setVersion(version); chain.setLastModified(releaseVersionDate); chain.setLastModifiedBy(loader); chain.setPublishable(true); chain.setPublished(true); chain .setAbbreviation("direct-substance o has-active-ingredient -> direct-substance"); chain.setExpandedForm(chain.getAbbreviation()); List<AdditionalRelationshipType> list = new ArrayList<>(); list.add(directSubstance); list.add(hasActiveIngredient); chain.setChain(list); chain.setResult(directSubstance); // do this only when the available rels exist if (chain.getChain().size() > 0 && chain.getResult() != null) { addPropertyChain(chain); } // semantic types - n/a // Root Terminology RootTerminology root = new RootTerminologyJpa(); root.setFamily(terminology); root.setHierarchicalName(getConcept(conceptIdMap.get(rootConceptId)) .getName()); root.setLanguage(rootLanguage); root.setTimestamp(releaseVersionDate); root.setLastModified(releaseVersionDate); root.setLastModifiedBy(loader); root.setPolyhierarchy(true); root.setPreferredName(root.getHierarchicalName()); root.setRestrictionLevel(-1); root.setTerminology(terminology); addRootTerminology(root); // Terminology Terminology term = new TerminologyJpa(); term.setTerminology(terminology); term.setVersion(version); term.setTimestamp(releaseVersionDate); term.setLastModified(releaseVersionDate); term.setLastModifiedBy(loader); term.setAssertsRelDirection(true); term.setCurrent(true); term.setDescriptionLogicTerminology(true); term.setOrganizingClassType(IdType.CONCEPT); term.setPreferredName(root.getPreferredName()); term.setRootTerminology(root); addTerminology(term); // Add general metadata entries for all the attribute values // that are concept ids. for (String conceptId : generalEntryValues) { // Skip if there is no concept for this thing if (!conceptIdMap.containsKey(conceptId)) { Logger.getLogger(getClass()).info( " Skipping Genral Metadata Entry = " + conceptId); continue; } String name = getConcept(conceptIdMap.get(conceptId)).getName(); Logger.getLogger(getClass()).info( " Genral Metadata Entry = " + conceptId + ", " + name); GeneralMetadataEntry entry = new GeneralMetadataEntryJpa(); entry.setTerminology(terminology); entry.setVersion(version); entry.setLastModified(releaseVersionDate); entry.setLastModifiedBy(loader); entry.setPublishable(true); entry.setPublished(true); entry.setAbbreviation(conceptId); entry.setExpandedForm(name); entry.setKey("concept_metadata"); entry.setType("concept_name"); addGeneralMetadataEntry(entry); } String[] labels = new String[] { "Atoms_Label", "Subsets_Label", "Attributes_Label", "Semantic_Types_Label", "Obsolete_Label", "Obsolete_Indicator", }; String[] labelValues = new String[] { "Descriptions", "Refsets", "Properties", "Semantic Tags", "Retired", "Retired" }; int i = 0; for (String label : labels) { GeneralMetadataEntry entry = new GeneralMetadataEntryJpa(); entry.setTerminology(terminology); entry.setVersion(version); entry.setLastModified(releaseVersionDate); entry.setLastModifiedBy(loader); entry.setPublishable(true); entry.setPublished(true); entry.setAbbreviation(label); entry.setExpandedForm(labelValues[i++]); entry.setKey("label_metadata"); entry.setType("label_values"); addGeneralMetadataEntry(entry); } commitClearBegin(); } /** * Load extension label sets. * * @throws Exception the exception */ private void loadExtensionLabelSets() throws Exception { // for each non core module, create a Subset object List<ConceptSubset> subsets = new ArrayList<>(); for (String moduleId : moduleIds) { Logger.getLogger(getClass()).info( " Create subset for module = " + moduleId); Concept concept = getConcept(conceptIdMap.get(moduleId)); ConceptSubset subset = new ConceptSubsetJpa(); subset.setName(concept.getName()); subset.setDescription("Represents the members of module " + moduleId); subset.setDisjointSubset(false); subset.setLabelSubset(true); subset.setLastModified(releaseVersionDate); subset.setTimestamp(releaseVersionDate); subset.setLastModifiedBy(loader); subset.setObsolete(false); subset.setSuppressible(false); subset.setPublishable(false); subset.setPublished(false); subset.setTerminology(terminology); subset.setTerminologyId(moduleId); subset.setVersion(version); addSubset(subset); subsets.add(subset); commitClearBegin(); // Create members int objectCt = 0; Logger.getLogger(getClass()).info(" Add subset members"); for (String conceptId : moduleConceptIdMap.get(moduleId)) { final Concept memberConcept = getConcept(conceptIdMap.get(conceptId)); ConceptSubsetMember member = new ConceptSubsetMemberJpa(); member.setLastModified(releaseVersionDate); member.setTimestamp(releaseVersionDate); member.setLastModifiedBy(loader); member.setMember(memberConcept); member.setObsolete(false); member.setSuppressible(false); member.setPublishable(false); member.setPublishable(false); member.setTerminologyId(""); member.setTerminology(terminology); member.setVersion(version); member.setSubset(subset); addSubsetMember(member); logAndCommit(++objectCt, RootService.logCt, RootService.commitCt); } } Logger.getLogger(getClass()).info(" count = " + objectCt); } /** * xsets the common fields. * * @param component the common fields * @param date the date */ private void setCommonFields(Component component, Date date) { component.setTimestamp(date); component.setTerminologyId(""); component.setTerminology(terminology); component.setVersion(version); component.setLastModified(date); component.setLastModifiedBy(loader); component.setObsolete(false); component.setPublishable(true); component.setPublished(true); component.setSuppressible(false); } /** * Cache attribute value. * * @param attribute the attribute */ private void cacheAttributeMetadata(Attribute attribute) { attributeNames.add(attribute.getName()); if (attribute.getValue().matches("^\\d[\\d]{6,}$")) { generalEntryValues.add(attribute.getValue()); } } /** * Indicates whether or not extension module is the case. * * @param moduleId the module id * @return <code>true</code> if so, <code>false</code> otherwise */ @SuppressWarnings("static-method") private boolean isExtensionModule(String moduleId) { return !moduleId.equals(coreModuleId) && !moduleId.equals(metadataModuleId); } /* see superclass */ @Override public void close() throws Exception { super.close(); readers = null; } }
RF2 Loader now loads association references as concept_relationships
jpa-services/src/main/java/com/wci/umls/server/jpa/algo/Rf2SnapshotLoaderAlgorithm.java
RF2 Loader now loads association references as concept_relationships
<ide><path>pa-services/src/main/java/com/wci/umls/server/jpa/algo/Rf2SnapshotLoaderAlgorithm.java <ide> /** <ide> * Implementation of an algorithm to import RF2 snapshot data. <ide> */ <del>public class Rf2SnapshotLoaderAlgorithm extends HistoryServiceJpa implements <del> Algorithm { <add>public class Rf2SnapshotLoaderAlgorithm extends HistoryServiceJpa <add> implements Algorithm { <ide> <ide> /** Listeners. */ <ide> private List<ProgressListener> listeners = new ArrayList<>(); <ide> <ide> /** The dpn ref set id. */ <ide> private Set<String> dpnRefSetIds = new HashSet<>(); <add> <ide> { <ide> // US English Language <ide> dpnRefSetIds.add("900000000000509007"); <ide> Logger.getLogger(getClass()).info(" Loading Language Ref Sets..."); <ide> loadLanguageRefSetMembers(); <ide> <del> Logger.getLogger(getClass()).info( <del> " Connecting atoms/concepts and computing preferred names..."); <add> Logger.getLogger(getClass()) <add> .info(" Connecting atoms/concepts and computing preferred names..."); <ide> connectAtomsAndConcepts(); <ide> <ide> // <ide> // <ide> // load AssocationReference RefSets (Content) <ide> // <del> Logger.getLogger(getClass()).info( <del> " Loading Association Reference Ref Sets..."); <add> Logger.getLogger(getClass()) <add> .info(" Loading Association Reference Ref Sets..."); <ide> loadAssociationReferenceRefSets(); <ide> commitClearBegin(); <ide> <ide> <ide> // load RefsetDescriptor RefSets (Content) <ide> // <del> Logger.getLogger(getClass()).info( <del> " Loading Refset Descriptor Ref Sets..."); <add> Logger.getLogger(getClass()) <add> .info(" Loading Refset Descriptor Ref Sets..."); <ide> loadRefsetDescriptorRefSets(); <ide> <ide> // <ide> // load ModuleDependency RefSets (Content) <ide> // <del> Logger.getLogger(getClass()).info( <del> " Loading Module Dependency Ref Sets..."); <add> Logger.getLogger(getClass()) <add> .info(" Loading Module Dependency Ref Sets..."); <ide> <ide> loadModuleDependencyRefSets(); <ide> <ide> // clear and commit <ide> commitClearBegin(); <ide> <del> Logger.getLogger(getClass()).info( <del> getComponentStats(terminology, version, Branch.ROOT)); <add> Logger.getLogger(getClass()) <add> .info(getComponentStats(terminology, version, Branch.ROOT)); <ide> <ide> Logger.getLogger(getClass()).info("Done ..."); <ide> <ide> PushBackReader reader = readers.getReader(Rf2Readers.Keys.CONCEPT); <ide> while ((line = reader.readLine()) != null) { <ide> <del> final String fields[] = FieldedStringTokenizer.split(line,"\t"); <add> final String fields[] = FieldedStringTokenizer.split(line, "\t"); <ide> final Concept concept = new ConceptJpa(); <ide> <ide> if (!fields[0].equals(id)) { // header <ide> while ((line = reader.readLine()) != null) { <ide> <ide> // Split line <del> final String fields[] = FieldedStringTokenizer.split(line,"\t"); <add> final String fields[] = FieldedStringTokenizer.split(line, "\t"); <ide> // Skip header <ide> if (!fields[0].equals(id)) { <ide> <ide> relationship.setObsolete(fields[2].equals("0")); // active <ide> relationship.setSuppressible(relationship.isObsolete()); <ide> relationship.setGroup(fields[6].intern()); // relationshipGroup <del> relationship.setRelationshipType(fields[7].equals(isaTypeRel) ? "Is a" <del> : "other"); // typeId <add> relationship.setRelationshipType( <add> fields[7].equals(isaTypeRel) ? "Is a" : "other"); // typeId <ide> relationship.setAdditionalRelationshipType(fields[7]); // typeId <del> relationship.setHierarchical(relationship.getRelationshipType().equals( <del> "Is a")); <add> relationship <add> .setHierarchical(relationship.getRelationshipType().equals("Is a")); <ide> generalEntryValues.add(relationship.getAdditionalRelationshipType()); <ide> additionalRelTypes.add(relationship.getAdditionalRelationshipType()); <ide> relationship.setStated(fields[8].equals("900000000000010007")); <ide> <ide> } else { <ide> if (fromConcept == null) { <del> throw new Exception("Relationship " <del> + relationship.getTerminologyId() <del> + " -existent source concept " + fields[4]); <add> throw new Exception( <add> "Relationship " + relationship.getTerminologyId() <add> + " -existent source concept " + fields[4]); <ide> } <ide> if (toConcept == null) { <del> throw new Exception("Relationship" <del> + relationship.getTerminologyId() <add> throw new Exception("Relationship" + relationship.getTerminologyId() <ide> + " references non-existent destination concept " + fields[5]); <ide> } <ide> } <ide> PushBackReader reader = readers.getReader(Rf2Readers.Keys.DESCRIPTION); <ide> while ((line = reader.readLine()) != null) { <ide> <del> final String fields[] = FieldedStringTokenizer.split(line,"\t"); <add> final String fields[] = FieldedStringTokenizer.split(line, "\t"); <ide> if (!fields[0].equals(id)) { <ide> // Stop if the effective time is past the release version <ide> if (fields[1].compareTo(releaseVersion) > 0) { <ide> PushBackReader reader = readers.getReader(Rf2Readers.Keys.DEFINITION); <ide> while ((line = reader.readLine()) != null) { <ide> <del> final String fields[] = FieldedStringTokenizer.split(line,"\t"); <add> final String fields[] = FieldedStringTokenizer.split(line, "\t"); <ide> if (!fields[0].equals(id)) { <ide> <ide> // Stop if the effective time is past the release version <ide> objectCt = 0; <ide> // NOTE: Hibernate-specific to support iterating <ide> Session session = manager.unwrap(Session.class); <del> org.hibernate.Query hQuery = <del> session <del> .createQuery( <del> "select a from AtomJpa a " + "where conceptId is not null " <del> + "and conceptId != '' and terminology = :terminology " <del> + "order by terminology, conceptId") <del> .setParameter("terminology", terminology) <del> .setReadOnly(true).setFetchSize(1000); <add> org.hibernate.Query hQuery = session <add> .createQuery("select a from AtomJpa a " + "where conceptId is not null " <add> + "and conceptId != '' and terminology = :terminology " <add> + "order by terminology, conceptId") <add> .setParameter("terminology", terminology).setReadOnly(true) <add> .setFetchSize(1000); <ide> ScrollableResults results = hQuery.scroll(ScrollMode.FORWARD_ONLY); <ide> String prevCui = null; <ide> String prefName = null; <ide> // compute preferred name <ide> if (prefName == null) { <ide> prefName = altPrefName; <del> Logger.getLogger(getClass()).error( <del> "Unable to determine preferred name for " <add> Logger.getLogger(getClass()) <add> .error("Unable to determine preferred name for " <ide> + concept.getTerminologyId()); <ide> if (altPrefName == null) { <ide> throw new Exception( <ide> String line; <ide> while ((line = reader.readLine()) != null) { <ide> <del> final String fields[] = FieldedStringTokenizer.split(line,"\t"); <add> final String fields[] = FieldedStringTokenizer.split(line, "\t"); <ide> <ide> if (!fields[0].equals(id)) { // header <ide> <ide> PushBackReader reader = readers.getReader(Rf2Readers.Keys.ATTRIBUTE_VALUE); <ide> while ((line = reader.readLine()) != null) { <ide> line = line.replace("\r", ""); <del> final String fields[] = FieldedStringTokenizer.split(line,"\t"); <add> final String fields[] = FieldedStringTokenizer.split(line, "\t"); <ide> <ide> if (!fields[0].equals(id)) { // header <ide> <ide> while ((line = reader.readLine()) != null) { <ide> <ide> line = line.replace("\r", ""); <del> final String fields[] = FieldedStringTokenizer.split(line,"\t"); <add> final String fields[] = FieldedStringTokenizer.split(line, "\t"); <ide> <ide> if (!fields[0].equals(id)) { // header <ide> <ide> break; <ide> } <ide> <del> final Date date = ConfigUtility.DATE_FORMAT.parse(fields[1]); <del> SubsetMember<? extends ComponentHasAttributesAndName, ? extends Subset> member = <del> null; <add> ConceptRelationship relationship = null; <add> <ide> if (conceptIdMap.get(fields[5]) != null) { <del> member = new ConceptSubsetMemberJpa(); <del> } else if (atomIdMap.get(fields[5]) != null) { <del> member = new AtomSubsetMemberJpa(); <add> relationship = new ConceptRelationshipJpa(); <ide> } else { <ide> throw new Exception( <del> "Attribute value member connected to nonexistent object"); <del> } <del> refsetHelper(member, fields); <del> <del> // Attributes <del> final Attribute attribute = new AttributeJpa(); <add> "Association reference member connected to nonexistent object"); <add> } <add> <add> final Date date = ConfigUtility.DATE_FORMAT.parse(fields[1]); <add> <add> // set the fields <add> // id effectiveTime active moduleId refsetId referencedComponentId <add> // targetComponentId <add> relationship.setTerminologyId(fields[0]); <add> relationship.setTimestamp(date); <add> relationship.setLastModified(date); <add> relationship.setObsolete(fields[2].equals("0")); // active <add> relationship.setSuppressible(relationship.isObsolete()); <add> relationship.setRelationshipType("RO"); <add> relationship.setHierarchical(false); <add> relationship.setAdditionalRelationshipType(fields[4]); <add> relationship.setStated(false); <add> relationship.setInferred(false); <add> relationship.setTerminology(terminology); <add> relationship.setVersion(version); <add> relationship.setLastModified(releaseVersionDate); <add> relationship.setLastModifiedBy(loader); <add> relationship.setPublished(true); <add> relationship.setPublishable(true); <add> relationship.setAssertedDirection(true); <add> <add> // ensure additional relationship type has been added <add> additionalRelTypes.add(relationship.getAdditionalRelationshipType()); <add> <add> // Module Id Attribute <add> Attribute attribute = new AttributeJpa(); <ide> setCommonFields(attribute, date); <del> attribute.setName("targetComponentId"); <del> attribute.setValue(fields[6].intern()); <del> attributeNames.add(attribute.getName()); <del> member.addAttribute(attribute); <del> addAttribute(attribute, member); <del> <del> // Add member <del> addSubsetMember(member); <add> attribute.setName("moduleId"); <add> attribute.setValue(fields[3].intern()); <add> relationship.addAttribute(attribute); <add> addAttribute(attribute, relationship); <add> <add> // get concepts from cache, they just need to have ids <add> final Concept fromConcept = getConcept(conceptIdMap.get(fields[4])); <add> final Concept toConcept = getConcept(conceptIdMap.get(fields[5])); <add> if (fromConcept != null && toConcept != null) { <add> relationship.setFrom(fromConcept); <add> relationship.setTo(toConcept); <add> addRelationship(relationship); <add> <add> } else { <add> if (fromConcept == null) { <add> throw new Exception( <add> "Relationship " + relationship.getTerminologyId() <add> + " -existent source concept " + fields[4]); <add> } <add> if (toConcept == null) { <add> throw new Exception("Relationship" + relationship.getTerminologyId() <add> + " references non-existent destination concept " + fields[5]); <add> } <add> } <ide> <ide> logAndCommit(++objectCt, RootService.logCt, RootService.commitCt); <ide> <ide> } <del> } <del> <add> <add> /** <add> * Make a ConceptRelationshipJpa id = terminologyId timestamp/lastModified <add> * = effectiveTime !active = obsolete published = true, publishable = <add> * true, ... moduleId = becomes an attribute, see how it works in <add> * loadRelationships referencedComponentId, look up the concept -> setFrom <add> * targetComponentId, look up the concept -> setTo relationshipType = "RO" <add> * additionalRelationshipType = refsetId Need to make sure a metadata <add> * additionalRelationshipType gets added abbreviation = refsetId, <add> * expandedForm = name of that concept (e.g. the part in capitals at the <add> * beginning, "POSSIBLY EQUIVALENT TO") make sure to not add it more than <add> * once. <add> */ <add> <add> /* <add> * SubsetMember<? extends ComponentHasAttributesAndName, ? extends Subset> <add> * member = null; if (conceptIdMap.get(fields[5]) != null) { member = new <add> * ConceptSubsetMemberJpa(); } else if (atomIdMap.get(fields[5]) != null) <add> * { member = new AtomSubsetMemberJpa(); } else { throw new Exception( <add> * "Attribute value member connected to nonexistent object"); } <add> * refsetHelper(member, fields); <add> * <add> * // Attributes final Attribute attribute = new AttributeJpa(); <add> * setCommonFields(attribute, date); <add> * attribute.setName("targetComponentId"); <add> * attribute.setValue(fields[6].intern()); <add> * attributeNames.add(attribute.getName()); <add> * member.addAttribute(attribute); addAttribute(attribute, member); <add> * <add> * // Add member addSubsetMember(member); <add> */ <add> <add> logAndCommit(++objectCt, RootService.logCt, RootService.commitCt); <add> <add> } <ide> } <ide> <ide> /** <ide> while ((line = reader.readLine()) != null) { <ide> <ide> line = line.replace("\r", ""); <del> final String fields[] = FieldedStringTokenizer.split(line,"\t"); <add> final String fields[] = FieldedStringTokenizer.split(line, "\t"); <ide> <ide> if (!fields[0].equals(id)) { // header <ide> <ide> while ((line = reader.readLine()) != null) { <ide> <ide> line = line.replace("\r", ""); <del> final String fields[] = FieldedStringTokenizer.split(line,"\t"); <add> final String fields[] = FieldedStringTokenizer.split(line, "\t"); <ide> <ide> if (!fields[0].equals(id)) { // header <ide> <ide> while ((line = reader.readLine()) != null) { <ide> <ide> line = line.replace("\r", ""); <del> final String fields[] = FieldedStringTokenizer.split(line,"\t"); <add> final String fields[] = FieldedStringTokenizer.split(line, "\t"); <ide> <ide> if (!fields[0].equals(id)) { // header <ide> <ide> while ((line = reader.readLine()) != null) { <ide> <ide> line = line.replace("\r", ""); <del> final String fields[] = FieldedStringTokenizer.split(line,"\t"); <add> final String fields[] = FieldedStringTokenizer.split(line, "\t"); <ide> <ide> if (!fields[0].equals(id)) { // header <ide> <ide> while ((line = reader.readLine()) != null) { <ide> <ide> line = line.replace("\r", ""); <del> final String fields[] = FieldedStringTokenizer.split(line,"\t"); <add> final String fields[] = FieldedStringTokenizer.split(line, "\t"); <ide> <ide> if (!fields[0].equals(id)) { // header <ide> <ide> chain.setLastModifiedBy(loader); <ide> chain.setPublishable(true); <ide> chain.setPublished(true); <del> chain <del> .setAbbreviation("direct-substance o has-active-ingredient -> direct-substance"); <add> chain.setAbbreviation( <add> "direct-substance o has-active-ingredient -> direct-substance"); <ide> chain.setExpandedForm(chain.getAbbreviation()); <ide> List<AdditionalRelationshipType> list = new ArrayList<>(); <ide> list.add(directSubstance); <ide> // Root Terminology <ide> RootTerminology root = new RootTerminologyJpa(); <ide> root.setFamily(terminology); <del> root.setHierarchicalName(getConcept(conceptIdMap.get(rootConceptId)) <del> .getName()); <add> root.setHierarchicalName( <add> getConcept(conceptIdMap.get(rootConceptId)).getName()); <ide> root.setLanguage(rootLanguage); <ide> root.setTimestamp(releaseVersionDate); <ide> root.setLastModified(releaseVersionDate); <ide> for (String conceptId : generalEntryValues) { <ide> // Skip if there is no concept for this thing <ide> if (!conceptIdMap.containsKey(conceptId)) { <del> Logger.getLogger(getClass()).info( <del> " Skipping Genral Metadata Entry = " + conceptId); <add> Logger.getLogger(getClass()) <add> .info(" Skipping Genral Metadata Entry = " + conceptId); <ide> continue; <ide> } <ide> String name = getConcept(conceptIdMap.get(conceptId)).getName(); <del> Logger.getLogger(getClass()).info( <del> " Genral Metadata Entry = " + conceptId + ", " + name); <add> Logger.getLogger(getClass()) <add> .info(" Genral Metadata Entry = " + conceptId + ", " + name); <ide> GeneralMetadataEntry entry = new GeneralMetadataEntryJpa(); <ide> entry.setTerminology(terminology); <ide> entry.setVersion(version); <ide> addGeneralMetadataEntry(entry); <ide> } <ide> <del> String[] labels = <del> new String[] { <del> "Atoms_Label", "Subsets_Label", "Attributes_Label", <del> "Semantic_Types_Label", "Obsolete_Label", "Obsolete_Indicator", <del> }; <del> String[] labelValues = <del> new String[] { <del> "Descriptions", "Refsets", "Properties", "Semantic Tags", <del> "Retired", "Retired" <del> }; <add> String[] labels = new String[] { <add> "Atoms_Label", "Subsets_Label", "Attributes_Label", <add> "Semantic_Types_Label", "Obsolete_Label", "Obsolete_Indicator", <add> }; <add> String[] labelValues = new String[] { <add> "Descriptions", "Refsets", "Properties", "Semantic Tags", "Retired", <add> "Retired" <add> }; <ide> int i = 0; <ide> for (String label : labels) { <ide> GeneralMetadataEntry entry = new GeneralMetadataEntryJpa(); <ide> // for each non core module, create a Subset object <ide> List<ConceptSubset> subsets = new ArrayList<>(); <ide> for (String moduleId : moduleIds) { <del> Logger.getLogger(getClass()).info( <del> " Create subset for module = " + moduleId); <add> Logger.getLogger(getClass()) <add> .info(" Create subset for module = " + moduleId); <ide> Concept concept = getConcept(conceptIdMap.get(moduleId)); <ide> ConceptSubset subset = new ConceptSubsetJpa(); <ide> subset.setName(concept.getName());
Java
mit
678c84ba0ec97a3692871d0926045e6940778b99
0
trendrr/java-oss-lib,MarkG/java-oss-lib
/** * */ package com.trendrr.oss; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; import com.trendrr.json.simple.JSONFormatter; import com.trendrr.json.simple.JSONObject; import com.trendrr.json.simple.JSONValue; /** * * A dynamic map. * * * caching: * * set cacheEnabled to use an internal cache of TypeCasted results. * This is usefull for frequently read maps, with expensive conversions (i.e. string -> map, or list conversions) * Raises the memory footprint somewhat and adds some time to puts and removes * * * * * * * @author Dustin Norlander * @created Dec 29, 2010 * */ public class DynMap extends HashMap<String,Object>{ Logger log = Logger.getLogger(DynMap.class.getCanonicalName()); ConcurrentHashMap<String, Object> cache = new ConcurrentHashMap<String, Object>(); boolean cacheEnabled = false; /* * Register Date and DynMap with the json formatter so we get properly encoded strings. */ static { JSONValue.registerFormatter(Date.class, new JSONFormatter() { @Override public String toJSONString(Object value) { return IsoDateUtil.getIsoDate((Date)value); } }); JSONValue.registerFormatter(DynMap.class, new JSONFormatter() { @Override public String toJSONString(Object value) { return ((DynMap)value).toJSONString(); } }); } /** * puts the value if the key is absent (or null). * @param key * @param val */ public void putIfAbsent(String key, Object val) { if (this.get(key) == null) { this.put(key, val); } } @Override public Object put(String key, Object val) { this.ejectFromCache(key); return super.put(key, val); } public void removeAll(String...keys) { for (String k : keys) { this.remove(k); } } @Override public Object remove(Object k) { this.ejectFromCache((String)k); return super.remove(k); } private void ejectFromCache(String key) { //TODO: this is a dreadful implementation. Set<String> keys = new HashSet<String>(); for (String k : cache.keySet()) { if (k.startsWith(key + ".")) { keys.add(k); } } for (String k : keys) { cache.remove(k); } cache.remove(key); } boolean isCacheEnabled() { return cacheEnabled; } void setCacheEnabled(boolean cacheEnabled) { this.cacheEnabled = cacheEnabled; } /** * Gets the requested object from the map. * * this differs from the standard map.get in that you can * use the dot operator to get a nested value: * * map.get("key1.key2.key3"); * * @param key * @return */ @Override public Object get(Object k) { String key = (String)k; Object val = super.get(key); if (val != null) { return val; } if (key.contains(".")) { //try to reach into the object.. String[] items = key.split("\\."); DynMap cur = this.get(DynMap.class, items[0]); for (int i= 1; i < items.length-1; i++) { cur = cur.get(DynMap.class, items[i]); // log.info("got map: " + items[i] + " " + cur); if (cur == null) return null; } // log.info("returning : " + items[items.length-1] + " " + cur.get(items[items.length-1])); return cur.get(items[items.length-1]); } return null; } public <T> T get(Class<T> cls, String key) { //cache the result.. if (this.cacheEnabled) { String cacheKey = key + "." + cls.getCanonicalName(); if (this.cache.containsKey(cacheKey)) { //null is an acceptable cache result. return (T)this.cache.get(cacheKey); } else { T val = TypeCast.cast(cls,this.get(key)); this.cache.put(cacheKey, val); return val; } } return TypeCast.cast(cls, this.get(key)); } public <T> T get(Class<T> cls, String key, T defaultValue) { T val = this.get(cls, key); if (val == null ) return defaultValue; return val; } /** * Returns a typed list. See TypeCast.getTypedList * * returns the typed list, or null, never empty. * @param <T> * @param cls * @param key * @param delimiters * @return */ public <T> List<T> getList(Class<T> cls, String key, String... delimiters) { //cache the result.. if (this.cacheEnabled) { String cacheKey = key + ".LIST." + cls.getCanonicalName() + "."; if (this.cache.containsKey(cacheKey)) { //null is an acceptable cache result. return (List<T>)this.cache.get(cacheKey); } else { List<T> val = TypeCast.getTypedList(cls, this.get(key), delimiters); this.cache.put(cacheKey, val); return val; } } return TypeCast.getTypedList(cls, this.get(key), delimiters); } /** * same principle as jquery extend. * * each successive map will override any properties in the one before it. * * Last map in the params is considered the most important one. * * * @param map1 * @param maps * @return this, allows for chaining */ public DynMap extend(Object map1, Object ...maps) { if (map1 == null) return this; DynMap mp1 = DynMapFactory.instance(map1); this.putAll(mp1); for (Object m : maps) { this.putAll(DynMapFactory.instance(m)); } return this; } public String toJSONString() { return JSONObject.toJSONString(this); } /** * will return the map as a url encoded string in the form: * key1=val1&key2=val2& ... * * This can be used as getstring or form-encoded post. * Lists are handled as multiple key /value pairs. * * will skip keys that contain null values. * keys are sorted alphabetically so ordering is consistent * * * @return The url encoded string, or empty string. */ public String toURLString() { StringBuilder str = new StringBuilder(); boolean amp = false; List<String> keys = new ArrayList<String>(); keys.addAll(this.keySet()); Collections.sort(keys); for (String key : keys) { try { String k = URLEncoder.encode(key, "utf-8"); List<String> vals = this.getList(String.class, key); for (String v : vals) { v = URLEncoder.encode(v, "utf-8"); if (v != null) { if (amp) str.append("&"); str.append(k); str.append("="); str.append(v); amp = true; } } } catch (Exception x) { log.log(Level.INFO, "Caught", x); continue; } } return str.toString(); } private String toXMLStringCollection(java.util.Collection c) { if (c == null) return ""; String collection = ""; for (Object o : c) { collection += "<item>"; if (o instanceof DynMap) collection += ((DynMap) o).toXMLString(); else if (o instanceof java.util.Collection) { for (Object b : (java.util.Collection) o) { collection += "<item>"; if (b instanceof java.util.Collection) collection += this .toXMLStringCollection((java.util.Collection) b); else collection += b.toString(); collection += "</item>"; } } else if (o instanceof java.util.Map) { DynMap dm = new DynMap(); dm.putAll((java.util.Map) o); collection += dm.toXMLString(); } else collection += o.toString(); collection += "</item>"; } return collection; } /** * Constructs an xml string from this dynmap. * @return */ public String toXMLString() { if (this.isEmpty()) return null; StringBuilder buf = new StringBuilder(); Iterator iter = this.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); String element = String.valueOf(entry.getKey()); buf.append("<" + element + ">"); if (entry.getValue() instanceof DynMap) { buf.append(((DynMap) entry.getValue()) .toXMLString()); } else if ((entry.getValue()) instanceof java.util.Collection) { buf.append(this .toXMLStringCollection((java.util.Collection) entry .getValue())); } else if ((entry.getValue()) instanceof java.util.Map) { DynMap dm = DynMapFactory.instance(entry.getValue()); buf.append(dm.toXMLString()); } else if ((entry.getValue()) instanceof Date) { buf.append(IsoDateUtil.getIsoDateNoMillis(((Date)entry.getValue()))); } else { buf.append(entry.getValue()); } buf.append("</" + element + ">"); } return buf.toString(); } }
src/com/trendrr/oss/DynMap.java
/** * */ package com.trendrr.oss; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; import com.trendrr.json.simple.JSONFormatter; import com.trendrr.json.simple.JSONObject; import com.trendrr.json.simple.JSONValue; /** * * A dynamic map. * * * caching: * * set cacheEnabled to use an internal cache of TypeCasted results. * This is usefull for frequently read maps, with expensive conversions (i.e. string -> map, or list conversions) * Raises the memory footprint somewhat and adds some time to puts and removes * * * * * * * @author Dustin Norlander * @created Dec 29, 2010 * */ public class DynMap extends HashMap<String,Object>{ Logger log = Logger.getLogger(DynMap.class.getCanonicalName()); ConcurrentHashMap<String, Object> cache = new ConcurrentHashMap<String, Object>(); boolean cacheEnabled = false; /* * Register Date and DynMap with the json formatter so we get properly encoded strings. */ static { JSONValue.registerFormatter(Date.class, new JSONFormatter() { @Override public String toJSONString(Object value) { return IsoDateUtil.getIsoDate((Date)value); } }); JSONValue.registerFormatter(DynMap.class, new JSONFormatter() { @Override public String toJSONString(Object value) { return ((DynMap)value).toJSONString(); } }); } /** * puts the value if the key is absent (or null). * @param key * @param val */ public void putIfAbsent(String key, Object val) { if (this.get(key) == null) { this.put(key, val); } } @Override public Object put(String key, Object val) { this.ejectFromCache(key); return super.put(key, val); } public void removeAll(String...keys) { for (String k : keys) { this.remove(k); } } @Override public Object remove(Object k) { this.ejectFromCache((String)k); return super.remove(k); } private void ejectFromCache(String key) { //TODO: this is a dreadful implementation. Set<String> keys = new HashSet<String>(); for (String k : cache.keySet()) { if (k.startsWith(key + ".")) { keys.add(k); } } for (String k : keys) { cache.remove(k); } cache.remove(key); } boolean isCacheEnabled() { return cacheEnabled; } void setCacheEnabled(boolean cacheEnabled) { this.cacheEnabled = cacheEnabled; } /** * Gets the requested object from the map. * * this differs from the standard map.get in that you can * use the dot operator to get a nested value: * * map.get("key1.key2.key3"); * * @param key * @return */ @Override public Object get(Object k) { String key = (String)k; Object val = super.get(key); if (val != null) { return val; } if (key.contains(".")) { //try to reach into the object.. String[] items = key.split("\\."); DynMap cur = this.get(DynMap.class, items[0]); for (int i= 1; i < items.length-1; i++) { cur = cur.get(DynMap.class, items[i]); // log.info("got map: " + items[i] + " " + cur); if (cur == null) return null; } // log.info("returning : " + items[items.length-1] + " " + cur.get(items[items.length-1])); return cur.get(items[items.length-1]); } return null; } public <T> T get(Class<T> cls, String key) { //cache the result.. if (this.cacheEnabled) { String cacheKey = key + "." + cls.getCanonicalName(); if (this.cache.containsKey(cacheKey)) { //null is an acceptable cache result. return (T)this.cache.get(cacheKey); } else { T val = TypeCast.cast(cls,this.get(key)); this.cache.put(cacheKey, val); return val; } } return TypeCast.cast(cls, this.get(key)); } public <T> T get(Class<T> cls, String key, T defaultValue) { T val = this.get(cls, key); if (val == null ) return defaultValue; return val; } /** * Returns a typed list. See TypeCast.getTypedList * * returns the typed list, or null, never empty. * @param <T> * @param cls * @param key * @param delimiters * @return */ public <T> List<T> getList(Class<T> cls, String key, String... delimiters) { //cache the result.. if (this.cacheEnabled) { String cacheKey = key + ".LIST." + cls.getCanonicalName() + "."; if (this.cache.containsKey(cacheKey)) { //null is an acceptable cache result. return (List<T>)this.cache.get(cacheKey); } else { List<T> val = TypeCast.getTypedList(cls, this.get(key), delimiters); this.cache.put(cacheKey, val); return val; } } return TypeCast.getTypedList(cls, this.get(key), delimiters); } /** * same principle as jquery extend. * * each successive map will override any properties in the one before it. * * Last map in the params is considered the most important one. * * * @param map1 * @param maps * @return this, allows for chaining */ public DynMap extend(Object map1, Object ...maps) { if (map1 == null) return this; DynMap mp1 = DynMapFactory.instance(map1); this.putAll(mp1); for (Object m : maps) { this.putAll(DynMapFactory.instance(m)); } return this; } public String toJSONString() { return JSONObject.toJSONString(this); } /** * will return the map as a url encoded string in the form: * key1=val1&key2=val2& ... * * This can be used as getstring or form-encoded post. * Lists are handled as multiple key /value pairs. * * will skip keys that contain null values. * keys are sorted alphabetically so ordering is consistent * * * @return The url encoded string, or empty string. */ public String toURLString() { StringBuilder str = new StringBuilder(); boolean amp = false; List<String> keys = new ArrayList<String>(); keys.addAll(this.keySet()); Collections.sort(keys); for (String key : keys) { try { String k = URLEncoder.encode(key, "utf-8"); List<String> vals = this.getList(String.class, key); for (String v : vals) { v = URLEncoder.encode(v, "utf-8"); if (v != null) { if (amp) str.append("&"); str.append(k); str.append("="); str.append(v); amp = true; } } } catch (Exception x) { log.log(Level.INFO, "Caught", x); continue; } } return str.toString(); } }
Add toXMLString method
src/com/trendrr/oss/DynMap.java
Add toXMLString method
<ide><path>rc/com/trendrr/oss/DynMap.java <ide> import java.util.Date; <ide> import java.util.HashMap; <ide> import java.util.HashSet; <add>import java.util.Iterator; <ide> import java.util.List; <add>import java.util.Map; <ide> import java.util.Set; <ide> import java.util.concurrent.ConcurrentHashMap; <ide> import java.util.logging.Level; <ide> } <ide> return str.toString(); <ide> } <add> <add> private String toXMLStringCollection(java.util.Collection c) { <add> if (c == null) <add> return ""; <add> <add> String collection = ""; <add> for (Object o : c) { <add> collection += "<item>"; <add> if (o instanceof DynMap) <add> collection += ((DynMap) o).toXMLString(); <add> else if (o instanceof java.util.Collection) { <add> for (Object b : (java.util.Collection) o) { <add> collection += "<item>"; <add> if (b instanceof java.util.Collection) <add> collection += this <add> .toXMLStringCollection((java.util.Collection) b); <add> else <add> collection += b.toString(); <add> collection += "</item>"; <add> } <add> } else if (o instanceof java.util.Map) { <add> DynMap dm = new DynMap(); <add> dm.putAll((java.util.Map) o); <add> collection += dm.toXMLString(); <add> } else <add> collection += o.toString(); <add> collection += "</item>"; <add> } <add> return collection; <add> } <add> <add> <add> /** <add> * Constructs an xml string from this dynmap. <add> * @return <add> */ <add> public String toXMLString() { <add> if (this.isEmpty()) <add> return null; <add> <add> StringBuilder buf = new StringBuilder(); <add> Iterator iter = this.entrySet().iterator(); <add> while (iter.hasNext()) { <add> Map.Entry entry = (Map.Entry) iter.next(); <add> String element = String.valueOf(entry.getKey()); <add> buf.append("<" + element + ">"); <add> if (entry.getValue() instanceof DynMap) { <add> buf.append(((DynMap) entry.getValue()) <add> .toXMLString()); <add> } else if ((entry.getValue()) instanceof java.util.Collection) { <add> buf.append(this <add> .toXMLStringCollection((java.util.Collection) entry <add> .getValue())); <add> } else if ((entry.getValue()) instanceof java.util.Map) { <add> DynMap dm = DynMapFactory.instance(entry.getValue()); <add> buf.append(dm.toXMLString()); <add> } else if ((entry.getValue()) instanceof Date) { <add> buf.append(IsoDateUtil.getIsoDateNoMillis(((Date)entry.getValue()))); <add> } else { <add> buf.append(entry.getValue()); <add> } <add> buf.append("</" + element + ">"); <add> } <add> <add> return buf.toString(); <add> } <ide> }
Java
apache-2.0
09bcb3615c38d7dd4e492290eaff4bdb35fbd3ea
0
jpallas/beakerx,twosigma/beaker-notebook,twosigma/beakerx,jpallas/beakerx,twosigma/beakerx,twosigma/beakerx,jpallas/beakerx,twosigma/beaker-notebook,twosigma/beakerx,jpallas/beakerx,jpallas/beakerx,twosigma/beakerx,twosigma/beaker-notebook,twosigma/beaker-notebook,twosigma/beaker-notebook,twosigma/beakerx,jpallas/beakerx
/* * Copyright 2014 TWO SIGMA OPEN SOURCE, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twosigma.beakerx.clojure.evaluator; import clojure.lang.DynamicClassLoader; import clojure.lang.RT; import clojure.lang.Var; import com.google.common.base.Charsets; import com.google.common.io.Resources; import com.twosigma.beakerx.autocomplete.AutocompleteResult; import com.twosigma.beakerx.clojure.autocomplete.ClojureAutocomplete; import com.twosigma.beakerx.evaluator.BaseEvaluator; import com.twosigma.beakerx.evaluator.JobDescriptor; import com.twosigma.beakerx.evaluator.TempFolderFactory; import com.twosigma.beakerx.evaluator.TempFolderFactoryImpl; import com.twosigma.beakerx.jvm.object.SimpleEvaluationObject; import com.twosigma.beakerx.jvm.threads.BeakerCellExecutor; import com.twosigma.beakerx.jvm.threads.CellExecutor; import com.twosigma.beakerx.kernel.ImportPath; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.StringReader; import java.net.URL; import java.util.ArrayList; import java.util.List; public class ClojureEvaluator extends BaseEvaluator { public static final String beaker_clojure_ns = "beaker_clojure_shell"; private final static Logger logger = LoggerFactory.getLogger(ClojureEvaluator.class.getName()); private List<String> requirements; private ClojureWorkerThread workerThread; private DynamicClassLoader loader; private Var clojureLoadString = null; public ClojureEvaluator(String id, String sId, CellExecutor cellExecutor, TempFolderFactory tempFolderFactory) { super(id, sId, cellExecutor, tempFolderFactory); requirements = new ArrayList<>(); init(); workerThread = new ClojureWorkerThread(this); workerThread.start(); } public ClojureEvaluator(String id, String sId) { this(id, sId, new BeakerCellExecutor("clojure"), new TempFolderFactoryImpl()); } @Override public void resetEnvironment() { killClojureThreads(); super.resetEnvironment(); } private void killClojureThreads() { runCode("(import 'clojure.lang.Agent)\n" + "(.shutdownNow Agent/soloExecutor)\n" + "(import 'java.util.concurrent.Executors) \n" + "(set! Agent/soloExecutor (Executors/newCachedThreadPool))"); } @Override protected void doResetEnvironment() { loader = ClojureClassLoaderFactory.newInstance(classPath, outDir); ClassLoader oldLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(loader); for (ImportPath s : imports.getImportPaths()) { String ss = s.asString(); if (!ss.isEmpty()) { try { loader.loadClass(ss); clojureLoadString.invoke(String.format("(import '%s)", ss)); } catch (ClassNotFoundException e) { logger.error("Could not find class while loading notebook: " + ss); } } } for (String s : requirements) { if (s != null && !s.isEmpty()) try { clojureLoadString.invoke(String.format("(require '%s)", s)); } catch (Exception e) { logger.error(e.getMessage()); } } Thread.currentThread().setContextClassLoader(oldLoader); workerThread.halt(); } @Override public void exit() { super.exit(); workerThread.doExit(); cancelExecution(); workerThread.halt(); } @Override public void evaluate(SimpleEvaluationObject seo, String code) { workerThread.add(new JobDescriptor(code, seo)); } @Override public AutocompleteResult autocomplete(String code, int caretPosition) { return ClojureAutocomplete.autocomplete(code, caretPosition, clojureLoadString, shellId); } Object runCode(String theCode) { return clojureLoadString.invoke(theCode); } private void init() { loader = ClojureClassLoaderFactory.newInstance(classPath, outDir); String loadFunctionPrefix = "run_str"; try { String clojureInitScript = String.format(initScriptSource(), beaker_clojure_ns, shellId, loadFunctionPrefix); clojureLoadString = RT.var(String.format("%1$s_%2$s", beaker_clojure_ns, shellId), String.format("%1$s_%2$s", loadFunctionPrefix, shellId)); clojure.lang.Compiler.load(new StringReader(clojureInitScript)); } catch (IOException e) { logger.error(e.getMessage()); } } private String initScriptSource() throws IOException { URL url = this.getClass().getClassLoader().getResource("init_clojure_script.txt"); return Resources.toString(url, Charsets.UTF_8); } DynamicClassLoader getLoader() { return loader; } }
kernel/clojure/src/main/java/com/twosigma/beakerx/clojure/evaluator/ClojureEvaluator.java
/* * Copyright 2014 TWO SIGMA OPEN SOURCE, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twosigma.beakerx.clojure.evaluator; import clojure.lang.DynamicClassLoader; import clojure.lang.RT; import clojure.lang.Var; import com.google.common.base.Charsets; import com.google.common.io.Resources; import com.twosigma.beakerx.autocomplete.AutocompleteResult; import com.twosigma.beakerx.clojure.autocomplete.ClojureAutocomplete; import com.twosigma.beakerx.evaluator.BaseEvaluator; import com.twosigma.beakerx.evaluator.JobDescriptor; import com.twosigma.beakerx.evaluator.TempFolderFactory; import com.twosigma.beakerx.evaluator.TempFolderFactoryImpl; import com.twosigma.beakerx.jvm.object.SimpleEvaluationObject; import com.twosigma.beakerx.jvm.threads.BeakerCellExecutor; import com.twosigma.beakerx.jvm.threads.CellExecutor; import com.twosigma.beakerx.kernel.ImportPath; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.StringReader; import java.net.URL; import java.util.ArrayList; import java.util.List; public class ClojureEvaluator extends BaseEvaluator { public static final String beaker_clojure_ns = "beaker_clojure_shell"; private final static Logger logger = LoggerFactory.getLogger(ClojureEvaluator.class.getName()); private List<String> requirements; private ClojureWorkerThread workerThread; private DynamicClassLoader loader; private Var clojureLoadString = null; public ClojureEvaluator(String id, String sId, CellExecutor cellExecutor, TempFolderFactory tempFolderFactory) { super(id, sId, cellExecutor, tempFolderFactory); requirements = new ArrayList<>(); init(); workerThread = new ClojureWorkerThread(this); workerThread.start(); } public ClojureEvaluator(String id, String sId) { this(id, sId, new BeakerCellExecutor("clojure"), new TempFolderFactoryImpl()); } @Override protected void doResetEnvironment() { loader = ClojureClassLoaderFactory.newInstance(classPath, outDir); ClassLoader oldLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(loader); for (ImportPath s : imports.getImportPaths()) { String ss = s.asString(); if (!ss.isEmpty()) { try { loader.loadClass(ss); clojureLoadString.invoke(String.format("(import '%s)", ss)); } catch (ClassNotFoundException e) { logger.error("Could not find class while loading notebook: " + ss); } } } for (String s : requirements) { if (s != null && !s.isEmpty()) try { clojureLoadString.invoke(String.format("(require '%s)", s)); } catch (Exception e) { logger.error(e.getMessage()); } } Thread.currentThread().setContextClassLoader(oldLoader); workerThread.halt(); } @Override public void exit() { super.exit(); workerThread.doExit(); cancelExecution(); workerThread.halt(); } @Override public void evaluate(SimpleEvaluationObject seo, String code) { workerThread.add(new JobDescriptor(code, seo)); } @Override public AutocompleteResult autocomplete(String code, int caretPosition) { return ClojureAutocomplete.autocomplete(code, caretPosition, clojureLoadString, shellId); } Object runCode(String theCode) { return clojureLoadString.invoke(theCode); } private void init() { loader = ClojureClassLoaderFactory.newInstance(classPath, outDir); String loadFunctionPrefix = "run_str"; try { String clojureInitScript = String.format(initScriptSource(), beaker_clojure_ns, shellId, loadFunctionPrefix); clojureLoadString = RT.var(String.format("%1$s_%2$s", beaker_clojure_ns, shellId), String.format("%1$s_%2$s", loadFunctionPrefix, shellId)); clojure.lang.Compiler.load(new StringReader(clojureInitScript)); } catch (IOException e) { logger.error(e.getMessage()); } } private String initScriptSource() throws IOException { URL url = this.getClass().getClassLoader().getResource("init_clojure_script.txt"); return Resources.toString(url, Charsets.UTF_8); } DynamicClassLoader getLoader() { return loader; } }
#5641: kill clojure threads (#6184) * #5641: kill clojure threads * #5641: change to one call of runCode method
kernel/clojure/src/main/java/com/twosigma/beakerx/clojure/evaluator/ClojureEvaluator.java
#5641: kill clojure threads (#6184)
<ide><path>ernel/clojure/src/main/java/com/twosigma/beakerx/clojure/evaluator/ClojureEvaluator.java <ide> <ide> public ClojureEvaluator(String id, String sId) { <ide> this(id, sId, new BeakerCellExecutor("clojure"), new TempFolderFactoryImpl()); <add> } <add> <add> @Override <add> public void resetEnvironment() { <add> killClojureThreads(); <add> super.resetEnvironment(); <add> } <add> <add> private void killClojureThreads() { <add> runCode("(import 'clojure.lang.Agent)\n" + <add> "(.shutdownNow Agent/soloExecutor)\n" + <add> "(import 'java.util.concurrent.Executors) \n" + <add> "(set! Agent/soloExecutor (Executors/newCachedThreadPool))"); <ide> } <ide> <ide> @Override
Java
mpl-2.0
24f2b3978b5058dfeefd7a794707b9a8c6a09d9f
0
opensensorhub/osh-android
/***************************** BEGIN LICENSE BLOCK *************************** The contents of this file are subject to the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The Initial Developer is Sensia Software LLC. Portions created by the Initial Developer are Copyright (C) 2014 the Initial Developer. All Rights Reserved. ******************************* END LICENSE BLOCK ***************************/ package org.sensorhub.impl.sensor.android; import net.opengis.swe.v20.DataBlock; import net.opengis.swe.v20.DataComponent; import net.opengis.swe.v20.DataEncoding; import org.sensorhub.api.sensor.SensorException; import org.sensorhub.impl.sensor.AbstractSensorOutput; import org.vast.data.TextEncodingImpl; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; /** * <p> * Implementation of data interface for Android sensors * </p> * * <p>Copyright (c) 2013</p> * @author Alexandre Robin <[email protected]> * @since Sep 6, 2013 */ public class AndroidSensorOutput extends AbstractSensorOutput<AndroidSensorsDriver> implements SensorEventListener { SensorManager aSensorManager; Sensor aSensor; protected AndroidSensorOutput(AndroidSensorsDriver parentModule, SensorManager aSensorManager, Sensor aSensor) { super(parentModule); this.aSensorManager = aSensorManager; this.aSensor = aSensor; } @Override public String getName() { return aSensor.getName() + "_data"; } protected void init() { aSensorManager.registerListener(this, aSensor, 10); } @Override public double getAverageSamplingPeriod() { // TODO Auto-generated method stub return 0; } @Override public DataComponent getRecordDescription() { // TODO Auto-generated method stub return null; } @Override public DataEncoding getRecommendedEncoding() { return new TextEncodingImpl(",", "\n"); } @Override public DataBlock getLatestRecord() throws SensorException { // TODO Auto-generated method stub return null; } @Override public double getLatestRecordTime() { // TODO Auto-generated method stub return Double.NaN; } @Override public void onAccuracyChanged(Sensor sensor, int arg1) { // TODO Auto-generated method stub } @Override public void onSensorChanged(SensorEvent e) { // TODO Auto-generated method stub } }
sensorhub-driver-android/src/main/java/org/sensorhub/impl/sensor/android/AndroidSensorOutput.java
/***************************** BEGIN LICENSE BLOCK *************************** The contents of this file are subject to the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The Initial Developer is Sensia Software LLC. Portions created by the Initial Developer are Copyright (C) 2014 the Initial Developer. All Rights Reserved. ******************************* END LICENSE BLOCK ***************************/ package org.sensorhub.impl.sensor.android; import net.opengis.swe.v20.DataBlock; import net.opengis.swe.v20.DataComponent; import net.opengis.swe.v20.DataEncoding; import org.sensorhub.api.sensor.SensorException; import org.sensorhub.impl.sensor.AbstractSensorOutput; import org.vast.data.TextEncodingImpl; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; /** * <p> * Implementation of data interface for Android sensors * </p> * * <p>Copyright (c) 2013</p> * @author Alexandre Robin <[email protected]> * @since Sep 6, 2013 */ public class AndroidSensorOutput extends AbstractSensorOutput<AndroidSensorsDriver> implements SensorEventListener { SensorManager aSensorManager; Sensor aSensor; protected AndroidSensorOutput(AndroidSensorsDriver parentModule, SensorManager aSensorManager, Sensor aSensor) { super(parentModule); this.aSensorManager = aSensorManager; this.aSensor = aSensor; } @Override public String getName() { return aSensor.getName() + "_data"; } protected void init() { aSensorManager.registerListener(this, aSensor, 10); } @Override public double getAverageSamplingPeriod() { // TODO Auto-generated method stub return 0; } @Override public DataComponent getRecordDescription() { // TODO Auto-generated method stub return null; } @Override public DataEncoding getRecommendedEncoding() { return new TextEncodingImpl(",", "\n"); } @Override public DataBlock getLatestRecord() throws SensorException { // TODO Auto-generated method stub return null; } @Override public double getLatestRecordTime() { // TODO Auto-generated method stub return 0; } @Override public void onAccuracyChanged(Sensor sensor, int arg1) { // TODO Auto-generated method stub } @Override public void onSensorChanged(SensorEvent e) { // TODO Auto-generated method stub } }
Clarified javadoc of getLatestRecordTime() and properly generate/handle NaN case everywhere
sensorhub-driver-android/src/main/java/org/sensorhub/impl/sensor/android/AndroidSensorOutput.java
Clarified javadoc of getLatestRecordTime() and properly generate/handle NaN case everywhere
<ide><path>ensorhub-driver-android/src/main/java/org/sensorhub/impl/sensor/android/AndroidSensorOutput.java <ide> public double getLatestRecordTime() <ide> { <ide> // TODO Auto-generated method stub <del> return 0; <add> return Double.NaN; <ide> } <ide> <ide>
Java
apache-2.0
271418cf7678ce99cd29c057ca391ef55c8d12c9
0
Inari-Soft/inari-dash-demo,InariSoft/inari-dash-demo
package com.inari.dash.game.tasks; import com.inari.dash.game.GameExitCondition; import com.inari.dash.game.GameSystem; import com.inari.dash.game.StartGameCondition; import com.inari.firefly.component.build.ComponentBuilder; import com.inari.firefly.state.StateChange; import com.inari.firefly.state.StateSystem; import com.inari.firefly.state.Workflow; import com.inari.firefly.system.FFContext; import com.inari.firefly.task.Task; import com.inari.firefly.task.TaskSystem; import com.inari.firefly.task.WorkflowEventTrigger; public class InitGameWorkflow extends Task { public static final String TASK_NAME = "InitGameWorkflow"; public enum TaskName { LOAD_GAME( LoadGame.class, true, new WorkflowEventTrigger( GameSystem.GAME_WORKFLOW_NAME, WorkflowEventTrigger.Type.ENTER_STATE, StateName.GAME_SELECTION.name() ) ), LOAD_GAME_SELECTION( LoadGameSelection.class ), LOAD_PLAY( LoadPlay.class, false, new WorkflowEventTrigger( GameSystem.GAME_WORKFLOW_NAME, WorkflowEventTrigger.Type.STATE_CHANGE, StateChangeName.PLAY_CAVE.name() ) ), LOAD_CAVE( LoadCave.class ), NEXT_CAVE( NextCave.class ), REPLAY_CAVE( ReplayCave.class ), DISPOSE_CAVE( DisposeCave.class ), DISPOSE_PLAY( DisposePlay.class, false, new WorkflowEventTrigger( GameSystem.GAME_WORKFLOW_NAME, WorkflowEventTrigger.Type.STATE_CHANGE, StateChangeName.EXIT_PLAY.name() ) ), DISPOSE_GAME_SELECTION( DisposeGameSelection.class ), DISPOSE_GAME( DisposeGame.class, true, new WorkflowEventTrigger( GameSystem.GAME_WORKFLOW_NAME, WorkflowEventTrigger.Type.STATE_CHANGE, StateChangeName.EXIT_GAME.name() ) ); public final boolean removeAfterRun; public final Class<? extends Task> type; public final WorkflowEventTrigger trigger; private TaskName( Class<? extends Task> type ) { this.type = type; this.removeAfterRun = false; trigger = null; } private TaskName( Class<? extends Task> type, boolean removeAfterRun, WorkflowEventTrigger trigger ) { this.type = type; this.removeAfterRun = removeAfterRun; this.trigger = trigger; } } public enum StateName { GAME_SELECTION, CAVE_PLAY } public enum StateChangeName { EXIT_GAME( StateName.GAME_SELECTION, null ), PLAY_CAVE( StateName.GAME_SELECTION, StateName.CAVE_PLAY ), EXIT_PLAY( StateName.CAVE_PLAY, StateName.GAME_SELECTION ) ; public final StateName from; public final StateName to; private StateChangeName( StateName from, StateName to ) { this.from = from; this.to = to; } } protected InitGameWorkflow( int id ) { super( id ); } @Override public void run( FFContext context ) { StateSystem stateSystem = context.getSystem( StateSystem.SYSTEM_KEY ); TaskSystem taskSystem = context.getSystem( TaskSystem.SYSTEM_KEY ); for ( TaskName taskName : TaskName.values() ) { ComponentBuilder taskBuilder = taskSystem.getTaskBuilder() .set( Task.NAME, taskName.name() ) .set( Task.REMOVE_AFTER_RUN, taskName.removeAfterRun ); if ( taskName.trigger != null ) { taskBuilder.add( Task.TRIGGERS, taskName.trigger ); } taskBuilder.build( taskName.type ); } stateSystem.getWorkflowBuilder() .set( Workflow.NAME, GameSystem.GAME_WORKFLOW_NAME ) .set( Workflow.START_STATE_NAME, StateName.GAME_SELECTION.name() ) .add( Workflow.STATES, StateName.GAME_SELECTION.name() ) .add( Workflow.STATES, StateName.CAVE_PLAY.name() ) .add( Workflow.STATE_CHANGES, new StateChange( StateChangeName.EXIT_GAME.name(), StateName.GAME_SELECTION.name(), null, new GameExitCondition() ) ) .add( Workflow.STATE_CHANGES, new StateChange( StateChangeName.PLAY_CAVE.name(), StateName.GAME_SELECTION.name(), StateName.CAVE_PLAY.name(), new StartGameCondition() ) ) .add( Workflow.STATE_CHANGES, new StateChange( StateChangeName.EXIT_PLAY.name(), StateName.GAME_SELECTION.name(), StateName.GAME_SELECTION.name() ) ) .activate(); } }
src/main/java/com/inari/dash/game/tasks/InitGameWorkflow.java
package com.inari.dash.game.tasks; import com.inari.dash.game.GameExitCondition; import com.inari.dash.game.GameSystem; import com.inari.dash.game.StartGameCondition; import com.inari.firefly.state.StateChange; import com.inari.firefly.state.StateSystem; import com.inari.firefly.state.Workflow; import com.inari.firefly.system.FFContext; import com.inari.firefly.task.Task; import com.inari.firefly.task.TaskSystem; import com.inari.firefly.task.WorkflowEventTrigger; public class InitGameWorkflow extends Task { public static final String TASK_NAME = "InitGameWorkflow"; public enum TaskName { LOAD_GAME( LoadGame.class, true ), LOAD_GAME_SELECTION( LoadGameSelection.class ), LOAD_PLAY( LoadPlay.class ), LOAD_CAVE( LoadCave.class ), NEXT_CAVE( NextCave.class ), REPLAY_CAVE( ReplayCave.class ), DISPOSE_CAVE( DisposeCave.class ), DISPOSE_PLAY( DisposePlay.class ), DISPOSE_GAME_SELECTION( DisposeGameSelection.class ), DISPOSE_GAME( DisposeGame.class, true ); public boolean removeAfterRun = false; public final Class<? extends Task> type; private TaskName( Class<? extends Task> type ) { this.type = type; } private TaskName( Class<? extends Task> type, boolean removeAfterRun ) { this.type = type; this.removeAfterRun = removeAfterRun; } } public enum StateName { GAME_SELECTION, CAVE_PLAY } public enum StateChangeName { EXIT_GAME( StateName.GAME_SELECTION, null ), PLAY_CAVE( StateName.GAME_SELECTION, StateName.CAVE_PLAY ), EXIT_PLAY( StateName.CAVE_PLAY, StateName.GAME_SELECTION ) ; public final StateName from; public final StateName to; private StateChangeName( StateName from, StateName to ) { this.from = from; this.to = to; } } protected InitGameWorkflow( int id ) { super( id ); } @Override public void run( FFContext context ) { StateSystem stateSystem = context.getSystem( StateSystem.SYSTEM_KEY ); TaskSystem taskSystem = context.getSystem( TaskSystem.SYSTEM_KEY ); for ( TaskName taskName : TaskName.values() ) { taskSystem.getTaskBuilder() .set( Task.NAME, taskName.name() ) .set( Task.REMOVE_AFTER_RUN, taskName.removeAfterRun ) .build( taskName.type ); } taskSystem.getTaskTriggerBuilder() .set( WorkflowEventTrigger.TASK_ID, taskSystem.getTaskId( TaskName.LOAD_GAME.name() ) ) .set( WorkflowEventTrigger.WORKFLOW_NAME, GameSystem.GAME_WORKFLOW_NAME ) .set( WorkflowEventTrigger.TRIGGER_TYPE, WorkflowEventTrigger.Type.ENTER_STATE ) .set( WorkflowEventTrigger.TRIGGER_NAME, StateName.GAME_SELECTION.name() ) .buildAndNext( WorkflowEventTrigger.class ) .set( WorkflowEventTrigger.TASK_ID, taskSystem.getTaskId( TaskName.DISPOSE_GAME.name() ) ) .set( WorkflowEventTrigger.WORKFLOW_NAME, GameSystem.GAME_WORKFLOW_NAME ) .set( WorkflowEventTrigger.TRIGGER_TYPE, WorkflowEventTrigger.Type.STATE_CHANGE ) .set( WorkflowEventTrigger.TRIGGER_NAME, StateChangeName.EXIT_GAME.name() ) .buildAndNext( WorkflowEventTrigger.class ) .set( WorkflowEventTrigger.TASK_ID, taskSystem.getTaskId( TaskName.LOAD_PLAY.name() ) ) .set( WorkflowEventTrigger.WORKFLOW_NAME, GameSystem.GAME_WORKFLOW_NAME ) .set( WorkflowEventTrigger.TRIGGER_TYPE, WorkflowEventTrigger.Type.STATE_CHANGE ) .set( WorkflowEventTrigger.TRIGGER_NAME, StateChangeName.PLAY_CAVE.name() ) .buildAndNext( WorkflowEventTrigger.class ) .set( WorkflowEventTrigger.TASK_ID, taskSystem.getTaskId( TaskName.DISPOSE_PLAY.name() ) ) .set( WorkflowEventTrigger.WORKFLOW_NAME, GameSystem.GAME_WORKFLOW_NAME ) .set( WorkflowEventTrigger.TRIGGER_TYPE, WorkflowEventTrigger.Type.STATE_CHANGE ) .set( WorkflowEventTrigger.TRIGGER_NAME, StateChangeName.EXIT_PLAY.name() ) .build( WorkflowEventTrigger.class ); stateSystem.getWorkflowBuilder() .set( Workflow.NAME, GameSystem.GAME_WORKFLOW_NAME ) .set( Workflow.START_STATE_NAME, StateName.GAME_SELECTION.name() ) .add( Workflow.STATES, StateName.GAME_SELECTION.name() ) .add( Workflow.STATES, StateName.CAVE_PLAY.name() ) .add( Workflow.STATE_CHANGES, new StateChange( StateChangeName.EXIT_GAME.name(), StateName.GAME_SELECTION.name(), null, new GameExitCondition() ) ) .add( Workflow.STATE_CHANGES, new StateChange( StateChangeName.PLAY_CAVE.name(), StateName.GAME_SELECTION.name(), StateName.CAVE_PLAY.name(), new StartGameCondition() ) ) .add( Workflow.STATE_CHANGES, new StateChange( StateChangeName.EXIT_PLAY.name(), StateName.GAME_SELECTION.name(), StateName.GAME_SELECTION.name() ) ) .activate(); } }
task trigger
src/main/java/com/inari/dash/game/tasks/InitGameWorkflow.java
task trigger
<ide><path>rc/main/java/com/inari/dash/game/tasks/InitGameWorkflow.java <ide> import com.inari.dash.game.GameExitCondition; <ide> import com.inari.dash.game.GameSystem; <ide> import com.inari.dash.game.StartGameCondition; <add>import com.inari.firefly.component.build.ComponentBuilder; <ide> import com.inari.firefly.state.StateChange; <ide> import com.inari.firefly.state.StateSystem; <ide> import com.inari.firefly.state.Workflow; <ide> public static final String TASK_NAME = "InitGameWorkflow"; <ide> <ide> public enum TaskName { <del> LOAD_GAME( LoadGame.class, true ), <add> LOAD_GAME( <add> LoadGame.class, <add> true, <add> new WorkflowEventTrigger( GameSystem.GAME_WORKFLOW_NAME, WorkflowEventTrigger.Type.ENTER_STATE, StateName.GAME_SELECTION.name() ) <add> ), <ide> LOAD_GAME_SELECTION( LoadGameSelection.class ), <del> LOAD_PLAY( LoadPlay.class ), <add> LOAD_PLAY( <add> LoadPlay.class, <add> false, <add> new WorkflowEventTrigger( GameSystem.GAME_WORKFLOW_NAME, WorkflowEventTrigger.Type.STATE_CHANGE, StateChangeName.PLAY_CAVE.name() ) <add> ), <ide> LOAD_CAVE( LoadCave.class ), <ide> NEXT_CAVE( NextCave.class ), <ide> REPLAY_CAVE( ReplayCave.class ), <ide> DISPOSE_CAVE( DisposeCave.class ), <del> DISPOSE_PLAY( DisposePlay.class ), <add> DISPOSE_PLAY( <add> DisposePlay.class, <add> false, <add> new WorkflowEventTrigger( GameSystem.GAME_WORKFLOW_NAME, WorkflowEventTrigger.Type.STATE_CHANGE, StateChangeName.EXIT_PLAY.name() ) <add> ), <ide> DISPOSE_GAME_SELECTION( DisposeGameSelection.class ), <del> DISPOSE_GAME( DisposeGame.class, true ); <add> DISPOSE_GAME( <add> DisposeGame.class, <add> true, <add> new WorkflowEventTrigger( GameSystem.GAME_WORKFLOW_NAME, WorkflowEventTrigger.Type.STATE_CHANGE, StateChangeName.EXIT_GAME.name() ) <add> ); <ide> <del> public boolean removeAfterRun = false; <add> public final boolean removeAfterRun; <ide> public final Class<? extends Task> type; <add> public final WorkflowEventTrigger trigger; <ide> <ide> private TaskName( Class<? extends Task> type ) { <ide> this.type = type; <add> this.removeAfterRun = false; <add> trigger = null; <ide> } <ide> <del> private TaskName( Class<? extends Task> type, boolean removeAfterRun ) { <add> private TaskName( Class<? extends Task> type, boolean removeAfterRun, WorkflowEventTrigger trigger ) { <ide> this.type = type; <ide> this.removeAfterRun = removeAfterRun; <add> this.trigger = trigger; <ide> } <ide> } <ide> <ide> TaskSystem taskSystem = context.getSystem( TaskSystem.SYSTEM_KEY ); <ide> <ide> for ( TaskName taskName : TaskName.values() ) { <del> taskSystem.getTaskBuilder() <add> ComponentBuilder taskBuilder = taskSystem.getTaskBuilder() <ide> .set( Task.NAME, taskName.name() ) <del> .set( Task.REMOVE_AFTER_RUN, taskName.removeAfterRun ) <del> .build( taskName.type ); <add> .set( Task.REMOVE_AFTER_RUN, taskName.removeAfterRun ); <add> <add> if ( taskName.trigger != null ) { <add> taskBuilder.add( Task.TRIGGERS, taskName.trigger ); <add> } <add> taskBuilder.build( taskName.type ); <ide> } <del> <del> taskSystem.getTaskTriggerBuilder() <del> .set( WorkflowEventTrigger.TASK_ID, taskSystem.getTaskId( TaskName.LOAD_GAME.name() ) ) <del> .set( WorkflowEventTrigger.WORKFLOW_NAME, GameSystem.GAME_WORKFLOW_NAME ) <del> .set( WorkflowEventTrigger.TRIGGER_TYPE, WorkflowEventTrigger.Type.ENTER_STATE ) <del> .set( WorkflowEventTrigger.TRIGGER_NAME, StateName.GAME_SELECTION.name() ) <del> .buildAndNext( WorkflowEventTrigger.class ) <del> .set( WorkflowEventTrigger.TASK_ID, taskSystem.getTaskId( TaskName.DISPOSE_GAME.name() ) ) <del> .set( WorkflowEventTrigger.WORKFLOW_NAME, GameSystem.GAME_WORKFLOW_NAME ) <del> .set( WorkflowEventTrigger.TRIGGER_TYPE, WorkflowEventTrigger.Type.STATE_CHANGE ) <del> .set( WorkflowEventTrigger.TRIGGER_NAME, StateChangeName.EXIT_GAME.name() ) <del> .buildAndNext( WorkflowEventTrigger.class ) <del> .set( WorkflowEventTrigger.TASK_ID, taskSystem.getTaskId( TaskName.LOAD_PLAY.name() ) ) <del> .set( WorkflowEventTrigger.WORKFLOW_NAME, GameSystem.GAME_WORKFLOW_NAME ) <del> .set( WorkflowEventTrigger.TRIGGER_TYPE, WorkflowEventTrigger.Type.STATE_CHANGE ) <del> .set( WorkflowEventTrigger.TRIGGER_NAME, StateChangeName.PLAY_CAVE.name() ) <del> .buildAndNext( WorkflowEventTrigger.class ) <del> .set( WorkflowEventTrigger.TASK_ID, taskSystem.getTaskId( TaskName.DISPOSE_PLAY.name() ) ) <del> .set( WorkflowEventTrigger.WORKFLOW_NAME, GameSystem.GAME_WORKFLOW_NAME ) <del> .set( WorkflowEventTrigger.TRIGGER_TYPE, WorkflowEventTrigger.Type.STATE_CHANGE ) <del> .set( WorkflowEventTrigger.TRIGGER_NAME, StateChangeName.EXIT_PLAY.name() ) <del> .build( WorkflowEventTrigger.class ); <ide> <ide> stateSystem.getWorkflowBuilder() <ide> .set( Workflow.NAME, GameSystem.GAME_WORKFLOW_NAME )
JavaScript
mit
5910efe01241f94942d2fb4be3d52125ff65bd10
0
TechnoX/rcj-rescue-scoring,TechnoX/rcj-rescue-scoring
// register the directive with your app module var app = angular.module('ddApp', ['ngAnimate', 'ui.bootstrap', 'rzModule']); // function referenced by the drop target app.controller('ddController', ['$scope', '$uibModal', '$log','$http', function($scope, $uibModal, $log, $http){ $scope.sliderOptions = { floor: 0, ceil: 0, vertical: true, showSelectionBar: true, showTicksValues: true, ticksValuesTooltip: function (v) { return 'Level ' + v; } }; $scope.z = 0; $scope.startTile = {x: 0, y: 0, z: 0}; $scope.height = 1; $scope.sliderOptions.ceil = $scope.height - 1; $scope.width = 1; $scope.length = 1; $scope.name = "Awesome Testbana"; $scope.cells = {}; if(mapId){ $http.get("/api/maps/maze/" + mapId + "?populate=true").then(function(response){ $scope.startTile = response.data.startTile; $scope.height = response.data.height; $scope.sliderOptions.ceil = $scope.height - 1; $scope.width = response.data.width; $scope.length = response.data.length; $scope.name = response.data.name; }, function(response){ console.log("Error: " + response.statusText); }); } $scope.range = function(n){ arr = []; for (var i=0; i < n; i++) { arr.push(i); } return arr; } $scope.$watchCollection('startTile', function(newValue, oldValue){ // If initialization if(newValue === oldValue) return; if($scope.cells[oldValue.x+','+oldValue.y+','+oldValue.z]) $scope.cells[oldValue.x+','+oldValue.y+','+oldValue.z].checkpoint = false; $scope.cells[newValue.x+','+newValue.y+','+newValue.z].checkpoint = true; $scope.recalculateLinear(); }); $scope.isUndefined = function (thing) { return (typeof thing === "undefined"); } $scope.recalculateLinear = function(){ if($scope.startNotSet()) return; // Reset all previous linear walls for(var index in $scope.cells){ $scope.cells[index].isLinear = false; } // Start it will all 4 walls around the starting tile recurs($scope.startTile.x-1, $scope.startTile.y, $scope.startTile.z); recurs($scope.startTile.x+1, $scope.startTile.y, $scope.startTile.z); recurs($scope.startTile.x, $scope.startTile.y-1, $scope.startTile.z); recurs($scope.startTile.x, $scope.startTile.y+1, $scope.startTile.z); } function isOdd(num) { return num % 2;} function recurs(x,y,z){ var cell = $scope.cells[x+','+y+','+z]; // If this is a wall that doesn't exists if(!cell) return; // Outside of the current maze size. if(x > $scope.width*2 + 1 || x < 0 || y > $scope.length*2 + 1 || y < 0 || z > $scope.height || z < 0) return; // Already visited this, returning if(cell.isLinear) return; if(cell.isWall){ cell.isLinear = true; // horizontal walls if(isOdd(x) && !isOdd(y)){ // Set tiles around this wall to linear setTileLinear(x-2,y-1,z); setTileLinear(x,y-1,z); setTileLinear(x+2,y-1,z); setTileLinear(x-2,y+1,z); setTileLinear(x,y+1,z); setTileLinear(x+2,y+1,z); // Check neighbours recurs(x+2,y,z); recurs(x-2,y,z); recurs(x-1,y-1,z); recurs(x-1,y+1,z); recurs(x+1,y-1,z); recurs(x+1,y+1,z); }// Vertical wall else if(!isOdd(x) && isOdd(y)){ // Set tiles around this wall to linear setTileLinear(x-1,y-2,z); setTileLinear(x-1,y,z); setTileLinear(x-1,y+2,z); setTileLinear(x+1,y-2,z); setTileLinear(x+1,y,z); setTileLinear(x+1,y+2,z); // Check neighbours recurs(x,y-2,z); recurs(x,y+2,z); recurs(x-1,y-1,z); recurs(x-1,y+1,z); recurs(x+1,y-1,z); recurs(x+1,y+1,z); } } } function setTileLinear(x,y,z){ // Check that this is an actual tile, not a wall var cell = $scope.cells[x+','+y+','+z]; if(cell){ cell.isLinear = true; }else{ $scope.cells[x+','+y+','+z] = {isTile: true, isLinear: true, changeFloorTo: z}; } } $scope.startNotSet = function(){ return $scope.startTile.x == 0 && $scope.startTile.y == 0 && $scope.startTile.z == 0; } $scope.saveMap = function(){ var map = { name: $scope.name, length: $scope.length, height: $scope.height, width: $scope.width, startTile: $scope.startTile }; console.log(map); $http.post("/api/maps/maze", map).then(function(response){ alert("Success!"); console.log(response.data); window.location.replace("/maze/editor/" + response.data.id) }, function(response){ console.log(response); console.log("Error: " + response.statusText); }); } $scope.cellClick = function(x,y,z,isWall,isTile){ var cell = $scope.cells[x+','+y+','+z]; // If wall if(isWall){ if(!cell){ $scope.cells[x+','+y+','+z] = {isWall: true}; }else{ cell.isWall = !cell.isWall; } $scope.recalculateLinear(); } else if(isTile){ if(!cell){ $scope.cells[x+','+y+','+z] = {isTile: true, changeFloorTo: z}; } $scope.open(x,y,z); } } $scope.open = function(x,y,z) { var modalInstance = $uibModal.open({ animation: true, templateUrl: '/templates/maze_editor_modal.html', controller: 'ModalInstanceCtrl', size: 'sm', scope: $scope, resolve: { x: function(){return x;}, y: function(){return y;}, z: function(){return z;} } }); }; }]); // Please note that $uibModalInstance represents a modal window (instance) dependency. // It is not the same as the $uibModal service used above. app.controller('ModalInstanceCtrl', function ($scope, $uibModalInstance, x, y, z) { $scope.tile = $scope.$parent.cells[x+','+y+','+z];; $scope.isStart = $scope.$parent.startTile.x == x && $scope.$parent.startTile.y == y && $scope.$parent.startTile.z == z; $scope.height = $scope.$parent.height; $scope.z = z; $scope.oldFloorDestination = $scope.tile.changeFloorTo; $scope.elevatorChanged = function(newValue){ console.log("old", $scope.oldFloorDestination); console.log("new", newValue); // Remove the old one if($scope.oldFloorDestination != z && $scope.$parent.cells[x+','+y+','+$scope.oldFloorDestination]){ console.log("Remove old elevator on " + x+','+y+','+$scope.oldFloorDestination); $scope.$parent.cells[x+','+y+','+$scope.oldFloorDestination].changeFloorTo = $scope.oldFloorDestination; } // Set the new one if($scope.$parent.cells[x+','+y+','+newValue]){ console.log("Create new elevator on " +x+','+y+','+newValue + " (1) to floor "+ z); $scope.$parent.cells[x+','+y+','+newValue].changeFloorTo = z; }else{ console.log("Create new elevator on " +x+','+y+','+newValue + " (2) to floor "+ z); $scope.$parent.cells[x+','+y+','+newValue] = {isTile: true, changeFloorTo: z}; } $scope.oldFloorDestination = newValue; } $scope.startChanged = function(){ if($scope.isStart){ $scope.$parent.startTile.x = x; $scope.$parent.startTile.y = y; $scope.$parent.startTile.z = z; } } $scope.range = function(n){ arr = []; for (var i=0; i < n; i++) { arr.push(i); } return arr; } $scope.ok = function () { $uibModalInstance.close(); }; });
public/javascripts/maze_editor.js
// register the directive with your app module var app = angular.module('ddApp', ['ngAnimate', 'ui.bootstrap', 'rzModule']); // function referenced by the drop target app.controller('ddController', ['$scope', '$uibModal', '$log','$http', function($scope, $uibModal, $log, $http){ $scope.sliderOptions = { floor: 0, ceil: 0, vertical: true, showSelectionBar: true, showTicksValues: true, ticksValuesTooltip: function (v) { return 'Level ' + v; } }; $scope.z = 0; $scope.startTile = {x: 0, y: 0, z: 0}; $scope.height = 1; $scope.sliderOptions.ceil = $scope.height - 1; $scope.width = 1; $scope.length = 1; $scope.name = "Awesome Testbana"; $scope.cells = {}; if(mapId){ $http.get("/api/maps/" + mapId + "?populate=true").then(function(response){ $scope.startTile = response.data.startTile; $scope.height = response.data.height; $scope.sliderOptions.ceil = $scope.height - 1; $scope.width = response.data.width; $scope.length = response.data.length; $scope.name = response.data.name; }, function(response){ console.log("Error: " + response.statusText); }); } $scope.range = function(n){ arr = []; for (var i=0; i < n; i++) { arr.push(i); } return arr; } $scope.$watchCollection('startTile', function(newValue, oldValue){ // If initialization if(newValue === oldValue) return; if($scope.cells[oldValue.x+','+oldValue.y+','+oldValue.z]) $scope.cells[oldValue.x+','+oldValue.y+','+oldValue.z].checkpoint = false; $scope.cells[newValue.x+','+newValue.y+','+newValue.z].checkpoint = true; $scope.recalculateLinear(); }); $scope.isUndefined = function (thing) { return (typeof thing === "undefined"); } $scope.recalculateLinear = function(){ if($scope.startNotSet()) return; // Reset all previous linear walls for(var index in $scope.cells){ $scope.cells[index].isLinear = false; } // Start it will all 4 walls around the starting tile recurs($scope.startTile.x-1, $scope.startTile.y, $scope.startTile.z); recurs($scope.startTile.x+1, $scope.startTile.y, $scope.startTile.z); recurs($scope.startTile.x, $scope.startTile.y-1, $scope.startTile.z); recurs($scope.startTile.x, $scope.startTile.y+1, $scope.startTile.z); } function isOdd(num) { return num % 2;} function recurs(x,y,z){ var cell = $scope.cells[x+','+y+','+z]; // If this is a wall that doesn't exists if(!cell) return; // Outside of the current maze size. if(x > $scope.width*2 + 1 || x < 0 || y > $scope.length*2 + 1 || y < 0 || z > $scope.height || z < 0) return; // Already visited this, returning if(cell.isLinear) return; if(cell.isWall){ cell.isLinear = true; // horizontal walls if(isOdd(x) && !isOdd(y)){ // Set tiles around this wall to linear setTileLinear(x-2,y-1,z); setTileLinear(x,y-1,z); setTileLinear(x+2,y-1,z); setTileLinear(x-2,y+1,z); setTileLinear(x,y+1,z); setTileLinear(x+2,y+1,z); // Check neighbours recurs(x+2,y,z); recurs(x-2,y,z); recurs(x-1,y-1,z); recurs(x-1,y+1,z); recurs(x+1,y-1,z); recurs(x+1,y+1,z); }// Vertical wall else if(!isOdd(x) && isOdd(y)){ // Set tiles around this wall to linear setTileLinear(x-1,y-2,z); setTileLinear(x-1,y,z); setTileLinear(x-1,y+2,z); setTileLinear(x+1,y-2,z); setTileLinear(x+1,y,z); setTileLinear(x+1,y+2,z); // Check neighbours recurs(x,y-2,z); recurs(x,y+2,z); recurs(x-1,y-1,z); recurs(x-1,y+1,z); recurs(x+1,y-1,z); recurs(x+1,y+1,z); } } } function setTileLinear(x,y,z){ // Check that this is an actual tile, not a wall var cell = $scope.cells[x+','+y+','+z]; if(cell){ cell.isLinear = true; }else{ $scope.cells[x+','+y+','+z] = {isTile: true, isLinear: true, changeFloorTo: z}; } } $scope.startNotSet = function(){ return $scope.startTile.x == 0 && $scope.startTile.y == 0 && $scope.startTile.z == 0; } $scope.saveMap = function(){ var map = { name: $scope.name, length: $scope.length, height: $scope.height, width: $scope.width, startTile: $scope.startTile }; $http.post("/api/maps/createmap/", map).then(function(response){ alert("Success!"); console.log(response.data); window.location.replace("/maze/editor/" + response.data.id) }, function(response){ console.log(response); console.log("Error: " + response.statusText); }); } $scope.cellClick = function(x,y,z,isWall,isTile){ var cell = $scope.cells[x+','+y+','+z]; // If wall if(isWall){ if(!cell){ $scope.cells[x+','+y+','+z] = {isWall: true}; }else{ cell.isWall = !cell.isWall; } $scope.recalculateLinear(); } else if(isTile){ if(!cell){ $scope.cells[x+','+y+','+z] = {isTile: true, changeFloorTo: z}; } $scope.open(x,y,z); } } $scope.open = function(x,y,z) { var modalInstance = $uibModal.open({ animation: true, templateUrl: '/templates/maze_editor_modal.html', controller: 'ModalInstanceCtrl', size: 'sm', scope: $scope, resolve: { x: function(){return x;}, y: function(){return y;}, z: function(){return z;} } }); }; }]); // Please note that $uibModalInstance represents a modal window (instance) dependency. // It is not the same as the $uibModal service used above. app.controller('ModalInstanceCtrl', function ($scope, $uibModalInstance, x, y, z) { $scope.tile = $scope.$parent.cells[x+','+y+','+z];; $scope.isStart = $scope.$parent.startTile.x == x && $scope.$parent.startTile.y == y && $scope.$parent.startTile.z == z; $scope.height = $scope.$parent.height; $scope.z = z; $scope.oldFloorDestination = $scope.tile.changeFloorTo; $scope.elevatorChanged = function(newValue){ console.log("old", $scope.oldFloorDestination); console.log("new", newValue); // Remove the old one if($scope.oldFloorDestination != z && $scope.$parent.cells[x+','+y+','+$scope.oldFloorDestination]){ console.log("Remove old elevator on " + x+','+y+','+$scope.oldFloorDestination); $scope.$parent.cells[x+','+y+','+$scope.oldFloorDestination].changeFloorTo = $scope.oldFloorDestination; } // Set the new one if($scope.$parent.cells[x+','+y+','+newValue]){ console.log("Create new elevator on " +x+','+y+','+newValue + " (1) to floor "+ z); $scope.$parent.cells[x+','+y+','+newValue].changeFloorTo = z; }else{ console.log("Create new elevator on " +x+','+y+','+newValue + " (2) to floor "+ z); $scope.$parent.cells[x+','+y+','+newValue] = {isTile: true, changeFloorTo: z}; } $scope.oldFloorDestination = newValue; } $scope.startChanged = function(){ if($scope.isStart){ $scope.$parent.startTile.x = x; $scope.$parent.startTile.y = y; $scope.$parent.startTile.z = z; } } $scope.range = function(n){ arr = []; for (var i=0; i < n; i++) { arr.push(i); } return arr; } $scope.ok = function () { $uibModalInstance.close(); }; });
Save and load maze map from correct URL
public/javascripts/maze_editor.js
Save and load maze map from correct URL
<ide><path>ublic/javascripts/maze_editor.js <ide> <ide> <ide> if(mapId){ <del> $http.get("/api/maps/" + mapId + "?populate=true").then(function(response){ <add> $http.get("/api/maps/maze/" + mapId + "?populate=true").then(function(response){ <ide> $scope.startTile = response.data.startTile; <ide> $scope.height = response.data.height; <ide> $scope.sliderOptions.ceil = $scope.height - 1; <ide> width: $scope.width, <ide> startTile: $scope.startTile <ide> }; <del> <del> $http.post("/api/maps/createmap/", map).then(function(response){ <add> console.log(map); <add> $http.post("/api/maps/maze", map).then(function(response){ <ide> alert("Success!"); <ide> console.log(response.data); <ide> window.location.replace("/maze/editor/" + response.data.id)
Java
apache-2.0
5cecd460eb15249e423493f4bb709dfc618ef172
0
gradle/gradle,gradle/gradle,gradle/gradle,gradle/gradle,gradle/gradle,gradle/gradle,gradle/gradle,gradle/gradle,gradle/gradle,gradle/gradle
/* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.plugin.devel; import org.gradle.api.Incubating; import org.gradle.api.Named; import org.gradle.api.Project; import org.gradle.api.provider.SetProperty; import java.io.Serializable; /** * Describes a Gradle plugin under development. * * @see org.gradle.plugin.devel.plugins.JavaGradlePluginPlugin * @since 2.14 */ public class PluginDeclaration implements Named, Serializable { // TODO: Shouldn't be serializable, remove the interface in Gradle 8.0. private final String name; private String id; private String implementationClass; private String displayName; private String description; private SetProperty<String> tags; public PluginDeclaration(Project project, String name) { this.name = name; this.tags = project.getObjects().setProperty(String.class); } @Override public String getName() { return name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getImplementationClass() { return implementationClass; } public void setImplementationClass(String implementationClass) { this.implementationClass = implementationClass; } /** * Returns the display name for this plugin declaration. * * <p>The display name is used when publishing this plugin to repositories * that support human-readable artifact names. * * @since 4.10 */ public String getDisplayName() { return displayName; } /** * Sets the display name for this plugin declaration. * * <p>The display name is used when publishing this plugin to repositories * that support human-readable artifact names. * * @since 4.10 */ public void setDisplayName(String displayName) { this.displayName = displayName; } /** * Returns the description for this plugin declaration. * * <p>The description is used when publishing this plugin to repositories * that support providing descriptions for artifacts. * * @since 4.10 */ public String getDescription() { return description; } /** * Sets the description for this plugin declaration. * * <p>The description is used when publishing this plugin to repositories * that support providing descriptions for artifacts. * * @since 4.10 */ public void setDescription(String description) { this.description = description; } /** * Returns the tags property for this plugin declaration. * * <p>Tags are used when publishing this plugin to repositories that support tagging plugins, * for example the <a href="http://plugins.gradle.org">Gradle Plugin Portal</a>. * * @since 7.6 */ @Incubating public SetProperty<String> getTags() { return tags; } }
subprojects/plugin-development/src/main/java/org/gradle/plugin/devel/PluginDeclaration.java
/* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.plugin.devel; import com.google.common.base.Objects; import org.gradle.api.Incubating; import org.gradle.api.Named; import java.io.Serializable; import java.util.Collection; import java.util.Collections; /** * Describes a Gradle plugin under development. * * @see org.gradle.plugin.devel.plugins.JavaGradlePluginPlugin * @since 2.14 */ public class PluginDeclaration implements Named, Serializable { // TODO: Shouldn't be serializable, remove the interface in Gradle 8.0. private final String name; private String id; private String implementationClass; private String displayName; private String description; private Collection<String> tags; public PluginDeclaration(String name) { this.name = name; } @Override public String getName() { return name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getImplementationClass() { return implementationClass; } public void setImplementationClass(String implementationClass) { this.implementationClass = implementationClass; } /** * Returns the display name for this plugin declaration. * * <p>The display name is used when publishing this plugin to repositories * that support human-readable artifact names. * * @since 4.10 */ public String getDisplayName() { return displayName; } /** * Sets the display name for this plugin declaration. * * <p>The display name is used when publishing this plugin to repositories * that support human-readable artifact names. * * @since 4.10 */ public void setDisplayName(String displayName) { this.displayName = displayName; } /** * Returns the description for this plugin declaration. * * <p>The description is used when publishing this plugin to repositories * that support providing descriptions for artifacts. * * @since 4.10 */ public String getDescription() { return description; } /** * Sets the description for this plugin declaration. * * <p>The description is used when publishing this plugin to repositories * that support providing descriptions for artifacts. * * @since 4.10 */ public void setDescription(String description) { this.description = description; } /** * Returns the tags for this plugin declaration. * * <p>Tags are used when publishing this plugin to repositories that support tagging plugins, * for example the <a href="http://plugins.gradle.org">Gradle Plugin Portal</a>. * * @since 7.6 */ @Incubating public Collection<String> getTags() { if (tags == null) { return Collections.emptyList(); } return tags; } /** * Set the tags for this plugin declaration. Tags describe the categories this plugin covers. * * <p>Tags are used when publishing this plugin to repositories that support tagging plugins, * for example the <a href="http://plugins.gradle.org">Gradle Plugin Portal</a>. * * @since 7.6 */ @Incubating public void setTags(Collection<String> tags) { this.tags = tags; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof PluginDeclaration) { PluginDeclaration other = (PluginDeclaration) obj; return Objects.equal(name, other.name) && Objects.equal(id, other.id) && Objects.equal(implementationClass, other.implementationClass) && Objects.equal(displayName, other.displayName) && Objects.equal(description, other.description) && Objects.equal(tags, other.tags); } return false; } @Override public int hashCode() { return Objects.hashCode(name, id, implementationClass, displayName, description, tags); } }
Convert tags into a property
subprojects/plugin-development/src/main/java/org/gradle/plugin/devel/PluginDeclaration.java
Convert tags into a property
<ide><path>ubprojects/plugin-development/src/main/java/org/gradle/plugin/devel/PluginDeclaration.java <ide> <ide> package org.gradle.plugin.devel; <ide> <del>import com.google.common.base.Objects; <ide> import org.gradle.api.Incubating; <ide> import org.gradle.api.Named; <add>import org.gradle.api.Project; <add>import org.gradle.api.provider.SetProperty; <ide> <ide> import java.io.Serializable; <del>import java.util.Collection; <del>import java.util.Collections; <ide> <ide> /** <ide> * Describes a Gradle plugin under development. <ide> private String implementationClass; <ide> private String displayName; <ide> private String description; <del> private Collection<String> tags; <add> private SetProperty<String> tags; <ide> <del> public PluginDeclaration(String name) { <add> public PluginDeclaration(Project project, String name) { <ide> this.name = name; <add> this.tags = project.getObjects().setProperty(String.class); <ide> } <ide> <ide> @Override <ide> } <ide> <ide> /** <del> * Returns the tags for this plugin declaration. <add> * Returns the tags property for this plugin declaration. <ide> * <ide> * <p>Tags are used when publishing this plugin to repositories that support tagging plugins, <ide> * for example the <a href="http://plugins.gradle.org">Gradle Plugin Portal</a>. <ide> * @since 7.6 <ide> */ <ide> @Incubating <del> public Collection<String> getTags() { <del> if (tags == null) { <del> return Collections.emptyList(); <del> } <add> public SetProperty<String> getTags() { <ide> return tags; <ide> } <ide> <del> /** <del> * Set the tags for this plugin declaration. Tags describe the categories this plugin covers. <del> * <del> * <p>Tags are used when publishing this plugin to repositories that support tagging plugins, <del> * for example the <a href="http://plugins.gradle.org">Gradle Plugin Portal</a>. <del> * <del> * @since 7.6 <del> */ <del> @Incubating <del> public void setTags(Collection<String> tags) { <del> this.tags = tags; <del> } <del> <del> @Override <del> public boolean equals(Object obj) { <del> if (this == obj) { <del> return true; <del> } <del> if (obj instanceof PluginDeclaration) { <del> PluginDeclaration other = (PluginDeclaration) obj; <del> return Objects.equal(name, other.name) <del> && Objects.equal(id, other.id) <del> && Objects.equal(implementationClass, other.implementationClass) <del> && Objects.equal(displayName, other.displayName) <del> && Objects.equal(description, other.description) <del> && Objects.equal(tags, other.tags); <del> } <del> return false; <del> } <del> <del> @Override <del> public int hashCode() { <del> return Objects.hashCode(name, id, implementationClass, displayName, description, tags); <del> } <ide> }
Java
mit
015a4c01a08d05d4a0665f650d8517b73605ce76
0
tblsoft/solr-cmd-utils,tblsoft/solr-cmd-utils
package de.tblsoft.solr.pipeline.filter; import com.google.common.base.Joiner; import de.tblsoft.solr.pipeline.AbstractFilter; import de.tblsoft.solr.pipeline.bean.Document; import de.tblsoft.solr.pipeline.bean.Field; import de.tblsoft.solr.util.IOUtils; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; /** * Created by tblsoft on 21.02.16. */ public class CSVWriter extends AbstractFilter { private CSVPrinter printer; private String multiValueSeperator; private boolean firstDocument = true; private String delimiter; private String[] headers; private String absoluteFilename; @Override public void init() { try { String filename = getProperty("filename", null); absoluteFilename = IOUtils.getAbsoluteFile(getBaseDir(), filename); delimiter = getProperty("delimiter", ","); headers = getPropertyAsArray("headers", null); multiValueSeperator = getProperty("multiValueSeperator", ";"); } catch (Exception e) { throw new RuntimeException(e); } super.init(); } String[] getFieldNames(Document document) { List<String> headersFromDocument = new ArrayList<String>(); for(Field field : document.getFields()) { headersFromDocument.add(field.getName()); } return headersFromDocument.toArray(new String[headersFromDocument.size()]); } @Override public void document(Document document) { if(firstDocument) { try { String[] headersFromDocument = getFieldNames(document); PrintWriter out = new PrintWriter(absoluteFilename); CSVFormat format = CSVFormat.RFC4180; printer = format.withDelimiter(delimiter.charAt(0)).withHeader(headersFromDocument).print(out); firstDocument = false; } catch (Exception e) { throw new RuntimeException(e); } } try { List<List<String>> csvRows = new ArrayList<List<String>>(); List<String> csvList = new ArrayList<String>(); for(Field field: document.getFields()) { String value = Joiner.on(multiValueSeperator).join(field.getValues()); csvList.add(value); } csvRows.add(csvList); printer.printRecords(csvRows); } catch (IOException e) { throw new RuntimeException(e); } } @Override public void end() { try { if(printer != null) { printer.close(); } } catch (IOException e) { throw new RuntimeException(e); } } }
src/main/java/de/tblsoft/solr/pipeline/filter/CSVWriter.java
package de.tblsoft.solr.pipeline.filter; import com.google.common.base.Joiner; import de.tblsoft.solr.pipeline.AbstractFilter; import de.tblsoft.solr.pipeline.bean.Document; import de.tblsoft.solr.pipeline.bean.Field; import de.tblsoft.solr.util.IOUtils; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; /** * Created by tblsoft on 21.02.16. */ public class CSVWriter extends AbstractFilter { private CSVPrinter printer; private String multiValueSeperator; private boolean firstDocument = true; private String delimiter; private String[] headers; private String absoluteFilename; @Override public void init() { try { String filename = getProperty("filename", null); absoluteFilename = IOUtils.getAbsoluteFile(getBaseDir(), filename); delimiter = getProperty("delimiter", ","); headers = getPropertyAsArray("headers", null); multiValueSeperator = getProperty("multiValueSeperator", ";"); } catch (Exception e) { throw new RuntimeException(e); } super.init(); } String[] getFieldNames(Document document) { List<String> headersFromDocument = new ArrayList<String>(); for(Field field : document.getFields()) { headersFromDocument.add(field.getName()); } return headersFromDocument.toArray(new String[headersFromDocument.size()]); } @Override public void document(Document document) { if(firstDocument) { try { String[] headersFromDocument = getFieldNames(document); PrintWriter out = new PrintWriter(absoluteFilename); CSVFormat format = CSVFormat.RFC4180; printer = format.withDelimiter(delimiter.charAt(0)).withHeader(headersFromDocument).print(out); firstDocument = false; } catch (Exception e) { throw new RuntimeException(e); } } try { List<List<String>> csvRows = new ArrayList<List<String>>(); List<String> csvList = new ArrayList<String>(); for(Field field: document.getFields()) { String value = Joiner.on(multiValueSeperator).join(field.getValues()); csvList.add(value); } csvRows.add(csvList); printer.printRecords(csvRows); } catch (IOException e) { throw new RuntimeException(e); } } @Override public void end() { try { printer.close(); } catch (IOException e) { throw new RuntimeException(e); } } }
only close the writer if its not null
src/main/java/de/tblsoft/solr/pipeline/filter/CSVWriter.java
only close the writer if its not null
<ide><path>rc/main/java/de/tblsoft/solr/pipeline/filter/CSVWriter.java <ide> @Override <ide> public void end() { <ide> try { <del> printer.close(); <add> if(printer != null) { <add> printer.close(); <add> } <ide> } catch (IOException e) { <ide> throw new RuntimeException(e); <ide> }
JavaScript
mit
27630d9b93add1f92fb1734d5343a0bd4a007be6
0
connorbode/datastructor,connorbode/datastructor
var colors = require('colors'); var port = 3000; global.app = {}; require('./config')(); app.tasks = require('./tasks'); app.models = require('./models'); app.controllers = require('./controllers')(); app.routing.get('*', function (req, res) { res.sendFile(__dirname + '/public/index.html'); }); app.routing.listen(port); console.log(('datastructor running on port ' + port).green);
app/index.js
var colors = require('colors'); var port = 3000; global.app = {}; require('./config')(); app.tasks = require('./tasks'); app.models = require('./models'); app.controllers = require('./controllers')(); app.routing.listen(port); console.log(('datastructor running on port ' + port).green);
redirect all traffic to index.html
app/index.js
redirect all traffic to index.html
<ide><path>pp/index.js <ide> app.models = require('./models'); <ide> app.controllers = require('./controllers')(); <ide> <add>app.routing.get('*', function (req, res) { <add> res.sendFile(__dirname + '/public/index.html'); <add>}); <ide> app.routing.listen(port); <ide> <ide> console.log(('datastructor running on port ' + port).green);
Java
apache-2.0
14a4bce2db0b73ca5a5dea35d519ba70ff4e37a2
0
ricepanda/rice-git3,ricepanda/rice-git2,ricepanda/rice-git2,kuali/rice-playground,ricepanda/rice-git3,ricepanda/rice-git3,kuali/rice-playground,kuali/rice-playground,kuali/rice-playground,ricepanda/rice-git3,ricepanda/rice-git2,ricepanda/rice-git2
/** * Copyright 2005-2012 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.rice.krad.datadictionary; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.collections.ListUtils; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.kuali.rice.core.api.util.ClassLoaderUtils; import org.kuali.rice.krad.bo.PersistableBusinessObjectExtension; import org.kuali.rice.krad.datadictionary.exception.AttributeValidationException; import org.kuali.rice.krad.datadictionary.exception.CompletionException; import org.kuali.rice.krad.datadictionary.parse.StringListConverter; import org.kuali.rice.krad.datadictionary.parse.StringMapConverter; import org.kuali.rice.krad.datadictionary.uif.UifDictionaryIndex; import org.kuali.rice.krad.datadictionary.validator.ValidationController; import org.kuali.rice.krad.service.KRADServiceLocator; import org.kuali.rice.krad.service.PersistenceStructureService; import org.kuali.rice.krad.uif.UifConstants.ViewType; import org.kuali.rice.krad.uif.util.ComponentBeanPostProcessor; import org.kuali.rice.krad.uif.util.UifBeanFactoryPostProcessor; import org.kuali.rice.krad.uif.view.View; import org.kuali.rice.krad.util.ObjectUtils; import org.springframework.beans.PropertyValues; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.beans.factory.support.KualiDefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.context.expression.StandardBeanExpressionResolver; import org.springframework.core.convert.support.GenericConversionService; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; import java.beans.PropertyDescriptor; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; /** * Encapsulates a bean factory and indexes to the beans within the factory for providing * framework metadata * * @author Kuali Rice Team ([email protected]) */ public class DataDictionary { private static final Log LOG = LogFactory.getLog(DataDictionary.class); protected static boolean validateEBOs = true; protected KualiDefaultListableBeanFactory ddBeans = new KualiDefaultListableBeanFactory(); protected XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ddBeans); protected DataDictionaryIndex ddIndex = new DataDictionaryIndex(ddBeans); protected UifDictionaryIndex uifIndex = new UifDictionaryIndex(ddBeans); protected DataDictionaryMapper ddMapper = new DataDictionaryIndexMapper(); protected Map<String, List<String>> moduleDictionaryFiles = new HashMap<String, List<String>>(); protected ArrayList<String> beanValidationFiles = new ArrayList<String>(); /** * Populates and processes the dictionary bean factory based on the configured files and * performs indexing * * @param allowConcurrentValidation - indicates whether the indexing should occur on a different thread * or the same thread */ public void parseDataDictionaryConfigurationFiles(boolean allowConcurrentValidation) { setupProcessor(ddBeans); loadDictionaryBeans(ddBeans,moduleDictionaryFiles,ddIndex,beanValidationFiles); performDictionaryPostProcessing(allowConcurrentValidation); } /** * Sets up the bean post processor and conversion service * * @param beans - The bean factory for the the dictionary beans */ public static void setupProcessor(KualiDefaultListableBeanFactory beans){ try { // UIF post processor that sets component ids BeanPostProcessor idPostProcessor = ComponentBeanPostProcessor.class.newInstance(); beans.addBeanPostProcessor(idPostProcessor); beans.setBeanExpressionResolver(new StandardBeanExpressionResolver()); // special converters for shorthand map and list property syntax GenericConversionService conversionService = new GenericConversionService(); conversionService.addConverter(new StringMapConverter()); conversionService.addConverter(new StringListConverter()); beans.setConversionService(conversionService); } catch (Exception e1) { throw new DataDictionaryException("Cannot create component decorator post processor: " + e1.getMessage(), e1); } } /** * Populates and processes the dictionary bean factory based on the configured files * * @param beans - The bean factory for the dictionary bean * @param moduleDictionaryFiles - List of bean xml files * @param index - Index of the data dictionary beans * @param validationFiles - The List of bean xml files loaded into the bean file */ public void loadDictionaryBeans(KualiDefaultListableBeanFactory beans, Map<String,List<String>> moduleDictionaryFiles, DataDictionaryIndex index,ArrayList<String> validationFiles){ // expand configuration locations into files LOG.info("Starting DD XML File Load"); List<String> allBeanNames = new ArrayList<String>(); for (Map.Entry<String, List<String>> moduleDictionary : moduleDictionaryFiles.entrySet()) { String namespaceCode = moduleDictionary.getKey(); XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(beans); String configFileLocationsArray[] = new String[moduleDictionary.getValue().size()]; configFileLocationsArray = moduleDictionary.getValue().toArray(configFileLocationsArray); for (int i = 0; i < configFileLocationsArray.length; i++) { validationFiles.add(configFileLocationsArray[i]); } try { xmlReader.loadBeanDefinitions(configFileLocationsArray); // get updated bean names from factory and compare to our previous list to get those that // were added by the last namespace List<String> addedBeanNames = Arrays.asList(beans.getBeanDefinitionNames()); addedBeanNames = ListUtils.removeAll(addedBeanNames, allBeanNames); index.addBeanNamesToNamespace(namespaceCode, addedBeanNames); allBeanNames.addAll(addedBeanNames); } catch (Exception e) { throw new DataDictionaryException("Error loading bean definitions: " + e.getLocalizedMessage()); } } LOG.info("Completed DD XML File Load"); } /** * Invokes post processors and builds indexes for the beans contained in the dictionary * * @param allowConcurrentValidation - indicates whether the indexing should occur on a different thread * or the same thread */ public void performDictionaryPostProcessing(boolean allowConcurrentValidation) { // invoke post processing of the dictionary bean definitions DictionaryBeanFactoryPostProcessor dictionaryBeanPostProcessor = new DictionaryBeanFactoryPostProcessor(this, ddBeans); dictionaryBeanPostProcessor.postProcessBeanFactory(); // post processes UIF beans for pulling out expressions within property values UifBeanFactoryPostProcessor factoryPostProcessor = new UifBeanFactoryPostProcessor(); factoryPostProcessor.postProcessBeanFactory(ddBeans); if (allowConcurrentValidation) { Thread t = new Thread(ddIndex); t.start(); Thread t2 = new Thread(uifIndex); t2.start(); } else { ddIndex.run(); uifIndex.run(); } } public void validateDD(boolean validateEbos) { DataDictionary.validateEBOs = validateEbos; // ValidationController validator = new ValidationController(); // String files[] = new String[beanValidationFiles.size()]; // files = beanValidationFiles.toArray(files); // validator.validate(files, xmlReader.getResourceLoader(), ddBeans, // LOG, false); Map<String, DataObjectEntry> doBeans = ddBeans.getBeansOfType(DataObjectEntry.class); for (DataObjectEntry entry : doBeans.values()) { entry.completeValidation(); } Map<String, DocumentEntry> docBeans = ddBeans.getBeansOfType(DocumentEntry.class); for (DocumentEntry entry : docBeans.values()) { entry.completeValidation(); } } public void validateDD() { validateDD(true); } /** * Adds a location of files or a individual resource to the data dictionary * * <p> * The location can either be an XML file on the classpath or a file or folder location within the * file system. If a folder location is given, the folder and all sub-folders will be traversed and any * XML files will be added to the dictionary * </p> * * @param namespaceCode - namespace the beans loaded from the location should be associated with * @param location - classpath resource or file system location * @throws IOException */ public void addConfigFileLocation(String namespaceCode, String location) throws IOException { indexSource(namespaceCode, location); } /** * Processes a given source for XML files to populate the dictionary with * * @param namespaceCode - namespace the beans loaded from the location should be associated with * @param sourceName - a file system or classpath resource locator * @throws IOException */ protected void indexSource(String namespaceCode, String sourceName) throws IOException { if (sourceName == null) { throw new DataDictionaryException("Source Name given is null"); } if (!sourceName.endsWith(".xml")) { Resource resource = getFileResource(sourceName); if (resource.exists()) { try { indexSource(namespaceCode, resource.getFile()); } catch (IOException e) { // ignore resources that exist and cause an error here // they may be directories resident in jar files LOG.debug("Skipped existing resource without absolute file path"); } } else { LOG.warn("Could not find " + sourceName); throw new DataDictionaryException("DD Resource " + sourceName + " not found"); } } else { if (LOG.isDebugEnabled()) { LOG.debug("adding sourceName " + sourceName + " "); } Resource resource = getFileResource(sourceName); if (!resource.exists()) { throw new DataDictionaryException("DD Resource " + sourceName + " not found"); } addModuleDictionaryFile(namespaceCode, sourceName); } } protected Resource getFileResource(String sourceName) { DefaultResourceLoader resourceLoader = new DefaultResourceLoader(ClassLoaderUtils.getDefaultClassLoader()); return resourceLoader.getResource(sourceName); } protected void indexSource(String namespaceCode, File dir) { for (File file : dir.listFiles()) { if (file.isDirectory()) { indexSource(namespaceCode, file); } else if (file.getName().endsWith(".xml")) { addModuleDictionaryFile(namespaceCode, "file:" + file.getAbsolutePath()); } else { if (LOG.isDebugEnabled()) { LOG.debug("Skipping non xml file " + file.getAbsolutePath() + " in DD load"); } } } } /** * Adds a file location to the list of dictionary files for the given namespace code * * @param namespaceCode - namespace to add location for * @param location - file or resource location to add */ protected void addModuleDictionaryFile(String namespaceCode, String location) { List<String> moduleFileLocations = new ArrayList<String>(); if (moduleDictionaryFiles.containsKey(namespaceCode)) { moduleFileLocations = moduleDictionaryFiles.get(namespaceCode); } moduleFileLocations.add(location); moduleDictionaryFiles.put(namespaceCode, moduleFileLocations); } /** * Mapping of namespace codes to dictionary files that are associated with * that namespace * * @return Map<String, List<String>> where map key is namespace code, and value is list of dictionary * file locations */ public Map<String, List<String>> getModuleDictionaryFiles() { return moduleDictionaryFiles; } /** * Setter for the map of module dictionary files * * @param moduleDictionaryFiles */ public void setModuleDictionaryFiles(Map<String, List<String>> moduleDictionaryFiles) { this.moduleDictionaryFiles = moduleDictionaryFiles; } /** * Sets the DataDictionaryMapper * * @param mapper the datadictionary mapper */ public void setDataDictionaryMapper(DataDictionaryMapper mapper) { this.ddMapper = mapper; } /** * @param className * @return BusinessObjectEntry for the named class, or null if none exists */ @Deprecated public BusinessObjectEntry getBusinessObjectEntry(String className) { return ddMapper.getBusinessObjectEntry(ddIndex, className); } /** * @param className * @return BusinessObjectEntry for the named class, or null if none exists */ public DataObjectEntry getDataObjectEntry(String className) { return ddMapper.getDataObjectEntry(ddIndex, className); } /** * This method gets the business object entry for a concrete class * * @param className * @return */ public BusinessObjectEntry getBusinessObjectEntryForConcreteClass(String className) { return ddMapper.getBusinessObjectEntryForConcreteClass(ddIndex, className); } /** * @return List of businessObject classnames */ public List<String> getBusinessObjectClassNames() { return ddMapper.getBusinessObjectClassNames(ddIndex); } /** * @return Map of (classname, BusinessObjectEntry) pairs */ public Map<String, BusinessObjectEntry> getBusinessObjectEntries() { return ddMapper.getBusinessObjectEntries(ddIndex); } /** * @param className * @return DataDictionaryEntryBase for the named class, or null if none * exists */ public DataDictionaryEntry getDictionaryObjectEntry(String className) { return ddMapper.getDictionaryObjectEntry(ddIndex, className); } /** * Returns the KNS document entry for the given lookup key. The documentTypeDDKey is interpreted * successively in the following ways until a mapping is found (or none if found): * <ol> * <li>KEW/workflow document type</li> * <li>business object class name</li> * <li>maintainable class name</li> * </ol> * This mapping is compiled when DataDictionary files are parsed on startup (or demand). Currently this * means the mapping is static, and one-to-one (one KNS document maps directly to one and only * one key). * * @param documentTypeDDKey the KEW/workflow document type name * @return the KNS DocumentEntry if it exists */ public DocumentEntry getDocumentEntry(String documentTypeDDKey) { return ddMapper.getDocumentEntry(ddIndex, documentTypeDDKey); } /** * Note: only MaintenanceDocuments are indexed by businessObject Class * * This is a special case that is referenced in one location. Do we need * another map for this stuff?? * * @param businessObjectClass * @return DocumentEntry associated with the given Class, or null if there * is none */ public MaintenanceDocumentEntry getMaintenanceDocumentEntryForBusinessObjectClass(Class<?> businessObjectClass) { return ddMapper.getMaintenanceDocumentEntryForBusinessObjectClass(ddIndex, businessObjectClass); } public Map<String, DocumentEntry> getDocumentEntries() { return ddMapper.getDocumentEntries(ddIndex); } /** * Returns the View entry identified by the given id * * @param viewId - unique id for view * @return View instance associated with the id */ public View getViewById(String viewId) { return ddMapper.getViewById(uifIndex, viewId); } /** * Returns View instance identified by the view type name and index * * @param viewTypeName - type name for the view * @param indexKey - Map of index key parameters, these are the parameters the * indexer used to index the view initially and needs to identify * an unique view instance * @return View instance that matches the given index */ public View getViewByTypeIndex(ViewType viewTypeName, Map<String, String> indexKey) { return ddMapper.getViewByTypeIndex(uifIndex, viewTypeName, indexKey); } /** * Indicates whether a <code>View</code> exists for the given view type and index information * * @param viewTypeName - type name for the view * @param indexKey - Map of index key parameters, these are the parameters the * indexer used to index the view initially and needs to identify * an unique view instance * @return boolean true if view exists, false if not */ public boolean viewByTypeExist(ViewType viewTypeName, Map<String, String> indexKey) { return ddMapper.viewByTypeExist(uifIndex, viewTypeName, indexKey); } /** * Gets all <code>View</code> prototypes configured for the given view type * name * * @param viewTypeName - view type name to retrieve * @return List<View> view prototypes with the given type name, or empty * list */ public List<View> getViewsForType(ViewType viewTypeName) { return ddMapper.getViewsForType(uifIndex, viewTypeName); } /** * Returns an object from the dictionary by its spring bean name * * @param beanName - id or name for the bean definition * @return Object object instance created or the singleton being maintained */ public Object getDictionaryObject(String beanName) { return ddBeans.getBean(beanName); } /** * Indicates whether the data dictionary contains a bean with the given id * * @param id - id of the bean to check for * @return boolean true if dictionary contains bean, false otherwise */ public boolean containsDictionaryObject(String id) { return ddBeans.containsBean(id); } /** * Retrieves the configured property values for the view bean definition associated with the given id * * <p> * Since constructing the View object can be expensive, when metadata only is needed this method can be used * to retrieve the configured property values. Note this looks at the merged bean definition * </p> * * @param viewId - id for the view to retrieve * @return PropertyValues configured on the view bean definition, or null if view is not found */ public PropertyValues getViewPropertiesById(String viewId) { return ddMapper.getViewPropertiesById(uifIndex, viewId); } /** * Retrieves the configured property values for the view bean definition associated with the given type and * index * * <p> * Since constructing the View object can be expensive, when metadata only is needed this method can be used * to retrieve the configured property values. Note this looks at the merged bean definition * </p> * * @param viewTypeName - type name for the view * @param indexKey - Map of index key parameters, these are the parameters the indexer used to index * the view initially and needs to identify an unique view instance * @return PropertyValues configured on the view bean definition, or null if view is not found */ public PropertyValues getViewPropertiesByType(ViewType viewTypeName, Map<String, String> indexKey) { return ddMapper.getViewPropertiesByType(uifIndex, viewTypeName, indexKey); } /** * Retrieves the list of dictionary bean names that are associated with the given namespace code * * @param namespaceCode - namespace code to retrieve associated bean names for * @return List<String> bean names associated with the namespace */ public List<String> getBeanNamesForNamespace(String namespaceCode) { List<String> namespaceBeans = new ArrayList<String>(); Map<String, List<String>> dictionaryBeansByNamespace = ddIndex.getDictionaryBeansByNamespace(); if (dictionaryBeansByNamespace.containsKey(namespaceCode)) { namespaceBeans = dictionaryBeansByNamespace.get(namespaceCode); } return namespaceBeans; } /** * Retrieves the namespace code the given bean name is associated with * * @param beanName - name of the dictionary bean to find namespace code for * @return String namespace code the bean is associated with, or null if a namespace was not found */ public String getNamespaceForBeanDefinition(String beanName) { String beanNamespace = null; Map<String, List<String>> dictionaryBeansByNamespace = ddIndex.getDictionaryBeansByNamespace(); for (Map.Entry<String, List<String>> moduleDefinitions : dictionaryBeansByNamespace.entrySet()) { List<String> namespaceBeans = moduleDefinitions.getValue(); if (namespaceBeans.contains(beanName)) { beanNamespace = moduleDefinitions.getKey(); break; } } return beanNamespace; } /** * @param targetClass * @param propertyName * @return true if the given propertyName names a property of the given class * @throws CompletionException if there is a problem accessing the named property on the given class */ public static boolean isPropertyOf(Class targetClass, String propertyName) { if (targetClass == null) { throw new IllegalArgumentException("invalid (null) targetClass"); } if (StringUtils.isBlank(propertyName)) { throw new IllegalArgumentException("invalid (blank) propertyName"); } PropertyDescriptor propertyDescriptor = buildReadDescriptor(targetClass, propertyName); boolean isPropertyOf = (propertyDescriptor != null); return isPropertyOf; } /** * @param targetClass * @param propertyName * @return true if the given propertyName names a Collection property of the given class * @throws CompletionException if there is a problem accessing the named property on the given class */ public static boolean isCollectionPropertyOf(Class targetClass, String propertyName) { boolean isCollectionPropertyOf = false; PropertyDescriptor propertyDescriptor = buildReadDescriptor(targetClass, propertyName); if (propertyDescriptor != null) { Class clazz = propertyDescriptor.getPropertyType(); if ((clazz != null) && Collection.class.isAssignableFrom(clazz)) { isCollectionPropertyOf = true; } } return isCollectionPropertyOf; } public static PersistenceStructureService persistenceStructureService; /** * @return the persistenceStructureService */ public static PersistenceStructureService getPersistenceStructureService() { if (persistenceStructureService == null) { persistenceStructureService = KRADServiceLocator.getPersistenceStructureService(); } return persistenceStructureService; } /** * This method determines the Class of the attributeName passed in. Null will be returned if the member is not * available, or if * a reflection exception is thrown. * * @param boClass - Class that the attributeName property exists in. * @param attributeName - Name of the attribute you want a class for. * @return The Class of the attributeName, if the attribute exists on the rootClass. Null otherwise. */ public static Class getAttributeClass(Class boClass, String attributeName) { // fail loudly if the attributeName isnt a member of rootClass if (!isPropertyOf(boClass, attributeName)) { throw new AttributeValidationException( "unable to find attribute '" + attributeName + "' in rootClass '" + boClass.getName() + "'"); } //Implementing Externalizable Business Object Services... //The boClass can be an interface, hence handling this separately, //since the original method was throwing exception if the class could not be instantiated. if (boClass.isInterface()) { return getAttributeClassWhenBOIsInterface(boClass, attributeName); } else { return getAttributeClassWhenBOIsClass(boClass, attributeName); } } /** * This method gets the property type of the given attributeName when the bo class is a concrete class * * @param boClass * @param attributeName * @return */ private static Class getAttributeClassWhenBOIsClass(Class boClass, String attributeName) { Object boInstance; try { boInstance = boClass.newInstance(); } catch (Exception e) { throw new RuntimeException("Unable to instantiate Data Object: " + boClass, e); } // attempt to retrieve the class of the property try { return ObjectUtils.getPropertyType(boInstance, attributeName, getPersistenceStructureService()); } catch (Exception e) { throw new RuntimeException( "Unable to determine property type for: " + boClass.getName() + "." + attributeName, e); } } /** * This method gets the property type of the given attributeName when the bo class is an interface * This method will also work if the bo class is not an interface, * but that case requires special handling, hence a separate method getAttributeClassWhenBOIsClass * * @param boClass * @param attributeName * @return */ private static Class getAttributeClassWhenBOIsInterface(Class boClass, String attributeName) { if (boClass == null) { throw new IllegalArgumentException("invalid (null) boClass"); } if (StringUtils.isBlank(attributeName)) { throw new IllegalArgumentException("invalid (blank) attributeName"); } PropertyDescriptor propertyDescriptor = null; String[] intermediateProperties = attributeName.split("\\."); int lastLevel = intermediateProperties.length - 1; Class currentClass = boClass; for (int i = 0; i <= lastLevel; ++i) { String currentPropertyName = intermediateProperties[i]; propertyDescriptor = buildSimpleReadDescriptor(currentClass, currentPropertyName); if (propertyDescriptor != null) { Class propertyType = propertyDescriptor.getPropertyType(); if (propertyType.equals(PersistableBusinessObjectExtension.class)) { propertyType = getPersistenceStructureService().getBusinessObjectAttributeClass(currentClass, currentPropertyName); } if (Collection.class.isAssignableFrom(propertyType)) { // TODO: determine property type using generics type definition throw new AttributeValidationException( "Can't determine the Class of Collection elements because when the business object is an (possibly ExternalizableBusinessObject) interface."); } else { currentClass = propertyType; } } else { throw new AttributeValidationException( "Can't find getter method of " + boClass.getName() + " for property " + attributeName); } } return currentClass; } /** * This method determines the Class of the elements in the collectionName passed in. * * @param boClass Class that the collectionName collection exists in. * @param collectionName the name of the collection you want the element class for * @return */ public static Class getCollectionElementClass(Class boClass, String collectionName) { if (boClass == null) { throw new IllegalArgumentException("invalid (null) boClass"); } if (StringUtils.isBlank(collectionName)) { throw new IllegalArgumentException("invalid (blank) collectionName"); } PropertyDescriptor propertyDescriptor = null; String[] intermediateProperties = collectionName.split("\\."); Class currentClass = boClass; for (int i = 0; i < intermediateProperties.length; ++i) { String currentPropertyName = intermediateProperties[i]; propertyDescriptor = buildSimpleReadDescriptor(currentClass, currentPropertyName); if (propertyDescriptor != null) { Class type = propertyDescriptor.getPropertyType(); if (Collection.class.isAssignableFrom(type)) { if (getPersistenceStructureService().isPersistable(currentClass)) { Map<String, Class> collectionClasses = new HashMap<String, Class>(); collectionClasses = getPersistenceStructureService().listCollectionObjectTypes(currentClass); currentClass = collectionClasses.get(currentPropertyName); } else { throw new RuntimeException( "Can't determine the Class of Collection elements because persistenceStructureService.isPersistable(" + currentClass.getName() + ") returns false."); } } else { currentClass = propertyDescriptor.getPropertyType(); } } } return currentClass; } static private Map<String, Map<String, PropertyDescriptor>> cache = new TreeMap<String, Map<String, PropertyDescriptor>>(); /** * @param propertyClass * @param propertyName * @return PropertyDescriptor for the getter for the named property of the given class, if one exists. */ public static PropertyDescriptor buildReadDescriptor(Class propertyClass, String propertyName) { if (propertyClass == null) { throw new IllegalArgumentException("invalid (null) propertyClass"); } if (StringUtils.isBlank(propertyName)) { throw new IllegalArgumentException("invalid (blank) propertyName"); } PropertyDescriptor propertyDescriptor = null; String[] intermediateProperties = propertyName.split("\\."); int lastLevel = intermediateProperties.length - 1; Class currentClass = propertyClass; for (int i = 0; i <= lastLevel; ++i) { String currentPropertyName = intermediateProperties[i]; propertyDescriptor = buildSimpleReadDescriptor(currentClass, currentPropertyName); if (i < lastLevel) { if (propertyDescriptor != null) { Class propertyType = propertyDescriptor.getPropertyType(); if (propertyType.equals(PersistableBusinessObjectExtension.class)) { propertyType = getPersistenceStructureService().getBusinessObjectAttributeClass(currentClass, currentPropertyName); } if (Collection.class.isAssignableFrom(propertyType)) { if (getPersistenceStructureService().isPersistable(currentClass)) { Map<String, Class> collectionClasses = new HashMap<String, Class>(); collectionClasses = getPersistenceStructureService().listCollectionObjectTypes( currentClass); currentClass = collectionClasses.get(currentPropertyName); } else { throw new RuntimeException( "Can't determine the Class of Collection elements because persistenceStructureService.isPersistable(" + currentClass.getName() + ") returns false."); } } else { currentClass = propertyType; } } } } return propertyDescriptor; } /** * @param propertyClass * @param propertyName * @return PropertyDescriptor for the getter for the named property of the given class, if one exists. */ public static PropertyDescriptor buildSimpleReadDescriptor(Class propertyClass, String propertyName) { if (propertyClass == null) { throw new IllegalArgumentException("invalid (null) propertyClass"); } if (StringUtils.isBlank(propertyName)) { throw new IllegalArgumentException("invalid (blank) propertyName"); } PropertyDescriptor p = null; // check to see if we've cached this descriptor already. if yes, return true. String propertyClassName = propertyClass.getName(); Map<String, PropertyDescriptor> m = cache.get(propertyClassName); if (null != m) { p = m.get(propertyName); if (null != p) { return p; } } // Use PropertyUtils.getPropertyDescriptors instead of manually constructing PropertyDescriptor because of // issues with introspection and generic/co-variant return types // See https://issues.apache.org/jira/browse/BEANUTILS-340 for more details PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(propertyClass); if (ArrayUtils.isNotEmpty(descriptors)) { for (PropertyDescriptor descriptor : descriptors) { if (descriptor.getName().equals(propertyName)) { p = descriptor; } } } // cache the property descriptor if we found it. if (p != null) { if (m == null) { m = new TreeMap<String, PropertyDescriptor>(); cache.put(propertyClassName, m); } m.put(propertyName, p); } return p; } public Set<InactivationBlockingMetadata> getAllInactivationBlockingMetadatas(Class blockedClass) { return ddMapper.getAllInactivationBlockingMetadatas(ddIndex, blockedClass); } /** * This method gathers beans of type BeanOverride and invokes each one's performOverride() method. */ // KULRICE-4513 public void performBeanOverrides() { Collection<BeanOverride> beanOverrides = ddBeans.getBeansOfType(BeanOverride.class).values(); if (beanOverrides.isEmpty()) { LOG.info("DataDictionary.performOverrides(): No beans to override"); } for (BeanOverride beanOverride : beanOverrides) { Object bean = ddBeans.getBean(beanOverride.getBeanName()); beanOverride.performOverride(bean); LOG.info("DataDictionary.performOverrides(): Performing override on bean: " + bean.toString()); } } }
krad/krad-web-framework/src/main/java/org/kuali/rice/krad/datadictionary/DataDictionary.java
/** * Copyright 2005-2012 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.rice.krad.datadictionary; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.collections.ListUtils; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.kuali.rice.core.api.util.ClassLoaderUtils; import org.kuali.rice.krad.bo.PersistableBusinessObjectExtension; import org.kuali.rice.krad.datadictionary.exception.AttributeValidationException; import org.kuali.rice.krad.datadictionary.exception.CompletionException; import org.kuali.rice.krad.datadictionary.parse.StringListConverter; import org.kuali.rice.krad.datadictionary.parse.StringMapConverter; import org.kuali.rice.krad.datadictionary.uif.UifDictionaryIndex; import org.kuali.rice.krad.datadictionary.validator.ValidationController; import org.kuali.rice.krad.service.KRADServiceLocator; import org.kuali.rice.krad.service.PersistenceStructureService; import org.kuali.rice.krad.uif.UifConstants.ViewType; import org.kuali.rice.krad.uif.util.ComponentBeanPostProcessor; import org.kuali.rice.krad.uif.util.UifBeanFactoryPostProcessor; import org.kuali.rice.krad.uif.view.View; import org.kuali.rice.krad.util.ObjectUtils; import org.springframework.beans.PropertyValues; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.beans.factory.support.KualiDefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.context.expression.StandardBeanExpressionResolver; import org.springframework.core.convert.support.GenericConversionService; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; import java.beans.PropertyDescriptor; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; /** * Encapsulates a bean factory and indexes to the beans within the factory for providing * framework metadata * * @author Kuali Rice Team ([email protected]) */ public class DataDictionary { private static final Log LOG = LogFactory.getLog(DataDictionary.class); protected static boolean validateEBOs = true; protected KualiDefaultListableBeanFactory ddBeans = new KualiDefaultListableBeanFactory(); protected XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ddBeans); protected DataDictionaryIndex ddIndex = new DataDictionaryIndex(ddBeans); protected UifDictionaryIndex uifIndex = new UifDictionaryIndex(ddBeans); protected DataDictionaryMapper ddMapper = new DataDictionaryIndexMapper(); protected Map<String, List<String>> moduleDictionaryFiles = new HashMap<String, List<String>>(); protected ArrayList<String> beanValidationFiles = new ArrayList<String>(); /** * Populates and processes the dictionary bean factory based on the configured files and * performs indexing * * @param allowConcurrentValidation - indicates whether the indexing should occur on a different thread * or the same thread */ public void parseDataDictionaryConfigurationFiles(boolean allowConcurrentValidation) { setupProcessor(ddBeans); loadDictionaryBeans(ddBeans,moduleDictionaryFiles,ddIndex,beanValidationFiles); performDictionaryPostProcessing(allowConcurrentValidation); } /** * Sets up the bean post processor and conversion service * * @param beans - The bean factory for the the dictionary beans */ public static void setupProcessor(KualiDefaultListableBeanFactory beans){ try { // UIF post processor that sets component ids BeanPostProcessor idPostProcessor = ComponentBeanPostProcessor.class.newInstance(); beans.addBeanPostProcessor(idPostProcessor); beans.setBeanExpressionResolver(new StandardBeanExpressionResolver()); // special converters for shorthand map and list property syntax GenericConversionService conversionService = new GenericConversionService(); conversionService.addConverter(new StringMapConverter()); conversionService.addConverter(new StringListConverter()); beans.setConversionService(conversionService); } catch (Exception e1) { throw new DataDictionaryException("Cannot create component decorator post processor: " + e1.getMessage(), e1); } } /** * Populates and processes the dictionary bean factory based on the configured files * * @param beans - The bean factory for the dictionary bean * @param moduleDictionaryFiles - List of bean xml files * @param index - Index of the data dictionary beans * @param validationFiles - The List of bean xml files loaded into the bean file */ public void loadDictionaryBeans(KualiDefaultListableBeanFactory beans, Map<String,List<String>> moduleDictionaryFiles, DataDictionaryIndex index,ArrayList<String> validationFiles){ // expand configuration locations into files LOG.info("Starting DD XML File Load"); List<String> allBeanNames = new ArrayList<String>(); for (Map.Entry<String, List<String>> moduleDictionary : moduleDictionaryFiles.entrySet()) { String namespaceCode = moduleDictionary.getKey(); XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(beans); String configFileLocationsArray[] = new String[moduleDictionary.getValue().size()]; configFileLocationsArray = moduleDictionary.getValue().toArray(configFileLocationsArray); for (int i = 0; i < configFileLocationsArray.length; i++) { validationFiles.add(configFileLocationsArray[i]); } try { xmlReader.loadBeanDefinitions(configFileLocationsArray); // get updated bean names from factory and compare to our previous list to get those that // were added by the last namespace List<String> addedBeanNames = Arrays.asList(beans.getBeanDefinitionNames()); addedBeanNames = ListUtils.removeAll(addedBeanNames, allBeanNames); index.addBeanNamesToNamespace(namespaceCode, addedBeanNames); allBeanNames.addAll(addedBeanNames); } catch (Exception e) { throw new DataDictionaryException("Error loading bean definitions: " + e.getLocalizedMessage()); } } LOG.info("Completed DD XML File Load"); } /** * Invokes post processors and builds indexes for the beans contained in the dictionary * * @param allowConcurrentValidation - indicates whether the indexing should occur on a different thread * or the same thread */ public void performDictionaryPostProcessing(boolean allowConcurrentValidation) { // invoke post processing of the dictionary bean definitions // DictionaryBeanFactoryPostProcessor dictionaryBeanPostProcessor = new DictionaryBeanFactoryPostProcessor(this, // ddBeans); // dictionaryBeanPostProcessor.postProcessBeanFactory(); // post processes UIF beans for pulling out expressions within property values UifBeanFactoryPostProcessor factoryPostProcessor = new UifBeanFactoryPostProcessor(); factoryPostProcessor.postProcessBeanFactory(ddBeans); if (allowConcurrentValidation) { Thread t = new Thread(ddIndex); t.start(); Thread t2 = new Thread(uifIndex); t2.start(); } else { ddIndex.run(); uifIndex.run(); } } public void validateDD(boolean validateEbos) { DataDictionary.validateEBOs = validateEbos; // ValidationController validator = new ValidationController(); // String files[] = new String[beanValidationFiles.size()]; // files = beanValidationFiles.toArray(files); // validator.validate(files, xmlReader.getResourceLoader(), ddBeans, // LOG, false); Map<String, DataObjectEntry> doBeans = ddBeans.getBeansOfType(DataObjectEntry.class); for (DataObjectEntry entry : doBeans.values()) { entry.completeValidation(); } Map<String, DocumentEntry> docBeans = ddBeans.getBeansOfType(DocumentEntry.class); for (DocumentEntry entry : docBeans.values()) { entry.completeValidation(); } } public void validateDD() { validateDD(true); } /** * Adds a location of files or a individual resource to the data dictionary * * <p> * The location can either be an XML file on the classpath or a file or folder location within the * file system. If a folder location is given, the folder and all sub-folders will be traversed and any * XML files will be added to the dictionary * </p> * * @param namespaceCode - namespace the beans loaded from the location should be associated with * @param location - classpath resource or file system location * @throws IOException */ public void addConfigFileLocation(String namespaceCode, String location) throws IOException { indexSource(namespaceCode, location); } /** * Processes a given source for XML files to populate the dictionary with * * @param namespaceCode - namespace the beans loaded from the location should be associated with * @param sourceName - a file system or classpath resource locator * @throws IOException */ protected void indexSource(String namespaceCode, String sourceName) throws IOException { if (sourceName == null) { throw new DataDictionaryException("Source Name given is null"); } if (!sourceName.endsWith(".xml")) { Resource resource = getFileResource(sourceName); if (resource.exists()) { try { indexSource(namespaceCode, resource.getFile()); } catch (IOException e) { // ignore resources that exist and cause an error here // they may be directories resident in jar files LOG.debug("Skipped existing resource without absolute file path"); } } else { LOG.warn("Could not find " + sourceName); throw new DataDictionaryException("DD Resource " + sourceName + " not found"); } } else { if (LOG.isDebugEnabled()) { LOG.debug("adding sourceName " + sourceName + " "); } Resource resource = getFileResource(sourceName); if (!resource.exists()) { throw new DataDictionaryException("DD Resource " + sourceName + " not found"); } addModuleDictionaryFile(namespaceCode, sourceName); } } protected Resource getFileResource(String sourceName) { DefaultResourceLoader resourceLoader = new DefaultResourceLoader(ClassLoaderUtils.getDefaultClassLoader()); return resourceLoader.getResource(sourceName); } protected void indexSource(String namespaceCode, File dir) { for (File file : dir.listFiles()) { if (file.isDirectory()) { indexSource(namespaceCode, file); } else if (file.getName().endsWith(".xml")) { addModuleDictionaryFile(namespaceCode, "file:" + file.getAbsolutePath()); } else { if (LOG.isDebugEnabled()) { LOG.debug("Skipping non xml file " + file.getAbsolutePath() + " in DD load"); } } } } /** * Adds a file location to the list of dictionary files for the given namespace code * * @param namespaceCode - namespace to add location for * @param location - file or resource location to add */ protected void addModuleDictionaryFile(String namespaceCode, String location) { List<String> moduleFileLocations = new ArrayList<String>(); if (moduleDictionaryFiles.containsKey(namespaceCode)) { moduleFileLocations = moduleDictionaryFiles.get(namespaceCode); } moduleFileLocations.add(location); moduleDictionaryFiles.put(namespaceCode, moduleFileLocations); } /** * Mapping of namespace codes to dictionary files that are associated with * that namespace * * @return Map<String, List<String>> where map key is namespace code, and value is list of dictionary * file locations */ public Map<String, List<String>> getModuleDictionaryFiles() { return moduleDictionaryFiles; } /** * Setter for the map of module dictionary files * * @param moduleDictionaryFiles */ public void setModuleDictionaryFiles(Map<String, List<String>> moduleDictionaryFiles) { this.moduleDictionaryFiles = moduleDictionaryFiles; } /** * Sets the DataDictionaryMapper * * @param mapper the datadictionary mapper */ public void setDataDictionaryMapper(DataDictionaryMapper mapper) { this.ddMapper = mapper; } /** * @param className * @return BusinessObjectEntry for the named class, or null if none exists */ @Deprecated public BusinessObjectEntry getBusinessObjectEntry(String className) { return ddMapper.getBusinessObjectEntry(ddIndex, className); } /** * @param className * @return BusinessObjectEntry for the named class, or null if none exists */ public DataObjectEntry getDataObjectEntry(String className) { return ddMapper.getDataObjectEntry(ddIndex, className); } /** * This method gets the business object entry for a concrete class * * @param className * @return */ public BusinessObjectEntry getBusinessObjectEntryForConcreteClass(String className) { return ddMapper.getBusinessObjectEntryForConcreteClass(ddIndex, className); } /** * @return List of businessObject classnames */ public List<String> getBusinessObjectClassNames() { return ddMapper.getBusinessObjectClassNames(ddIndex); } /** * @return Map of (classname, BusinessObjectEntry) pairs */ public Map<String, BusinessObjectEntry> getBusinessObjectEntries() { return ddMapper.getBusinessObjectEntries(ddIndex); } /** * @param className * @return DataDictionaryEntryBase for the named class, or null if none * exists */ public DataDictionaryEntry getDictionaryObjectEntry(String className) { return ddMapper.getDictionaryObjectEntry(ddIndex, className); } /** * Returns the KNS document entry for the given lookup key. The documentTypeDDKey is interpreted * successively in the following ways until a mapping is found (or none if found): * <ol> * <li>KEW/workflow document type</li> * <li>business object class name</li> * <li>maintainable class name</li> * </ol> * This mapping is compiled when DataDictionary files are parsed on startup (or demand). Currently this * means the mapping is static, and one-to-one (one KNS document maps directly to one and only * one key). * * @param documentTypeDDKey the KEW/workflow document type name * @return the KNS DocumentEntry if it exists */ public DocumentEntry getDocumentEntry(String documentTypeDDKey) { return ddMapper.getDocumentEntry(ddIndex, documentTypeDDKey); } /** * Note: only MaintenanceDocuments are indexed by businessObject Class * * This is a special case that is referenced in one location. Do we need * another map for this stuff?? * * @param businessObjectClass * @return DocumentEntry associated with the given Class, or null if there * is none */ public MaintenanceDocumentEntry getMaintenanceDocumentEntryForBusinessObjectClass(Class<?> businessObjectClass) { return ddMapper.getMaintenanceDocumentEntryForBusinessObjectClass(ddIndex, businessObjectClass); } public Map<String, DocumentEntry> getDocumentEntries() { return ddMapper.getDocumentEntries(ddIndex); } /** * Returns the View entry identified by the given id * * @param viewId - unique id for view * @return View instance associated with the id */ public View getViewById(String viewId) { return ddMapper.getViewById(uifIndex, viewId); } /** * Returns View instance identified by the view type name and index * * @param viewTypeName - type name for the view * @param indexKey - Map of index key parameters, these are the parameters the * indexer used to index the view initially and needs to identify * an unique view instance * @return View instance that matches the given index */ public View getViewByTypeIndex(ViewType viewTypeName, Map<String, String> indexKey) { return ddMapper.getViewByTypeIndex(uifIndex, viewTypeName, indexKey); } /** * Indicates whether a <code>View</code> exists for the given view type and index information * * @param viewTypeName - type name for the view * @param indexKey - Map of index key parameters, these are the parameters the * indexer used to index the view initially and needs to identify * an unique view instance * @return boolean true if view exists, false if not */ public boolean viewByTypeExist(ViewType viewTypeName, Map<String, String> indexKey) { return ddMapper.viewByTypeExist(uifIndex, viewTypeName, indexKey); } /** * Gets all <code>View</code> prototypes configured for the given view type * name * * @param viewTypeName - view type name to retrieve * @return List<View> view prototypes with the given type name, or empty * list */ public List<View> getViewsForType(ViewType viewTypeName) { return ddMapper.getViewsForType(uifIndex, viewTypeName); } /** * Returns an object from the dictionary by its spring bean name * * @param beanName - id or name for the bean definition * @return Object object instance created or the singleton being maintained */ public Object getDictionaryObject(String beanName) { return ddBeans.getBean(beanName); } /** * Indicates whether the data dictionary contains a bean with the given id * * @param id - id of the bean to check for * @return boolean true if dictionary contains bean, false otherwise */ public boolean containsDictionaryObject(String id) { return ddBeans.containsBean(id); } /** * Retrieves the configured property values for the view bean definition associated with the given id * * <p> * Since constructing the View object can be expensive, when metadata only is needed this method can be used * to retrieve the configured property values. Note this looks at the merged bean definition * </p> * * @param viewId - id for the view to retrieve * @return PropertyValues configured on the view bean definition, or null if view is not found */ public PropertyValues getViewPropertiesById(String viewId) { return ddMapper.getViewPropertiesById(uifIndex, viewId); } /** * Retrieves the configured property values for the view bean definition associated with the given type and * index * * <p> * Since constructing the View object can be expensive, when metadata only is needed this method can be used * to retrieve the configured property values. Note this looks at the merged bean definition * </p> * * @param viewTypeName - type name for the view * @param indexKey - Map of index key parameters, these are the parameters the indexer used to index * the view initially and needs to identify an unique view instance * @return PropertyValues configured on the view bean definition, or null if view is not found */ public PropertyValues getViewPropertiesByType(ViewType viewTypeName, Map<String, String> indexKey) { return ddMapper.getViewPropertiesByType(uifIndex, viewTypeName, indexKey); } /** * Retrieves the list of dictionary bean names that are associated with the given namespace code * * @param namespaceCode - namespace code to retrieve associated bean names for * @return List<String> bean names associated with the namespace */ public List<String> getBeanNamesForNamespace(String namespaceCode) { List<String> namespaceBeans = new ArrayList<String>(); Map<String, List<String>> dictionaryBeansByNamespace = ddIndex.getDictionaryBeansByNamespace(); if (dictionaryBeansByNamespace.containsKey(namespaceCode)) { namespaceBeans = dictionaryBeansByNamespace.get(namespaceCode); } return namespaceBeans; } /** * Retrieves the namespace code the given bean name is associated with * * @param beanName - name of the dictionary bean to find namespace code for * @return String namespace code the bean is associated with, or null if a namespace was not found */ public String getNamespaceForBeanDefinition(String beanName) { String beanNamespace = null; Map<String, List<String>> dictionaryBeansByNamespace = ddIndex.getDictionaryBeansByNamespace(); for (Map.Entry<String, List<String>> moduleDefinitions : dictionaryBeansByNamespace.entrySet()) { List<String> namespaceBeans = moduleDefinitions.getValue(); if (namespaceBeans.contains(beanName)) { beanNamespace = moduleDefinitions.getKey(); break; } } return beanNamespace; } /** * @param targetClass * @param propertyName * @return true if the given propertyName names a property of the given class * @throws CompletionException if there is a problem accessing the named property on the given class */ public static boolean isPropertyOf(Class targetClass, String propertyName) { if (targetClass == null) { throw new IllegalArgumentException("invalid (null) targetClass"); } if (StringUtils.isBlank(propertyName)) { throw new IllegalArgumentException("invalid (blank) propertyName"); } PropertyDescriptor propertyDescriptor = buildReadDescriptor(targetClass, propertyName); boolean isPropertyOf = (propertyDescriptor != null); return isPropertyOf; } /** * @param targetClass * @param propertyName * @return true if the given propertyName names a Collection property of the given class * @throws CompletionException if there is a problem accessing the named property on the given class */ public static boolean isCollectionPropertyOf(Class targetClass, String propertyName) { boolean isCollectionPropertyOf = false; PropertyDescriptor propertyDescriptor = buildReadDescriptor(targetClass, propertyName); if (propertyDescriptor != null) { Class clazz = propertyDescriptor.getPropertyType(); if ((clazz != null) && Collection.class.isAssignableFrom(clazz)) { isCollectionPropertyOf = true; } } return isCollectionPropertyOf; } public static PersistenceStructureService persistenceStructureService; /** * @return the persistenceStructureService */ public static PersistenceStructureService getPersistenceStructureService() { if (persistenceStructureService == null) { persistenceStructureService = KRADServiceLocator.getPersistenceStructureService(); } return persistenceStructureService; } /** * This method determines the Class of the attributeName passed in. Null will be returned if the member is not * available, or if * a reflection exception is thrown. * * @param boClass - Class that the attributeName property exists in. * @param attributeName - Name of the attribute you want a class for. * @return The Class of the attributeName, if the attribute exists on the rootClass. Null otherwise. */ public static Class getAttributeClass(Class boClass, String attributeName) { // fail loudly if the attributeName isnt a member of rootClass if (!isPropertyOf(boClass, attributeName)) { throw new AttributeValidationException( "unable to find attribute '" + attributeName + "' in rootClass '" + boClass.getName() + "'"); } //Implementing Externalizable Business Object Services... //The boClass can be an interface, hence handling this separately, //since the original method was throwing exception if the class could not be instantiated. if (boClass.isInterface()) { return getAttributeClassWhenBOIsInterface(boClass, attributeName); } else { return getAttributeClassWhenBOIsClass(boClass, attributeName); } } /** * This method gets the property type of the given attributeName when the bo class is a concrete class * * @param boClass * @param attributeName * @return */ private static Class getAttributeClassWhenBOIsClass(Class boClass, String attributeName) { Object boInstance; try { boInstance = boClass.newInstance(); } catch (Exception e) { throw new RuntimeException("Unable to instantiate Data Object: " + boClass, e); } // attempt to retrieve the class of the property try { return ObjectUtils.getPropertyType(boInstance, attributeName, getPersistenceStructureService()); } catch (Exception e) { throw new RuntimeException( "Unable to determine property type for: " + boClass.getName() + "." + attributeName, e); } } /** * This method gets the property type of the given attributeName when the bo class is an interface * This method will also work if the bo class is not an interface, * but that case requires special handling, hence a separate method getAttributeClassWhenBOIsClass * * @param boClass * @param attributeName * @return */ private static Class getAttributeClassWhenBOIsInterface(Class boClass, String attributeName) { if (boClass == null) { throw new IllegalArgumentException("invalid (null) boClass"); } if (StringUtils.isBlank(attributeName)) { throw new IllegalArgumentException("invalid (blank) attributeName"); } PropertyDescriptor propertyDescriptor = null; String[] intermediateProperties = attributeName.split("\\."); int lastLevel = intermediateProperties.length - 1; Class currentClass = boClass; for (int i = 0; i <= lastLevel; ++i) { String currentPropertyName = intermediateProperties[i]; propertyDescriptor = buildSimpleReadDescriptor(currentClass, currentPropertyName); if (propertyDescriptor != null) { Class propertyType = propertyDescriptor.getPropertyType(); if (propertyType.equals(PersistableBusinessObjectExtension.class)) { propertyType = getPersistenceStructureService().getBusinessObjectAttributeClass(currentClass, currentPropertyName); } if (Collection.class.isAssignableFrom(propertyType)) { // TODO: determine property type using generics type definition throw new AttributeValidationException( "Can't determine the Class of Collection elements because when the business object is an (possibly ExternalizableBusinessObject) interface."); } else { currentClass = propertyType; } } else { throw new AttributeValidationException( "Can't find getter method of " + boClass.getName() + " for property " + attributeName); } } return currentClass; } /** * This method determines the Class of the elements in the collectionName passed in. * * @param boClass Class that the collectionName collection exists in. * @param collectionName the name of the collection you want the element class for * @return */ public static Class getCollectionElementClass(Class boClass, String collectionName) { if (boClass == null) { throw new IllegalArgumentException("invalid (null) boClass"); } if (StringUtils.isBlank(collectionName)) { throw new IllegalArgumentException("invalid (blank) collectionName"); } PropertyDescriptor propertyDescriptor = null; String[] intermediateProperties = collectionName.split("\\."); Class currentClass = boClass; for (int i = 0; i < intermediateProperties.length; ++i) { String currentPropertyName = intermediateProperties[i]; propertyDescriptor = buildSimpleReadDescriptor(currentClass, currentPropertyName); if (propertyDescriptor != null) { Class type = propertyDescriptor.getPropertyType(); if (Collection.class.isAssignableFrom(type)) { if (getPersistenceStructureService().isPersistable(currentClass)) { Map<String, Class> collectionClasses = new HashMap<String, Class>(); collectionClasses = getPersistenceStructureService().listCollectionObjectTypes(currentClass); currentClass = collectionClasses.get(currentPropertyName); } else { throw new RuntimeException( "Can't determine the Class of Collection elements because persistenceStructureService.isPersistable(" + currentClass.getName() + ") returns false."); } } else { currentClass = propertyDescriptor.getPropertyType(); } } } return currentClass; } static private Map<String, Map<String, PropertyDescriptor>> cache = new TreeMap<String, Map<String, PropertyDescriptor>>(); /** * @param propertyClass * @param propertyName * @return PropertyDescriptor for the getter for the named property of the given class, if one exists. */ public static PropertyDescriptor buildReadDescriptor(Class propertyClass, String propertyName) { if (propertyClass == null) { throw new IllegalArgumentException("invalid (null) propertyClass"); } if (StringUtils.isBlank(propertyName)) { throw new IllegalArgumentException("invalid (blank) propertyName"); } PropertyDescriptor propertyDescriptor = null; String[] intermediateProperties = propertyName.split("\\."); int lastLevel = intermediateProperties.length - 1; Class currentClass = propertyClass; for (int i = 0; i <= lastLevel; ++i) { String currentPropertyName = intermediateProperties[i]; propertyDescriptor = buildSimpleReadDescriptor(currentClass, currentPropertyName); if (i < lastLevel) { if (propertyDescriptor != null) { Class propertyType = propertyDescriptor.getPropertyType(); if (propertyType.equals(PersistableBusinessObjectExtension.class)) { propertyType = getPersistenceStructureService().getBusinessObjectAttributeClass(currentClass, currentPropertyName); } if (Collection.class.isAssignableFrom(propertyType)) { if (getPersistenceStructureService().isPersistable(currentClass)) { Map<String, Class> collectionClasses = new HashMap<String, Class>(); collectionClasses = getPersistenceStructureService().listCollectionObjectTypes( currentClass); currentClass = collectionClasses.get(currentPropertyName); } else { throw new RuntimeException( "Can't determine the Class of Collection elements because persistenceStructureService.isPersistable(" + currentClass.getName() + ") returns false."); } } else { currentClass = propertyType; } } } } return propertyDescriptor; } /** * @param propertyClass * @param propertyName * @return PropertyDescriptor for the getter for the named property of the given class, if one exists. */ public static PropertyDescriptor buildSimpleReadDescriptor(Class propertyClass, String propertyName) { if (propertyClass == null) { throw new IllegalArgumentException("invalid (null) propertyClass"); } if (StringUtils.isBlank(propertyName)) { throw new IllegalArgumentException("invalid (blank) propertyName"); } PropertyDescriptor p = null; // check to see if we've cached this descriptor already. if yes, return true. String propertyClassName = propertyClass.getName(); Map<String, PropertyDescriptor> m = cache.get(propertyClassName); if (null != m) { p = m.get(propertyName); if (null != p) { return p; } } // Use PropertyUtils.getPropertyDescriptors instead of manually constructing PropertyDescriptor because of // issues with introspection and generic/co-variant return types // See https://issues.apache.org/jira/browse/BEANUTILS-340 for more details PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(propertyClass); if (ArrayUtils.isNotEmpty(descriptors)) { for (PropertyDescriptor descriptor : descriptors) { if (descriptor.getName().equals(propertyName)) { p = descriptor; } } } // cache the property descriptor if we found it. if (p != null) { if (m == null) { m = new TreeMap<String, PropertyDescriptor>(); cache.put(propertyClassName, m); } m.put(propertyName, p); } return p; } public Set<InactivationBlockingMetadata> getAllInactivationBlockingMetadatas(Class blockedClass) { return ddMapper.getAllInactivationBlockingMetadatas(ddIndex, blockedClass); } /** * This method gathers beans of type BeanOverride and invokes each one's performOverride() method. */ // KULRICE-4513 public void performBeanOverrides() { Collection<BeanOverride> beanOverrides = ddBeans.getBeansOfType(BeanOverride.class).values(); if (beanOverrides.isEmpty()) { LOG.info("DataDictionary.performOverrides(): No beans to override"); } for (BeanOverride beanOverride : beanOverrides) { Object bean = ddBeans.getBean(beanOverride.getBeanName()); beanOverride.performOverride(bean); LOG.info("DataDictionary.performOverrides(): Performing override on bean: " + bean.toString()); } } }
KULRICE-8326 - enabling external message processing git-svn-id: 2a5d2b5a02908a0c4ba7967b726d8c4198d1b9ed@35397 7a7aa7f6-c479-11dc-97e2-85a2497f191d
krad/krad-web-framework/src/main/java/org/kuali/rice/krad/datadictionary/DataDictionary.java
KULRICE-8326 - enabling external message processing
<ide><path>rad/krad-web-framework/src/main/java/org/kuali/rice/krad/datadictionary/DataDictionary.java <ide> */ <ide> public void performDictionaryPostProcessing(boolean allowConcurrentValidation) { <ide> // invoke post processing of the dictionary bean definitions <del>// DictionaryBeanFactoryPostProcessor dictionaryBeanPostProcessor = new DictionaryBeanFactoryPostProcessor(this, <del>// ddBeans); <del>// dictionaryBeanPostProcessor.postProcessBeanFactory(); <add> DictionaryBeanFactoryPostProcessor dictionaryBeanPostProcessor = new DictionaryBeanFactoryPostProcessor(this, <add> ddBeans); <add> dictionaryBeanPostProcessor.postProcessBeanFactory(); <ide> <ide> // post processes UIF beans for pulling out expressions within property values <ide> UifBeanFactoryPostProcessor factoryPostProcessor = new UifBeanFactoryPostProcessor();
JavaScript
mit
20536466a88c2a66067b50407a83c10ea63ea3d0
0
mweststrate/fume
/* jshint immed:true, latedef:true, newcap:true, browser:true, node:true */ var _ = require("lodash"); var clutility = require("clutility"); /** @namespace Fume */ var Fume = Fume || {}; Fume.trace = false; /** @namespace Fume.util */ Fume.util = {}; /** Throws illegal state exception. Use this for code / state that should never occur @method @param {String} msg - (optional) additional details for this error */ var fail = Fume.util.fail = function(msg) { msg = msg || "This code shouldn't be triggered"; throw new Error("IllegalStateException: " + msg); }; /** The Event class describes all event types that can be send through Fume streams. In, for exampel RxJs there are just three types of events: `Next`, `Completed` and `Error`. However, fume consists of many more event types, being: ### Control events * dirty - the stream will be changed soon * ready - the stream has sent all its changes and is stable again * stop - this stream ends (similar to complete in RxJs) * error - an error has occurred. Like in Bacon.js, and unlike RxJs. `error` will not end the stream. ### Value related events * value(value) - a new value is sent through this stream. Similar to next in RxJs ### Complex structure (@see List or @see Dict) related events * clear - reset all state / data of this structure * listInsert(index, value) - a new item was added to a list at the specified index * itemRemove(index) - the item at the specified index (key) was removed from the structure * itemUpdate(index, value) - the value at the specified index / key was replaced with a new value For each event type there is a static method that creates the event, for example: `Event.insert(index, value)`, and there is instance function to check whether instance is a specific type of event. For example: `this.isInsert()` The index parameter should always be a positive integer (for Lists) or any string (for Dicts) that is a valid identifier. @class */ var Event = Fume.Event = clutility({ initialize : function(type, props) { this.type = type; if (props) _.extend(this, props); }, isStop : function() { return this.type === "STOP"; }, isDirty : function() { return this.type === "DIRTY"; }, isReady : function() { return this.type === "READY"; }, isValue : function() { return this.type === "VALUE"; }, isError : function() { return this.type === "ERROR"; }, isClear : function() { return this.type === "CLEAR"; }, isInsert : function() { return this.type === "INSERT"; }, isRemove : function() { return this.type === "REMOVE"; }, isUpdate : function() { return this.type === "UPDATE"; }, isComplexEvent : function() { return this.type in { CLEAR : 1, INSERT : 1, REMOVE : 1, UPDATE : 1}; }, toString : function() { var res = {}; for (var key in this) if (this.hasOwnProperty(key)) res[key] = res[key] instanceof Object ? res[key].toString() : res[key]; return JSON.stringify(res); } }); Event.stop = function() { return new Event("STOP"); //Optimize: use single event instance }; Event.dirty = function() { return new Event("DIRTY"); }; Event.ready = function() { return new Event("READY"); }; Event.value = function(value) { return new Event("VALUE", { value : value }); }; Event.error = function(code, error) { return new Event("ERROR", { code : code, error : error}); }; Event.clear = function() { return new Event("CLEAR"); }; Event.insert = function(index, value) { return new Event("INSERT", { index : index, value : value}); }; Event.remove = function(index, value) { return new Event("REMOVE", { index : index, value : value}); }; Event.update = function(index, value) { return new Event("UPDATE", { index : index, value : value }); }; /** Stream is the heart of fume. A stream is an event emitter that can be observed by one or more Observers. Stream is very similar to RxJs's Observable or Bacon.js's Stream. A stream will always send one of the events as described by @see Event. New observers can subscribe to the stream by using the `subscribe` method. (Similar to RxJs) New values can be pushed by the stream to its observers by using the `out` method. (Similar to RxJs Observable.next). For example: `this.out(Event.value(2));` When a new observer registers, it will be send to the `replay` method. The replay has the opportunity to push the current state of the stream to the observer. This is not required and depends on the character of the stream whether this should happen. @class */ var Stream = Fume.Stream = clutility({ /** Create a new stream. */ initialize : function() { this.isStopped = false; this.observersIdx = 0; this.observers = {}; this.name = "STREAM"; }, /** Subscribes an observer to this stream. Observables should implement the 'in(event)' method. On subscribing, the current state of this stream can be pushed to the observable by invoking the `replay` function. @param {Observer} observer - Observer object that will receive the events. It is allowed to pass in a function as well. @returns {Disposable} - disposable object. Call the @see Fume.Disposable#dispose function to stop listening to this observer */ subscribe : function(observer) { if (this.isStopped) fail(this + ": cannot perform 'subscribe'; already stopped."); if (typeof observer === "function") observer = new AnonymousObserver(observer); this.replayForObserver(observer); this.observersIdx += 1; this.observers[this.observersIdx] = observer; var observing = this; return { observerId : this.observersIdx, isDisposed : false, dispose : function(){ if (this.isDisposed) fail(); this.isDisposed = true; observing.unsubcribe(this); } }; }, /** Called by the dispose function of any disposables returned by the subscribe method. @private */ unsubcribe : function(disposable) { delete this.observers[disposable.observerId]; if (!this.hasObservers()) this.stop(); }, /** @return {Boolean} - Returns whether any observers are listening to this observable */ hasObservers : function() { if (this.observers) for(var key in this.observers) return true; return false; }, /** Makes sure that the observer is brought in to sync with any other observers, so that it correctly reflects the current state of this stream (whatever that means). Usually replay should start with sending the `Dirty` event and end with the `Ready` event. @param {Observer} observer Observer that should receives the initial state. */ replay : function(observer) { //stub }, /** * Replays this stream for a specific observer only */ replayForObserver : function(observer) { var observers = this.observers; this.observers = { tmp : observer }; this.replay(); this.observers = observers; }, /** Use this method to push a value to all observers of this stream @protected @param {Event} - event to be passed to the subscribers */ out : function(value) { this.trace("OUT: " + value); if (this.enableLogging) console.log(value); if (this.isStopped) fail(this + ": cannot perform 'next'; already stopped"); for(var key in this.observers) this.observers[key].in(value); }, log : function() { this.enableLogging = true; return this; }, /* Stops this observable from emitting events. Will distribute the Stop event to all its subscribers */ stop : function() { if (this.isStopped) return; if (this.hasObservers()) this.out(Event.stop()); this.isStopped = true; this.observers = null; }, setName : function(name) { this.name = name; return this; }, trace : function(msg) { if (Fume.trace) console.log(this + ": " + msg); }, toString : function() { return _.isFunction(this.name) ? this.name() : this.name; } }); /** Class / interface. An item that listens to a stream. For every event that is being send through a stream's `out` method, the `in` method of this observer is invoked @class */ var Observer = Fume.Observer = clutility({ /** @param {Event} value - event that is being received by this observer. */ in : function(value) { //Just a stub } }); /** Class, or merely interface, that exposes a `dispose` function. Used to unsubscribe observers from a stream. @class */ var Disposable = Fume.Disposable = clutility({ dispose : function() { //stub } }); /** Utility class. Simple observer that is constructed by directly passing in the `in` method to the constructor. Sample usage: ```javascript Stream.subscribe(new AnonymousObserver(function(event) { //code })); ``` @class */ var AnonymousObserver = Fume.AnonymousObserver = clutility(Observer, { /** @param {function(Event)} func - implementation of the `in` method of this Observer */ initialize : function(func) { if (func) this.in = func; } }); /** Utility class. Observer and Disposable that subscribes itself to a stream. This object can dispose itself from the stream. @class */ var DisposableObserver = Fume.DisposableObserver = clutility(AnonymousObserver, { /** @param {Stream} stream - stream to listen to @param {function(Event)} func - (Optional) implementation of the `in` method */ initialize : function($super, stream, func) { $super(func); this.subscription = stream.subscribe(this); }, /** Disposes this observer, it will no longer listen to its stream. */ dispose : function() { this.subscription.dispose(); } }); /** Transformer transforms one stream into another stream, by passing Events trough the transform function. The transform function should have the signature transform(Observer, Event) @class */ var Transformer = Fume.Transformer = clutility(Stream, { initialize : function($super, stream, transformFunction){ $super(); if (transformFunction) this.transform = transformFunction; stream = Stream.fromValue(stream); this.observing = stream; this.subscription = stream.subscribe(this); }, in : function(event) { if (event.isStop()) this.stop(); else if (event.isDirty() || event.isReady()) this.out(event); else this.transform(event); }, replay : function() { this.out(Event.dirty()); this.observing.replayForObserver(this); this.out(Event.ready()); }, transform : function(event) { //stub implementation, just pass in the events this.out(event); }, stop : function($super) { $super(); if (this.subscription) { this.subscription.dispose(); this.subscription = null; } } }); /** A relay is a stream that observes another stream. The stream which it is observing might change over time, by using the `observe` method. @class */ var Relay = Fume.Relay = clutility(Stream, { initialize : function($super, stream){ $super(); this.dirtyCount = 0; this.isSwitchingObserver = false; this.cycleDetected = false; this.observe(stream); }, in : function(event) { if (!this.hasObservers()) { //empty block } else if (event.isStop()) this.stop(); else this.out(event); }, replay : function() { if (this.isSwitchingObserver) this.cycleDetected = true; else this.observing.replayForObserver(this); }, observe : function(stream) { if (this.isStopped) fail(this + ": cannot perform 'observe', already stopped"); stream = Stream.fromValue(stream); if (stream !== this.observing && !Constant.equals(stream, this.observing)) { this.isSwitchingObserver = true; if (this.subscription) this.subscription.dispose(); this.observing = stream; this.subscription = stream.subscribe(this); if (this.cycleDetected) { this.cycleDetected = false; this.observe(new FumeError("cycle_detected", "Circular reference detected in '" + this.toString() + "'")); } this.isSwitchingObserver = false; } }, stop : function($super) { $super(); if (this.subscription) { this.subscription.dispose(); this.subscription = null; } } }); /** Merge takes multiple streams, and whenever a stream fires, and all input streams are ready again, it will combine the latest state of the input streams into an array, an emit that as new value. @class */ var LatestEventMerger = Fume.LatestEventMerger = clutility(Stream, { initialize : function($super, streams) { $super(); this.inputStreams = _.map(streams, Stream.fromValue); this.inputDirtyCount = 0; this.inputStates = []; //last event per input this.inputObservers = _.map(this.inputStreams, function(stream, idx) { return new DisposableObserver(stream, _.bind(this.in, this, idx)); }, this); }, in : function(inputIndex, event) { if (event.isStop()) this.stop(); else if (event.isDirty()) { if (this.inputDirtyCount === 0) this.out(event); this.inputDirtyCount += 1; } else if (event.isReady()) { this.inputDirtyCount -= 1; /* if all inputs are satisfied, apply the process function */ if (this.inputDirtyCount === 0) { this.out(this.statesToEvent(this.inputStates)); this.out(event); } } else if (event.isComplexEvent()) this.inputStates[inputIndex] = Event.error("Complex events are not supported by LatestEventMerger"); else this.inputStates[inputIndex] = event; }, replay : function() { this.out(Event.dirty()); if (this.inputDirtyCount == 0) { this.out(this.statesToEvent(this.inputStates)); this.out(Event.ready()); } }, statesToEvent : function(states) { var values = []; for (var i = 0; i < states.length; i++) { if (states[i].isError()) return states[i]; else values.push(states[i].value); } return Event.value(values); }, stop : function($super) { _.forEach(this.inputObservers, function(observer) { observer.dispose(); }); $super(); } }); Fume.Let = clutility(Relay, { initialize : function($super, varname, value, expression) { this.varname = varname; this.value = value; this.expression = expression; $super(expression); }, setClosure : function(closure) { this.closure = closure; this.value.setClosure && value.setClosure(closure); this.expression.setClosure && this.expression.setClosure(this); }, resolve : function(varname) { if (this.varname == varname) return this.value; else return this.closure ? this.closure.resolve(varname) : new FumeError("Undefined: " + varname, "Variable with name '" + varname + "' is not in scope"); } }); Fume.Get = clutility(Relay, { hasClosure : false, initialize : function($super, varname) { this.varname = varname; $super(); }, setClosure : function(closure) { this.hasClosure = true; this.observe(closure.resolve(this.varname)); this.out(Event.ready()); //to those already listening... }, replay : function($super) { if (!this.hasClosure) this.out(Event.dirty()); else $super(); } }); /** A primitve transformer takes a function which accepts native JS values and a bunch of streams. Based on the merge of the streams the function will be applied, and the return value of the function will be emitted. */ var PrimitiveTransformer = Fume.PrimitiveTransformer = clutility(Transformer, { initialize : function($super, func, streams) { var self = this; this.simpleFunc = func; this.latestEvent = null; this.streams = streams; $super(new LatestEventMerger(streams), null); }, transform : function(event) { var args = event.value; this.out(this.latestEvent = Event.value(this.simpleFunc.apply(this, args))); }, replay : function() { this.out(Event.dirty()); if (this.latestEvent) { this.out(this.latestEvent); this.out(Event.ready()); } }, setClosure : function(closure) { this.streams.forEach(function(stream) { stream.setClosure && stream.setClosure(closure); }); } }); /** A constant is a stream that is initialized by a single value and will not change over time. Each observer that subscribes to the constant will receive its initial value. @class */ var Constant = Fume.Constant = clutility(Fume.Stream, { /** @param {Any} value - The initial value of the constant. */ initialize : function($super, value) { $super(); this.value = value; }, replay : function() { this.out(Event.dirty()); this.out(Event.value(this.value)); this.out(Event.ready()); }, toString : function() { return "(" + this.value + ")"; } }); Constant.equals = function(left, right) { return left instanceof Constant && right instanceof Constant && left.value === right.value; }; /** * FumeError is a constant that is used to indicate that an error occurred. * The FumeError class will emit `error` events. * * @class * @param {String} code Machine recognizable code of the error. Should not change over time * @param {[type]} error Description of the error */ var FumeError = Fume.FumeError = clutility(Fume.Stream, { initialize : function($super, code, error) { $super(); this.code = code; this.error = error; }, replay : function() { this.out(Event.dirty()); this.out(Event.error(this.code, this.error)); this.out(Event.ready()); }, toString : function() { return "FumeError(" + this.code + ", " + this.error + ")"; } }); /** ChildItem is a Relay, contained by a complex object (list or dict). It has a notion of a parent position and when it starts observing a new stream, it will notify its parent so that the proper events can be triggered. @class @private */ var ChildItem = clutility(Relay, { initialize : function($super, parent, idx, initialValue) { this.parent = parent; this.index = idx; this.isStarting = true; $super(initialValue); this.isStarting = false; }, observe : function($super, newValue) { var oldValue = this.get(); newValue = Stream.fromValue(newValue); if (newValue === oldValue || Constant.equals(newValue, oldValue)) return; if (this.isStarting) $super(newValue); else { this.parent.markDirty(false); $super(newValue); this.parent.out(Event.update(this.index, newValue)); this.parent.markReady(false); } }, set : function(newValue) { this.observe(newValue); }, get : function() { return this.observing; }, toString : function() { return this.index + ":" + this.observing.toString(); } }); /** A list presents an ordered set of values / streams and provides functions to manipulate the individual streams, but proved combined streams with special events as well. @class */ var List = Fume.List = clutility(Stream, { initialize : function($super) { $super(); this.items = []; this.lengthPipe = new Stream(); }, /** Inserts a new item to this list at the specified index. @param {Integer} index - Position where the item should be inserted. Should be positive, and smaller or equal to the length of this list @param {Any} value - Value to be inserted at the specified position. Will be converted to a Stream if necessary. */ insert : function(index, value) { return this.insertAll(index, [value]); }, /** Updates the value at the specified index. This will replace any stream which is already in there @param {Integer} index - Index of the item to be updated. Should be positive and smaller than the length of the List @param {Any} value - the new value. Will be converted into a stream if necessary. */ set : function(index, value) { this.items[index].set(value); return this; }, /** Removes the item at the specified index @param {Integer} index - Index of the item to be removed. Should be positive and smaller than the length of the List */ remove : function(index) { return this.removeRange(index, 1); }, removeRange : function(index, amount) { this.markDirty(true); this.items.splice(index, amount).forEach(function(item){ this.out(Event.remove(item.index)); item.stop(); }, this); for (var i = index; i < this.items.length; i++) this.items[i].index -= amount; this.lengthPipe.out(Event.value(this.items.length)); this.markReady(true); return this; }, /** Removes all items from this list */ clear : function() { if (this.length === 0) return; this.markDirty(true); for (var i = this.items.length -1; i >= 0; i--) this.items[i].stop(); this.items = []; this.out(Event.clear()); this.lengthPipe.out(Event.value(0)); this.markReady(true); return this; }, /** Returns a Stream to which the length of this list will be emitted, whenever it changes */ length : function() { return this.lengthPipe; }, replay : function() { this.out(Event.dirty()); this.out(Event.clear()); for(var i = 0, l = this.items.length; i < l; i++) this.out(Event.insert(i, this.items[i].get())); this.out(Event.ready()); return this; }, /** Shorthand for inserting an item at the last position of this list. @see List#insert */ add : function(value) { return this.insert(this.items.length, value); }, addAll : function(values) { return this.insertAll(this.items.length, values); }, insertAll : function(index, values) { this.markDirty(true); //create and insert the items var toInsert = values.map(function(value, i) { var child = new ChildItem(this, index + i, value); this.out(Event.insert(index + i, child.get())); return child; }, this); this.items.splice.apply(this.items, [index, 0].concat(toInsert)); //update indexes for (var i = index + values.length; i < this.items.length; i++) this.items[i].index += values.length; this.lengthPipe.out(Event.value(this.items.length)); this.markReady(true); return this; }, /** Returns the Stream which is stored at the specified index. The stream will be bound to the value which is *currently* at the specified index. @param {Integer} index - Stream to be requested. Should be positive and smaller than the length of this list. */ get : function(index) { return this.items[index]; }, toArray : function() { var res = []; _.forEach(this.items, function(x){ res.push(x.get().value); }); return res; }, stop : function($super) { this.clear(); this.lengthPipe.stop(); _.forEach(this.items, function(item) { item.stop(); }); $super(); }, markDirty : function(includeLength) { this.out(Event.dirty()); if (includeLength) this.lengthPipe.out(Event.dirty()); return this; }, markReady : function(includeLength) { this.out(Event.ready()); if (includeLength) this.lengthPipe.out(Event.ready()); return this; }, toString : function() { return "[" + this.toArray().join(",") + "]"; } }); var Dict = Fume.Dict = clutility(Stream, { initialize : function($super) { $super(); this.items = {}; this.futures = {}; this.keys = new List(); }, /** Updates the value at the specified key. This will replace any stream which is already in there @param {String} key - Key of the item to be updated. @param {Any} value - the new value. Will be converted into a stream if necessary. */ set : function(key, value) { var o = {}; o[key] = value; return this.extend(o); }, extend : function(valueObject) { this.markDirty(true); if (valueObject instanceof Dict) return this.extend(valueObject.items); else if (!_.isObject(valueObject)) throw new Error("Dict.extend expected plain Object or dict"); for (var key in valueObject) if (valueObject.hasOwnProperty(key)) { if (!key || !_.isString(key)) throw new Error("Key should be a valid string, got: " + key); var value = valueObject[key]; //new key if (!this.items[key]) { if (this.futures[key]) { this.items[key] = this.futures[key]; delete this.futures[key]; this.items[key].set(value); } else { this.items[key] = new ChildItem(this, key, value); } this.out(Event.update(key, this.items[key].get())); this.keys.add(key); } //existing key else this.items[key].set(value); } this.markDirty(false); return this; }, /** Removes the item at the specified key */ remove : function(key) { return this.reduce([key]); }, reduce : function(keys) { this.markDirty(true); keys.forEach(function(key){ if (this.items[key]) { var child = this.items[key]; child.observe(undefined); if (child.hasObservers()) this.futures[key] = child; else child.stop(); delete this.items[key]; this.keys.remove(key); } }, this); this.markReady(true); return this; }, /** Removes all items from this Dict */ clear : function() { if (this.length === 0) return; this.markDirty(true); //Optimization: supress all events introduced by this:... this.reduce(this.keys.toArray()); this.out(Event.clear()); this.keys.clear(); this.markReady(true); return this; }, replay : function() { this.out(Event.dirty()); this.out(Event.clear()); for(var key in this.items) this.out(Event.update(key, this.items[key].get())); this.out(Event.ready()); return this; }, /** Returns the Stream which is stored at the specified key. The stream will be bound to the value which is now or in in the future at te specified key. This means that it is possible to observe keys which are not defined yet @param {Integer} key */ get : function(key) { if (!key || !_.isString(key)) throw new Error("Key should be a valid string, got: " + key); else if (this.items[key]) return this.items[key]; else if (this.futures[key]) return this.futures[key]; else return this.futures[key] = new ChildItem(this, key, undefined); }, /* Returns a stream of booleans that indicates whether the specified key is in use */ has : function(key) { return this.keys.contains(key); }, toObject : function() { var res = {}; for (var key in this.items) res[key] = this.items[key].get().value; return res; }, stop : function($super) { this.clear(); this.keys.clear(); $super(); }, markDirty : function(includeKeys) { this.out(Event.dirty()); if (includeKeys) this.keys.markDirty(true); return this; }, markReady : function(includeKeys) { this.out(Event.ready()); if (includeKeys) this.keys.markReady(true); return this; }, toString : function() { return "{" + this.keys.map(function(key){ return key + ": " + this.items[key].get().value; }, this).join(",") + "}"; } }); Stream.fromValue = function(value) { if (value instanceof Stream) return value; if (_.isArray(value)) { var l = new List(); l.addAll(value); return l; } if (_.isObject(value)) { var d = new Dict(); d.extend(value); return d; } return new Constant(value); //TODO: error, function... }; Stream.asDict = function(stream) { //Or Dict.fromStream.. //TODO: }; Stream.asList = function(stream) { //Or List.fromStream.. //TODO: }; Fume.multiply = function(left, right) { return new PrimitiveTransformer(function(x, y) { return x * y; }, [left, right]); }; Fume.ValueBuffer = clutility({ initialize : function() { this.reset(); }, in : function(x) { if (x.isValue()) this.buffer.push(x.value); else if (x.isError()) this.buffer.push(x); }, reset : function() { this.buffer = []; return this; } }); Fume.EventTypeBuffer = clutility(Fume.ValueBuffer, { in : function(x) { this.buffer.push(x.type); } }); module.exports = Fume;
src/fume.js
/* jshint immed:true, latedef:true, newcap:true, browser:true, node:true */ var _ = require("lodash"); var clutility = require("clutility"); /** @namespace Fume */ var Fume = Fume || {}; Fume.trace = false; /** @namespace Fume.util */ Fume.util = {}; /** Throws illegal state exception. Use this for code / state that should never occur @method @param {String} msg - (optional) additional details for this error */ var fail = Fume.util.fail = function(msg) { msg = msg || "This code shouldn't be triggered"; throw new Error("IllegalStateException: " + msg); }; /** The Event class describes all event types that can be send through Fume streams. In, for exampel RxJs there are just three types of events: `Next`, `Completed` and `Error`. However, fume consists of many more event types, being: ### Control events * dirty - the stream will be changed soon * ready - the stream has sent all its changes and is stable again * stop - this stream ends (similar to complete in RxJs) * error - an error has occurred. Like in Bacon.js, and unlike RxJs. `error` will not end the stream. ### Value related events * value(value) - a new value is sent through this stream. Similar to next in RxJs ### Complex structure (@see List or @see Dict) related events * clear - reset all state / data of this structure * listInsert(index, value) - a new item was added to a list at the specified index * itemRemove(index) - the item at the specified index (key) was removed from the structure * itemUpdate(index, value) - the value at the specified index / key was replaced with a new value For each event type there is a static method that creates the event, for example: `Event.insert(index, value)`, and there is instance function to check whether instance is a specific type of event. For example: `this.isInsert()` The index parameter should always be a positive integer (for Lists) or any string (for Dicts) that is a valid identifier. @class */ var Event = Fume.Event = clutility({ initialize : function(type, props) { this.type = type; if (props) _.extend(this, props); }, isStop : function() { return this.type === "STOP"; }, isDirty : function() { return this.type === "DIRTY"; }, isReady : function() { return this.type === "READY"; }, isValue : function() { return this.type === "VALUE"; }, isError : function() { return this.type === "ERROR"; }, isClear : function() { return this.type === "CLEAR"; }, isInsert : function() { return this.type === "INSERT"; }, isRemove : function() { return this.type === "REMOVE"; }, isUpdate : function() { return this.type === "UPDATE"; }, isComplexEvent : function() { return this.type in { CLEAR : 1, INSERT : 1, REMOVE : 1, UPDATE : 1}; }, toString : function() { var res = {}; for (var key in this) if (this.hasOwnProperty(key)) res[key] = res[key] instanceof Object ? res[key].toString() : res[key]; return JSON.stringify(res); } }); Event.stop = function() { return new Event("STOP"); //Optimize: use single event instance }; Event.dirty = function() { return new Event("DIRTY"); }; Event.ready = function() { return new Event("READY"); }; Event.value = function(value) { return new Event("VALUE", { value : value }); }; Event.error = function(code, error) { return new Event("ERROR", { code : code, error : error}); }; Event.clear = function() { return new Event("CLEAR"); }; Event.insert = function(index, value) { return new Event("INSERT", { index : index, value : value}); }; Event.remove = function(index, value) { return new Event("REMOVE", { index : index, value : value}); }; Event.update = function(index, value) { return new Event("UPDATE", { index : index, value : value }); }; /** Stream is the heart of fume. A stream is an event emitter that can be observed by one or more Observers. Stream is very similar to RxJs's Observable or Bacon.js's Stream. A stream will always send one of the events as described by @see Event. New observers can subscribe to the stream by using the `subscribe` method. (Similar to RxJs) New values can be pushed by the stream to its observers by using the `out` method. (Similar to RxJs Observable.next). For example: `this.out(Event.value(2));` When a new observer registers, it will be send to the `replay` method. The replay has the opportunity to push the current state of the stream to the observer. This is not required and depends on the character of the stream whether this should happen. @class */ var Stream = Fume.Stream = clutility({ /** Create a new stream. */ initialize : function() { this.isStopped = false; this.observersIdx = 0; this.observers = {}; this.name = "STREAM"; }, /** Subscribes an observer to this stream. Observables should implement the 'in(event)' method. On subscribing, the current state of this stream can be pushed to the observable by invoking the `replay` function. @param {Observer} observer - Observer object that will receive the events. It is allowed to pass in a function as well. @returns {Disposable} - disposable object. Call the @see Fume.Disposable#dispose function to stop listening to this observer */ subscribe : function(observer) { if (this.isStopped) fail(this + ": cannot perform 'subscribe'; already stopped."); if (typeof observer === "function") observer = new AnonymousObserver(observer); this.replayForObserver(observer); this.observersIdx += 1; this.observers[this.observersIdx] = observer; var observing = this; return { observerId : this.observersIdx, isDisposed : false, dispose : function(){ if (this.isDisposed) fail(); this.isDisposed = true; observing.unsubcribe(this); } }; }, /** Called by the dispose function of any disposables returned by the subscribe method. @private */ unsubcribe : function(disposable) { delete this.observers[disposable.observerId]; if (!this.hasObservers()) this.stop(); }, /** @return {Boolean} - Returns whether any observers are listening to this observable */ hasObservers : function() { if (this.observers) for(var key in this.observers) return true; return false; }, /** Makes sure that the observer is brought in to sync with any other observers, so that it correctly reflects the current state of this stream (whatever that means). Usually replay should start with sending the `Dirty` event and end with the `Ready` event. @param {Observer} observer Observer that should receives the initial state. */ replay : function(observer) { //stub }, /** * Replays this stream for a specific observer only */ replayForObserver : function(observer) { var observers = this.observers; this.observers = { tmp : observer }; this.replay(); this.observers = observers; }, /** Use this method to push a value to all observers of this stream @protected @param {Event} - event to be passed to the subscribers */ out : function(value) { this.trace("OUT: " + value); if (this.enableLogging) console.log(value); if (this.isStopped) fail(this + ": cannot perform 'next'; already stopped"); for(var key in this.observers) this.observers[key].in(value); }, log : function() { this.enableLogging = true; return this; }, /* Stops this observable from emitting events. Will distribute the Stop event to all its subscribers */ stop : function() { if (this.isStopped) return; if (this.hasObservers()) this.out(Event.stop()); this.isStopped = true; this.observers = null; }, setName : function(name) { this.name = name; return this; }, trace : function(msg) { if (Fume.trace) console.log(this + ": " + msg); }, toString : function() { return _.isFunction(this.name) ? this.name() : this.name; } }); /** Class / interface. An item that listens to a stream. For every event that is being send through a stream's `out` method, the `in` method of this observer is invoked @class */ var Observer = Fume.Observer = clutility({ /** @param {Event} value - event that is being received by this observer. */ in : function(value) { //Just a stub } }); /** Class, or merely interface, that exposes a `dispose` function. Used to unsubscribe observers from a stream. @class */ var Disposable = Fume.Disposable = clutility({ dispose : function() { //stub } }); /** Utility class. Simple observer that is constructed by directly passing in the `in` method to the constructor. Sample usage: ```javascript Stream.subscribe(new AnonymousObserver(function(event) { //code })); ``` @class */ var AnonymousObserver = Fume.AnonymousObserver = clutility(Observer, { /** @param {function(Event)} func - implementation of the `in` method of this Observer */ initialize : function(func) { if (func) this.in = func; } }); /** Utility class. Observer and Disposable that subscribes itself to a stream. This object can dispose itself from the stream. @class */ var DisposableObserver = Fume.DisposableObserver = clutility(AnonymousObserver, { /** @param {Stream} stream - stream to listen to @param {function(Event)} func - (Optional) implementation of the `in` method */ initialize : function($super, stream, func) { $super(func); this.subscription = stream.subscribe(this); }, /** Disposes this observer, it will no longer listen to its stream. */ dispose : function() { this.subscription.dispose(); } }); /** Transformer transforms one stream into another stream, by passing Events trough the transform function. The transform function should have the signature transform(Observer, Event) @class */ var Transformer = Fume.Transformer = clutility(Stream, { initialize : function($super, stream, transformFunction){ $super(); if (transformFunction) this.transform = transformFunction; stream = Stream.fromValue(stream); this.observing = stream; this.subscription = stream.subscribe(this); }, in : function(event) { if (event.isStop()) this.stop(); else if (event.isDirty() || event.isReady()) this.out(event); else this.transform(event); }, replay : function() { this.out(Event.dirty()); this.observing.replayForObserver(this); this.out(Event.ready()); }, transform : function(event) { //stub implementation, just pass in the events this.out(event); }, stop : function($super) { $super(); if (this.subscription) { this.subscription.dispose(); this.subscription = null; } } }); /** A relay is a stream that observes another stream. The stream which it is observing might change over time, by using the `observe` method. @class */ var Relay = Fume.Relay = clutility(Stream, { initialize : function($super, stream){ $super(); this.dirtyCount = 0; this.isSwitchingObserver = false; this.cycleDetected = false; this.observe(stream); }, in : function(event) { if (!this.hasObservers()) { //empty block } else if (event.isStop()) this.stop(); else this.out(event); }, replay : function() { if (this.isSwitchingObserver) this.cycleDetected = true; else this.observing.replayForObserver(this); }, observe : function(stream) { if (this.isStopped) fail(this + ": cannot perform 'observe', already stopped"); stream = Stream.fromValue(stream); if (stream !== this.observing && !Constant.equals(stream, this.observing)) { this.isSwitchingObserver = true; if (this.subscription) this.subscription.dispose(); this.observing = stream; this.subscription = stream.subscribe(this); if (this.cycleDetected) { this.cycleDetected = false; this.observe(new FumeError("cycle_detected", "Circular reference detected in '" + this.toString() + "'")); } this.isSwitchingObserver = false; } }, stop : function($super) { $super(); if (this.subscription) { this.subscription.dispose(); this.subscription = null; } } }); /** Merge takes multiple streams, and whenever a stream fires, and all input streams are ready again, it will combine the latest state of the input streams into an array, an emit that as new value. @class */ var LatestEventMerger = Fume.LatestEventMerger = clutility(Stream, { initialize : function($super, streams) { $super(); this.inputStreams = _.map(streams, Stream.fromValue); this.inputDirtyCount = 0; this.inputStates = []; //last event per input this.inputObservers = _.map(this.inputStreams, function(stream, idx) { return new DisposableObserver(stream, _.bind(this.in, this, idx)); }, this); }, in : function(inputIndex, event) { if (event.isStop()) this.stop(); else if (event.isDirty()) { if (this.inputDirtyCount === 0) this.out(event); this.inputDirtyCount += 1; } else if (event.isReady()) { this.inputDirtyCount -= 1; /* if all inputs are satisfied, apply the process function */ if (this.inputDirtyCount === 0) { this.out(this.statesToEvent(this.inputStates)); this.out(event); } } else if (event.isComplexEvent()) this.inputStates[inputIndex] = Event.error("Complex events are not supported by LatestEventMerger"); else this.inputStates[inputIndex] = event; }, replay : function() { this.out(Event.dirty()); if (this.inputDirtyCount == 0) { this.out(this.statesToEvent(this.inputStates)); this.out(Event.ready()); } }, statesToEvent : function(states) { var values = []; for (var i = 0; i < states.length; i++) { if (states[i].isError()) return states[i]; else values.push(states[i].value); } return Event.value(values); }, stop : function($super) { _.forEach(this.inputObservers, function(observer) { observer.dispose(); }); $super(); } }); var Expression = Fume.Expression = clutility(Relay, { closure : null, inputStreams : null, initialize : function($super, streams) { this.inputStreams = _.map(streams, Stream.fromValue); $super(); }, setClosure : function(closure) { if (this.closure) throw "Closure already set"; _.forEach(this.inputStreams, function(stream) { if (stream.setClosure) stream.setClosure(closure); }); } }); Fume.Let = clutility(Relay, { initialize : function($super, varname, value, expression) { this.varname = varname; this.value = value; this.expression = expression; $super(expression); }, setClosure : function(closure) { this.closure = closure; this.value.setClosure && value.setClosure(closure); this.expression.setClosure && this.expression.setClosure(this); }, resolve : function(varname) { if (this.varname == varname) return this.value; else return this.closure ? this.closure.resolve(varname) : new FumeError("Undefined: " + varname, "Variable with name '" + varname + "' is not in scope"); } }); Fume.Get = clutility(Relay, { hasClosure : false, initialize : function($super, varname) { this.varname = varname; $super(); }, setClosure : function(closure) { this.hasClosure = true; this.observe(closure.resolve(this.varname)); this.out(Event.ready()); //to those already listening... }, replay : function($super) { if (!this.hasClosure) this.out(Event.dirty()); else $super(); } }); /** A primitve transformer takes a function which accepts native JS values and a bunch of streams. Based on the merge of the streams the function will be applied, and the return value of the function will be emitted. */ var PrimitiveTransformer = Fume.PrimitiveTransformer = clutility(Transformer, { initialize : function($super, func, streams) { var self = this; this.simpleFunc = func; this.latestEvent = null; this.streams = streams; $super(new LatestEventMerger(streams), null); }, transform : function(event) { var args = event.value; this.out(this.latestEvent = Event.value(this.simpleFunc.apply(this, args))); }, replay : function() { this.out(Event.dirty()); this.out(this.latestEvent); this.out(Event.ready()); }, setClosure : function(closure) { this.streams.forEach(function(stream) { stream.setClosure && stream.setClosure(closure); }); } }); /** A constant is a stream that is initialized by a single value and will not change over time. Each observer that subscribes to the constant will receive its initial value. @class */ var Constant = Fume.Constant = clutility(Fume.Stream, { /** @param {Any} value - The initial value of the constant. */ initialize : function($super, value) { $super(); this.value = value; }, replay : function() { this.out(Event.dirty()); this.out(Event.value(this.value)); this.out(Event.ready()); }, toString : function() { return "(" + this.value + ")"; } }); Constant.equals = function(left, right) { return left instanceof Constant && right instanceof Constant && left.value === right.value; }; /** * FumeError is a constant that is used to indicate that an error occurred. * The FumeError class will emit `error` events. * * @class * @param {String} code Machine recognizable code of the error. Should not change over time * @param {[type]} error Description of the error */ var FumeError = Fume.FumeError = clutility(Fume.Stream, { initialize : function($super, code, error) { $super(); this.code = code; this.error = error; }, replay : function() { this.out(Event.dirty()); this.out(Event.error(this.code, this.error)); this.out(Event.ready()); }, toString : function() { return "FumeError(" + this.code + ", " + this.error + ")"; } }); /** ChildItem is a Relay, contained by a complex object (list or dict). It has a notion of a parent position and when it starts observing a new stream, it will notify its parent so that the proper events can be triggered. @class @private */ var ChildItem = clutility(Relay, { initialize : function($super, parent, idx, initialValue) { this.parent = parent; this.index = idx; this.isStarting = true; $super(initialValue); this.isStarting = false; }, observe : function($super, newValue) { var oldValue = this.get(); newValue = Stream.fromValue(newValue); if (newValue === oldValue || Constant.equals(newValue, oldValue)) return; if (this.isStarting) $super(newValue); else { this.parent.markDirty(false); $super(newValue); this.parent.out(Event.update(this.index, newValue)); this.parent.markReady(false); } }, set : function(newValue) { this.observe(newValue); }, get : function() { return this.observing; }, toString : function() { return this.index + ":" + this.observing.toString(); } }); /** A list presents an ordered set of values / streams and provides functions to manipulate the individual streams, but proved combined streams with special events as well. @class */ var List = Fume.List = clutility(Stream, { initialize : function($super) { $super(); this.items = []; this.lengthPipe = new Stream(); }, /** Inserts a new item to this list at the specified index. @param {Integer} index - Position where the item should be inserted. Should be positive, and smaller or equal to the length of this list @param {Any} value - Value to be inserted at the specified position. Will be converted to a Stream if necessary. */ insert : function(index, value) { return this.insertAll(index, [value]); }, /** Updates the value at the specified index. This will replace any stream which is already in there @param {Integer} index - Index of the item to be updated. Should be positive and smaller than the length of the List @param {Any} value - the new value. Will be converted into a stream if necessary. */ set : function(index, value) { this.items[index].set(value); return this; }, /** Removes the item at the specified index @param {Integer} index - Index of the item to be removed. Should be positive and smaller than the length of the List */ remove : function(index) { return this.removeRange(index, 1); }, removeRange : function(index, amount) { this.markDirty(true); this.items.splice(index, amount).forEach(function(item){ this.out(Event.remove(item.index)); item.stop(); }, this); for (var i = index; i < this.items.length; i++) this.items[i].index -= amount; this.lengthPipe.out(Event.value(this.items.length)); this.markReady(true); return this; }, /** Removes all items from this list */ clear : function() { if (this.length === 0) return; this.markDirty(true); for (var i = this.items.length -1; i >= 0; i--) this.items[i].stop(); this.items = []; this.out(Event.clear()); this.lengthPipe.out(Event.value(0)); this.markReady(true); return this; }, /** Returns a Stream to which the length of this list will be emitted, whenever it changes */ length : function() { return this.lengthPipe; }, replay : function() { this.out(Event.dirty()); this.out(Event.clear()); for(var i = 0, l = this.items.length; i < l; i++) this.out(Event.insert(i, this.items[i].get())); this.out(Event.ready()); return this; }, /** Shorthand for inserting an item at the last position of this list. @see List#insert */ add : function(value) { return this.insert(this.items.length, value); }, addAll : function(values) { return this.insertAll(this.items.length, values); }, insertAll : function(index, values) { this.markDirty(true); //create and insert the items var toInsert = values.map(function(value, i) { var child = new ChildItem(this, index + i, value); this.out(Event.insert(index + i, child.get())); return child; }, this); this.items.splice.apply(this.items, [index, 0].concat(toInsert)); //update indexes for (var i = index + values.length; i < this.items.length; i++) this.items[i].index += values.length; this.lengthPipe.out(Event.value(this.items.length)); this.markReady(true); return this; }, /** Returns the Stream which is stored at the specified index. The stream will be bound to the value which is *currently* at the specified index. @param {Integer} index - Stream to be requested. Should be positive and smaller than the length of this list. */ get : function(index) { return this.items[index]; }, toArray : function() { var res = []; _.forEach(this.items, function(x){ res.push(x.get().value); }); return res; }, stop : function($super) { this.clear(); this.lengthPipe.stop(); _.forEach(this.items, function(item) { item.stop(); }); $super(); }, markDirty : function(includeLength) { this.out(Event.dirty()); if (includeLength) this.lengthPipe.out(Event.dirty()); return this; }, markReady : function(includeLength) { this.out(Event.ready()); if (includeLength) this.lengthPipe.out(Event.ready()); return this; }, toString : function() { return "[" + this.toArray().join(",") + "]"; } }); var Dict = Fume.Dict = clutility(Stream, { initialize : function($super) { $super(); this.items = {}; this.futures = {}; this.keys = new List(); }, /** Updates the value at the specified key. This will replace any stream which is already in there @param {String} key - Key of the item to be updated. @param {Any} value - the new value. Will be converted into a stream if necessary. */ set : function(key, value) { var o = {}; o[key] = value; return this.extend(o); }, extend : function(valueObject) { this.markDirty(true); if (valueObject instanceof Dict) return this.extend(valueObject.items); else if (!_.isObject(valueObject)) throw new Error("Dict.extend expected plain Object or dict"); for (var key in valueObject) if (valueObject.hasOwnProperty(key)) { if (!key || !_.isString(key)) throw new Error("Key should be a valid string, got: " + key); var value = valueObject[key]; //new key if (!this.items[key]) { if (this.futures[key]) { this.items[key] = this.futures[key]; delete this.futures[key]; this.items[key].set(value); } else { this.items[key] = new ChildItem(this, key, value); } this.out(Event.update(key, this.items[key].get())); this.keys.add(key); } //existing key else this.items[key].set(value); } this.markDirty(false); return this; }, /** Removes the item at the specified key */ remove : function(key) { return this.reduce([key]); }, reduce : function(keys) { this.markDirty(true); keys.forEach(function(key){ if (this.items[key]) { var child = this.items[key]; child.observe(undefined); if (child.hasObservers()) this.futures[key] = child; else child.stop(); delete this.items[key]; this.keys.remove(key); } }, this); this.markReady(true); return this; }, /** Removes all items from this Dict */ clear : function() { if (this.length === 0) return; this.markDirty(true); //Optimization: supress all events introduced by this:... this.reduce(this.keys.toArray()); this.out(Event.clear()); this.keys.clear(); this.markReady(true); return this; }, replay : function() { this.out(Event.dirty()); this.out(Event.clear()); for(var key in this.items) this.out(Event.update(key, this.items[key].get())); this.out(Event.ready()); return this; }, /** Returns the Stream which is stored at the specified key. The stream will be bound to the value which is now or in in the future at te specified key. This means that it is possible to observe keys which are not defined yet @param {Integer} key */ get : function(key) { if (!key || !_.isString(key)) throw new Error("Key should be a valid string, got: " + key); else if (this.items[key]) return this.items[key]; else if (this.futures[key]) return this.futures[key]; else return this.futures[key] = new ChildItem(this, key, undefined); }, /* Returns a stream of booleans that indicates whether the specified key is in use */ has : function(key) { return this.keys.contains(key); }, toObject : function() { var res = {}; for (var key in this.items) res[key] = this.items[key].get().value; return res; }, stop : function($super) { this.clear(); this.keys.clear(); $super(); }, markDirty : function(includeKeys) { this.out(Event.dirty()); if (includeKeys) this.keys.markDirty(true); return this; }, markReady : function(includeKeys) { this.out(Event.ready()); if (includeKeys) this.keys.markReady(true); return this; }, toString : function() { return "{" + this.keys.map(function(key){ return key + ": " + this.items[key].get().value; }, this).join(",") + "}"; } }); Stream.fromValue = function(value) { if (value instanceof Stream) return value; if (_.isArray(value)) { var l = new List(); l.addAll(value); return l; } if (_.isObject(value)) { var d = new Dict(); d.extend(value); return d; } return new Constant(value); //TODO: error, function... }; Stream.asDict = function(stream) { //Or Dict.fromStream.. //TODO: }; Stream.asList = function(stream) { //Or List.fromStream.. //TODO: }; Fume.multiply = function(left, right) { return new PrimitiveTransformer(function(x, y) { return x * y; }, [left, right]); }; Fume.ValueBuffer = clutility({ initialize : function() { this.reset(); }, in : function(x) { if (x.isValue()) this.buffer.push(x.value); else if (x.isError()) this.buffer.push(x); }, reset : function() { this.buffer = []; return this; } }); Fume.EventTypeBuffer = clutility(Fume.ValueBuffer, { in : function(x) { this.buffer.push(x.type); } }); module.exports = Fume;
Bye, Expression (for now)
src/fume.js
Bye, Expression (for now)
<ide><path>rc/fume.js <ide> } <ide> }); <ide> <del>var Expression = Fume.Expression = clutility(Relay, { <del> closure : null, <del> inputStreams : null, <del> initialize : function($super, streams) { <del> this.inputStreams = _.map(streams, Stream.fromValue); <del> $super(); <del> }, <del> setClosure : function(closure) { <del> if (this.closure) <del> throw "Closure already set"; <del> _.forEach(this.inputStreams, function(stream) { <del> if (stream.setClosure) <del> stream.setClosure(closure); <del> }); <del> } <del>}); <del> <ide> Fume.Let = clutility(Relay, { <ide> initialize : function($super, varname, value, expression) { <ide> this.varname = varname; <ide> }, <ide> replay : function() { <ide> this.out(Event.dirty()); <del> this.out(this.latestEvent); <del> this.out(Event.ready()); <add> if (this.latestEvent) { <add> this.out(this.latestEvent); <add> this.out(Event.ready()); <add> } <ide> }, <ide> setClosure : function(closure) { <ide> this.streams.forEach(function(stream) {
Java
apache-2.0
61f04283ef2a7140854328b455debd0eac75df19
0
HtmlUnit/selenium,joshmgrant/selenium,HtmlUnit/selenium,valfirst/selenium,titusfortner/selenium,SeleniumHQ/selenium,titusfortner/selenium,SeleniumHQ/selenium,joshmgrant/selenium,SeleniumHQ/selenium,titusfortner/selenium,joshmgrant/selenium,HtmlUnit/selenium,SeleniumHQ/selenium,joshmgrant/selenium,valfirst/selenium,valfirst/selenium,HtmlUnit/selenium,HtmlUnit/selenium,valfirst/selenium,SeleniumHQ/selenium,valfirst/selenium,titusfortner/selenium,SeleniumHQ/selenium,titusfortner/selenium,valfirst/selenium,titusfortner/selenium,titusfortner/selenium,titusfortner/selenium,HtmlUnit/selenium,HtmlUnit/selenium,valfirst/selenium,valfirst/selenium,valfirst/selenium,titusfortner/selenium,valfirst/selenium,joshmgrant/selenium,valfirst/selenium,joshmgrant/selenium,titusfortner/selenium,joshmgrant/selenium,joshmgrant/selenium,joshmgrant/selenium,SeleniumHQ/selenium,SeleniumHQ/selenium,joshmgrant/selenium,titusfortner/selenium,SeleniumHQ/selenium,SeleniumHQ/selenium,joshmgrant/selenium,HtmlUnit/selenium,HtmlUnit/selenium,HtmlUnit/selenium,SeleniumHQ/selenium
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.openqa.selenium.docker.v1_40; import org.openqa.selenium.docker.DockerException; import org.openqa.selenium.docker.internal.Reference; import org.openqa.selenium.internal.Require; import org.openqa.selenium.json.Json; import org.openqa.selenium.remote.http.Contents; import org.openqa.selenium.remote.http.HttpHandler; import org.openqa.selenium.remote.http.HttpRequest; import org.openqa.selenium.remote.http.HttpResponse; import java.util.Map; import java.util.logging.Logger; import static org.openqa.selenium.json.Json.JSON_UTF_8; import static org.openqa.selenium.json.Json.MAP_TYPE; import static org.openqa.selenium.remote.http.HttpMethod.POST; class PullImage { private static final Json JSON = new Json(); private static final Logger LOG = Logger.getLogger(PullImage.class.getName()); private final HttpHandler client; public PullImage(HttpHandler client) { this.client = Require.nonNull("HTTP client", client); } public void apply(Reference ref) { Require.nonNull("Reference to pull", ref); LOG.info("Pulling " + ref); String image = String.format("%s/%s/%s", ref.getDomain(), ref.getRepository(), ref.getName()); HttpRequest req = new HttpRequest(POST, "/v1.40/images/create") .addHeader("Content-Type", JSON_UTF_8) .addHeader("Content-Length", "0") .addQueryParameter("fromImage", image); if (ref.getDigest() != null) { req.addQueryParameter("tag", ref.getDigest()); } else if (ref.getTag() != null) { req.addQueryParameter("tag", ref.getTag()); } HttpResponse res = client.execute(req); LOG.info("Have response from server"); if (!res.isSuccessful()) { String message = "Unable to pull image: " + ref.getFamiliarName(); try { Map<String, Object> value = JSON.toType(Contents.string(res), MAP_TYPE); message = (String) value.get("message"); } catch (Exception e) { // fall through } throw new DockerException(message); } } }
java/server/src/org/openqa/selenium/docker/v1_40/PullImage.java
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.openqa.selenium.docker.v1_40; import org.openqa.selenium.docker.DockerException; import org.openqa.selenium.docker.internal.Reference; import org.openqa.selenium.internal.Require; import org.openqa.selenium.json.Json; import org.openqa.selenium.remote.http.Contents; import org.openqa.selenium.remote.http.HttpHandler; import org.openqa.selenium.remote.http.HttpRequest; import org.openqa.selenium.remote.http.HttpResponse; import java.util.Map; import java.util.logging.Logger; import static org.openqa.selenium.json.Json.JSON_UTF_8; import static org.openqa.selenium.json.Json.MAP_TYPE; import static org.openqa.selenium.remote.http.HttpMethod.POST; class PullImage { private static final Json JSON = new Json(); private static final Logger LOG = Logger.getLogger(PullImage.class.getName()); private final HttpHandler client; public PullImage(HttpHandler client) { this.client = Require.nonNull("HTTP client", client); } public void apply(Reference ref) { Require.nonNull("Reference to pull", ref); LOG.info("Pulling " + ref); HttpRequest req = new HttpRequest(POST, "/v1.40/images/create") .addHeader("Content-Type", JSON_UTF_8) .addHeader("Content-Length", "0") .addQueryParameter("fromImage", String.format("%s/%s", ref.getRepository(), ref.getName())); if (ref.getDigest() != null) { req.addQueryParameter("tag", ref.getDigest()); } else if (ref.getTag() != null) { req.addQueryParameter("tag", ref.getTag()); } HttpResponse res = client.execute(req); LOG.info("Have response from server"); if (!res.isSuccessful()) { String message = "Unable to pull image: " + ref.getFamiliarName(); try { Map<String, Object> value = JSON.toType(Contents.string(res), MAP_TYPE); message = (String) value.get("message"); } catch (Exception e) { // fall through } throw new DockerException(message); } } }
[grid] Pulling images from custom registries Fixes https://github.com/SeleniumHQ/docker-selenium/issues/1264
java/server/src/org/openqa/selenium/docker/v1_40/PullImage.java
[grid] Pulling images from custom registries
<ide><path>ava/server/src/org/openqa/selenium/docker/v1_40/PullImage.java <ide> <ide> LOG.info("Pulling " + ref); <ide> <add> String image = String.format("%s/%s/%s", ref.getDomain(), ref.getRepository(), ref.getName()); <ide> HttpRequest req = new HttpRequest(POST, "/v1.40/images/create") <ide> .addHeader("Content-Type", JSON_UTF_8) <ide> .addHeader("Content-Length", "0") <del> .addQueryParameter("fromImage", String.format("%s/%s", ref.getRepository(), ref.getName())); <add> .addQueryParameter("fromImage", image); <ide> <ide> if (ref.getDigest() != null) { <ide> req.addQueryParameter("tag", ref.getDigest());
Java
epl-1.0
9a52fe336e4dfa5f782f7fd8385699cf09b75c32
0
rrimmana/birt-1,sguan-actuate/birt,Charling-Huang/birt,Charling-Huang/birt,rrimmana/birt-1,Charling-Huang/birt,sguan-actuate/birt,rrimmana/birt-1,sguan-actuate/birt,Charling-Huang/birt,sguan-actuate/birt,rrimmana/birt-1,sguan-actuate/birt,rrimmana/birt-1,Charling-Huang/birt
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.data.engine.impl; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.birt.data.engine.api.IBaseDataSetDesign; import org.eclipse.birt.data.engine.api.IBaseExpression; import org.eclipse.birt.data.engine.api.IBaseQueryDefinition; import org.eclipse.birt.data.engine.api.IConditionalExpression; import org.eclipse.birt.data.engine.api.IFilterDefinition; import org.eclipse.birt.data.engine.api.IGroupDefinition; import org.eclipse.birt.data.engine.api.IJointDataSetDesign; import org.eclipse.birt.data.engine.api.IOdaDataSetDesign; import org.eclipse.birt.data.engine.api.IPreparedQuery; import org.eclipse.birt.data.engine.api.IQueryDefinition; import org.eclipse.birt.data.engine.api.IScriptDataSetDesign; import org.eclipse.birt.data.engine.api.IScriptExpression; import org.eclipse.birt.data.engine.core.DataException; import org.eclipse.birt.data.engine.expression.ExpressionCompilerUtil; import org.eclipse.birt.data.engine.i18n.ResourceConstants; import org.eclipse.birt.data.engine.impl.document.FilterDefnUtil; import org.eclipse.birt.data.engine.impl.document.GroupDefnUtil; import org.eclipse.birt.data.engine.impl.document.QueryDefnUtil; import org.eclipse.birt.data.engine.impl.document.QueryResultIDUtil; import org.eclipse.birt.data.engine.impl.document.QueryResultInfo; import org.eclipse.birt.data.engine.impl.document.RDLoad; import org.eclipse.birt.data.engine.impl.document.RDUtil; import org.eclipse.birt.data.engine.impl.document.StreamManager; /** * Create concreate class of IPreparedQuery */ class PreparedQueryUtil { /** * Creates a new instance of the proper subclass based on the type of the * query passed in. * * @param dataEngine * @param queryDefn * @param appContext * Application context map; could be null. * @return PreparedReportQuery * @throws DataException */ static IPreparedQuery newInstance( DataEngineImpl dataEngine, IQueryDefinition queryDefn, Map appContext ) throws DataException { assert dataEngine != null; assert queryDefn != null; if ( queryDefn.getQueryResultsID( ) != null ) return newIVInstance( dataEngine, queryDefn ); IBaseDataSetDesign dset = dataEngine.getDataSetDesign( queryDefn.getDataSetName( ) ); if ( dset == null ) { // In new column binding feature, when there is no data set, // it is indicated that a dummy data set needs to be created // internally. But using the dummy one, the binding expression only // can refer to row object and no other object can be refered such // as rows. if ( queryDefn.getQueryResultsID( ) == null ) return new PreparedDummyQuery( dataEngine.getContext( ), queryDefn, dataEngine.getSharedScope( ) ); } IPreparedQuery preparedQuery; if ( dset instanceof IScriptDataSetDesign ) { preparedQuery = new PreparedScriptDSQuery( dataEngine, queryDefn, dset, appContext ); } else if ( dset instanceof IOdaDataSetDesign ) { preparedQuery = new PreparedOdaDSQuery( dataEngine, queryDefn, dset, appContext ); } else if ( dset instanceof IJointDataSetDesign ) { preparedQuery = new PreparedJointDataSourceQuery( dataEngine, queryDefn, dset, appContext ); } else { throw new DataException( ResourceConstants.UNSUPPORTED_DATASET_TYPE, dset.getName( ) ); } return preparedQuery; } /** * @param dataEngine * @param queryDefn * @return * @throws DataException */ private static IPreparedQuery newIVInstance( DataEngineImpl dataEngine, IQueryDefinition queryDefn ) throws DataException { if ( runQueryOnRS( dataEngine, queryDefn ) ) return new PreparedIVQuery( dataEngine, queryDefn ); else return new PreparedIVDataSourceQuery( dataEngine, queryDefn ); } /** * Whether query is running based on the result set of report document or * the data set. * * @param dataEngine * @param queryDefn * @return true, running on result set * @throws DataException */ private static boolean runQueryOnRS( DataEngineImpl dataEngine, IQueryDefinition queryDefn ) throws DataException { if( !queryDefn.usesDetails( ) ) { queryDefn.getSorts( ).clear( ); } String queryResultID = queryDefn.getQueryResultsID( ); String rootQueryResultID = QueryResultIDUtil.get1PartID( queryResultID ); String parentQueryResultID = null; if ( rootQueryResultID != null ) parentQueryResultID = QueryResultIDUtil.get2PartID( queryResultID ); else rootQueryResultID = queryResultID; QueryResultInfo queryResultInfo = new QueryResultInfo( rootQueryResultID, parentQueryResultID, null, null, -1 ); RDLoad rdLoad = RDUtil.newLoad( dataEngine.getContext( ), queryResultInfo ); boolean runningOnRS = GroupDefnUtil.isEqualGroups( queryDefn.getGroups( ), rdLoad.loadGroupDefn( StreamManager.ROOT_STREAM, StreamManager.BASE_SCOPE ) ); if ( runningOnRS == false ) return false; runningOnRS = !hasTopBottomNInFilter( queryDefn.getFilters( ) ); if ( runningOnRS == false ) return false; runningOnRS = isCompatibleRSMap( rdLoad.loadQueryDefn( StreamManager.ROOT_STREAM, StreamManager.BASE_SCOPE ) .getResultSetExpressions( ), queryDefn.getResultSetExpressions( ) ); if ( runningOnRS == false ) return false; runningOnRS = isCompatibleSubQuery( rdLoad.loadQueryDefn( StreamManager.ROOT_STREAM, StreamManager.BASE_SCOPE ), queryDefn ); if ( runningOnRS == false ) return false; IBaseQueryDefinition qd = rdLoad.loadQueryDefn( StreamManager.ROOT_STREAM, StreamManager.BASE_SCOPE ); List filters = qd.getFilters( ); if ( FilterDefnUtil.isConflictFilter( filters, queryDefn.getFilters( ) ) ) { runningOnRS = false; FilterDefnUtil.getRealFilterList( rdLoad.loadOriginalQueryDefn( StreamManager.ROOT_STREAM, StreamManager.BASE_SCOPE ).getFilters( ), queryDefn.getFilters( ) ); } if ( runningOnRS == false ) return false; // TODO enhance me // If the following conditions hold, running on data set // 1.There are sorts that different from that of original design // 2.The query has subqueries. if ( hasSubquery( queryDefn ) ) { if ( !QueryDefnUtil.isEqualSorts( queryDefn.getSorts( ), qd.getSorts( ) ) ) { runningOnRS = false; } Collection subqueries = queryDefn.getSubqueries( ); List gps = queryDefn.getGroups( ); if ( gps != null && gps.size( ) > 0 ) { for ( int i = 0; i < gps.size( ); i++ ) { subqueries.addAll( ( (IGroupDefinition) gps.get( i ) ).getSubqueries( ) ); } } Iterator it = subqueries.iterator( ); while ( it.hasNext( ) ) { IBaseQueryDefinition query = (IBaseQueryDefinition) it.next( ); if ( !query.usesDetails( ) ) query.getSorts( ).clear( ); if ( query.getFilters( ) != null && query.getFilters( ).size( ) > 0 ) { runningOnRS = false; break; } List groups = query.getGroups( ); for ( int i = 0; i < groups.size( ); i++ ) { List groupFilters = ( (IGroupDefinition) groups.get( i ) ).getFilters( ); if ( groupFilters != null && groupFilters.size( ) > 0 ) { runningOnRS = false; break; } } if ( runningOnRS == false ) break; } } if ( runningOnRS == false ) return false; if ( queryDefn.getFilters( ) != null && queryDefn.getFilters( ).size( ) > 0 ) { if( !isFiltersEquals(filters, queryDefn.getFilters( ))) runningOnRS = queryDefn.getResultSetExpressions( ).values( ) == null || !hasAggregationOnRowObjects( queryDefn.getResultSetExpressions( ) .values( ) .iterator( ) ); } return runningOnRS; } /** * * @param oldFilter * @param newFilter * @return */ private static boolean isFiltersEquals( List oldFilter, List newFilter ) { if( oldFilter.size() != newFilter.size( )) return false; for( int i = 0; i < oldFilter.size( ); i++ ) { if( !FilterDefnUtil.isEqualFilter( (IFilterDefinition)oldFilter.get(i), (IFilterDefinition)newFilter.get(i ))) return false; } return true; } /** * @param filters * @return */ private static boolean hasTopBottomNInFilter( List filters ) { if ( filters == null || filters.size( ) == 0 ) return false; for ( int i = 0; i < filters.size( ); i++ ) { Object o = ( (IFilterDefinition) filters.get( i ) ).getExpression( ); if ( o instanceof IConditionalExpression ) { int type = ( (IConditionalExpression) o ).getOperator( ); if ( type == IConditionalExpression.OP_TOP_N || type == IConditionalExpression.OP_BOTTOM_N || type == IConditionalExpression.OP_TOP_PERCENT || type == IConditionalExpression.OP_BOTTOM_PERCENT ) return true; } } return false; } /** * @return */ private static boolean isCompatibleRSMap( Map oldMap, Map newMap ) { if ( oldMap == null ) return newMap.size( ) == 0; else if ( newMap == null ) return oldMap.size( ) == 0; if ( newMap.size( ) > oldMap.size( ) ) return false; Iterator it = newMap.keySet( ).iterator( ); while( it.hasNext( ) ) { Object key = it.next( ); Object oldObj = oldMap.get( key ); Object newObj = newMap.get( key ); if ( oldObj != null ) { if( isTwoExpressionEqual((IBaseExpression)newObj, (IBaseExpression)oldObj) ) return false; }else { return false; } } return true; } /** * * @param obj1 * @param obj2 * @return */ private static boolean isTwoExpressionEqual( IBaseExpression obj1, IBaseExpression obj2 ) { if( obj1 == null || obj2!= null ) return false; if( obj1 != null || obj2 == null ) return false; if( !obj1.getClass( ).equals( obj2.getClass( ) )) return false; if( obj1 instanceof IScriptExpression ) { return isTwoExpressionEqual( (IScriptExpression)obj1, (IScriptExpression)obj2 ); }else if ( obj1 instanceof IConditionalExpression ) { return isTwoExpressionEqual( (IConditionalExpression)obj1, (IConditionalExpression)obj2 ); } return false; } /** * Return whether two IScriptExpression instance equals. * @param obj1 * @param obj2 * @return */ private static boolean isTwoExpressionEqual( IScriptExpression obj1, IScriptExpression obj2 ) { return isTwoStringEqual( obj1.getText( ), obj2.getText( ) ) && isTwoStringEqual( obj1.getGroupName( ), obj2.getGroupName( )) && isTwoStringEqual( obj1.getText( ), obj2.getText( )) && obj1.getDataType( ) == obj2.getDataType( ); } /** * * @param obj1 * @param obj2 * @return */ private static boolean isTwoExpressionEqual( IConditionalExpression obj1, IConditionalExpression obj2 ) { if( obj1.getOperator( ) != obj2.getOperator( ) ) return false; return isTwoStringEqual( obj1.getGroupName( ), obj2.getGroupName( )) && isTwoExpressionEqual( obj1.getExpression( ), obj2.getExpression( )) && isTwoExpressionEqual( obj1.getOperand1( ), obj2.getOperand1( )) && isTwoExpressionEqual( obj1.getOperand2( ), obj2.getOperand2( )); } /** * * @param s1 * @param s2 * @return */ private static boolean isTwoStringEqual( String s1, String s2 ) { if( s1 == null && s2 != null ) return false; if( s1 != null && s2 == null ) return false; return s1.equals( s2 ); } /** * @param oldSubQuery * @param newSubQuery * @return */ private static boolean isCompatibleSubQuery( IBaseQueryDefinition oldDefn, IBaseQueryDefinition newDefn ) { boolean isComp = QueryDefnUtil.isCompatibleSQs( oldDefn.getSubqueries( ), newDefn.getSubqueries( ) ); if ( isComp == false ) return false; Iterator oldIt = oldDefn.getGroups( ).iterator( ); Iterator newIt = newDefn.getGroups( ).iterator( ); while ( newIt.hasNext( ) ) { IGroupDefinition oldGroupDefn = (IGroupDefinition) oldIt.next( ); IGroupDefinition newGroupDefn = (IGroupDefinition) newIt.next( ); isComp = QueryDefnUtil.isCompatibleSQs( oldGroupDefn.getSubqueries( ), newGroupDefn.getSubqueries( ) ); if ( isComp == false ) return false; } return true; } /** * * @param query * @return */ private static boolean hasAggregationOnRowObjects( Iterator it ) { while ( it.hasNext( ) ) { Object o = it.next( ); if ( ExpressionCompilerUtil.hasAggregationInExpr( (IBaseExpression) o ) ) { return true; } } return false; } /** * * @param qd * @return */ private static boolean hasSubquery( IQueryDefinition qd ) { assert qd != null; if ( qd.getSubqueries( ) != null && qd.getSubqueries( ).size( ) > 0 ) { return true; } if ( qd.getGroups( ) != null ) { for ( int i = 0; i < qd.getGroups( ).size( ); i++ ) { IGroupDefinition gd = (IGroupDefinition) qd.getGroups( ) .get( i ); if ( gd.getSubqueries( ) != null && gd.getSubqueries( ).size( ) > 0 ) { return true; } } } return false; } }
data/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/PreparedQueryUtil.java
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.data.engine.impl; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.birt.data.engine.api.IBaseDataSetDesign; import org.eclipse.birt.data.engine.api.IBaseExpression; import org.eclipse.birt.data.engine.api.IBaseQueryDefinition; import org.eclipse.birt.data.engine.api.IConditionalExpression; import org.eclipse.birt.data.engine.api.IFilterDefinition; import org.eclipse.birt.data.engine.api.IGroupDefinition; import org.eclipse.birt.data.engine.api.IJointDataSetDesign; import org.eclipse.birt.data.engine.api.IOdaDataSetDesign; import org.eclipse.birt.data.engine.api.IPreparedQuery; import org.eclipse.birt.data.engine.api.IQueryDefinition; import org.eclipse.birt.data.engine.api.IScriptDataSetDesign; import org.eclipse.birt.data.engine.core.DataException; import org.eclipse.birt.data.engine.expression.ExpressionCompilerUtil; import org.eclipse.birt.data.engine.i18n.ResourceConstants; import org.eclipse.birt.data.engine.impl.document.FilterDefnUtil; import org.eclipse.birt.data.engine.impl.document.GroupDefnUtil; import org.eclipse.birt.data.engine.impl.document.QueryDefnUtil; import org.eclipse.birt.data.engine.impl.document.QueryResultIDUtil; import org.eclipse.birt.data.engine.impl.document.QueryResultInfo; import org.eclipse.birt.data.engine.impl.document.RDLoad; import org.eclipse.birt.data.engine.impl.document.RDUtil; import org.eclipse.birt.data.engine.impl.document.StreamManager; /** * Create concreate class of IPreparedQuery */ class PreparedQueryUtil { /** * Creates a new instance of the proper subclass based on the type of the * query passed in. * * @param dataEngine * @param queryDefn * @param appContext * Application context map; could be null. * @return PreparedReportQuery * @throws DataException */ static IPreparedQuery newInstance( DataEngineImpl dataEngine, IQueryDefinition queryDefn, Map appContext ) throws DataException { assert dataEngine != null; assert queryDefn != null; if ( queryDefn.getQueryResultsID( ) != null ) return newIVInstance( dataEngine, queryDefn ); IBaseDataSetDesign dset = dataEngine.getDataSetDesign( queryDefn.getDataSetName( ) ); if ( dset == null ) { // In new column binding feature, when there is no data set, // it is indicated that a dummy data set needs to be created // internally. But using the dummy one, the binding expression only // can refer to row object and no other object can be refered such // as rows. if ( queryDefn.getQueryResultsID( ) == null ) return new PreparedDummyQuery( dataEngine.getContext( ), queryDefn, dataEngine.getSharedScope( ) ); } IPreparedQuery preparedQuery; if ( dset instanceof IScriptDataSetDesign ) { preparedQuery = new PreparedScriptDSQuery( dataEngine, queryDefn, dset, appContext ); } else if ( dset instanceof IOdaDataSetDesign ) { preparedQuery = new PreparedOdaDSQuery( dataEngine, queryDefn, dset, appContext ); } else if ( dset instanceof IJointDataSetDesign ) { preparedQuery = new PreparedJointDataSourceQuery( dataEngine, queryDefn, dset, appContext ); } else { throw new DataException( ResourceConstants.UNSUPPORTED_DATASET_TYPE, dset.getName( ) ); } return preparedQuery; } /** * @param dataEngine * @param queryDefn * @return * @throws DataException */ private static IPreparedQuery newIVInstance( DataEngineImpl dataEngine, IQueryDefinition queryDefn ) throws DataException { if ( runQueryOnRS( dataEngine, queryDefn ) ) return new PreparedIVQuery( dataEngine, queryDefn ); else return new PreparedIVDataSourceQuery( dataEngine, queryDefn ); } /** * Whether query is running based on the result set of report document or * the data set. * * @param dataEngine * @param queryDefn * @return true, running on result set * @throws DataException */ private static boolean runQueryOnRS( DataEngineImpl dataEngine, IQueryDefinition queryDefn ) throws DataException { if( !queryDefn.usesDetails( ) ) { queryDefn.getSorts( ).clear( ); } String queryResultID = queryDefn.getQueryResultsID( ); String rootQueryResultID = QueryResultIDUtil.get1PartID( queryResultID ); String parentQueryResultID = null; if ( rootQueryResultID != null ) parentQueryResultID = QueryResultIDUtil.get2PartID( queryResultID ); else rootQueryResultID = queryResultID; QueryResultInfo queryResultInfo = new QueryResultInfo( rootQueryResultID, parentQueryResultID, null, null, -1 ); RDLoad rdLoad = RDUtil.newLoad( dataEngine.getContext( ), queryResultInfo ); boolean runningOnRS = GroupDefnUtil.isEqualGroups( queryDefn.getGroups( ), rdLoad.loadGroupDefn( StreamManager.ROOT_STREAM, StreamManager.BASE_SCOPE ) ); if ( runningOnRS == false ) return false; runningOnRS = !hasTopBottomNInFilter( queryDefn.getFilters( ) ); if ( runningOnRS == false ) return false; runningOnRS = isCompatibleRSMap( rdLoad.loadQueryDefn( StreamManager.ROOT_STREAM, StreamManager.BASE_SCOPE ) .getResultSetExpressions( ), queryDefn.getResultSetExpressions( ) ); if ( runningOnRS == false ) return false; runningOnRS = isCompatibleSubQuery( rdLoad.loadQueryDefn( StreamManager.ROOT_STREAM, StreamManager.BASE_SCOPE ), queryDefn ); if ( runningOnRS == false ) return false; IBaseQueryDefinition qd = rdLoad.loadQueryDefn( StreamManager.ROOT_STREAM, StreamManager.BASE_SCOPE ); List filters = qd.getFilters( ); if ( FilterDefnUtil.isConflictFilter( filters, queryDefn.getFilters( ) ) ) { runningOnRS = false; FilterDefnUtil.getRealFilterList( rdLoad.loadOriginalQueryDefn( StreamManager.ROOT_STREAM, StreamManager.BASE_SCOPE ).getFilters( ), queryDefn.getFilters( ) ); } if ( runningOnRS == false ) return false; // TODO enhance me // If the following conditions hold, running on data set // 1.There are sorts that different from that of original design // 2.The query has subqueries. if ( hasSubquery( queryDefn ) ) { if ( !QueryDefnUtil.isEqualSorts( queryDefn.getSorts( ), qd.getSorts( ) ) ) { runningOnRS = false; } Collection subqueries = queryDefn.getSubqueries( ); List gps = queryDefn.getGroups( ); if ( gps != null && gps.size( ) > 0 ) { for ( int i = 0; i < gps.size( ); i++ ) { subqueries.addAll( ( (IGroupDefinition) gps.get( i ) ).getSubqueries( ) ); } } Iterator it = subqueries.iterator( ); while ( it.hasNext( ) ) { IBaseQueryDefinition query = (IBaseQueryDefinition) it.next( ); if ( !query.usesDetails( ) ) query.getSorts( ).clear( ); if ( query.getFilters( ) != null && query.getFilters( ).size( ) > 0 ) { runningOnRS = false; break; } List groups = query.getGroups( ); for ( int i = 0; i < groups.size( ); i++ ) { List groupFilters = ( (IGroupDefinition) groups.get( i ) ).getFilters( ); if ( groupFilters != null && groupFilters.size( ) > 0 ) { runningOnRS = false; break; } } if ( runningOnRS == false ) break; } } if ( runningOnRS == false ) return false; if ( queryDefn.getFilters( ) != null && queryDefn.getFilters( ).size( ) > 0 ) { if( !isFiltersEquals(filters, queryDefn.getFilters( ))) runningOnRS = queryDefn.getResultSetExpressions( ).values( ) == null || !hasAggregationOnRowObjects( queryDefn.getResultSetExpressions( ) .values( ) .iterator( ) ); } return runningOnRS; } /** * * @param oldFilter * @param newFilter * @return */ private static boolean isFiltersEquals( List oldFilter, List newFilter ) { if( oldFilter.size() != newFilter.size( )) return false; for( int i = 0; i < oldFilter.size( ); i++ ) { if( !FilterDefnUtil.isEqualFilter( (IFilterDefinition)oldFilter.get(i), (IFilterDefinition)newFilter.get(i ))) return false; } return true; } /** * @param filters * @return */ private static boolean hasTopBottomNInFilter( List filters ) { if ( filters == null || filters.size( ) == 0 ) return false; for ( int i = 0; i < filters.size( ); i++ ) { Object o = ( (IFilterDefinition) filters.get( i ) ).getExpression( ); if ( o instanceof IConditionalExpression ) { int type = ( (IConditionalExpression) o ).getOperator( ); if ( type == IConditionalExpression.OP_TOP_N || type == IConditionalExpression.OP_BOTTOM_N || type == IConditionalExpression.OP_TOP_PERCENT || type == IConditionalExpression.OP_BOTTOM_PERCENT ) return true; } } return false; } /** * @return */ private static boolean isCompatibleRSMap( Map oldMap, Map newMap ) { if ( oldMap == newMap ) return true; else if ( oldMap == null ) return newMap.size( ) == 0; else if ( newMap == null ) return oldMap.size( ) == 0; return oldMap.size( ) >= newMap.size( ); } /** * @param oldSubQuery * @param newSubQuery * @return */ private static boolean isCompatibleSubQuery( IBaseQueryDefinition oldDefn, IBaseQueryDefinition newDefn ) { boolean isComp = QueryDefnUtil.isCompatibleSQs( oldDefn.getSubqueries( ), newDefn.getSubqueries( ) ); if ( isComp == false ) return false; Iterator oldIt = oldDefn.getGroups( ).iterator( ); Iterator newIt = newDefn.getGroups( ).iterator( ); while ( newIt.hasNext( ) ) { IGroupDefinition oldGroupDefn = (IGroupDefinition) oldIt.next( ); IGroupDefinition newGroupDefn = (IGroupDefinition) newIt.next( ); isComp = QueryDefnUtil.isCompatibleSQs( oldGroupDefn.getSubqueries( ), newGroupDefn.getSubqueries( ) ); if ( isComp == false ) return false; } return true; } /** * * @param query * @return */ private static boolean hasAggregationOnRowObjects( Iterator it ) { while ( it.hasNext( ) ) { Object o = it.next( ); if ( ExpressionCompilerUtil.hasAggregationInExpr( (IBaseExpression) o ) ) { return true; } } return false; } /** * * @param qd * @return */ private static boolean hasSubquery( IQueryDefinition qd ) { assert qd != null; if ( qd.getSubqueries( ) != null && qd.getSubqueries( ).size( ) > 0 ) { return true; } if ( qd.getGroups( ) != null ) { for ( int i = 0; i < qd.getGroups( ).size( ); i++ ) { IGroupDefinition gd = (IGroupDefinition) qd.getGroups( ) .get( i ); if ( gd.getSubqueries( ) != null && gd.getSubqueries( ).size( ) > 0 ) { return true; } } } return false; } }
CheckIn: Fix 87980 IV - Aggregation UI - Exception when modifying existing aggregation defn.
data/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/PreparedQueryUtil.java
CheckIn: Fix 87980 IV - Aggregation UI - Exception when modifying existing aggregation defn.
<ide><path>ata/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/PreparedQueryUtil.java <ide> import org.eclipse.birt.data.engine.api.IPreparedQuery; <ide> import org.eclipse.birt.data.engine.api.IQueryDefinition; <ide> import org.eclipse.birt.data.engine.api.IScriptDataSetDesign; <add>import org.eclipse.birt.data.engine.api.IScriptExpression; <ide> import org.eclipse.birt.data.engine.core.DataException; <ide> import org.eclipse.birt.data.engine.expression.ExpressionCompilerUtil; <ide> import org.eclipse.birt.data.engine.i18n.ResourceConstants; <ide> */ <ide> private static boolean isCompatibleRSMap( Map oldMap, Map newMap ) <ide> { <del> if ( oldMap == newMap ) <del> return true; <del> else if ( oldMap == null ) <add> if ( oldMap == null ) <ide> return newMap.size( ) == 0; <ide> else if ( newMap == null ) <ide> return oldMap.size( ) == 0; <ide> <del> return oldMap.size( ) >= newMap.size( ); <del> } <del> <add> if ( newMap.size( ) > oldMap.size( ) ) <add> return false; <add> <add> Iterator it = newMap.keySet( ).iterator( ); <add> while( it.hasNext( ) ) <add> { <add> Object key = it.next( ); <add> Object oldObj = oldMap.get( key ); <add> Object newObj = newMap.get( key ); <add> if ( oldObj != null ) <add> { <add> if( isTwoExpressionEqual((IBaseExpression)newObj, (IBaseExpression)oldObj) ) <add> return false; <add> }else <add> { <add> return false; <add> } <add> } <add> return true; <add> } <add> <add> /** <add> * <add> * @param obj1 <add> * @param obj2 <add> * @return <add> */ <add> private static boolean isTwoExpressionEqual( IBaseExpression obj1, IBaseExpression obj2 ) <add> { <add> if( obj1 == null || obj2!= null ) <add> return false; <add> if( obj1 != null || obj2 == null ) <add> return false; <add> if( !obj1.getClass( ).equals( obj2.getClass( ) )) <add> return false; <add> <add> if( obj1 instanceof IScriptExpression ) <add> { <add> return isTwoExpressionEqual( (IScriptExpression)obj1, (IScriptExpression)obj2 ); <add> }else if ( obj1 instanceof IConditionalExpression ) <add> { <add> return isTwoExpressionEqual( (IConditionalExpression)obj1, (IConditionalExpression)obj2 ); <add> } <add> return false; <add> } <add> <add> /** <add> * Return whether two IScriptExpression instance equals. <add> * @param obj1 <add> * @param obj2 <add> * @return <add> */ <add> private static boolean isTwoExpressionEqual( IScriptExpression obj1, IScriptExpression obj2 ) <add> { <add> return isTwoStringEqual( obj1.getText( ), obj2.getText( ) ) <add> && isTwoStringEqual( obj1.getGroupName( ), obj2.getGroupName( )) <add> && isTwoStringEqual( obj1.getText( ), obj2.getText( )) <add> && obj1.getDataType( ) == obj2.getDataType( ); <add> } <add> <add> /** <add> * <add> * @param obj1 <add> * @param obj2 <add> * @return <add> */ <add> private static boolean isTwoExpressionEqual( IConditionalExpression obj1, IConditionalExpression obj2 ) <add> { <add> if( obj1.getOperator( ) != obj2.getOperator( ) ) <add> return false; <add> <add> return isTwoStringEqual( obj1.getGroupName( ), obj2.getGroupName( )) <add> && isTwoExpressionEqual( obj1.getExpression( ), obj2.getExpression( )) <add> && isTwoExpressionEqual( obj1.getOperand1( ), obj2.getOperand1( )) <add> && isTwoExpressionEqual( obj1.getOperand2( ), obj2.getOperand2( )); <add> } <add> <add> /** <add> * <add> * @param s1 <add> * @param s2 <add> * @return <add> */ <add> private static boolean isTwoStringEqual( String s1, String s2 ) <add> { <add> if( s1 == null && s2 != null ) <add> return false; <add> <add> if( s1 != null && s2 == null ) <add> return false; <add> <add> return s1.equals( s2 ); <add> } <add> <ide> /** <ide> * @param oldSubQuery <ide> * @param newSubQuery
Java
apache-2.0
487010cfb945afe15a8fc4072aac0e4d31d6962f
0
ruspl-afed/dbeaver,ruspl-afed/dbeaver,liuyuanyuan/dbeaver,AndrewKhitrin/dbeaver,liuyuanyuan/dbeaver,ruspl-afed/dbeaver,liuyuanyuan/dbeaver,liuyuanyuan/dbeaver,AndrewKhitrin/dbeaver,AndrewKhitrin/dbeaver,AndrewKhitrin/dbeaver,ruspl-afed/dbeaver,liuyuanyuan/dbeaver
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2016 Serge Rieder ([email protected]) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License (version 2) * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.jkiss.dbeaver.ui.controls.resultset; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.JobChangeAdapter; import org.eclipse.jface.action.*; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.StringConverter; import org.eclipse.jface.text.IFindReplaceTarget; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.Viewer; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.*; import org.eclipse.swt.events.*; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.*; import org.eclipse.ui.*; import org.eclipse.ui.actions.CompoundContributionItem; import org.eclipse.ui.menus.CommandContributionItem; import org.eclipse.ui.menus.CommandContributionItemParameter; import org.eclipse.ui.part.MultiPageEditorPart; import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.DBeaverPreferences; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.core.CoreCommands; import org.jkiss.dbeaver.core.CoreMessages; import org.jkiss.dbeaver.core.DBeaverCore; import org.jkiss.dbeaver.core.DBeaverUI; import org.jkiss.dbeaver.model.*; import org.jkiss.dbeaver.model.data.*; import org.jkiss.dbeaver.model.edit.DBEPersistAction; import org.jkiss.dbeaver.model.exec.*; import org.jkiss.dbeaver.model.impl.local.StatResultSet; import org.jkiss.dbeaver.model.navigator.DBNDatabaseNode; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.runtime.DBRRunnableWithProgress; import org.jkiss.dbeaver.model.runtime.VoidProgressMonitor; import org.jkiss.dbeaver.model.sql.SQLUtils; import org.jkiss.dbeaver.model.struct.*; import org.jkiss.dbeaver.model.virtual.*; import org.jkiss.dbeaver.tools.transfer.IDataTransferProducer; import org.jkiss.dbeaver.tools.transfer.database.DatabaseTransferProducer; import org.jkiss.dbeaver.tools.transfer.wizard.DataTransferWizard; import org.jkiss.dbeaver.ui.*; import org.jkiss.dbeaver.ui.actions.navigator.NavigatorHandlerObjectOpen; import org.jkiss.dbeaver.ui.controls.CImageCombo; import org.jkiss.dbeaver.ui.controls.resultset.view.EmptyPresentation; import org.jkiss.dbeaver.ui.controls.resultset.view.StatisticsPresentation; import org.jkiss.dbeaver.ui.data.IValueController; import org.jkiss.dbeaver.ui.data.managers.BaseValueManager; import org.jkiss.dbeaver.ui.dialogs.ActiveWizardDialog; import org.jkiss.dbeaver.ui.dialogs.ConfirmationDialog; import org.jkiss.dbeaver.ui.dialogs.EditTextDialog; import org.jkiss.dbeaver.ui.dialogs.struct.EditConstraintDialog; import org.jkiss.dbeaver.ui.dialogs.struct.EditDictionaryDialog; import org.jkiss.dbeaver.ui.editors.data.DatabaseDataEditor; import org.jkiss.dbeaver.ui.preferences.PrefPageDataFormat; import org.jkiss.dbeaver.ui.preferences.PrefPageDatabaseGeneral; import org.jkiss.dbeaver.utils.RuntimeUtils; import org.jkiss.utils.ArrayUtils; import org.jkiss.utils.CommonUtils; import java.lang.reflect.InvocationTargetException; import java.util.*; import java.util.List; /** * ResultSetViewer * * TODO: fix copy multiple cells - tabulation broken * TODO: links in both directions, multiple links support (context menu) * TODO: not-editable cells (struct owners in record mode) * TODO: PROBLEM. Multiple occurrences of the same struct type in a single table. * Need to make wrapper over DBSAttributeBase or something. Or maybe it is not a problem * because we search for binding by attribute only in constraints and for unique key columns which are unique? * But what PK has struct type? * */ public class ResultSetViewer extends Viewer implements DBPContextProvider, IResultSetController, ISaveablePart2, IAdaptable { private static final Log log = Log.getLog(ResultSetViewer.class); public static final String SETTINGS_SECTION_PRESENTATIONS = "presentations"; @NotNull private static IResultSetFilterManager filterManager = new SimpleFilterManager(); @NotNull private final IWorkbenchPartSite site; private final Composite viewerPanel; private ResultSetFilterPanel filtersPanel; private SashForm viewerSash; private CTabFolder panelFolder; private ToolBarManager panelToolBar; private final Composite presentationPanel; private Text statusLabel; private final DynamicFindReplaceTarget findReplaceTarget; // Presentation @NotNull private IResultSetPresentation activePresentation; private ResultSetPresentationDescriptor activePresentationDescriptor; private List<ResultSetPresentationDescriptor> availablePresentations; private PresentationSwitchCombo presentationSwitchCombo; private final List<ResultSetPanelDescriptor> availablePanels = new ArrayList<>(); private final Map<ResultSetPresentationDescriptor, PresentationSettings> presentationSettings = new HashMap<>(); private final Map<String, IResultSetPanel> activePanels = new HashMap<>(); @NotNull private final IResultSetContainer container; @NotNull private final ResultSetDataReceiver dataReceiver; private ToolBarManager mainToolbar; // Current row/col number @Nullable private ResultSetRow curRow; // Mode private boolean recordMode; private final List<IResultSetListener> listeners = new ArrayList<>(); private volatile ResultSetDataPumpJob dataPumpJob; private final ResultSetModel model = new ResultSetModel(); private HistoryStateItem curState = null; private final List<HistoryStateItem> stateHistory = new ArrayList<>(); private int historyPosition = -1; private final IDialogSettings viewerSettings; private final Color colorRed; private boolean actionsDisabled; public ResultSetViewer(@NotNull Composite parent, @NotNull IWorkbenchPartSite site, @NotNull IResultSetContainer container) { super(); this.site = site; this.recordMode = false; this.container = container; this.dataReceiver = new ResultSetDataReceiver(this); this.colorRed = Display.getDefault().getSystemColor(SWT.COLOR_RED); this.viewerSettings = UIUtils.getDialogSettings(ResultSetViewer.class.getSimpleName()); loadPresentationSettings(); this.viewerPanel = UIUtils.createPlaceholder(parent, 1); UIUtils.setHelp(this.viewerPanel, IHelpContextIds.CTX_RESULT_SET_VIEWER); this.filtersPanel = new ResultSetFilterPanel(this); this.findReplaceTarget = new DynamicFindReplaceTarget(); this.viewerSash = UIUtils.createPartDivider(site.getPart(), viewerPanel, SWT.HORIZONTAL | SWT.SMOOTH); this.viewerSash.setLayoutData(new GridData(GridData.FILL_BOTH)); this.presentationPanel = UIUtils.createPlaceholder(this.viewerSash, 1); this.presentationPanel.setLayoutData(new GridData(GridData.FILL_BOTH)); this.panelFolder = new CTabFolder(this.viewerSash, SWT.FLAT | SWT.TOP); this.panelFolder.marginWidth = 0; this.panelFolder.marginHeight = 0; this.panelFolder.setMinimizeVisible(true); this.panelFolder.setMRUVisible(true); this.panelFolder.setLayoutData(new GridData(GridData.FILL_BOTH)); this.panelToolBar = new ToolBarManager(SWT.HORIZONTAL | SWT.RIGHT | SWT.FLAT); ToolBar panelToolbarControl = this.panelToolBar.createControl(panelFolder); this.panelFolder.setTopRight(panelToolbarControl, SWT.RIGHT | SWT.WRAP); this.panelFolder.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { CTabItem activeTab = panelFolder.getSelection(); if (activeTab != null) { setActivePanel((String) activeTab.getData()); } } }); this.panelFolder.addListener(SWT.Resize, new Listener() { @Override public void handleEvent(Event event) { if (!viewerSash.isDisposed()) { int[] weights = viewerSash.getWeights(); getPresentationSettings().panelRatio = weights[1]; } } }); this.panelFolder.addCTabFolder2Listener(new CTabFolder2Adapter() { @Override public void close(CTabFolderEvent event) { CTabItem item = (CTabItem) event.item; String panelId = (String) item.getData(); removePanel(panelId); } @Override public void minimize(CTabFolderEvent event) { showPanels(false); } @Override public void maximize(CTabFolderEvent event) { } }); setActivePresentation(new EmptyPresentation()); createStatusBar(); this.viewerPanel.addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { dispose(); } }); changeMode(false); } @Override @NotNull public IResultSetContainer getContainer() { return container; } //////////////////////////////////////////////////////////// // Filters boolean supportsDataFilter() { DBSDataContainer dataContainer = getDataContainer(); return dataContainer != null && (dataContainer.getSupportedFeatures() & DBSDataContainer.DATA_FILTER) == DBSDataContainer.DATA_FILTER; } public void resetDataFilter(boolean refresh) { setDataFilter(model.createDataFilter(), refresh); } public void updateFiltersText() { updateFiltersText(true); } private void updateFiltersText(boolean resetFilterValue) { boolean enableFilters = false; DBCExecutionContext context = getExecutionContext(); if (context != null) { if (activePresentation instanceof StatisticsPresentation) { enableFilters = false; } else { StringBuilder where = new StringBuilder(); SQLUtils.appendConditionString(model.getDataFilter(), context.getDataSource(), null, where, true); String whereCondition = where.toString().trim(); if (resetFilterValue) { filtersPanel.setFilterValue(whereCondition); if (!whereCondition.isEmpty()) { filtersPanel.addFiltersHistory(whereCondition); } } if (container.isReadyToRun() && !model.isUpdateInProgress() && model.getVisibleAttributeCount() > 0) { enableFilters = true; } } } filtersPanel.enableFilters(enableFilters); presentationSwitchCombo.combo.setEnabled(enableFilters); } public void setDataFilter(final DBDDataFilter dataFilter, boolean refreshData) { if (!model.getDataFilter().equals(dataFilter)) { //model.setDataFilter(dataFilter); if (refreshData) { refreshWithFilter(dataFilter); } else { model.setDataFilter(dataFilter); activePresentation.refreshData(true, false); updateFiltersText(); } } } //////////////////////////////////////////////////////////// // Misc @NotNull public DBPPreferenceStore getPreferenceStore() { DBCExecutionContext context = getExecutionContext(); if (context != null) { return context.getDataSource().getContainer().getPreferenceStore(); } return DBeaverCore.getGlobalPreferenceStore(); } @Override public IDialogSettings getViewerSettings() { return viewerSettings; } @NotNull @Override public Color getDefaultBackground() { return filtersPanel.getEditControl().getBackground(); } @NotNull @Override public Color getDefaultForeground() { return filtersPanel.getEditControl().getForeground(); } private void persistConfig() { DBCExecutionContext context = getExecutionContext(); if (context != null) { context.getDataSource().getContainer().persistConfiguration(); } } //////////////////////////////////////// // Presentation & panels public List<ResultSetPresentationDescriptor> getAvailablePresentations() { return availablePresentations; } @Override @NotNull public IResultSetPresentation getActivePresentation() { return activePresentation; } void updatePresentation(final DBCResultSet resultSet) { try { if (resultSet instanceof StatResultSet) { // Statistics - let's use special presentation for it availablePresentations = Collections.emptyList(); setActivePresentation(new StatisticsPresentation()); activePresentationDescriptor = null; } else { // Regular results IResultSetContext context = new IResultSetContext() { @Override public boolean supportsAttributes() { DBDAttributeBinding[] attrs = model.getAttributes(); return attrs.length > 0 && (attrs[0].getDataKind() != DBPDataKind.DOCUMENT || !CommonUtils.isEmpty(attrs[0].getNestedBindings())); } @Override public boolean supportsDocument() { return model.getDocumentAttribute() != null; } @Override public String getDocumentContentType() { DBDAttributeBinding docAttr = model.getDocumentAttribute(); return docAttr == null ? null : docAttr.getValueHandler().getValueContentType(docAttr); } }; availablePresentations = ResultSetPresentationRegistry.getInstance().getAvailablePresentations(resultSet, context); if (!availablePresentations.isEmpty()) { for (ResultSetPresentationDescriptor pd : availablePresentations) { if (pd == activePresentationDescriptor) { // Keep the same presentation return; } } String defaultPresentationId = getPreferenceStore().getString(DBeaverPreferences.RESULT_SET_PRESENTATION); ResultSetPresentationDescriptor newPresentation = null; if (!CommonUtils.isEmpty(defaultPresentationId)) { for (ResultSetPresentationDescriptor pd : availablePresentations) { if (pd.getId().equals(defaultPresentationId)) { newPresentation = pd; break; } } } if (newPresentation == null) { newPresentation = availablePresentations.get(0); } try { IResultSetPresentation instance = newPresentation.createInstance(); activePresentationDescriptor = newPresentation; setActivePresentation(instance); } catch (DBException e) { log.error(e); } } } } finally { // Update combo CImageCombo combo = presentationSwitchCombo.combo; combo.setRedraw(false); try { if (activePresentationDescriptor == null) { combo.setEnabled(false); } else { combo.setEnabled(true); combo.removeAll(); for (ResultSetPresentationDescriptor pd : availablePresentations) { combo.add(DBeaverIcons.getImage(pd.getIcon()), pd.getLabel(), null, pd); } combo.select(activePresentationDescriptor); } } finally { // Enable redraw combo.setRedraw(true); } } } private void setActivePresentation(@NotNull IResultSetPresentation presentation) { // Dispose previous presentation and panels for (Control child : presentationPanel.getChildren()) { child.dispose(); } for (CTabItem panelItem : panelFolder.getItems()) { panelItem.dispose(); } // Set new presentation activePresentation = presentation; availablePanels.clear(); activePanels.clear(); if (activePresentationDescriptor != null) { availablePanels.addAll(ResultSetPresentationRegistry.getInstance().getSupportedPanels(activePresentationDescriptor)); } activePresentation.createPresentation(this, presentationPanel); // Activate panels { boolean panelsVisible = false; int[] panelWeights = new int[]{700, 300}; if (activePresentationDescriptor != null) { PresentationSettings settings = getPresentationSettings(); panelsVisible = settings.panelsVisible; if (settings.panelRatio > 0) { panelWeights = new int[] {1000 - settings.panelRatio, settings.panelRatio}; } activateDefaultPanels(settings); } showPanels(panelsVisible); viewerSash.setWeights(panelWeights); } presentationPanel.layout(); // Update dynamic find/replace target { IFindReplaceTarget nested = null; if (presentation instanceof IAdaptable) { nested = ((IAdaptable) presentation).getAdapter(IFindReplaceTarget.class); } findReplaceTarget.setTarget(nested); } if (mainToolbar != null) { mainToolbar.update(true); } // Set focus in presentation control // Use async exec to avoid focus switch after user UI interaction (e.g. combo) Display display = getControl().getDisplay(); if (UIUtils.isParent(viewerPanel, display.getFocusControl())) { DBeaverUI.asyncExec(new Runnable() { @Override public void run() { activePresentation.getControl().setFocus(); } }); } } /** * Switch to the next presentation */ void switchPresentation() { if (availablePresentations.size() < 2) { return; } int index = availablePresentations.indexOf(activePresentationDescriptor); if (index < availablePresentations.size() - 1) { index++; } else { index = 0; } switchPresentation(availablePresentations.get(index)); } private void switchPresentation(ResultSetPresentationDescriptor selectedPresentation) { try { IResultSetPresentation instance = selectedPresentation.createInstance(); activePresentationDescriptor = selectedPresentation; setActivePresentation(instance); instance.refreshData(true, false); presentationSwitchCombo.combo.select(activePresentationDescriptor); // Save in global preferences DBeaverCore.getGlobalPreferenceStore().setValue(DBeaverPreferences.RESULT_SET_PRESENTATION, activePresentationDescriptor.getId()); savePresentationSettings(); } catch (Throwable e1) { UIUtils.showErrorDialog( viewerPanel.getShell(), "Presentation switch", "Can't switch presentation", e1); } } private void loadPresentationSettings() { IDialogSettings pSections = viewerSettings.getSection(SETTINGS_SECTION_PRESENTATIONS); if (pSections != null) { for (IDialogSettings pSection : ArrayUtils.safeArray(pSections.getSections())) { String pId = pSection.getName(); ResultSetPresentationDescriptor presentation = ResultSetPresentationRegistry.getInstance().getPresentation(pId); if (presentation == null) { log.warn("Presentation '" + pId + "' not found. "); continue; } PresentationSettings settings = new PresentationSettings(); String panelIdList = pSection.get("enabledPanelIds"); if (panelIdList != null) { Collections.addAll(settings.enabledPanelIds, panelIdList.split(",")); } settings.activePanelId = pSection.get("activePanelId"); settings.panelRatio = pSection.getInt("panelRatio"); settings.panelsVisible = pSection.getBoolean("panelsVisible"); presentationSettings.put(presentation, settings); } } } private PresentationSettings getPresentationSettings() { PresentationSettings settings = this.presentationSettings.get(activePresentationDescriptor); if (settings == null) { settings = new PresentationSettings(); this.presentationSettings.put(activePresentationDescriptor, settings); } return settings; } private void savePresentationSettings() { IDialogSettings pSections = UIUtils.getSettingsSection(viewerSettings, SETTINGS_SECTION_PRESENTATIONS); for (Map.Entry<ResultSetPresentationDescriptor, PresentationSettings> pEntry : presentationSettings.entrySet()) { if (pEntry.getKey() == null) { continue; } String pId = pEntry.getKey().getId(); PresentationSettings settings = pEntry.getValue(); IDialogSettings pSection = UIUtils.getSettingsSection(pSections, pId); pSection.put("enabledPanelIds", CommonUtils.joinStrings(",", settings.enabledPanelIds)); pSection.put("activePanelId", settings.activePanelId); pSection.put("panelRatio", settings.panelRatio); pSection.put("panelsVisible", settings.panelsVisible); } } public IResultSetPanel getVisiblePanel() { return activePanels.get(getPresentationSettings().activePanelId); } @Override public IResultSetPanel[] getActivePanels() { return activePanels.values().toArray(new IResultSetPanel[activePanels.size()]); } @Override public void activatePanel(String id, boolean setActive, boolean showPanels) { if (showPanels && !isPanelsVisible()) { showPanels(true); } PresentationSettings presentationSettings = getPresentationSettings(); IResultSetPanel panel = activePanels.get(id); if (panel != null) { CTabItem panelTab = getPanelTab(id); if (panelTab != null) { if (setActive) { panelFolder.setSelection(panelTab); presentationSettings.activePanelId = id; } return; } else { log.warn("Panel '" + id + "' tab not found"); } } // Create panel ResultSetPanelDescriptor panelDescriptor = getPanelDescriptor(id); if (panelDescriptor == null) { log.error("Panel '" + id + "' not found"); return; } try { panel = panelDescriptor.createInstance(); } catch (DBException e) { UIUtils.showErrorDialog(getSite().getShell(), "Can't show panel", "Can't create panel '" + id + "'", e); return; } activePanels.put(id, panel); // Create control and tab item Control panelControl = panel.createContents(activePresentation, panelFolder); boolean firstPanel = panelFolder.getItemCount() == 0; CTabItem panelTab = new CTabItem(panelFolder, SWT.CLOSE); panelTab.setData(id); panelTab.setText(panel.getPanelTitle()); panelTab.setImage(DBeaverIcons.getImage(panelDescriptor.getIcon())); panelTab.setToolTipText(panel.getPanelDescription()); panelTab.setControl(panelControl); if (setActive || firstPanel) { panelFolder.setSelection(panelTab); } presentationSettings.enabledPanelIds.add(id); if (setActive) { setActivePanel(id); } } private void activateDefaultPanels(PresentationSettings settings) { // Cleanup unavailable panels for (Iterator<String> iter = settings.enabledPanelIds.iterator(); iter.hasNext(); ) { if (CommonUtils.isEmpty(iter.next())) { iter.remove(); } } // Add default panels if needed if (settings.enabledPanelIds.isEmpty()) { for (ResultSetPanelDescriptor pd : availablePanels) { if (pd.isShowByDefault()) { settings.enabledPanelIds.add(pd.getId()); } } } if (!settings.enabledPanelIds.isEmpty()) { for (String panelId : settings.enabledPanelIds) { if (!CommonUtils.isEmpty(panelId)) { activatePanel(panelId, panelId.equals(settings.activePanelId), false); } } } } private void setActivePanel(String panelId) { PresentationSettings settings = getPresentationSettings(); settings.activePanelId = panelId; IResultSetPanel panel = activePanels.get(panelId); if (panel != null) { panel.activatePanel(); updatePanelActions(); } } private void removePanel(String panelId) { IResultSetPanel panel = activePanels.remove(panelId); if (panel != null) { panel.deactivatePanel(); } getPresentationSettings().enabledPanelIds.remove(panelId); if (activePanels.isEmpty()) { showPanels(false); } } private ResultSetPanelDescriptor getPanelDescriptor(String id) { for (ResultSetPanelDescriptor panel : availablePanels) { if (panel.getId().equals(id)) { return panel; } } return null; } private CTabItem getPanelTab(String panelId) { for (CTabItem tab : panelFolder.getItems()) { if (CommonUtils.equalObjects(tab.getData(), panelId)) { return tab; } } return null; } public boolean isPanelsVisible() { return viewerSash.getMaximizedControl() == null; } public void showPanels(boolean show) { if (!show) { viewerSash.setMaximizedControl(presentationPanel); } else { activateDefaultPanels(getPresentationSettings()); viewerSash.setMaximizedControl(null); updatePanelActions(); activePresentation.updateValueView(); } getPresentationSettings().panelsVisible = show; } private List<IContributionItem> fillPanelsMenu() { List<IContributionItem> items = new ArrayList<>(); for (final ResultSetPanelDescriptor panel : availablePanels) { Action panelAction = new Action(panel.getLabel(), Action.AS_CHECK_BOX) { @Override public boolean isChecked() { return activePanels.containsKey(panel.getId()); } @Override public void run() { if (isPanelsVisible() && isChecked()) { CTabItem panelTab = getPanelTab(panel.getId()); if (panelTab != null) { panelTab.dispose(); removePanel(panel.getId()); } } else { activatePanel(panel.getId(), true, true); } } }; //panelAction.setImageDescriptor(DBeaverIcons.getImageDescriptor(panel.getIcon())); items.add(new ActionContributionItem(panelAction)); } return items; } private void addDefaultPanelActions() { panelToolBar.add(new Action("View Menu", ImageDescriptor.createFromImageData(DBeaverIcons.getViewMenuImage().getImageData())) { @Override public void run() { ToolBar tb = panelToolBar.getControl(); for (ToolItem item : tb.getItems()) { if (item.getData() instanceof ActionContributionItem && ((ActionContributionItem) item.getData()).getAction() == this) { MenuManager panelMenu = new MenuManager(); for (IContributionItem menuItem : fillPanelsMenu()) { panelMenu.add(menuItem); } final Menu swtMenu = panelMenu.createContextMenu(panelToolBar.getControl()); Rectangle ib = item.getBounds(); Point displayAt = item.getParent().toDisplay(ib.x, ib.y + ib.height); swtMenu.setLocation(displayAt); swtMenu.setVisible(true); return; } } } }); } //////////////////////////////////////// // Actions public boolean isActionsDisabled() { return actionsDisabled; } @Override public void lockActionsByControl(Control lockedBy) { if (checkDoubleLock(lockedBy)) { return; } actionsDisabled = true; lockedBy.addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { actionsDisabled = false; } }); } @Override public void lockActionsByFocus(final Control lockedBy) { lockedBy.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { checkDoubleLock(lockedBy); actionsDisabled = true; } @Override public void focusLost(FocusEvent e) { actionsDisabled = false; } }); lockedBy.addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { actionsDisabled = false; } }); } private boolean checkDoubleLock(Control lockedBy) { if (actionsDisabled) { log.debug("Internal error: actions double-lock by [" + lockedBy + "]"); return true; } return false; } @Nullable @Override public <T> T getAdapter(Class<T> adapter) { if (adapter == IFindReplaceTarget.class) { return adapter.cast(findReplaceTarget); } if (adapter.isAssignableFrom(activePresentation.getClass())) { return adapter.cast(activePresentation); } // Try to get it from adapter if (activePresentation instanceof IAdaptable) { return ((IAdaptable) activePresentation).getAdapter(adapter); } return null; } public void addListener(IResultSetListener listener) { synchronized (listeners) { listeners.add(listener); } } public void removeListener(IResultSetListener listener) { synchronized (listeners) { listeners.remove(listener); } } private void updateRecordMode() { //Object state = savePresentationState(); //this.redrawData(false); activePresentation.refreshData(true, false); this.updateStatusMessage(); //restorePresentationState(state); } public void updateEditControls() { ResultSetPropertyTester.firePropertyChange(ResultSetPropertyTester.PROP_EDITABLE); ResultSetPropertyTester.firePropertyChange(ResultSetPropertyTester.PROP_CHANGED); updateToolbar(); } /** * It is a hack function. Generally all command associated widgets should be updated automatically by framework. * Freaking E4 do not do it. I've spent a couple of days fighting it. Guys, you owe me. */ private void updateToolbar() { UIUtils.updateContributionItems(mainToolbar); UIUtils.updateContributionItems(panelToolBar); } public void redrawData(boolean rowsChanged) { if (viewerPanel.isDisposed()) { return; } if (rowsChanged) { int rowCount = model.getRowCount(); if (curRow == null || curRow.getVisualNumber() >= rowCount) { curRow = rowCount == 0 ? null : model.getRow(rowCount - 1); } // Set cursor on new row if (!recordMode) { activePresentation.refreshData(false, false); this.updateFiltersText(); this.updateStatusMessage(); } else { this.updateRecordMode(); } } else { activePresentation.refreshData(false, false); } } private void createStatusBar() { UIUtils.createHorizontalLine(viewerPanel); Composite statusBar = new Composite(viewerPanel, SWT.NONE); GridData gd = new GridData(GridData.FILL_HORIZONTAL); statusBar.setLayoutData(gd); GridLayout gl = new GridLayout(4, false); gl.marginWidth = 0; gl.marginHeight = 0; //gl.marginBottom = 5; statusBar.setLayout(gl); statusLabel = new Text(statusBar, SWT.READ_ONLY); gd = new GridData(GridData.FILL_HORIZONTAL); statusLabel.setLayoutData(gd); statusLabel.addMouseListener(new MouseAdapter() { @Override public void mouseDoubleClick(MouseEvent e) { EditTextDialog.showText(site.getShell(), CoreMessages.controls_resultset_viewer_dialog_status_title, statusLabel.getText()); } }); mainToolbar = new ToolBarManager(SWT.FLAT | SWT.HORIZONTAL); // Add presentation switcher presentationSwitchCombo = new PresentationSwitchCombo(); presentationSwitchCombo.createControl(statusBar); //mainToolbar.add(presentationSwitchCombo); //mainToolbar.add(new Separator()); // handle own commands mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_APPLY_CHANGES)); mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_REJECT_CHANGES)); mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_GENERATE_SCRIPT)); mainToolbar.add(new Separator()); mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_EDIT)); mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_ADD)); mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_COPY)); mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_DELETE)); mainToolbar.add(new Separator()); mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_FIRST)); mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_PREVIOUS)); mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_NEXT)); mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_LAST)); mainToolbar.add(new Separator()); mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_FETCH_PAGE)); mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_FETCH_ALL)); // Use simple action for refresh to avoid ambiguous behaviour of F5 shortcut mainToolbar.add(new Separator()); // // FIXME: Link to standard Find/Replace action - it has to be handled by owner site // mainToolbar.add(ActionUtils.makeCommandContribution( // site, // IWorkbenchCommandConstants.EDIT_FIND_AND_REPLACE, // CommandContributionItem.STYLE_PUSH, // UIIcon.FIND_TEXT)); mainToolbar.add(new Separator()); //mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_TOGGLE_MODE, CommandContributionItem.STYLE_CHECK)); mainToolbar.add(new ToggleModeAction()); CommandContributionItem panelsAction = new CommandContributionItem(new CommandContributionItemParameter( site, "org.jkiss.dbeaver.core.resultset.panels", ResultSetCommandHandler.CMD_TOGGLE_PANELS, CommandContributionItem.STYLE_PULLDOWN)); //panelsAction. mainToolbar.add(panelsAction); mainToolbar.add(new Separator()); mainToolbar.add(new ConfigAction()); mainToolbar.createControl(statusBar); //updateEditControls(); } @Nullable public DBSDataContainer getDataContainer() { return curState != null ? curState.dataContainer : container.getDataContainer(); } //////////////////////////////////////////////////////////// // Grid/Record mode @Override public boolean isRecordMode() { return recordMode; } public void toggleMode() { changeMode(!recordMode); updateEditControls(); } private void changeMode(boolean recordMode) { //Object state = savePresentationState(); this.recordMode = recordMode; //redrawData(false); activePresentation.refreshData(true, false); activePresentation.changeMode(recordMode); updateStatusMessage(); //restorePresentationState(state); } //////////////////////////////////////////////////////////// // Misc private void dispose() { savePresentationSettings(); clearData(); if (mainToolbar != null) { try { mainToolbar.dispose(); } catch (Throwable e) { // ignore log.debug("Error disposing toolbar", e); } } } public boolean isAttributeReadOnly(DBDAttributeBinding attribute) { if (isReadOnly()) { return true; } if (!model.isAttributeReadOnly(attribute)) { return false; } boolean newRow = (curRow != null && curRow.getState() == ResultSetRow.STATE_ADDED); return !newRow; } private Object savePresentationState() { if (activePresentation instanceof IStatefulControl) { return ((IStatefulControl) activePresentation).saveState(); } else { return null; } } private void restorePresentationState(Object state) { if (activePresentation instanceof IStatefulControl) { ((IStatefulControl) activePresentation).restoreState(state); } } /////////////////////////////////////// // History List<HistoryStateItem> getStateHistory() { return stateHistory; } private void setNewState(DBSDataContainer dataContainer, @Nullable DBDDataFilter dataFilter) { // Create filter copy to avoid modifications dataFilter = new DBDDataFilter(dataFilter); // Search in history for (int i = 0; i < stateHistory.size(); i++) { HistoryStateItem item = stateHistory.get(i); if (item.dataContainer == dataContainer && CommonUtils.equalObjects(item.filter, dataFilter)) { curState = item; historyPosition = i; return; } } // Save current state in history while (historyPosition < stateHistory.size() - 1) { stateHistory.remove(stateHistory.size() - 1); } curState = new HistoryStateItem( dataContainer, dataFilter, curRow == null ? -1 : curRow.getVisualNumber()); stateHistory.add(curState); historyPosition = stateHistory.size() - 1; } public void resetHistory() { curState = null; stateHistory.clear(); historyPosition = -1; } /////////////////////////////////////// // Misc @Nullable public ResultSetRow getCurrentRow() { return curRow; } @Override public void setCurrentRow(@Nullable ResultSetRow curRow) { this.curRow = curRow; if (curState != null && curRow != null) { curState.rowNumber = curRow.getVisualNumber(); } // if (recordMode) { // updateRecordMode(); // } } /////////////////////////////////////// // Status public void setStatus(String status) { setStatus(status, false); } public void setStatus(String status, boolean error) { if (statusLabel.isDisposed()) { return; } if (error) { statusLabel.setForeground(colorRed); } else if (colorRed.equals(statusLabel.getForeground())) { statusLabel.setForeground(getDefaultForeground()); } if (status == null) { status = "???"; //$NON-NLS-1$ } statusLabel.setText(status); } public void updateStatusMessage() { if (model.getRowCount() == 0) { if (model.getVisibleAttributeCount() == 0) { setStatus(CoreMessages.controls_resultset_viewer_status_empty + getExecutionTimeMessage()); } else { setStatus(CoreMessages.controls_resultset_viewer_status_no_data + getExecutionTimeMessage()); } } else { if (recordMode) { setStatus(CoreMessages.controls_resultset_viewer_status_row + (curRow == null ? 0 : curRow.getVisualNumber() + 1) + "/" + model.getRowCount() + getExecutionTimeMessage()); } else { setStatus(String.valueOf(model.getRowCount()) + CoreMessages.controls_resultset_viewer_status_rows_fetched + getExecutionTimeMessage()); } } } private String getExecutionTimeMessage() { DBCStatistics statistics = model.getStatistics(); if (statistics == null || statistics.isEmpty()) { return ""; } return " - " + RuntimeUtils.formatExecutionTime(statistics.getTotalTime()); } /** * Sets new metadata of result set * @param attributes attributes metadata */ void setMetaData(DBDAttributeBinding[] attributes) { model.setMetaData(attributes); activePresentation.clearMetaData(); } void setData(List<Object[]> rows) { if (viewerPanel.isDisposed()) { return; } this.curRow = null; this.model.setData(rows); this.curRow = (this.model.getRowCount() > 0 ? this.model.getRow(0) : null); { if (getPreferenceStore().getBoolean(DBeaverPreferences.RESULT_SET_AUTO_SWITCH_MODE)) { boolean newRecordMode = (rows.size() == 1); if (newRecordMode != recordMode) { toggleMode(); // ResultSetPropertyTester.firePropertyChange(ResultSetPropertyTester.PROP_CAN_TOGGLE); } } } this.activePresentation.refreshData(true, false); if (recordMode) { this.updateRecordMode(); } this.updateFiltersText(); this.updateStatusMessage(); this.updateEditControls(); } void appendData(List<Object[]> rows) { model.appendData(rows); //redrawData(true); activePresentation.refreshData(false, true); setStatus(NLS.bind(CoreMessages.controls_resultset_viewer_status_rows_size, model.getRowCount(), rows.size()) + getExecutionTimeMessage()); updateEditControls(); } @Override public int promptToSaveOnClose() { if (!isDirty()) { return ISaveablePart2.YES; } int result = ConfirmationDialog.showConfirmDialog( viewerPanel.getShell(), DBeaverPreferences.CONFIRM_RS_EDIT_CLOSE, ConfirmationDialog.QUESTION_WITH_CANCEL); if (result == IDialogConstants.YES_ID) { return ISaveablePart2.YES; } else if (result == IDialogConstants.NO_ID) { rejectChanges(); return ISaveablePart2.NO; } else { return ISaveablePart2.CANCEL; } } @Override public void doSave(IProgressMonitor monitor) { applyChanges(RuntimeUtils.makeMonitor(monitor)); } public void doSave(DBRProgressMonitor monitor) { applyChanges(monitor); } @Override public void doSaveAs() { } @Override public boolean isDirty() { return model.isDirty(); } @Override public boolean isSaveAsAllowed() { return false; } @Override public boolean isSaveOnCloseNeeded() { return true; } @Override public boolean hasData() { return model.hasData(); } @Override public boolean isHasMoreData() { return getExecutionContext() != null && dataReceiver.isHasMoreData(); } @Override public boolean isReadOnly() { if (model.isUpdateInProgress() || !(activePresentation instanceof IResultSetEditor)) { return true; } DBCExecutionContext executionContext = getExecutionContext(); return executionContext == null || !executionContext.isConnected() || executionContext.getDataSource().getContainer().isConnectionReadOnly() || executionContext.getDataSource().getInfo().isReadOnlyData(); } /** * Checks that current state of result set allows to insert new rows * @return true if new rows insert is allowed */ public boolean isInsertable() { return !isReadOnly() && model.isSingleSource() && model.getVisibleAttributeCount() > 0; } public boolean isRefreshInProgress() { return dataPumpJob != null; } /////////////////////////////////////////////////////// // Context menu & filters @NotNull public static IResultSetFilterManager getFilterManager() { return filterManager; } public static void registerFilterManager(@Nullable IResultSetFilterManager filterManager) { if (filterManager == null) { filterManager = new SimpleFilterManager(); } ResultSetViewer.filterManager = filterManager; } public void showFiltersMenu() { DBDAttributeBinding curAttribute = getActivePresentation().getCurrentAttribute(); if (curAttribute == null) { return; } Control control = getActivePresentation().getControl(); Point cursorLocation = getActivePresentation().getCursorLocation(); Point location = control.getDisplay().map(control, null, cursorLocation); MenuManager menuManager = new MenuManager(); fillFiltersMenu(curAttribute, menuManager); final Menu contextMenu = menuManager.createContextMenu(control); contextMenu.setLocation(location); contextMenu.setVisible(true); } @Override public void fillContextMenu(@NotNull IMenuManager manager, @Nullable final DBDAttributeBinding attr, @Nullable final ResultSetRow row) { final DBPDataSource dataSource = getDataContainer() == null ? null : getDataContainer().getDataSource(); // Custom oldValue items final ResultSetValueController valueController; if (attr != null && row != null) { valueController = new ResultSetValueController( this, attr, row, IValueController.EditType.NONE, null); final Object value = valueController.getValue(); { // Standard items manager.add(ActionUtils.makeCommandContribution(site, IWorkbenchCommandConstants.EDIT_CUT)); manager.add(ActionUtils.makeCommandContribution(site, IWorkbenchCommandConstants.EDIT_COPY)); MenuManager extCopyMenu = new MenuManager(ActionUtils.findCommandName(CoreCommands.CMD_COPY_SPECIAL)); extCopyMenu.add(ActionUtils.makeCommandContribution(site, CoreCommands.CMD_COPY_SPECIAL)); extCopyMenu.add(new Action("Copy column name(s)") { @Override public void run() { StringBuilder buffer = new StringBuilder(); for (DBDAttributeBinding attr : getSelection().getSelectedAttributes()) { if (buffer.length() > 0) { buffer.append("\t"); } buffer.append(attr.getName()); } ResultSetUtils.copyToClipboard(buffer.toString()); } }); extCopyMenu.add(new Action("Copy row number(s)") { @Override public void run() { StringBuilder buffer = new StringBuilder(); for (ResultSetRow row : getSelection().getSelectedRows()) { if (buffer.length() > 0) { buffer.append("\n"); } buffer.append(row.getVisualNumber()); } ResultSetUtils.copyToClipboard(buffer.toString()); } }); manager.add(extCopyMenu); manager.add(ActionUtils.makeCommandContribution(site, IWorkbenchCommandConstants.EDIT_PASTE)); manager.add(ActionUtils.makeCommandContribution(site, CoreCommands.CMD_PASTE_SPECIAL)); manager.add(ActionUtils.makeCommandContribution(site, IWorkbenchCommandConstants.EDIT_DELETE)); // Edit items manager.add(new Separator()); manager.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_EDIT)); manager.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_EDIT_INLINE)); if (!valueController.isReadOnly() && !DBUtils.isNullValue(value)/* && !attr.isRequired()*/) { manager.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_CELL_SET_NULL)); } manager.add(new GroupMarker(MENU_GROUP_EDIT)); } // Menus from value handler try { manager.add(new Separator()); valueController.getValueManager().contributeActions(manager, valueController, null); } catch (Exception e) { log.error(e); } if (row.isChanged() && row.changes.containsKey(attr)) { manager.insertAfter(IResultSetController.MENU_GROUP_EDIT, ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_CELL_RESET)); } } else { valueController = null; } if (dataSource != null && attr != null && model.getVisibleAttributeCount() > 0 && !model.isUpdateInProgress()) { // Filters and View manager.add(new Separator()); { String filtersShortcut = ActionUtils.findCommandDescription(ResultSetCommandHandler.CMD_FILTER_MENU, getSite(), true); String menuName = CoreMessages.controls_resultset_viewer_action_order_filter; if (!CommonUtils.isEmpty(filtersShortcut)) { menuName += " (" + filtersShortcut + ")"; } MenuManager filtersMenu = new MenuManager( menuName, DBeaverIcons.getImageDescriptor(UIIcon.FILTER), "filters"); //$NON-NLS-1$ filtersMenu.setRemoveAllWhenShown(true); filtersMenu.addMenuListener(new IMenuListener() { @Override public void menuAboutToShow(IMenuManager manager) { fillFiltersMenu(attr, manager); } }); manager.add(filtersMenu); } { MenuManager viewMenu = new MenuManager( "View/Format", null, "view"); //$NON-NLS-1$ List<? extends DBDAttributeTransformerDescriptor> transformers = dataSource.getContainer().getApplication().getValueHandlerRegistry().findTransformers( dataSource, attr, null); if (!CommonUtils.isEmpty(transformers)) { MenuManager transformersMenu = new MenuManager("View as"); transformersMenu.setRemoveAllWhenShown(true); transformersMenu.addMenuListener(new IMenuListener() { @Override public void menuAboutToShow(IMenuManager manager) { fillAttributeTransformersMenu(manager, attr); } }); viewMenu.add(transformersMenu); } else { final Action customizeAction = new Action("View as") {}; customizeAction.setEnabled(false); viewMenu.add(customizeAction); } if (getModel().isSingleSource()) { if (valueController != null) { viewMenu.add(new SetRowColorAction(attr, valueController.getValue())); if (getModel().hasColorMapping(attr)) { viewMenu.add(new ResetRowColorAction(attr, valueController.getValue())); } } viewMenu.add(new CustomizeColorsAction(attr, row)); viewMenu.add(new Separator()); } viewMenu.add(new Action("Data formats ...") { @Override public void run() { UIUtils.showPreferencesFor( getControl().getShell(), null, PrefPageDataFormat.PAGE_ID); } }); manager.add(viewMenu); } { // Navigate MenuManager navigateMenu = new MenuManager( "Navigate", null, "navigate"); //$NON-NLS-1$ if (ActionUtils.isCommandEnabled(ResultSetCommandHandler.CMD_NAVIGATE_LINK, site)) { navigateMenu.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_NAVIGATE_LINK)); navigateMenu.add(new Separator()); } navigateMenu.add(new Separator()); navigateMenu.add(ActionUtils.makeCommandContribution(site, ITextEditorActionDefinitionIds.LINE_GOTO)); navigateMenu.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_FIRST)); navigateMenu.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_NEXT)); navigateMenu.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_PREVIOUS)); navigateMenu.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_LAST)); manager.add(navigateMenu); } { // Layout MenuManager layoutMenu = new MenuManager( "Layout", null, "layout"); //$NON-NLS-1$ layoutMenu.add(new ToggleModeAction()); layoutMenu.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_TOGGLE_PANELS)); layoutMenu.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_SWITCH_PRESENTATION)); { layoutMenu.add(new Separator()); for (IContributionItem item : fillPanelsMenu()) { layoutMenu.add(item); } } manager.add(layoutMenu); } manager.add(new Separator()); } // Fill general menu final DBSDataContainer dataContainer = getDataContainer(); if (dataContainer != null && model.hasData()) { manager.add(new Action(CoreMessages.controls_resultset_viewer_action_export, DBeaverIcons.getImageDescriptor(UIIcon.EXPORT)) { @Override public void run() { ActiveWizardDialog dialog = new ActiveWizardDialog( site.getWorkbenchWindow(), new DataTransferWizard( new IDataTransferProducer[]{ new DatabaseTransferProducer(dataContainer, model.getDataFilter())}, null ), getSelection() ); dialog.open(); } }); } manager.add(new GroupMarker(CoreCommands.GROUP_TOOLS)); if (dataContainer != null && model.hasData()) { manager.add(new Separator()); manager.add(ActionUtils.makeCommandContribution(site, IWorkbenchCommandConstants.FILE_REFRESH)); } manager.add(new Separator()); manager.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); } private class TransformerAction extends Action { private final DBDAttributeBinding attrribute; public TransformerAction(DBDAttributeBinding attr, String text, int style, boolean checked) { super(text, style); this.attrribute = attr; setChecked(checked); } @NotNull DBVTransformSettings getTransformSettings() { final DBVTransformSettings settings = DBVUtils.getTransformSettings(attrribute, true); if (settings == null) { throw new IllegalStateException("Can't get/create transformer settings for '" + attrribute.getFullyQualifiedName(DBPEvaluationContext.UI) + "'"); } return settings; } protected void saveTransformerSettings() { attrribute.getDataSource().getContainer().persistConfiguration(); refreshData(null); } } private void fillAttributeTransformersMenu(IMenuManager manager, final DBDAttributeBinding attr) { final DBSDataContainer dataContainer = getDataContainer(); if (dataContainer == null) { return; } final DBPDataSource dataSource = dataContainer.getDataSource(); final DBDRegistry registry = dataSource.getContainer().getApplication().getValueHandlerRegistry(); final DBVTransformSettings transformSettings = DBVUtils.getTransformSettings(attr, false); DBDAttributeTransformerDescriptor customTransformer = null; if (transformSettings != null && transformSettings.getCustomTransformer() != null) { customTransformer = registry.getTransformer(transformSettings.getCustomTransformer()); } List<? extends DBDAttributeTransformerDescriptor> customTransformers = registry.findTransformers(dataSource, attr, true); if (customTransformers != null && !customTransformers.isEmpty()) { manager.add(new TransformerAction( attr, "Default", IAction.AS_RADIO_BUTTON, transformSettings == null || CommonUtils.isEmpty(transformSettings.getCustomTransformer())) { @Override public void run() { if (isChecked()) { getTransformSettings().setCustomTransformer(null); saveTransformerSettings(); } } }); for (final DBDAttributeTransformerDescriptor descriptor : customTransformers) { final TransformerAction action = new TransformerAction( attr, descriptor.getName(), IAction.AS_RADIO_BUTTON, transformSettings != null && descriptor.getId().equals(transformSettings.getCustomTransformer())) { @Override public void run() { if (isChecked()) { final DBVTransformSettings settings = getTransformSettings(); final String oldCustomTransformer = settings.getCustomTransformer(); settings.setCustomTransformer(descriptor.getId()); TransformerSettingsDialog settingsDialog = new TransformerSettingsDialog( ResultSetViewer.this, attr, settings); if (settingsDialog.open() == IDialogConstants.OK_ID) { saveTransformerSettings(); } else { settings.setCustomTransformer(oldCustomTransformer); } } } }; manager.add(action); } } if (customTransformer != null && !CommonUtils.isEmpty(customTransformer.getProperties())) { manager.add(new TransformerAction(attr, "Settings ...", IAction.AS_UNSPECIFIED, false) { @Override public void run() { TransformerSettingsDialog settingsDialog = new TransformerSettingsDialog( ResultSetViewer.this, attr, transformSettings); if (settingsDialog.open() == IDialogConstants.OK_ID) { saveTransformerSettings(); } } }); } List<? extends DBDAttributeTransformerDescriptor> applicableTransformers = registry.findTransformers(dataSource, attr, false); if (applicableTransformers != null) { manager.add(new Separator()); for (final DBDAttributeTransformerDescriptor descriptor : applicableTransformers) { boolean checked; if (transformSettings != null) { if (descriptor.isApplicableByDefault()) { checked = !transformSettings.isExcluded(descriptor.getId()); } else { checked = transformSettings.isIncluded(descriptor.getId()); } } else { checked = descriptor.isApplicableByDefault(); } manager.add(new TransformerAction(attr, descriptor.getName(), IAction.AS_CHECK_BOX, checked) { @Override public void run() { getTransformSettings().enableTransformer(descriptor, !isChecked()); saveTransformerSettings(); } }); } } } private void fillFiltersMenu(@NotNull DBDAttributeBinding attribute, @NotNull IMenuManager filtersMenu) { if (supportsDataFilter()) { //filtersMenu.add(new FilterByListAction(operator, type, attribute)); DBCLogicalOperator[] operators = attribute.getValueHandler().getSupportedOperators(attribute); // Operators with multiple inputs for (DBCLogicalOperator operator : operators) { if (operator.getArgumentCount() < 0) { filtersMenu.add(new FilterByAttributeAction(operator, FilterByAttributeType.INPUT, attribute)); } } filtersMenu.add(new Separator()); // Operators with no inputs for (DBCLogicalOperator operator : operators) { if (operator.getArgumentCount() == 0) { filtersMenu.add(new FilterByAttributeAction(operator, FilterByAttributeType.NONE, attribute)); } } for (FilterByAttributeType type : FilterByAttributeType.values()) { if (type == FilterByAttributeType.NONE) { // Value filters are available only if certain cell is selected continue; } filtersMenu.add(new Separator()); if (type.getValue(this, attribute, DBCLogicalOperator.EQUALS, true) == null) { // Null cell value - no operators can be applied continue; } for (DBCLogicalOperator operator : operators) { if (operator.getArgumentCount() > 0) { filtersMenu.add(new FilterByAttributeAction(operator, type, attribute)); } } } filtersMenu.add(new Separator()); DBDAttributeConstraint constraint = model.getDataFilter().getConstraint(attribute); if (constraint != null && constraint.hasCondition()) { filtersMenu.add(new FilterResetAttributeAction(attribute)); } } filtersMenu.add(new Separator()); filtersMenu.add(new ToggleServerSideOrderingAction()); filtersMenu.add(new ShowFiltersAction(true)); } @Override public void navigateAssociation(@NotNull DBRProgressMonitor monitor, @NotNull DBDAttributeBinding attr, @NotNull ResultSetRow row, boolean newWindow) throws DBException { if (getExecutionContext() == null) { throw new DBException("Not connected"); } DBSEntityAssociation association = null; List<DBSEntityReferrer> referrers = attr.getReferrers(); if (referrers != null) { for (final DBSEntityReferrer referrer : referrers) { if (referrer instanceof DBSEntityAssociation) { association = (DBSEntityAssociation) referrer; break; } } } if (association == null) { throw new DBException("Association not found in attribute [" + attr.getName() + "]"); } DBSEntityConstraint refConstraint = association.getReferencedConstraint(); if (refConstraint == null) { throw new DBException("Broken association (referenced constraint missing)"); } if (!(refConstraint instanceof DBSEntityReferrer)) { throw new DBException("Referenced constraint [" + refConstraint + "] is not a referrer"); } DBSEntity targetEntity = refConstraint.getParentObject(); if (targetEntity == null) { throw new DBException("Null constraint parent"); } if (!(targetEntity instanceof DBSDataContainer)) { throw new DBException("Entity [" + DBUtils.getObjectFullName(targetEntity, DBPEvaluationContext.UI) + "] is not a data container"); } // make constraints List<DBDAttributeConstraint> constraints = new ArrayList<>(); int visualPosition = 0; // Set conditions List<? extends DBSEntityAttributeRef> ownAttrs = CommonUtils.safeList(((DBSEntityReferrer) association).getAttributeReferences(monitor)); List<? extends DBSEntityAttributeRef> refAttrs = CommonUtils.safeList(((DBSEntityReferrer) refConstraint).getAttributeReferences(monitor)); if (ownAttrs.size() != refAttrs.size()) { throw new DBException( "Entity [" + DBUtils.getObjectFullName(targetEntity, DBPEvaluationContext.UI) + "] association [" + association.getName() + "] columns differs from referenced constraint [" + refConstraint.getName() + "] (" + ownAttrs.size() + "<>" + refAttrs.size() + ")"); } // Add association constraints for (int i = 0; i < ownAttrs.size(); i++) { DBSEntityAttributeRef ownAttr = ownAttrs.get(i); DBSEntityAttributeRef refAttr = refAttrs.get(i); DBDAttributeBinding ownBinding = model.getAttributeBinding(ownAttr.getAttribute()); assert ownBinding != null; DBDAttributeConstraint constraint = new DBDAttributeConstraint(refAttr.getAttribute(), visualPosition++); constraint.setVisible(true); constraints.add(constraint); Object keyValue = model.getCellValue(ownBinding, row); constraint.setOperator(DBCLogicalOperator.EQUALS); constraint.setValue(keyValue); } DBDDataFilter newFilter = new DBDDataFilter(constraints); if (newWindow) { openResultsInNewWindow(monitor, targetEntity, newFilter); } else { runDataPump((DBSDataContainer) targetEntity, newFilter, 0, getSegmentMaxRows(), -1, null); } } private void openResultsInNewWindow(DBRProgressMonitor monitor, DBSEntity targetEntity, final DBDDataFilter newFilter) { final DBNDatabaseNode targetNode = getExecutionContext().getDataSource().getContainer().getApplication().getNavigatorModel().getNodeByObject(monitor, targetEntity, false); if (targetNode == null) { UIUtils.showMessageBox(null, "Open link", "Can't navigate to '" + DBUtils.getObjectFullName(targetEntity, DBPEvaluationContext.UI) + "' - navigator node not found", SWT.ICON_ERROR); return; } DBeaverUI.asyncExec(new Runnable() { @Override public void run() { openNewDataEditor(targetNode, newFilter); } }); } @Override public int getHistoryPosition() { return historyPosition; } @Override public int getHistorySize() { return stateHistory.size(); } @Override public void navigateHistory(int position) { if (position < 0 || position >= stateHistory.size()) { // out of range log.debug("Wrong history position: " + position); return; } HistoryStateItem state = stateHistory.get(position); int segmentSize = getSegmentMaxRows(); if (state.rowNumber >= 0 && state.rowNumber >= segmentSize && segmentSize > 0) { segmentSize = (state.rowNumber / segmentSize + 1) * segmentSize; } runDataPump(state.dataContainer, state.filter, 0, segmentSize, state.rowNumber, null); } @Override public void updatePanelsContent() { updateEditControls(); for (IResultSetPanel panel : getActivePanels()) { panel.refresh(); } } @Override public void updatePanelActions() { IResultSetPanel visiblePanel = getVisiblePanel(); panelToolBar.removeAll(); if (visiblePanel != null) { visiblePanel.contributeActions(panelToolBar); } addDefaultPanelActions(); panelToolBar.update(true); } @Override public Composite getControl() { return this.viewerPanel; } @NotNull @Override public IWorkbenchPartSite getSite() { return site; } @Override @NotNull public ResultSetModel getModel() { return model; } @Override public ResultSetModel getInput() { return model; } @Override public void setInput(Object input) { throw new IllegalArgumentException("ResultSet model can't be changed"); } @Override @NotNull public IResultSetSelection getSelection() { if (activePresentation instanceof ISelectionProvider) { ISelection selection = ((ISelectionProvider) activePresentation).getSelection(); if (selection instanceof IResultSetSelection) { return (IResultSetSelection) selection; } else { log.debug("Bad selection type (" + selection + ") in presentation " + activePresentation); } } return new EmptySelection(); } @Override public void setSelection(ISelection selection, boolean reveal) { if (activePresentation instanceof ISelectionProvider) { ((ISelectionProvider) activePresentation).setSelection(selection); } } @NotNull @Override public DBDDataReceiver getDataReceiver() { return dataReceiver; } @Nullable @Override public DBCExecutionContext getExecutionContext() { return container.getExecutionContext(); } @Override public void refresh() { // Check if we are dirty if (isDirty()) { switch (promptToSaveOnClose()) { case ISaveablePart2.CANCEL: return; case ISaveablePart2.YES: // Apply changes applyChanges(null, new ResultSetPersister.DataUpdateListener() { @Override public void onUpdate(boolean success) { if (success) { DBeaverUI.asyncExec(new Runnable() { @Override public void run() { refresh(); } }); } } }); return; default: // Just ignore previous RS values break; } } // Pump data ResultSetRow oldRow = curRow; DBSDataContainer dataContainer = getDataContainer(); if (container.isReadyToRun() && dataContainer != null && dataPumpJob == null) { int segmentSize = getSegmentMaxRows(); if (oldRow != null && oldRow.getVisualNumber() >= segmentSize && segmentSize > 0) { segmentSize = (oldRow.getVisualNumber() / segmentSize + 1) * segmentSize; } runDataPump(dataContainer, null, 0, segmentSize, oldRow == null ? -1 : oldRow.getVisualNumber(), new Runnable() { @Override public void run() { activePresentation.formatData(true); } }); } else { UIUtils.showErrorDialog( null, "Error executing query", dataContainer == null ? "Viewer detached from data source" : dataPumpJob == null ? "Can't refresh after reconnect. Re-execute query." : "Previous query is still running"); } } public void refreshWithFilter(DBDDataFilter filter) { DBSDataContainer dataContainer = getDataContainer(); if (dataContainer != null) { runDataPump( dataContainer, filter, 0, getSegmentMaxRows(), -1, null); } } @Override public boolean refreshData(@Nullable Runnable onSuccess) { DBSDataContainer dataContainer = getDataContainer(); if (container.isReadyToRun() && dataContainer != null && dataPumpJob == null) { int segmentSize = getSegmentMaxRows(); if (curRow != null && curRow.getVisualNumber() >= segmentSize && segmentSize > 0) { segmentSize = (curRow.getVisualNumber() / segmentSize + 1) * segmentSize; } return runDataPump(dataContainer, null, 0, segmentSize, -1, onSuccess); } else { return false; } } public synchronized void readNextSegment() { if (!dataReceiver.isHasMoreData()) { return; } DBSDataContainer dataContainer = getDataContainer(); if (dataContainer != null && !model.isUpdateInProgress() && dataPumpJob == null) { dataReceiver.setHasMoreData(false); dataReceiver.setNextSegmentRead(true); runDataPump( dataContainer, null, model.getRowCount(), getSegmentMaxRows(), -1,//curRow == null ? -1 : curRow.getRowNumber(), // Do not reposition cursor after next segment read! null); } } @Override public void readAllData() { if (!dataReceiver.isHasMoreData()) { return; } if (ConfirmationDialog.showConfirmDialogEx( viewerPanel.getShell(), DBeaverPreferences.CONFIRM_RS_FETCH_ALL, ConfirmationDialog.QUESTION, ConfirmationDialog.WARNING) != IDialogConstants.YES_ID) { return; } DBSDataContainer dataContainer = getDataContainer(); if (dataContainer != null && !model.isUpdateInProgress() && dataPumpJob == null) { dataReceiver.setHasMoreData(false); dataReceiver.setNextSegmentRead(true); runDataPump( dataContainer, null, model.getRowCount(), -1, curRow == null ? -1 : curRow.getRowNumber(), null); } } int getSegmentMaxRows() { if (getDataContainer() == null) { return 0; } return getPreferenceStore().getInt(DBeaverPreferences.RESULT_SET_MAX_ROWS); } synchronized boolean runDataPump( @NotNull final DBSDataContainer dataContainer, @Nullable final DBDDataFilter dataFilter, final int offset, final int maxRows, final int focusRow, @Nullable final Runnable finalizer) { if (dataPumpJob != null) { UIUtils.showMessageBox(viewerPanel.getShell(), "Data read", "Data read is in progress - can't run another", SWT.ICON_WARNING); return false; } // Read data final DBDDataFilter useDataFilter = dataFilter != null ? dataFilter : (dataContainer == getDataContainer() ? model.getDataFilter() : null); Composite progressControl = viewerPanel; if (activePresentation.getControl() instanceof Composite) { progressControl = (Composite) activePresentation.getControl(); } final Object presentationState = savePresentationState(); dataPumpJob = new ResultSetDataPumpJob( dataContainer, useDataFilter, this, getExecutionContext(), progressControl); dataPumpJob.addJobChangeListener(new JobChangeAdapter() { @Override public void aboutToRun(IJobChangeEvent event) { model.setUpdateInProgress(true); DBeaverUI.asyncExec(new Runnable() { @Override public void run() { filtersPanel.enableFilters(false); } }); } @Override public void done(IJobChangeEvent event) { ResultSetDataPumpJob job = (ResultSetDataPumpJob)event.getJob(); final Throwable error = job.getError(); if (job.getStatistics() != null) { model.setStatistics(job.getStatistics()); } final Control control = getControl(); if (control.isDisposed()) { return; } DBeaverUI.asyncExec(new Runnable() { @Override public void run() { try { if (control.isDisposed()) { return; } final Shell shell = control.getShell(); if (error != null) { //setStatus(error.getMessage(), true); UIUtils.showErrorDialog( shell, "Error executing query", "Query execution failed", error); } else if (focusRow >= 0 && focusRow < model.getRowCount() && model.getVisibleAttributeCount() > 0) { // Seems to be refresh // Restore original position curRow = model.getRow(focusRow); //curAttribute = model.getVisibleAttribute(0); if (recordMode) { updateRecordMode(); } else { updateStatusMessage(); } restorePresentationState(presentationState); } activePresentation.updateValueView(); updatePanelsContent(); if (error == null) { setNewState(dataContainer, dataFilter != null ? dataFilter : (dataContainer == getDataContainer() ? model.getDataFilter() : null)); } model.setUpdateInProgress(false); if (error == null && dataFilter != null) { model.updateDataFilter(dataFilter); activePresentation.refreshData(true, false); } updateFiltersText(error == null); updateToolbar(); fireResultSetLoad(); } finally { if (finalizer != null) { try { finalizer.run(); } catch (Throwable e) { log.error(e); } } dataPumpJob = null; } } }); } }); dataPumpJob.setOffset(offset); dataPumpJob.setMaxRows(maxRows); dataPumpJob.schedule(); return true; } private void clearData() { this.model.clearData(); this.curRow = null; this.activePresentation.clearMetaData(); } @Override public boolean applyChanges(@Nullable DBRProgressMonitor monitor) { return applyChanges(monitor, null); } /** * Saves changes to database * @param monitor monitor. If null then save will be executed in async job * @param listener finish listener (may be null) */ public boolean applyChanges(@Nullable DBRProgressMonitor monitor, @Nullable ResultSetPersister.DataUpdateListener listener) { try { ResultSetPersister persister = createDataPersister(false); return persister.applyChanges(monitor, false, listener); } catch (DBException e) { UIUtils.showErrorDialog(null, "Apply changes error", "Error saving changes in database", e); return false; } } @Override public void rejectChanges() { if (!isDirty()) { return; } try { createDataPersister(true).rejectChanges(); } catch (DBException e) { log.debug(e); } } @Override public List<DBEPersistAction> generateChangesScript(@NotNull DBRProgressMonitor monitor) { try { ResultSetPersister persister = createDataPersister(false); persister.applyChanges(monitor, true, null); return persister.getScript(); } catch (DBException e) { UIUtils.showErrorDialog(null, "SQL script generate error", "Error saving changes in database", e); return Collections.emptyList(); } } @NotNull private ResultSetPersister createDataPersister(boolean skipKeySearch) throws DBException { if (!skipKeySearch && !model.isSingleSource()) { throw new DBException("Can't save data for result set from multiple sources"); } boolean needPK = false; if (!skipKeySearch) { for (ResultSetRow row : model.getAllRows()) { if (row.getState() == ResultSetRow.STATE_REMOVED || (row.getState() == ResultSetRow.STATE_NORMAL && row.isChanged())) { needPK = true; break; } } } if (needPK) { // If we have deleted or updated rows then check for unique identifier if (!checkEntityIdentifier()) { throw new DBException("No unique identifier defined"); } } return new ResultSetPersister(this); } void addNewRow(final boolean copyCurrent, boolean afterCurrent) { int rowNum = curRow == null ? 0 : curRow.getVisualNumber(); if (rowNum >= model.getRowCount()) { rowNum = model.getRowCount() - 1; } if (rowNum < 0) { rowNum = 0; } final DBCExecutionContext executionContext = getExecutionContext(); if (executionContext == null) { return; } // Add new row final DBDAttributeBinding docAttribute = model.getDocumentAttribute(); final DBDAttributeBinding[] attributes = model.getAttributes(); final Object[] cells; final int currentRowNumber = rowNum; // Copy cell values in new context try (DBCSession session = executionContext.openSession(VoidProgressMonitor.INSTANCE, DBCExecutionPurpose.UTIL, CoreMessages.controls_resultset_viewer_add_new_row_context_name)) { if (docAttribute != null) { cells = new Object[1]; if (copyCurrent && currentRowNumber >= 0 && currentRowNumber < model.getRowCount()) { Object[] origRow = model.getRowData(currentRowNumber); try { cells[0] = docAttribute.getValueHandler().getValueFromObject(session, docAttribute, origRow[0], true); } catch (DBCException e) { log.warn(e); } } if (cells[0] == null) { try { cells[0] = DBUtils.makeNullValue(session, docAttribute.getValueHandler(), docAttribute.getAttribute()); } catch (DBCException e) { log.warn(e); } } } else { cells = new Object[attributes.length]; if (copyCurrent && currentRowNumber >= 0 && currentRowNumber < model.getRowCount()) { Object[] origRow = model.getRowData(currentRowNumber); for (int i = 0; i < attributes.length; i++) { DBDAttributeBinding metaAttr = attributes[i]; DBSAttributeBase attribute = metaAttr.getAttribute(); if (attribute.isAutoGenerated() || attribute.isPseudoAttribute()) { // set pseudo and autoincrement attributes to null cells[i] = null; } else { try { cells[i] = metaAttr.getValueHandler().getValueFromObject(session, attribute, origRow[i], true); } catch (DBCException e) { log.warn(e); try { cells[i] = DBUtils.makeNullValue(session, metaAttr.getValueHandler(), attribute); } catch (DBCException e1) { log.warn(e1); } } } } } else { // Initialize new values for (int i = 0; i < attributes.length; i++) { DBDAttributeBinding metaAttr = attributes[i]; try { cells[i] = DBUtils.makeNullValue(session, metaAttr.getValueHandler(), metaAttr.getAttribute()); } catch (DBCException e) { log.warn(e); } } } } } curRow = model.addNewRow(afterCurrent ? rowNum + 1 : rowNum, cells); redrawData(true); updateEditControls(); fireResultSetChange(); } void deleteSelectedRows() { Set<ResultSetRow> rowsToDelete = new LinkedHashSet<>(); if (recordMode) { rowsToDelete.add(curRow); } else { IResultSetSelection selection = getSelection(); if (!selection.isEmpty()) { rowsToDelete.addAll(selection.getSelectedRows()); } } if (rowsToDelete.isEmpty()) { return; } int rowsRemoved = 0; int lastRowNum = -1; for (ResultSetRow row : rowsToDelete) { if (model.deleteRow(row)) { rowsRemoved++; } lastRowNum = row.getVisualNumber(); } redrawData(rowsRemoved > 0); // Move one row down (if we are in grid mode) if (!recordMode && lastRowNum < model.getRowCount() - 1 && rowsRemoved == 0) { activePresentation.scrollToRow(IResultSetPresentation.RowPosition.NEXT); } else { activePresentation.scrollToRow(IResultSetPresentation.RowPosition.CURRENT); } updateEditControls(); fireResultSetChange(); } ////////////////////////////////// // Virtual identifier management @Nullable DBDRowIdentifier getVirtualEntityIdentifier() { if (!model.isSingleSource() || model.getVisibleAttributeCount() == 0) { return null; } DBDRowIdentifier rowIdentifier = model.getVisibleAttribute(0).getRowIdentifier(); DBSEntityReferrer identifier = rowIdentifier == null ? null : rowIdentifier.getUniqueKey(); if (identifier != null && identifier instanceof DBVEntityConstraint) { return rowIdentifier; } else { return null; } } boolean checkEntityIdentifier() throws DBException { DBSEntity entity = model.getSingleSource(); if (entity == null) { UIUtils.showErrorDialog( null, "Unrecognized entity", "Can't detect source entity"); return false; } final DBCExecutionContext executionContext = getExecutionContext(); if (executionContext == null) { return false; } // Check for value locators // Probably we have only virtual one with empty attribute set final DBDRowIdentifier identifier = getVirtualEntityIdentifier(); if (identifier != null) { if (CommonUtils.isEmpty(identifier.getAttributes())) { // Empty identifier. We have to define it return new UIConfirmation() { @Override public Boolean runTask() { return ValidateUniqueKeyUsageDialog.validateUniqueKey(ResultSetViewer.this, executionContext); } }.confirm(); } } { // Check attributes of non-virtual identifier DBDRowIdentifier rowIdentifier = model.getVisibleAttribute(0).getRowIdentifier(); if (rowIdentifier == null) { // We shouldn't be here ever! // Virtual id should be created if we missing natural one UIUtils.showErrorDialog( null, "No entity identifier", "Entity " + entity.getName() + " has no unique key"); return false; } else if (CommonUtils.isEmpty(rowIdentifier.getAttributes())) { UIUtils.showErrorDialog( null, "No entity identifier", "Attributes of '" + DBUtils.getObjectFullName(rowIdentifier.getUniqueKey(), DBPEvaluationContext.UI) + "' are missing in result set"); return false; } } return true; } boolean editEntityIdentifier(DBRProgressMonitor monitor) throws DBException { DBDRowIdentifier virtualEntityIdentifier = getVirtualEntityIdentifier(); if (virtualEntityIdentifier == null) { log.warn("No virtual identifier"); return false; } DBVEntityConstraint constraint = (DBVEntityConstraint) virtualEntityIdentifier.getUniqueKey(); EditConstraintDialog dialog = new EditConstraintDialog( getControl().getShell(), "Define virtual unique identifier", constraint); if (dialog.open() != IDialogConstants.OK_ID) { return false; } Collection<DBSEntityAttribute> uniqueAttrs = dialog.getSelectedAttributes(); constraint.setAttributes(uniqueAttrs); virtualEntityIdentifier = getVirtualEntityIdentifier(); if (virtualEntityIdentifier == null) { log.warn("No virtual identifier defined"); return false; } virtualEntityIdentifier.reloadAttributes(monitor, model.getAttributes()); persistConfig(); return true; } void clearEntityIdentifier(DBRProgressMonitor monitor) throws DBException { DBDAttributeBinding firstAttribute = model.getVisibleAttribute(0); DBDRowIdentifier rowIdentifier = firstAttribute.getRowIdentifier(); if (rowIdentifier != null) { DBVEntityConstraint virtualKey = (DBVEntityConstraint) rowIdentifier.getUniqueKey(); virtualKey.setAttributes(Collections.<DBSEntityAttribute>emptyList()); rowIdentifier.reloadAttributes(monitor, model.getAttributes()); virtualKey.getParentObject().setProperty(DBVConstants.PROPERTY_USE_VIRTUAL_KEY_QUIET, null); } persistConfig(); } public void fireResultSetChange() { synchronized (listeners) { if (!listeners.isEmpty()) { for (IResultSetListener listener : listeners) { listener.handleResultSetChange(); } } } } public void fireResultSetLoad() { synchronized (listeners) { if (!listeners.isEmpty()) { for (IResultSetListener listener : listeners) { listener.handleResultSetLoad(); } } } } private static class SimpleFilterManager implements IResultSetFilterManager { private final Map<String, List<String>> filterHistory = new HashMap<>(); @NotNull @Override public List<String> getQueryFilterHistory(@NotNull String query) throws DBException { final List<String> filters = filterHistory.get(query); if (filters != null) { return filters; } return Collections.emptyList(); } @Override public void saveQueryFilterValue(@NotNull String query, @NotNull String filterValue) throws DBException { List<String> filters = filterHistory.get(query); if (filters == null) { filters = new ArrayList<>(); filterHistory.put(query, filters); } filters.add(filterValue); } @Override public void deleteQueryFilterValue(@NotNull String query, String filterValue) throws DBException { List<String> filters = filterHistory.get(query); if (filters != null) { filters.add(filterValue); } } } private class EmptySelection extends StructuredSelection implements IResultSetSelection { @NotNull @Override public IResultSetController getController() { return ResultSetViewer.this; } @NotNull @Override public Collection<DBDAttributeBinding> getSelectedAttributes() { return Collections.emptyList(); } @NotNull @Override public Collection<ResultSetRow> getSelectedRows() { return Collections.emptyList(); } @Override public DBDAttributeBinding getElementAttribute(Object element) { return null; } @Override public ResultSetRow getElementRow(Object element) { return null; } } public static class PanelsMenuContributor extends CompoundContributionItem { @Override protected IContributionItem[] getContributionItems() { final ResultSetViewer rsv = (ResultSetViewer) ResultSetCommandHandler.getActiveResultSet( DBeaverUI.getActiveWorkbenchWindow().getActivePage().getActivePart()); if (rsv == null) { return new IContributionItem[0]; } List<IContributionItem> items = rsv.fillPanelsMenu(); return items.toArray(new IContributionItem[items.size()]); } } private class ConfigAction extends Action implements IMenuCreator { public ConfigAction() { super(CoreMessages.controls_resultset_viewer_action_options, IAction.AS_DROP_DOWN_MENU); setImageDescriptor(DBeaverIcons.getImageDescriptor(UIIcon.CONFIGURATION)); } @Override public IMenuCreator getMenuCreator() { return this; } @Override public void runWithEvent(Event event) { Menu menu = getMenu(activePresentation.getControl()); if (menu != null && event.widget instanceof ToolItem) { Rectangle bounds = ((ToolItem) event.widget).getBounds(); Point point = ((ToolItem) event.widget).getParent().toDisplay(bounds.x, bounds.y + bounds.height); menu.setLocation(point.x, point.y); menu.setVisible(true); } } @Override public void dispose() { } @Override public Menu getMenu(Control parent) { MenuManager menuManager = new MenuManager(); menuManager.add(new ShowFiltersAction(false)); menuManager.add(new CustomizeColorsAction()); menuManager.add(new Separator()); menuManager.add(new VirtualKeyEditAction(true)); menuManager.add(new VirtualKeyEditAction(false)); menuManager.add(new DictionaryEditAction()); menuManager.add(new Separator()); menuManager.add(new ToggleModeAction()); activePresentation.fillMenu(menuManager); if (!CommonUtils.isEmpty(availablePresentations) && availablePresentations.size() > 1) { menuManager.add(new Separator()); for (final ResultSetPresentationDescriptor pd : availablePresentations) { Action action = new Action(pd.getLabel(), IAction.AS_RADIO_BUTTON) { @Override public boolean isEnabled() { return !isRefreshInProgress(); } @Override public boolean isChecked() { return pd == activePresentationDescriptor; } @Override public void run() { switchPresentation(pd); } }; if (pd.getIcon() != null) { //action.setImageDescriptor(ImageDescriptor.createFromImage(pd.getIcon())); } menuManager.add(action); } } menuManager.add(new Separator()); menuManager.add(new Action("Preferences") { @Override public void run() { UIUtils.showPreferencesFor( getControl().getShell(), ResultSetViewer.this, PrefPageDatabaseGeneral.PAGE_ID); } }); return menuManager.createContextMenu(parent); } @Nullable @Override public Menu getMenu(Menu parent) { return null; } } private class ShowFiltersAction extends Action { public ShowFiltersAction(boolean context) { super(context ? "Customize ..." : "Order/Filter ...", DBeaverIcons.getImageDescriptor(UIIcon.FILTER)); } @Override public void run() { new FilterSettingsDialog(ResultSetViewer.this).open(); } } private class ToggleServerSideOrderingAction extends Action { public ToggleServerSideOrderingAction() { super(CoreMessages.pref_page_database_resultsets_label_server_side_order); } @Override public int getStyle() { return AS_CHECK_BOX; } @Override public boolean isChecked() { return getPreferenceStore().getBoolean(DBeaverPreferences.RESULT_SET_ORDER_SERVER_SIDE); } @Override public void run() { DBPPreferenceStore preferenceStore = getPreferenceStore(); preferenceStore.setValue( DBeaverPreferences.RESULT_SET_ORDER_SERVER_SIDE, !preferenceStore.getBoolean(DBeaverPreferences.RESULT_SET_ORDER_SERVER_SIDE)); } } private enum FilterByAttributeType { VALUE(UIIcon.FILTER_VALUE) { @Override Object getValue(@NotNull ResultSetViewer viewer, @NotNull DBDAttributeBinding attribute, @NotNull DBCLogicalOperator operator, boolean useDefault) { final ResultSetRow row = viewer.getCurrentRow(); if (attribute == null || row == null) { return null; } Object cellValue = viewer.model.getCellValue(attribute, row); if (operator == DBCLogicalOperator.LIKE && cellValue != null) { cellValue = "%" + cellValue + "%"; } return cellValue; } }, INPUT(UIIcon.FILTER_INPUT) { @Override Object getValue(@NotNull ResultSetViewer viewer, @NotNull DBDAttributeBinding attribute, @NotNull DBCLogicalOperator operator, boolean useDefault) { if (useDefault) { return ".."; } else { ResultSetRow[] rows = null; if (operator.getArgumentCount() < 0) { Collection<ResultSetRow> selectedRows = viewer.getSelection().getSelectedRows(); rows = selectedRows.toArray(new ResultSetRow[selectedRows.size()]); } else { ResultSetRow focusRow = viewer.getCurrentRow(); if (focusRow != null) { rows = new ResultSetRow[] { focusRow }; } } if (rows == null || rows.length == 0) { return null; } FilterValueEditDialog dialog = new FilterValueEditDialog(viewer, attribute, rows, operator); if (dialog.open() == IDialogConstants.OK_ID) { return dialog.getValue(); } else { return null; } } } }, CLIPBOARD(UIIcon.FILTER_CLIPBOARD) { @Override Object getValue(@NotNull ResultSetViewer viewer, @NotNull DBDAttributeBinding attribute, @NotNull DBCLogicalOperator operator, boolean useDefault) { try { return ResultSetUtils.getAttributeValueFromClipboard(attribute); } catch (DBCException e) { log.debug("Error copying from clipboard", e); return null; } } }, NONE(UIIcon.FILTER_VALUE) { @Override Object getValue(@NotNull ResultSetViewer viewer, @NotNull DBDAttributeBinding attribute, @NotNull DBCLogicalOperator operator, boolean useDefault) { return null; } }; final ImageDescriptor icon; FilterByAttributeType(DBPImage icon) { this.icon = DBeaverIcons.getImageDescriptor(icon); } @Nullable abstract Object getValue(@NotNull ResultSetViewer viewer, @NotNull DBDAttributeBinding attribute, @NotNull DBCLogicalOperator operator, boolean useDefault); } private String translateFilterPattern(DBCLogicalOperator operator, FilterByAttributeType type, DBDAttributeBinding attribute) { Object value = type.getValue(this, attribute, operator, true); DBCExecutionContext executionContext = getExecutionContext(); String strValue = executionContext == null ? String.valueOf(value) : attribute.getValueHandler().getValueDisplayString(attribute, value, DBDDisplayFormat.UI); if (operator.getArgumentCount() == 0) { return operator.getStringValue(); } else { return operator.getStringValue() + " " + CommonUtils.truncateString(strValue, 64); } } private class FilterByAttributeAction extends Action { private final DBCLogicalOperator operator; private final FilterByAttributeType type; private final DBDAttributeBinding attribute; public FilterByAttributeAction(DBCLogicalOperator operator, FilterByAttributeType type, DBDAttributeBinding attribute) { super(attribute.getName() + " " + translateFilterPattern(operator, type, attribute), type.icon); this.operator = operator; this.type = type; this.attribute = attribute; } @Override public void run() { Object value = type.getValue(ResultSetViewer.this, attribute, operator, false); if (operator.getArgumentCount() != 0 && value == null) { return; } DBDDataFilter filter = new DBDDataFilter(model.getDataFilter()); DBDAttributeConstraint constraint = filter.getConstraint(attribute); if (constraint != null) { constraint.setOperator(operator); constraint.setValue(value); setDataFilter(filter, true); } } } private class FilterResetAttributeAction extends Action { private final DBDAttributeBinding attribute; public FilterResetAttributeAction(DBDAttributeBinding attribute) { super("Remove filter for '" + attribute.getName() + "'", DBeaverIcons.getImageDescriptor(UIIcon.REVERT)); this.attribute = attribute; } @Override public void run() { DBDDataFilter dataFilter = new DBDDataFilter(model.getDataFilter()); DBDAttributeConstraint constraint = dataFilter.getConstraint(attribute); if (constraint != null) { constraint.setCriteria(null); setDataFilter(dataFilter, true); } } } private abstract class ColorAction extends Action { protected ColorAction(String name) { super(name); } @NotNull protected DBVEntity getVirtualEntity(DBDAttributeBinding binding) { final DBSEntity entity = getModel().getSingleSource(); if (entity == null) { throw new IllegalStateException("No virtual entity for multi-source query"); } final DBVEntity vEntity = DBVUtils.findVirtualEntity(entity, true); assert vEntity != null; return vEntity; } protected void updateColors(DBVEntity entity) { model.updateColorMapping(); redrawData(false); entity.getDataSource().getContainer().persistConfiguration(); } } private class SetRowColorAction extends ColorAction { private final DBDAttributeBinding attribute; private final Object value; public SetRowColorAction(DBDAttributeBinding attr, Object value) { super("Color by " + attr.getName()); this.attribute = attr; this.value = value; } @Override public void run() { RGB color; final Shell shell = UIUtils.createCenteredShell(getControl().getShell()); try { ColorDialog cd = new ColorDialog(shell); color = cd.open(); if (color == null) { return; } } finally { shell.dispose(); } final DBVEntity vEntity = getVirtualEntity(attribute); vEntity.setColorOverride(attribute, value, null, StringConverter.asString(color)); updateColors(vEntity); } } private class ResetRowColorAction extends ColorAction { private final DBDAttributeBinding attribute; public ResetRowColorAction(DBDAttributeBinding attr, Object value) { super("Reset color by " + attr.getName()); this.attribute = attr; } @Override public void run() { final DBVEntity vEntity = getVirtualEntity(attribute); vEntity.removeColorOverride(attribute); updateColors(vEntity); } } private class CustomizeColorsAction extends ColorAction { private final DBDAttributeBinding curAttribute; private final ResultSetRow row; public CustomizeColorsAction() { this(null, null); } public CustomizeColorsAction(DBDAttributeBinding curAttribute, ResultSetRow row) { super("Row colors ..."); this.curAttribute = curAttribute; this.row = row; } @Override public void run() { ColorSettingsDialog dialog = new ColorSettingsDialog(ResultSetViewer.this, curAttribute, row); if (dialog.open() != IDialogConstants.OK_ID) { return; } final DBVEntity vEntity = getVirtualEntity(curAttribute); //vEntity.removeColorOverride(attribute); updateColors(vEntity); } @Override public boolean isEnabled() { return false; } } private class VirtualKeyEditAction extends Action { private boolean define; public VirtualKeyEditAction(boolean define) { super(define ? "Define virtual unique key" : "Clear virtual unique key"); this.define = define; } @Override public boolean isEnabled() { DBDRowIdentifier identifier = getVirtualEntityIdentifier(); return identifier != null && (define || !CommonUtils.isEmpty(identifier.getAttributes())); } @Override public void run() { DBeaverUI.runUIJob("Edit virtual key", new DBRRunnableWithProgress() { @Override public void run(DBRProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { if (define) { editEntityIdentifier(monitor); } else { clearEntityIdentifier(monitor); } } catch (DBException e) { throw new InvocationTargetException(e); } } }); } } private class DictionaryEditAction extends Action { public DictionaryEditAction() { super("Define dictionary"); } @Override public void run() { EditDictionaryDialog dialog = new EditDictionaryDialog( getSite().getShell(), "Edit dictionary", model.getSingleSource()); dialog.open(); } @Override public boolean isEnabled() { final DBSEntity singleSource = model.getSingleSource(); return singleSource != null; } } private class ToggleModeAction extends Action { { setActionDefinitionId(ResultSetCommandHandler.CMD_TOGGLE_MODE); setImageDescriptor(DBeaverIcons.getImageDescriptor(UIIcon.RS_GRID)); } public ToggleModeAction() { super("Toggle mode", Action.AS_CHECK_BOX); } @Override public boolean isChecked() { return isRecordMode(); } @Override public void run() { toggleMode(); } } private class PresentationSwitchCombo extends ContributionItem implements SelectionListener { private ToolItem toolitem; private CImageCombo combo; @Override public void fill(ToolBar parent, int index) { toolitem = new ToolItem(parent, SWT.SEPARATOR, index); Control control = createControl(parent); toolitem.setControl(control); } @Override public void fill(Composite parent) { createControl(parent); } protected Control createControl(Composite parent) { combo = new CImageCombo(parent, SWT.BORDER | SWT.DROP_DOWN | SWT.READ_ONLY); combo.add(DBeaverIcons.getImage(DBIcon.TYPE_UNKNOWN), "", null, null); final int textWidth = parent.getFont().getFontData()[0].getHeight() * 10; combo.setWidthHint(textWidth); if (toolitem != null) { toolitem.setWidth(textWidth); } combo.addSelectionListener(this); combo.setToolTipText(ActionUtils.findCommandDescription(ResultSetCommandHandler.CMD_SWITCH_PRESENTATION, getSite(), false)); return combo; } @Override public void widgetSelected(SelectionEvent e) { ResultSetPresentationDescriptor selectedPresentation = (ResultSetPresentationDescriptor) combo.getData(combo.getSelectionIndex()); if (activePresentationDescriptor == selectedPresentation) { return; } switchPresentation(selectedPresentation); } @Override public void widgetDefaultSelected(SelectionEvent e) { } } class HistoryStateItem { DBSDataContainer dataContainer; DBDDataFilter filter; int rowNumber; public HistoryStateItem(DBSDataContainer dataContainer, @Nullable DBDDataFilter filter, int rowNumber) { this.dataContainer = dataContainer; this.filter = filter; this.rowNumber = rowNumber; } public String describeState() { DBCExecutionContext context = getExecutionContext(); String desc = dataContainer.getName(); if (context != null && filter != null && filter.hasConditions()) { StringBuilder condBuffer = new StringBuilder(); SQLUtils.appendConditionString(filter, context.getDataSource(), null, condBuffer, true); desc += " [" + condBuffer + "]"; } return desc; } } static class PresentationSettings { final Set<String> enabledPanelIds = new LinkedHashSet<>(); String activePanelId; int panelRatio; boolean panelsVisible; } public static void openNewDataEditor(DBNDatabaseNode targetNode, DBDDataFilter newFilter) { IEditorPart entityEditor = NavigatorHandlerObjectOpen.openEntityEditor( targetNode, DatabaseDataEditor.class.getName(), Collections.<String, Object>singletonMap(DatabaseDataEditor.ATTR_DATA_FILTER, newFilter), DBeaverUI.getActiveWorkbenchWindow() ); if (entityEditor instanceof MultiPageEditorPart) { Object selectedPage = ((MultiPageEditorPart) entityEditor).getSelectedPage(); if (selectedPage instanceof IResultSetContainer) { ResultSetViewer rsv = (ResultSetViewer) ((IResultSetContainer) selectedPage).getResultSetController(); if (rsv != null && !rsv.isRefreshInProgress() && !newFilter.equals(rsv.getModel().getDataFilter())) { // Set filter directly rsv.refreshWithFilter(newFilter); } } } } }
plugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/ui/controls/resultset/ResultSetViewer.java
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2016 Serge Rieder ([email protected]) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License (version 2) * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.jkiss.dbeaver.ui.controls.resultset; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.JobChangeAdapter; import org.eclipse.jface.action.*; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.StringConverter; import org.eclipse.jface.text.IFindReplaceTarget; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.Viewer; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.*; import org.eclipse.swt.events.*; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.*; import org.eclipse.ui.*; import org.eclipse.ui.actions.CompoundContributionItem; import org.eclipse.ui.menus.CommandContributionItem; import org.eclipse.ui.menus.CommandContributionItemParameter; import org.eclipse.ui.part.MultiPageEditorPart; import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.DBeaverPreferences; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.core.CoreCommands; import org.jkiss.dbeaver.core.CoreMessages; import org.jkiss.dbeaver.core.DBeaverCore; import org.jkiss.dbeaver.core.DBeaverUI; import org.jkiss.dbeaver.model.*; import org.jkiss.dbeaver.model.data.*; import org.jkiss.dbeaver.model.edit.DBEPersistAction; import org.jkiss.dbeaver.model.exec.*; import org.jkiss.dbeaver.model.impl.local.StatResultSet; import org.jkiss.dbeaver.model.navigator.DBNDatabaseNode; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.runtime.DBRRunnableWithProgress; import org.jkiss.dbeaver.model.runtime.VoidProgressMonitor; import org.jkiss.dbeaver.model.sql.SQLUtils; import org.jkiss.dbeaver.model.struct.*; import org.jkiss.dbeaver.model.virtual.*; import org.jkiss.dbeaver.tools.transfer.IDataTransferProducer; import org.jkiss.dbeaver.tools.transfer.database.DatabaseTransferProducer; import org.jkiss.dbeaver.tools.transfer.wizard.DataTransferWizard; import org.jkiss.dbeaver.ui.*; import org.jkiss.dbeaver.ui.actions.navigator.NavigatorHandlerObjectOpen; import org.jkiss.dbeaver.ui.controls.CImageCombo; import org.jkiss.dbeaver.ui.controls.resultset.view.EmptyPresentation; import org.jkiss.dbeaver.ui.controls.resultset.view.StatisticsPresentation; import org.jkiss.dbeaver.ui.data.IValueController; import org.jkiss.dbeaver.ui.data.managers.BaseValueManager; import org.jkiss.dbeaver.ui.dialogs.ActiveWizardDialog; import org.jkiss.dbeaver.ui.dialogs.ConfirmationDialog; import org.jkiss.dbeaver.ui.dialogs.EditTextDialog; import org.jkiss.dbeaver.ui.dialogs.struct.EditConstraintDialog; import org.jkiss.dbeaver.ui.dialogs.struct.EditDictionaryDialog; import org.jkiss.dbeaver.ui.editors.data.DatabaseDataEditor; import org.jkiss.dbeaver.ui.preferences.PrefPageDataFormat; import org.jkiss.dbeaver.ui.preferences.PrefPageDatabaseGeneral; import org.jkiss.dbeaver.utils.RuntimeUtils; import org.jkiss.utils.ArrayUtils; import org.jkiss.utils.CommonUtils; import java.lang.reflect.InvocationTargetException; import java.util.*; import java.util.List; /** * ResultSetViewer * * TODO: fix copy multiple cells - tabulation broken * TODO: links in both directions, multiple links support (context menu) * TODO: not-editable cells (struct owners in record mode) * TODO: PROBLEM. Multiple occurrences of the same struct type in a single table. * Need to make wrapper over DBSAttributeBase or something. Or maybe it is not a problem * because we search for binding by attribute only in constraints and for unique key columns which are unique? * But what PK has struct type? * */ public class ResultSetViewer extends Viewer implements DBPContextProvider, IResultSetController, ISaveablePart2, IAdaptable { private static final Log log = Log.getLog(ResultSetViewer.class); public static final String SETTINGS_SECTION_PRESENTATIONS = "presentations"; @NotNull private static IResultSetFilterManager filterManager = new SimpleFilterManager(); @NotNull private final IWorkbenchPartSite site; private final Composite viewerPanel; private ResultSetFilterPanel filtersPanel; private SashForm viewerSash; private CTabFolder panelFolder; private ToolBarManager panelToolBar; private final Composite presentationPanel; private Text statusLabel; private final DynamicFindReplaceTarget findReplaceTarget; // Presentation @NotNull private IResultSetPresentation activePresentation; private ResultSetPresentationDescriptor activePresentationDescriptor; private List<ResultSetPresentationDescriptor> availablePresentations; private PresentationSwitchCombo presentationSwitchCombo; private final List<ResultSetPanelDescriptor> availablePanels = new ArrayList<>(); private final Map<ResultSetPresentationDescriptor, PresentationSettings> presentationSettings = new HashMap<>(); private final Map<String, IResultSetPanel> activePanels = new HashMap<>(); @NotNull private final IResultSetContainer container; @NotNull private final ResultSetDataReceiver dataReceiver; private ToolBarManager mainToolbar; // Current row/col number @Nullable private ResultSetRow curRow; // Mode private boolean recordMode; private final List<IResultSetListener> listeners = new ArrayList<>(); private volatile ResultSetDataPumpJob dataPumpJob; private final ResultSetModel model = new ResultSetModel(); private HistoryStateItem curState = null; private final List<HistoryStateItem> stateHistory = new ArrayList<>(); private int historyPosition = -1; private final IDialogSettings viewerSettings; private final Color colorRed; private boolean actionsDisabled; public ResultSetViewer(@NotNull Composite parent, @NotNull IWorkbenchPartSite site, @NotNull IResultSetContainer container) { super(); this.site = site; this.recordMode = false; this.container = container; this.dataReceiver = new ResultSetDataReceiver(this); this.colorRed = Display.getDefault().getSystemColor(SWT.COLOR_RED); this.viewerSettings = UIUtils.getDialogSettings(ResultSetViewer.class.getSimpleName()); loadPresentationSettings(); this.viewerPanel = UIUtils.createPlaceholder(parent, 1); UIUtils.setHelp(this.viewerPanel, IHelpContextIds.CTX_RESULT_SET_VIEWER); this.filtersPanel = new ResultSetFilterPanel(this); this.findReplaceTarget = new DynamicFindReplaceTarget(); this.viewerSash = UIUtils.createPartDivider(site.getPart(), viewerPanel, SWT.HORIZONTAL | SWT.SMOOTH); this.viewerSash.setLayoutData(new GridData(GridData.FILL_BOTH)); this.presentationPanel = UIUtils.createPlaceholder(this.viewerSash, 1); this.presentationPanel.setLayoutData(new GridData(GridData.FILL_BOTH)); this.panelFolder = new CTabFolder(this.viewerSash, SWT.FLAT | SWT.TOP); this.panelFolder.marginWidth = 0; this.panelFolder.marginHeight = 0; this.panelFolder.setMinimizeVisible(true); this.panelFolder.setMRUVisible(true); this.panelFolder.setLayoutData(new GridData(GridData.FILL_BOTH)); this.panelToolBar = new ToolBarManager(SWT.HORIZONTAL | SWT.RIGHT | SWT.FLAT); ToolBar panelToolbarControl = this.panelToolBar.createControl(panelFolder); this.panelFolder.setTopRight(panelToolbarControl, SWT.RIGHT | SWT.WRAP); this.panelFolder.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { CTabItem activeTab = panelFolder.getSelection(); if (activeTab != null) { setActivePanel((String) activeTab.getData()); } } }); this.panelFolder.addListener(SWT.Resize, new Listener() { @Override public void handleEvent(Event event) { if (!viewerSash.isDisposed()) { int[] weights = viewerSash.getWeights(); getPresentationSettings().panelRatio = weights[1]; } } }); this.panelFolder.addCTabFolder2Listener(new CTabFolder2Adapter() { @Override public void close(CTabFolderEvent event) { CTabItem item = (CTabItem) event.item; String panelId = (String) item.getData(); removePanel(panelId); } @Override public void minimize(CTabFolderEvent event) { showPanels(false); } @Override public void maximize(CTabFolderEvent event) { } }); setActivePresentation(new EmptyPresentation()); createStatusBar(); this.viewerPanel.addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { dispose(); } }); changeMode(false); } @Override @NotNull public IResultSetContainer getContainer() { return container; } //////////////////////////////////////////////////////////// // Filters boolean supportsDataFilter() { DBSDataContainer dataContainer = getDataContainer(); return dataContainer != null && (dataContainer.getSupportedFeatures() & DBSDataContainer.DATA_FILTER) == DBSDataContainer.DATA_FILTER; } public void resetDataFilter(boolean refresh) { setDataFilter(model.createDataFilter(), refresh); } public void updateFiltersText() { updateFiltersText(true); } private void updateFiltersText(boolean resetFilterValue) { boolean enableFilters = false; DBCExecutionContext context = getExecutionContext(); if (context != null) { if (activePresentation instanceof StatisticsPresentation) { enableFilters = false; } else { StringBuilder where = new StringBuilder(); SQLUtils.appendConditionString(model.getDataFilter(), context.getDataSource(), null, where, true); String whereCondition = where.toString().trim(); if (resetFilterValue) { filtersPanel.setFilterValue(whereCondition); if (!whereCondition.isEmpty()) { filtersPanel.addFiltersHistory(whereCondition); } } if (container.isReadyToRun() && !model.isUpdateInProgress() && model.getVisibleAttributeCount() > 0) { enableFilters = true; } } } filtersPanel.enableFilters(enableFilters); presentationSwitchCombo.combo.setEnabled(enableFilters); } public void setDataFilter(final DBDDataFilter dataFilter, boolean refreshData) { if (!model.getDataFilter().equals(dataFilter)) { //model.setDataFilter(dataFilter); if (refreshData) { refreshWithFilter(dataFilter); } else { model.setDataFilter(dataFilter); activePresentation.refreshData(true, false); updateFiltersText(); } } } //////////////////////////////////////////////////////////// // Misc @NotNull public DBPPreferenceStore getPreferenceStore() { DBCExecutionContext context = getExecutionContext(); if (context != null) { return context.getDataSource().getContainer().getPreferenceStore(); } return DBeaverCore.getGlobalPreferenceStore(); } @Override public IDialogSettings getViewerSettings() { return viewerSettings; } @NotNull @Override public Color getDefaultBackground() { return filtersPanel.getEditControl().getBackground(); } @NotNull @Override public Color getDefaultForeground() { return filtersPanel.getEditControl().getForeground(); } private void persistConfig() { DBCExecutionContext context = getExecutionContext(); if (context != null) { context.getDataSource().getContainer().persistConfiguration(); } } //////////////////////////////////////// // Presentation & panels public List<ResultSetPresentationDescriptor> getAvailablePresentations() { return availablePresentations; } @Override @NotNull public IResultSetPresentation getActivePresentation() { return activePresentation; } void updatePresentation(final DBCResultSet resultSet) { try { if (resultSet instanceof StatResultSet) { // Statistics - let's use special presentation for it availablePresentations = Collections.emptyList(); setActivePresentation(new StatisticsPresentation()); activePresentationDescriptor = null; } else { // Regular results IResultSetContext context = new IResultSetContext() { @Override public boolean supportsAttributes() { DBDAttributeBinding[] attrs = model.getAttributes(); return attrs.length > 0 && (attrs[0].getDataKind() != DBPDataKind.DOCUMENT || !CommonUtils.isEmpty(attrs[0].getNestedBindings())); } @Override public boolean supportsDocument() { return model.getDocumentAttribute() != null; } @Override public String getDocumentContentType() { DBDAttributeBinding docAttr = model.getDocumentAttribute(); return docAttr == null ? null : docAttr.getValueHandler().getValueContentType(docAttr); } }; availablePresentations = ResultSetPresentationRegistry.getInstance().getAvailablePresentations(resultSet, context); if (!availablePresentations.isEmpty()) { for (ResultSetPresentationDescriptor pd : availablePresentations) { if (pd == activePresentationDescriptor) { // Keep the same presentation return; } } String defaultPresentationId = getPreferenceStore().getString(DBeaverPreferences.RESULT_SET_PRESENTATION); ResultSetPresentationDescriptor newPresentation = null; if (!CommonUtils.isEmpty(defaultPresentationId)) { for (ResultSetPresentationDescriptor pd : availablePresentations) { if (pd.getId().equals(defaultPresentationId)) { newPresentation = pd; break; } } } if (newPresentation == null) { newPresentation = availablePresentations.get(0); } try { IResultSetPresentation instance = newPresentation.createInstance(); activePresentationDescriptor = newPresentation; setActivePresentation(instance); } catch (DBException e) { log.error(e); } } } } finally { // Update combo CImageCombo combo = presentationSwitchCombo.combo; combo.setRedraw(false); try { if (activePresentationDescriptor == null) { combo.setEnabled(false); } else { combo.setEnabled(true); combo.removeAll(); for (ResultSetPresentationDescriptor pd : availablePresentations) { combo.add(DBeaverIcons.getImage(pd.getIcon()), pd.getLabel(), null, pd); } combo.select(activePresentationDescriptor); } } finally { // Enable redraw combo.setRedraw(true); } } } private void setActivePresentation(@NotNull IResultSetPresentation presentation) { // Dispose previous presentation and panels for (Control child : presentationPanel.getChildren()) { child.dispose(); } for (CTabItem panelItem : panelFolder.getItems()) { panelItem.dispose(); } // Set new presentation activePresentation = presentation; availablePanels.clear(); activePanels.clear(); if (activePresentationDescriptor != null) { availablePanels.addAll(ResultSetPresentationRegistry.getInstance().getSupportedPanels(activePresentationDescriptor)); } activePresentation.createPresentation(this, presentationPanel); // Activate panels { boolean panelsVisible = false; int[] panelWeights = new int[]{700, 300}; if (activePresentationDescriptor != null) { PresentationSettings settings = getPresentationSettings(); panelsVisible = settings.panelsVisible; if (settings.panelRatio > 0) { panelWeights = new int[] {1000 - settings.panelRatio, settings.panelRatio}; } activateDefaultPanels(settings); } showPanels(panelsVisible); viewerSash.setWeights(panelWeights); } presentationPanel.layout(); // Update dynamic find/replace target { IFindReplaceTarget nested = null; if (presentation instanceof IAdaptable) { nested = ((IAdaptable) presentation).getAdapter(IFindReplaceTarget.class); } findReplaceTarget.setTarget(nested); } if (mainToolbar != null) { mainToolbar.update(true); } // Set focus in presentation control // Use async exec to avoid focus switch after user UI interaction (e.g. combo) Display display = getControl().getDisplay(); if (UIUtils.isParent(viewerPanel, display.getFocusControl())) { DBeaverUI.asyncExec(new Runnable() { @Override public void run() { activePresentation.getControl().setFocus(); } }); } } /** * Switch to the next presentation */ void switchPresentation() { if (availablePresentations.size() < 2) { return; } int index = availablePresentations.indexOf(activePresentationDescriptor); if (index < availablePresentations.size() - 1) { index++; } else { index = 0; } switchPresentation(availablePresentations.get(index)); } private void switchPresentation(ResultSetPresentationDescriptor selectedPresentation) { try { IResultSetPresentation instance = selectedPresentation.createInstance(); activePresentationDescriptor = selectedPresentation; setActivePresentation(instance); instance.refreshData(true, false); presentationSwitchCombo.combo.select(activePresentationDescriptor); // Save in global preferences DBeaverCore.getGlobalPreferenceStore().setValue(DBeaverPreferences.RESULT_SET_PRESENTATION, activePresentationDescriptor.getId()); savePresentationSettings(); } catch (Throwable e1) { UIUtils.showErrorDialog( viewerPanel.getShell(), "Presentation switch", "Can't switch presentation", e1); } } private void loadPresentationSettings() { IDialogSettings pSections = viewerSettings.getSection(SETTINGS_SECTION_PRESENTATIONS); if (pSections != null) { for (IDialogSettings pSection : ArrayUtils.safeArray(pSections.getSections())) { String pId = pSection.getName(); ResultSetPresentationDescriptor presentation = ResultSetPresentationRegistry.getInstance().getPresentation(pId); if (presentation == null) { log.warn("Presentation '" + pId + "' not found. "); continue; } PresentationSettings settings = new PresentationSettings(); String panelIdList = pSection.get("enabledPanelIds"); if (panelIdList != null) { Collections.addAll(settings.enabledPanelIds, panelIdList.split(",")); } settings.activePanelId = pSection.get("activePanelId"); settings.panelRatio = pSection.getInt("panelRatio"); settings.panelsVisible = pSection.getBoolean("panelsVisible"); presentationSettings.put(presentation, settings); } } } private PresentationSettings getPresentationSettings() { PresentationSettings settings = this.presentationSettings.get(activePresentationDescriptor); if (settings == null) { settings = new PresentationSettings(); this.presentationSettings.put(activePresentationDescriptor, settings); } return settings; } private void savePresentationSettings() { IDialogSettings pSections = UIUtils.getSettingsSection(viewerSettings, SETTINGS_SECTION_PRESENTATIONS); for (Map.Entry<ResultSetPresentationDescriptor, PresentationSettings> pEntry : presentationSettings.entrySet()) { if (pEntry.getKey() == null) { continue; } String pId = pEntry.getKey().getId(); PresentationSettings settings = pEntry.getValue(); IDialogSettings pSection = UIUtils.getSettingsSection(pSections, pId); pSection.put("enabledPanelIds", CommonUtils.joinStrings(",", settings.enabledPanelIds)); pSection.put("activePanelId", settings.activePanelId); pSection.put("panelRatio", settings.panelRatio); pSection.put("panelsVisible", settings.panelsVisible); } } public IResultSetPanel getVisiblePanel() { return activePanels.get(getPresentationSettings().activePanelId); } @Override public IResultSetPanel[] getActivePanels() { return activePanels.values().toArray(new IResultSetPanel[activePanels.size()]); } @Override public void activatePanel(String id, boolean setActive, boolean showPanels) { if (showPanels && !isPanelsVisible()) { showPanels(true); } PresentationSettings presentationSettings = getPresentationSettings(); IResultSetPanel panel = activePanels.get(id); if (panel != null) { CTabItem panelTab = getPanelTab(id); if (panelTab != null) { if (setActive) { panelFolder.setSelection(panelTab); presentationSettings.activePanelId = id; } return; } else { log.warn("Panel '" + id + "' tab not found"); } } // Create panel ResultSetPanelDescriptor panelDescriptor = getPanelDescriptor(id); if (panelDescriptor == null) { log.error("Panel '" + id + "' not found"); return; } try { panel = panelDescriptor.createInstance(); } catch (DBException e) { UIUtils.showErrorDialog(getSite().getShell(), "Can't show panel", "Can't create panel '" + id + "'", e); return; } activePanels.put(id, panel); // Create control and tab item Control panelControl = panel.createContents(activePresentation, panelFolder); boolean firstPanel = panelFolder.getItemCount() == 0; CTabItem panelTab = new CTabItem(panelFolder, SWT.CLOSE); panelTab.setData(id); panelTab.setText(panel.getPanelTitle()); panelTab.setImage(DBeaverIcons.getImage(panelDescriptor.getIcon())); panelTab.setToolTipText(panel.getPanelDescription()); panelTab.setControl(panelControl); if (setActive || firstPanel) { panelFolder.setSelection(panelTab); } presentationSettings.enabledPanelIds.add(id); if (setActive) { setActivePanel(id); } } private void activateDefaultPanels(PresentationSettings settings) { // Cleanup unavailable panels for (Iterator<String> iter = settings.enabledPanelIds.iterator(); iter.hasNext(); ) { if (CommonUtils.isEmpty(iter.next())) { iter.remove(); } } // Add default panels if needed if (settings.enabledPanelIds.isEmpty()) { for (ResultSetPanelDescriptor pd : availablePanels) { if (pd.isShowByDefault()) { settings.enabledPanelIds.add(pd.getId()); } } } if (!settings.enabledPanelIds.isEmpty()) { for (String panelId : settings.enabledPanelIds) { if (!CommonUtils.isEmpty(panelId)) { activatePanel(panelId, panelId.equals(settings.activePanelId), false); } } } } private void setActivePanel(String panelId) { PresentationSettings settings = getPresentationSettings(); settings.activePanelId = panelId; IResultSetPanel panel = activePanels.get(panelId); if (panel != null) { panel.activatePanel(); updatePanelActions(); } } private void removePanel(String panelId) { IResultSetPanel panel = activePanels.remove(panelId); if (panel != null) { panel.deactivatePanel(); } getPresentationSettings().enabledPanelIds.remove(panelId); if (activePanels.isEmpty()) { showPanels(false); } } private ResultSetPanelDescriptor getPanelDescriptor(String id) { for (ResultSetPanelDescriptor panel : availablePanels) { if (panel.getId().equals(id)) { return panel; } } return null; } private CTabItem getPanelTab(String panelId) { for (CTabItem tab : panelFolder.getItems()) { if (CommonUtils.equalObjects(tab.getData(), panelId)) { return tab; } } return null; } public boolean isPanelsVisible() { return viewerSash.getMaximizedControl() == null; } public void showPanels(boolean show) { if (!show) { viewerSash.setMaximizedControl(presentationPanel); } else { activateDefaultPanels(getPresentationSettings()); viewerSash.setMaximizedControl(null); updatePanelActions(); activePresentation.updateValueView(); } getPresentationSettings().panelsVisible = show; } private List<IContributionItem> fillPanelsMenu() { List<IContributionItem> items = new ArrayList<>(); for (final ResultSetPanelDescriptor panel : availablePanels) { Action panelAction = new Action(panel.getLabel(), Action.AS_CHECK_BOX) { @Override public boolean isChecked() { return activePanels.containsKey(panel.getId()); } @Override public void run() { if (isPanelsVisible() && isChecked()) { CTabItem panelTab = getPanelTab(panel.getId()); if (panelTab != null) { panelTab.dispose(); removePanel(panel.getId()); } } else { activatePanel(panel.getId(), true, true); } } }; //panelAction.setImageDescriptor(DBeaverIcons.getImageDescriptor(panel.getIcon())); items.add(new ActionContributionItem(panelAction)); } return items; } private void addDefaultPanelActions() { panelToolBar.add(new Action("View Menu", ImageDescriptor.createFromImageData(DBeaverIcons.getViewMenuImage().getImageData())) { @Override public void run() { ToolBar tb = panelToolBar.getControl(); for (ToolItem item : tb.getItems()) { if (item.getData() instanceof ActionContributionItem && ((ActionContributionItem) item.getData()).getAction() == this) { MenuManager panelMenu = new MenuManager(); for (IContributionItem menuItem : fillPanelsMenu()) { panelMenu.add(menuItem); } final Menu swtMenu = panelMenu.createContextMenu(panelToolBar.getControl()); Rectangle ib = item.getBounds(); Point displayAt = item.getParent().toDisplay(ib.x, ib.y + ib.height); swtMenu.setLocation(displayAt); swtMenu.setVisible(true); return; } } } }); } //////////////////////////////////////// // Actions public boolean isActionsDisabled() { return actionsDisabled; } @Override public void lockActionsByControl(Control lockedBy) { if (checkDoubleLock(lockedBy)) { return; } actionsDisabled = true; lockedBy.addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { actionsDisabled = false; } }); } @Override public void lockActionsByFocus(final Control lockedBy) { lockedBy.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { checkDoubleLock(lockedBy); actionsDisabled = true; } @Override public void focusLost(FocusEvent e) { actionsDisabled = false; } }); lockedBy.addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { actionsDisabled = false; } }); } private boolean checkDoubleLock(Control lockedBy) { if (actionsDisabled) { log.debug("Internal error: actions double-lock by [" + lockedBy + "]"); return true; } return false; } @Nullable @Override public <T> T getAdapter(Class<T> adapter) { if (adapter == IFindReplaceTarget.class) { return adapter.cast(findReplaceTarget); } if (adapter.isAssignableFrom(activePresentation.getClass())) { return adapter.cast(activePresentation); } // Try to get it from adapter if (activePresentation instanceof IAdaptable) { return ((IAdaptable) activePresentation).getAdapter(adapter); } return null; } public void addListener(IResultSetListener listener) { synchronized (listeners) { listeners.add(listener); } } public void removeListener(IResultSetListener listener) { synchronized (listeners) { listeners.remove(listener); } } private void updateRecordMode() { //Object state = savePresentationState(); //this.redrawData(false); activePresentation.refreshData(true, false); this.updateStatusMessage(); //restorePresentationState(state); } public void updateEditControls() { ResultSetPropertyTester.firePropertyChange(ResultSetPropertyTester.PROP_EDITABLE); ResultSetPropertyTester.firePropertyChange(ResultSetPropertyTester.PROP_CHANGED); updateToolbar(); } /** * It is a hack function. Generally all command associated widgets should be updated automatically by framework. * Freaking E4 do not do it. I've spent a couple of days fighting it. Guys, you owe me. */ private void updateToolbar() { UIUtils.updateContributionItems(mainToolbar); UIUtils.updateContributionItems(panelToolBar); } public void redrawData(boolean rowsChanged) { if (viewerPanel.isDisposed()) { return; } if (rowsChanged) { int rowCount = model.getRowCount(); if (curRow == null || curRow.getVisualNumber() >= rowCount) { curRow = rowCount == 0 ? null : model.getRow(rowCount - 1); } // Set cursor on new row if (!recordMode) { activePresentation.refreshData(false, false); this.updateFiltersText(); this.updateStatusMessage(); } else { this.updateRecordMode(); } } else { activePresentation.refreshData(false, false); } } private void createStatusBar() { UIUtils.createHorizontalLine(viewerPanel); Composite statusBar = new Composite(viewerPanel, SWT.NONE); GridData gd = new GridData(GridData.FILL_HORIZONTAL); statusBar.setLayoutData(gd); GridLayout gl = new GridLayout(4, false); gl.marginWidth = 0; gl.marginHeight = 0; //gl.marginBottom = 5; statusBar.setLayout(gl); statusLabel = new Text(statusBar, SWT.READ_ONLY); gd = new GridData(GridData.FILL_HORIZONTAL); statusLabel.setLayoutData(gd); statusLabel.addMouseListener(new MouseAdapter() { @Override public void mouseDoubleClick(MouseEvent e) { EditTextDialog.showText(site.getShell(), CoreMessages.controls_resultset_viewer_dialog_status_title, statusLabel.getText()); } }); mainToolbar = new ToolBarManager(SWT.FLAT | SWT.HORIZONTAL); // Add presentation switcher presentationSwitchCombo = new PresentationSwitchCombo(); presentationSwitchCombo.createControl(statusBar); //mainToolbar.add(presentationSwitchCombo); //mainToolbar.add(new Separator()); // handle own commands mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_APPLY_CHANGES)); mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_REJECT_CHANGES)); mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_GENERATE_SCRIPT)); mainToolbar.add(new Separator()); mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_EDIT)); mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_ADD)); mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_COPY)); mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_DELETE)); mainToolbar.add(new Separator()); mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_FIRST)); mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_PREVIOUS)); mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_NEXT)); mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_LAST)); mainToolbar.add(new Separator()); mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_FETCH_PAGE)); mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_FETCH_ALL)); // Use simple action for refresh to avoid ambiguous behaviour of F5 shortcut mainToolbar.add(new Separator()); // // FIXME: Link to standard Find/Replace action - it has to be handled by owner site // mainToolbar.add(ActionUtils.makeCommandContribution( // site, // IWorkbenchCommandConstants.EDIT_FIND_AND_REPLACE, // CommandContributionItem.STYLE_PUSH, // UIIcon.FIND_TEXT)); mainToolbar.add(new Separator()); //mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_TOGGLE_MODE, CommandContributionItem.STYLE_CHECK)); mainToolbar.add(new ToggleModeAction()); CommandContributionItem panelsAction = new CommandContributionItem(new CommandContributionItemParameter( site, "org.jkiss.dbeaver.core.resultset.panels", ResultSetCommandHandler.CMD_TOGGLE_PANELS, CommandContributionItem.STYLE_PULLDOWN)); //panelsAction. mainToolbar.add(panelsAction); mainToolbar.add(new Separator()); mainToolbar.add(new ConfigAction()); mainToolbar.createControl(statusBar); //updateEditControls(); } @Nullable public DBSDataContainer getDataContainer() { return curState != null ? curState.dataContainer : container.getDataContainer(); } //////////////////////////////////////////////////////////// // Grid/Record mode @Override public boolean isRecordMode() { return recordMode; } public void toggleMode() { changeMode(!recordMode); updateEditControls(); } private void changeMode(boolean recordMode) { //Object state = savePresentationState(); this.recordMode = recordMode; //redrawData(false); activePresentation.refreshData(true, false); activePresentation.changeMode(recordMode); updateStatusMessage(); //restorePresentationState(state); } //////////////////////////////////////////////////////////// // Misc private void dispose() { savePresentationSettings(); clearData(); if (mainToolbar != null) { try { mainToolbar.dispose(); } catch (Throwable e) { // ignore log.debug("Error disposing toolbar", e); } } } public boolean isAttributeReadOnly(DBDAttributeBinding attribute) { if (isReadOnly()) { return true; } if (!model.isAttributeReadOnly(attribute)) { return false; } boolean newRow = (curRow != null && curRow.getState() == ResultSetRow.STATE_ADDED); return !newRow; } private Object savePresentationState() { if (activePresentation instanceof IStatefulControl) { return ((IStatefulControl) activePresentation).saveState(); } else { return null; } } private void restorePresentationState(Object state) { if (activePresentation instanceof IStatefulControl) { ((IStatefulControl) activePresentation).restoreState(state); } } /////////////////////////////////////// // History List<HistoryStateItem> getStateHistory() { return stateHistory; } private void setNewState(DBSDataContainer dataContainer, @Nullable DBDDataFilter dataFilter) { // Create filter copy to avoid modifications dataFilter = new DBDDataFilter(dataFilter); // Search in history for (int i = 0; i < stateHistory.size(); i++) { HistoryStateItem item = stateHistory.get(i); if (item.dataContainer == dataContainer && CommonUtils.equalObjects(item.filter, dataFilter)) { curState = item; historyPosition = i; return; } } // Save current state in history while (historyPosition < stateHistory.size() - 1) { stateHistory.remove(stateHistory.size() - 1); } curState = new HistoryStateItem( dataContainer, dataFilter, curRow == null ? -1 : curRow.getVisualNumber()); stateHistory.add(curState); historyPosition = stateHistory.size() - 1; } public void resetHistory() { curState = null; stateHistory.clear(); historyPosition = -1; } /////////////////////////////////////// // Misc @Nullable public ResultSetRow getCurrentRow() { return curRow; } @Override public void setCurrentRow(@Nullable ResultSetRow curRow) { this.curRow = curRow; if (curState != null && curRow != null) { curState.rowNumber = curRow.getVisualNumber(); } // if (recordMode) { // updateRecordMode(); // } } /////////////////////////////////////// // Status public void setStatus(String status) { setStatus(status, false); } public void setStatus(String status, boolean error) { if (statusLabel.isDisposed()) { return; } if (error) { statusLabel.setForeground(colorRed); } else if (colorRed.equals(statusLabel.getForeground())) { statusLabel.setForeground(getDefaultForeground()); } if (status == null) { status = "???"; //$NON-NLS-1$ } statusLabel.setText(status); } public void updateStatusMessage() { if (model.getRowCount() == 0) { if (model.getVisibleAttributeCount() == 0) { setStatus(CoreMessages.controls_resultset_viewer_status_empty + getExecutionTimeMessage()); } else { setStatus(CoreMessages.controls_resultset_viewer_status_no_data + getExecutionTimeMessage()); } } else { if (recordMode) { setStatus(CoreMessages.controls_resultset_viewer_status_row + (curRow == null ? 0 : curRow.getVisualNumber() + 1) + "/" + model.getRowCount() + getExecutionTimeMessage()); } else { setStatus(String.valueOf(model.getRowCount()) + CoreMessages.controls_resultset_viewer_status_rows_fetched + getExecutionTimeMessage()); } } } private String getExecutionTimeMessage() { DBCStatistics statistics = model.getStatistics(); if (statistics == null || statistics.isEmpty()) { return ""; } return " - " + RuntimeUtils.formatExecutionTime(statistics.getTotalTime()); } /** * Sets new metadata of result set * @param attributes attributes metadata */ void setMetaData(DBDAttributeBinding[] attributes) { model.setMetaData(attributes); activePresentation.clearMetaData(); } void setData(List<Object[]> rows) { if (viewerPanel.isDisposed()) { return; } this.curRow = null; this.model.setData(rows); this.curRow = (this.model.getRowCount() > 0 ? this.model.getRow(0) : null); { if (getPreferenceStore().getBoolean(DBeaverPreferences.RESULT_SET_AUTO_SWITCH_MODE)) { boolean newRecordMode = (rows.size() == 1); if (newRecordMode != recordMode) { toggleMode(); // ResultSetPropertyTester.firePropertyChange(ResultSetPropertyTester.PROP_CAN_TOGGLE); } } } this.activePresentation.refreshData(true, false); if (recordMode) { this.updateRecordMode(); } this.updateFiltersText(); this.updateStatusMessage(); this.updateEditControls(); } void appendData(List<Object[]> rows) { model.appendData(rows); //redrawData(true); activePresentation.refreshData(false, true); setStatus(NLS.bind(CoreMessages.controls_resultset_viewer_status_rows_size, model.getRowCount(), rows.size()) + getExecutionTimeMessage()); updateEditControls(); } @Override public int promptToSaveOnClose() { if (!isDirty()) { return ISaveablePart2.YES; } int result = ConfirmationDialog.showConfirmDialog( viewerPanel.getShell(), DBeaverPreferences.CONFIRM_RS_EDIT_CLOSE, ConfirmationDialog.QUESTION_WITH_CANCEL); if (result == IDialogConstants.YES_ID) { return ISaveablePart2.YES; } else if (result == IDialogConstants.NO_ID) { rejectChanges(); return ISaveablePart2.NO; } else { return ISaveablePart2.CANCEL; } } @Override public void doSave(IProgressMonitor monitor) { applyChanges(RuntimeUtils.makeMonitor(monitor)); } public void doSave(DBRProgressMonitor monitor) { applyChanges(monitor); } @Override public void doSaveAs() { } @Override public boolean isDirty() { return model.isDirty(); } @Override public boolean isSaveAsAllowed() { return false; } @Override public boolean isSaveOnCloseNeeded() { return true; } @Override public boolean hasData() { return model.hasData(); } @Override public boolean isHasMoreData() { return getExecutionContext() != null && dataReceiver.isHasMoreData(); } @Override public boolean isReadOnly() { if (model.isUpdateInProgress() || !(activePresentation instanceof IResultSetEditor)) { return true; } DBCExecutionContext executionContext = getExecutionContext(); return executionContext == null || !executionContext.isConnected() || executionContext.getDataSource().getContainer().isConnectionReadOnly() || executionContext.getDataSource().getInfo().isReadOnlyData(); } /** * Checks that current state of result set allows to insert new rows * @return true if new rows insert is allowed */ public boolean isInsertable() { return !isReadOnly() && model.isSingleSource() && model.getVisibleAttributeCount() > 0; } public boolean isRefreshInProgress() { return dataPumpJob != null; } /////////////////////////////////////////////////////// // Context menu & filters @NotNull public static IResultSetFilterManager getFilterManager() { return filterManager; } public static void registerFilterManager(@Nullable IResultSetFilterManager filterManager) { if (filterManager == null) { filterManager = new SimpleFilterManager(); } ResultSetViewer.filterManager = filterManager; } public void showFiltersMenu() { DBDAttributeBinding curAttribute = getActivePresentation().getCurrentAttribute(); if (curAttribute == null) { return; } Control control = getActivePresentation().getControl(); Point cursorLocation = getActivePresentation().getCursorLocation(); Point location = control.getDisplay().map(control, null, cursorLocation); MenuManager menuManager = new MenuManager(); fillFiltersMenu(curAttribute, menuManager); final Menu contextMenu = menuManager.createContextMenu(control); contextMenu.setLocation(location); contextMenu.setVisible(true); } @Override public void fillContextMenu(@NotNull IMenuManager manager, @Nullable final DBDAttributeBinding attr, @Nullable final ResultSetRow row) { final DBPDataSource dataSource = getDataContainer() == null ? null : getDataContainer().getDataSource(); // Custom oldValue items final ResultSetValueController valueController; if (attr != null && row != null) { valueController = new ResultSetValueController( this, attr, row, IValueController.EditType.NONE, null); final Object value = valueController.getValue(); { // Standard items manager.add(ActionUtils.makeCommandContribution(site, IWorkbenchCommandConstants.EDIT_CUT)); manager.add(ActionUtils.makeCommandContribution(site, IWorkbenchCommandConstants.EDIT_COPY)); MenuManager extCopyMenu = new MenuManager(ActionUtils.findCommandName(CoreCommands.CMD_COPY_SPECIAL)); extCopyMenu.add(ActionUtils.makeCommandContribution(site, CoreCommands.CMD_COPY_SPECIAL)); extCopyMenu.add(new Action("Copy column name(s)") { @Override public void run() { StringBuilder buffer = new StringBuilder(); for (DBDAttributeBinding attr : getSelection().getSelectedAttributes()) { if (buffer.length() > 0) { buffer.append("\t"); } buffer.append(attr.getName()); } ResultSetUtils.copyToClipboard(buffer.toString()); } }); extCopyMenu.add(new Action("Copy row number(s)") { @Override public void run() { StringBuilder buffer = new StringBuilder(); for (ResultSetRow row : getSelection().getSelectedRows()) { if (buffer.length() > 0) { buffer.append("\n"); } buffer.append(row.getVisualNumber()); } ResultSetUtils.copyToClipboard(buffer.toString()); } }); manager.add(extCopyMenu); manager.add(ActionUtils.makeCommandContribution(site, IWorkbenchCommandConstants.EDIT_PASTE)); manager.add(ActionUtils.makeCommandContribution(site, CoreCommands.CMD_PASTE_SPECIAL)); manager.add(ActionUtils.makeCommandContribution(site, IWorkbenchCommandConstants.EDIT_DELETE)); // Edit items manager.add(new Separator()); manager.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_EDIT)); manager.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_EDIT_INLINE)); if (!valueController.isReadOnly() && !DBUtils.isNullValue(value)/* && !attr.isRequired()*/) { manager.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_CELL_SET_NULL)); } manager.add(new GroupMarker(MENU_GROUP_EDIT)); } // Menus from value handler try { manager.add(new Separator()); valueController.getValueManager().contributeActions(manager, valueController, null); } catch (Exception e) { log.error(e); } if (row.isChanged() && row.changes.containsKey(attr)) { manager.insertAfter(IResultSetController.MENU_GROUP_EDIT, ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_CELL_RESET)); } } else { valueController = null; } if (dataSource != null && attr != null && model.getVisibleAttributeCount() > 0 && !model.isUpdateInProgress()) { // Filters and View manager.add(new Separator()); { String filtersShortcut = ActionUtils.findCommandDescription(ResultSetCommandHandler.CMD_FILTER_MENU, getSite(), true); String menuName = CoreMessages.controls_resultset_viewer_action_order_filter; if (!CommonUtils.isEmpty(filtersShortcut)) { menuName += " (" + filtersShortcut + ")"; } MenuManager filtersMenu = new MenuManager( menuName, DBeaverIcons.getImageDescriptor(UIIcon.FILTER), "filters"); //$NON-NLS-1$ filtersMenu.setRemoveAllWhenShown(true); filtersMenu.addMenuListener(new IMenuListener() { @Override public void menuAboutToShow(IMenuManager manager) { fillFiltersMenu(attr, manager); } }); manager.add(filtersMenu); } { MenuManager viewMenu = new MenuManager( "View/Format", null, "view"); //$NON-NLS-1$ List<? extends DBDAttributeTransformerDescriptor> transformers = dataSource.getContainer().getApplication().getValueHandlerRegistry().findTransformers( dataSource, attr, null); if (!CommonUtils.isEmpty(transformers)) { MenuManager transformersMenu = new MenuManager("View as"); transformersMenu.setRemoveAllWhenShown(true); transformersMenu.addMenuListener(new IMenuListener() { @Override public void menuAboutToShow(IMenuManager manager) { fillAttributeTransformersMenu(manager, attr); } }); viewMenu.add(transformersMenu); } else { final Action customizeAction = new Action("View as") {}; customizeAction.setEnabled(false); viewMenu.add(customizeAction); } if (getModel().isSingleSource()) { if (valueController != null) { viewMenu.add(new SetRowColorAction(attr, valueController.getValue())); if (getModel().hasColorMapping(attr)) { viewMenu.add(new ResetRowColorAction(attr, valueController.getValue())); } } viewMenu.add(new CustomizeColorsAction(attr, row)); viewMenu.add(new Separator()); } viewMenu.add(new Action("Data formats ...") { @Override public void run() { UIUtils.showPreferencesFor( getControl().getShell(), null, PrefPageDataFormat.PAGE_ID); } }); manager.add(viewMenu); } { // Navigate MenuManager navigateMenu = new MenuManager( "Navigate", null, "navigate"); //$NON-NLS-1$ if (ActionUtils.isCommandEnabled(ResultSetCommandHandler.CMD_NAVIGATE_LINK, site)) { navigateMenu.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_NAVIGATE_LINK)); navigateMenu.add(new Separator()); } navigateMenu.add(new Separator()); navigateMenu.add(ActionUtils.makeCommandContribution(site, ITextEditorActionDefinitionIds.LINE_GOTO)); navigateMenu.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_FIRST)); navigateMenu.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_NEXT)); navigateMenu.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_PREVIOUS)); navigateMenu.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_LAST)); manager.add(navigateMenu); } { // Layout MenuManager layoutMenu = new MenuManager( "Layout", null, "layout"); //$NON-NLS-1$ layoutMenu.add(new ToggleModeAction()); layoutMenu.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_TOGGLE_PANELS)); layoutMenu.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_SWITCH_PRESENTATION)); { layoutMenu.add(new Separator()); for (IContributionItem item : fillPanelsMenu()) { layoutMenu.add(item); } } manager.add(layoutMenu); } manager.add(new Separator()); } // Fill general menu final DBSDataContainer dataContainer = getDataContainer(); if (dataContainer != null && model.hasData()) { manager.add(new Action(CoreMessages.controls_resultset_viewer_action_export, DBeaverIcons.getImageDescriptor(UIIcon.EXPORT)) { @Override public void run() { ActiveWizardDialog dialog = new ActiveWizardDialog( site.getWorkbenchWindow(), new DataTransferWizard( new IDataTransferProducer[]{ new DatabaseTransferProducer(dataContainer, model.getDataFilter())}, null ), getSelection() ); dialog.open(); } }); } manager.add(new GroupMarker(CoreCommands.GROUP_TOOLS)); if (dataContainer != null && model.hasData()) { manager.add(new Separator()); manager.add(ActionUtils.makeCommandContribution(site, IWorkbenchCommandConstants.FILE_REFRESH)); } manager.add(new Separator()); manager.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); } private class TransformerAction extends Action { private final DBDAttributeBinding attrribute; public TransformerAction(DBDAttributeBinding attr, String text, int style, boolean checked) { super(text, style); this.attrribute = attr; setChecked(checked); } @NotNull DBVTransformSettings getTransformSettings() { final DBVTransformSettings settings = DBVUtils.getTransformSettings(attrribute, true); if (settings == null) { throw new IllegalStateException("Can't get/create transformer settings for '" + attrribute.getFullyQualifiedName(DBPEvaluationContext.UI) + "'"); } return settings; } protected void saveTransformerSettings() { attrribute.getDataSource().getContainer().persistConfiguration(); refreshData(null); } } private void fillAttributeTransformersMenu(IMenuManager manager, final DBDAttributeBinding attr) { final DBSDataContainer dataContainer = getDataContainer(); if (dataContainer == null) { return; } final DBPDataSource dataSource = dataContainer.getDataSource(); final DBDRegistry registry = dataSource.getContainer().getApplication().getValueHandlerRegistry(); final DBVTransformSettings transformSettings = DBVUtils.getTransformSettings(attr, false); DBDAttributeTransformerDescriptor customTransformer = null; if (transformSettings != null && transformSettings.getCustomTransformer() != null) { customTransformer = registry.getTransformer(transformSettings.getCustomTransformer()); } List<? extends DBDAttributeTransformerDescriptor> customTransformers = registry.findTransformers(dataSource, attr, true); if (customTransformers != null && !customTransformers.isEmpty()) { manager.add(new TransformerAction( attr, "Default", IAction.AS_RADIO_BUTTON, transformSettings == null || CommonUtils.isEmpty(transformSettings.getCustomTransformer())) { @Override public void run() { if (isChecked()) { getTransformSettings().setCustomTransformer(null); saveTransformerSettings(); } } }); for (final DBDAttributeTransformerDescriptor descriptor : customTransformers) { final TransformerAction action = new TransformerAction( attr, descriptor.getName(), IAction.AS_RADIO_BUTTON, transformSettings != null && descriptor.getId().equals(transformSettings.getCustomTransformer())) { @Override public void run() { if (isChecked()) { final DBVTransformSettings settings = getTransformSettings(); final String oldCustomTransformer = settings.getCustomTransformer(); settings.setCustomTransformer(descriptor.getId()); TransformerSettingsDialog settingsDialog = new TransformerSettingsDialog( ResultSetViewer.this, attr, settings); if (settingsDialog.open() == IDialogConstants.OK_ID) { saveTransformerSettings(); } else { settings.setCustomTransformer(oldCustomTransformer); } } } }; manager.add(action); } } if (customTransformer != null && !CommonUtils.isEmpty(customTransformer.getProperties())) { manager.add(new TransformerAction(attr, "Settings ...", IAction.AS_UNSPECIFIED, false) { @Override public void run() { TransformerSettingsDialog settingsDialog = new TransformerSettingsDialog( ResultSetViewer.this, attr, transformSettings); if (settingsDialog.open() == IDialogConstants.OK_ID) { saveTransformerSettings(); } } }); } List<? extends DBDAttributeTransformerDescriptor> applicableTransformers = registry.findTransformers(dataSource, attr, false); if (applicableTransformers != null) { manager.add(new Separator()); for (final DBDAttributeTransformerDescriptor descriptor : applicableTransformers) { boolean checked; if (transformSettings != null) { if (descriptor.isApplicableByDefault()) { checked = !transformSettings.isExcluded(descriptor.getId()); } else { checked = transformSettings.isIncluded(descriptor.getId()); } } else { checked = descriptor.isApplicableByDefault(); } manager.add(new TransformerAction(attr, descriptor.getName(), IAction.AS_CHECK_BOX, checked) { @Override public void run() { getTransformSettings().enableTransformer(descriptor, !isChecked()); saveTransformerSettings(); } }); } } } private void fillFiltersMenu(@NotNull DBDAttributeBinding attribute, @NotNull IMenuManager filtersMenu) { if (supportsDataFilter()) { //filtersMenu.add(new FilterByListAction(operator, type, attribute)); DBCLogicalOperator[] operators = attribute.getValueHandler().getSupportedOperators(attribute); // Operators with multiple inputs for (DBCLogicalOperator operator : operators) { if (operator.getArgumentCount() < 0) { filtersMenu.add(new FilterByAttributeAction(operator, FilterByAttributeType.INPUT, attribute)); } } filtersMenu.add(new Separator()); // Operators with no inputs for (DBCLogicalOperator operator : operators) { if (operator.getArgumentCount() == 0) { filtersMenu.add(new FilterByAttributeAction(operator, FilterByAttributeType.NONE, attribute)); } } for (FilterByAttributeType type : FilterByAttributeType.values()) { if (type == FilterByAttributeType.NONE) { // Value filters are available only if certain cell is selected continue; } filtersMenu.add(new Separator()); if (type.getValue(this, attribute, DBCLogicalOperator.EQUALS, true) == null) { // Null cell value - no operators can be applied continue; } for (DBCLogicalOperator operator : operators) { if (operator.getArgumentCount() > 0) { filtersMenu.add(new FilterByAttributeAction(operator, type, attribute)); } } } filtersMenu.add(new Separator()); DBDAttributeConstraint constraint = model.getDataFilter().getConstraint(attribute); if (constraint != null && constraint.hasCondition()) { filtersMenu.add(new FilterResetAttributeAction(attribute)); } } filtersMenu.add(new Separator()); filtersMenu.add(new ToggleServerSideOrderingAction()); filtersMenu.add(new ShowFiltersAction(true)); } @Override public void navigateAssociation(@NotNull DBRProgressMonitor monitor, @NotNull DBDAttributeBinding attr, @NotNull ResultSetRow row, boolean newWindow) throws DBException { if (getExecutionContext() == null) { throw new DBException("Not connected"); } DBSEntityAssociation association = null; List<DBSEntityReferrer> referrers = attr.getReferrers(); if (referrers != null) { for (final DBSEntityReferrer referrer : referrers) { if (referrer instanceof DBSEntityAssociation) { association = (DBSEntityAssociation) referrer; break; } } } if (association == null) { throw new DBException("Association not found in attribute [" + attr.getName() + "]"); } DBSEntityConstraint refConstraint = association.getReferencedConstraint(); if (refConstraint == null) { throw new DBException("Broken association (referenced constraint missing)"); } if (!(refConstraint instanceof DBSEntityReferrer)) { throw new DBException("Referenced constraint [" + refConstraint + "] is not a referrer"); } DBSEntity targetEntity = refConstraint.getParentObject(); if (targetEntity == null) { throw new DBException("Null constraint parent"); } if (!(targetEntity instanceof DBSDataContainer)) { throw new DBException("Entity [" + DBUtils.getObjectFullName(targetEntity, DBPEvaluationContext.UI) + "] is not a data container"); } // make constraints List<DBDAttributeConstraint> constraints = new ArrayList<>(); int visualPosition = 0; // Set conditions List<? extends DBSEntityAttributeRef> ownAttrs = CommonUtils.safeList(((DBSEntityReferrer) association).getAttributeReferences(monitor)); List<? extends DBSEntityAttributeRef> refAttrs = CommonUtils.safeList(((DBSEntityReferrer) refConstraint).getAttributeReferences(monitor)); if (ownAttrs.size() != refAttrs.size()) { throw new DBException( "Entity [" + DBUtils.getObjectFullName(targetEntity, DBPEvaluationContext.UI) + "] association [" + association.getName() + "] columns differs from referenced constraint [" + refConstraint.getName() + "] (" + ownAttrs.size() + "<>" + refAttrs.size() + ")"); } // Add association constraints for (int i = 0; i < ownAttrs.size(); i++) { DBSEntityAttributeRef ownAttr = ownAttrs.get(i); DBSEntityAttributeRef refAttr = refAttrs.get(i); DBDAttributeBinding ownBinding = model.getAttributeBinding(ownAttr.getAttribute()); assert ownBinding != null; DBDAttributeConstraint constraint = new DBDAttributeConstraint(refAttr.getAttribute(), visualPosition++); constraint.setVisible(true); constraints.add(constraint); Object keyValue = model.getCellValue(ownBinding, row); constraint.setOperator(DBCLogicalOperator.EQUALS); constraint.setValue(keyValue); } DBDDataFilter newFilter = new DBDDataFilter(constraints); if (newWindow) { openResultsInNewWindow(monitor, targetEntity, newFilter); } else { runDataPump((DBSDataContainer) targetEntity, newFilter, 0, getSegmentMaxRows(), -1, null); } } private void openResultsInNewWindow(DBRProgressMonitor monitor, DBSEntity targetEntity, final DBDDataFilter newFilter) { final DBNDatabaseNode targetNode = getExecutionContext().getDataSource().getContainer().getApplication().getNavigatorModel().getNodeByObject(monitor, targetEntity, false); if (targetNode == null) { UIUtils.showMessageBox(null, "Open link", "Can't navigate to '" + DBUtils.getObjectFullName(targetEntity, DBPEvaluationContext.UI) + "' - navigator node not found", SWT.ICON_ERROR); return; } DBeaverUI.asyncExec(new Runnable() { @Override public void run() { openNewDataEditor(targetNode, newFilter); } }); } @Override public int getHistoryPosition() { return historyPosition; } @Override public int getHistorySize() { return stateHistory.size(); } @Override public void navigateHistory(int position) { if (position < 0 || position >= stateHistory.size()) { // out of range log.debug("Wrong history position: " + position); return; } HistoryStateItem state = stateHistory.get(position); int segmentSize = getSegmentMaxRows(); if (state.rowNumber >= 0 && state.rowNumber >= segmentSize && segmentSize > 0) { segmentSize = (state.rowNumber / segmentSize + 1) * segmentSize; } runDataPump(state.dataContainer, state.filter, 0, segmentSize, state.rowNumber, null); } @Override public void updatePanelsContent() { updateEditControls(); for (IResultSetPanel panel : getActivePanels()) { panel.refresh(); } } @Override public void updatePanelActions() { IResultSetPanel visiblePanel = getVisiblePanel(); panelToolBar.removeAll(); if (visiblePanel != null) { visiblePanel.contributeActions(panelToolBar); } addDefaultPanelActions(); panelToolBar.update(true); } @Override public Composite getControl() { return this.viewerPanel; } @NotNull @Override public IWorkbenchPartSite getSite() { return site; } @Override @NotNull public ResultSetModel getModel() { return model; } @Override public ResultSetModel getInput() { return model; } @Override public void setInput(Object input) { throw new IllegalArgumentException("ResultSet model can't be changed"); } @Override @NotNull public IResultSetSelection getSelection() { if (activePresentation instanceof ISelectionProvider) { ISelection selection = ((ISelectionProvider) activePresentation).getSelection(); if (selection instanceof IResultSetSelection) { return (IResultSetSelection) selection; } else { log.debug("Bad selection type (" + selection + ") in presentation " + activePresentation); } } return new EmptySelection(); } @Override public void setSelection(ISelection selection, boolean reveal) { if (activePresentation instanceof ISelectionProvider) { ((ISelectionProvider) activePresentation).setSelection(selection); } } @NotNull @Override public DBDDataReceiver getDataReceiver() { return dataReceiver; } @Nullable @Override public DBCExecutionContext getExecutionContext() { return container.getExecutionContext(); } @Override public void refresh() { // Check if we are dirty if (isDirty()) { switch (promptToSaveOnClose()) { case ISaveablePart2.CANCEL: return; case ISaveablePart2.YES: // Apply changes applyChanges(null, new ResultSetPersister.DataUpdateListener() { @Override public void onUpdate(boolean success) { if (success) { DBeaverUI.asyncExec(new Runnable() { @Override public void run() { refresh(); } }); } } }); return; default: // Just ignore previous RS values break; } } // Pump data ResultSetRow oldRow = curRow; DBSDataContainer dataContainer = getDataContainer(); if (container.isReadyToRun() && dataContainer != null && dataPumpJob == null) { int segmentSize = getSegmentMaxRows(); if (oldRow != null && oldRow.getVisualNumber() >= segmentSize && segmentSize > 0) { segmentSize = (oldRow.getVisualNumber() / segmentSize + 1) * segmentSize; } runDataPump(dataContainer, null, 0, segmentSize, oldRow == null ? -1 : oldRow.getVisualNumber(), new Runnable() { @Override public void run() { activePresentation.formatData(true); } }); } else { UIUtils.showErrorDialog( null, "Error executing query", dataContainer == null ? "Viewer detached from data source" : dataPumpJob == null ? "Can't refresh after reconnect. Re-execute query." : "Previous query is still running"); } } public void refreshWithFilter(DBDDataFilter filter) { DBSDataContainer dataContainer = getDataContainer(); if (dataContainer != null) { runDataPump( dataContainer, filter, 0, getSegmentMaxRows(), -1, null); } } @Override public boolean refreshData(@Nullable Runnable onSuccess) { DBSDataContainer dataContainer = getDataContainer(); if (container.isReadyToRun() && dataContainer != null && dataPumpJob == null) { int segmentSize = getSegmentMaxRows(); if (curRow != null && curRow.getVisualNumber() >= segmentSize && segmentSize > 0) { segmentSize = (curRow.getVisualNumber() / segmentSize + 1) * segmentSize; } return runDataPump(dataContainer, null, 0, segmentSize, -1, onSuccess); } else { return false; } } public synchronized void readNextSegment() { if (!dataReceiver.isHasMoreData()) { return; } DBSDataContainer dataContainer = getDataContainer(); if (dataContainer != null && !model.isUpdateInProgress() && dataPumpJob == null) { dataReceiver.setHasMoreData(false); dataReceiver.setNextSegmentRead(true); runDataPump( dataContainer, null, model.getRowCount(), getSegmentMaxRows(), -1,//curRow == null ? -1 : curRow.getRowNumber(), // Do not reposition cursor after next segment read! null); } } @Override public void readAllData() { if (!dataReceiver.isHasMoreData()) { return; } if (ConfirmationDialog.showConfirmDialogEx( viewerPanel.getShell(), DBeaverPreferences.CONFIRM_RS_FETCH_ALL, ConfirmationDialog.QUESTION, ConfirmationDialog.WARNING) != IDialogConstants.YES_ID) { return; } DBSDataContainer dataContainer = getDataContainer(); if (dataContainer != null && !model.isUpdateInProgress() && dataPumpJob == null) { dataReceiver.setHasMoreData(false); dataReceiver.setNextSegmentRead(true); runDataPump( dataContainer, null, model.getRowCount(), -1, curRow == null ? -1 : curRow.getRowNumber(), null); } } int getSegmentMaxRows() { if (getDataContainer() == null) { return 0; } return getPreferenceStore().getInt(DBeaverPreferences.RESULT_SET_MAX_ROWS); } synchronized boolean runDataPump( @NotNull final DBSDataContainer dataContainer, @Nullable final DBDDataFilter dataFilter, final int offset, final int maxRows, final int focusRow, @Nullable final Runnable finalizer) { if (dataPumpJob != null) { UIUtils.showMessageBox(viewerPanel.getShell(), "Data read", "Data read is in progress - can't run another", SWT.ICON_WARNING); return false; } // Read data final DBDDataFilter useDataFilter = dataFilter != null ? dataFilter : (dataContainer == getDataContainer() ? model.getDataFilter() : null); Composite progressControl = viewerPanel; if (activePresentation.getControl() instanceof Composite) { progressControl = (Composite) activePresentation.getControl(); } final Object presentationState = savePresentationState(); dataPumpJob = new ResultSetDataPumpJob( dataContainer, useDataFilter, this, getExecutionContext(), progressControl); dataPumpJob.addJobChangeListener(new JobChangeAdapter() { @Override public void aboutToRun(IJobChangeEvent event) { model.setUpdateInProgress(true); DBeaverUI.asyncExec(new Runnable() { @Override public void run() { filtersPanel.enableFilters(false); } }); } @Override public void done(IJobChangeEvent event) { ResultSetDataPumpJob job = (ResultSetDataPumpJob)event.getJob(); final Throwable error = job.getError(); if (job.getStatistics() != null) { model.setStatistics(job.getStatistics()); } final Control control = getControl(); if (control.isDisposed()) { return; } DBeaverUI.asyncExec(new Runnable() { @Override public void run() { try { if (control.isDisposed()) { return; } final Shell shell = control.getShell(); if (error != null) { //setStatus(error.getMessage(), true); UIUtils.showErrorDialog( shell, "Error executing query", "Query execution failed", error); } else if (focusRow >= 0 && focusRow < model.getRowCount() && model.getVisibleAttributeCount() > 0) { // Seems to be refresh // Restore original position curRow = model.getRow(focusRow); //curAttribute = model.getVisibleAttribute(0); if (recordMode) { updateRecordMode(); } else { updateStatusMessage(); } restorePresentationState(presentationState); } activePresentation.updateValueView(); updatePanelsContent(); if (error == null) { setNewState(dataContainer, dataFilter != null ? dataFilter : (dataContainer == getDataContainer() ? model.getDataFilter() : null)); } model.setUpdateInProgress(false); if (error == null && dataFilter != null) { model.updateDataFilter(dataFilter); activePresentation.refreshData(true, false); } updateFiltersText(error == null); updateToolbar(); fireResultSetLoad(); } finally { if (finalizer != null) { try { finalizer.run(); } catch (Throwable e) { log.error(e); } } dataPumpJob = null; } } }); } }); dataPumpJob.setOffset(offset); dataPumpJob.setMaxRows(maxRows); dataPumpJob.schedule(); return true; } private void clearData() { this.model.clearData(); this.curRow = null; this.activePresentation.clearMetaData(); } @Override public boolean applyChanges(@Nullable DBRProgressMonitor monitor) { return applyChanges(monitor, null); } /** * Saves changes to database * @param monitor monitor. If null then save will be executed in async job * @param listener finish listener (may be null) */ public boolean applyChanges(@Nullable DBRProgressMonitor monitor, @Nullable ResultSetPersister.DataUpdateListener listener) { try { ResultSetPersister persister = createDataPersister(false); return persister.applyChanges(monitor, false, listener); } catch (DBException e) { UIUtils.showErrorDialog(null, "Apply changes error", "Error saving changes in database", e); return false; } } @Override public void rejectChanges() { if (!isDirty()) { return; } try { createDataPersister(true).rejectChanges(); } catch (DBException e) { log.debug(e); } } @Override public List<DBEPersistAction> generateChangesScript(@NotNull DBRProgressMonitor monitor) { try { ResultSetPersister persister = createDataPersister(false); persister.applyChanges(monitor, true, null); return persister.getScript(); } catch (DBException e) { UIUtils.showErrorDialog(null, "SQL script generate error", "Error saving changes in database", e); return Collections.emptyList(); } } @NotNull private ResultSetPersister createDataPersister(boolean skipKeySearch) throws DBException { if (!skipKeySearch && !model.isSingleSource()) { throw new DBException("Can't save data for result set from multiple sources"); } boolean needPK = false; if (!skipKeySearch) { for (ResultSetRow row : model.getAllRows()) { if (row.getState() == ResultSetRow.STATE_REMOVED || (row.getState() == ResultSetRow.STATE_NORMAL && row.isChanged())) { needPK = true; break; } } } if (needPK) { // If we have deleted or updated rows then check for unique identifier if (!checkEntityIdentifier()) { throw new DBException("No unique identifier defined"); } } return new ResultSetPersister(this); } void addNewRow(final boolean copyCurrent, boolean afterCurrent) { int rowNum = curRow == null ? 0 : curRow.getVisualNumber(); if (rowNum >= model.getRowCount()) { rowNum = model.getRowCount() - 1; } if (rowNum < 0) { rowNum = 0; } final DBCExecutionContext executionContext = getExecutionContext(); if (executionContext == null) { return; } // Add new row final DBDAttributeBinding docAttribute = model.getDocumentAttribute(); final DBDAttributeBinding[] attributes = model.getAttributes(); final Object[] cells; final int currentRowNumber = rowNum; // Copy cell values in new context try (DBCSession session = executionContext.openSession(VoidProgressMonitor.INSTANCE, DBCExecutionPurpose.UTIL, CoreMessages.controls_resultset_viewer_add_new_row_context_name)) { if (docAttribute != null) { cells = new Object[1]; if (copyCurrent && currentRowNumber >= 0 && currentRowNumber < model.getRowCount()) { Object[] origRow = model.getRowData(currentRowNumber); try { cells[0] = docAttribute.getValueHandler().getValueFromObject(session, docAttribute, origRow[0], true); } catch (DBCException e) { log.warn(e); } } if (cells[0] == null) { try { cells[0] = DBUtils.makeNullValue(session, docAttribute.getValueHandler(), docAttribute.getAttribute()); } catch (DBCException e) { log.warn(e); } } } else { cells = new Object[attributes.length]; if (copyCurrent && currentRowNumber >= 0 && currentRowNumber < model.getRowCount()) { Object[] origRow = model.getRowData(currentRowNumber); for (int i = 0; i < attributes.length; i++) { DBDAttributeBinding metaAttr = attributes[i]; DBSAttributeBase attribute = metaAttr.getAttribute(); if (attribute.isAutoGenerated() || attribute.isPseudoAttribute()) { // set pseudo and autoincrement attributes to null cells[i] = null; } else { try { cells[i] = metaAttr.getValueHandler().getValueFromObject(session, attribute, origRow[i], true); } catch (DBCException e) { log.warn(e); try { cells[i] = DBUtils.makeNullValue(session, metaAttr.getValueHandler(), attribute); } catch (DBCException e1) { log.warn(e1); } } } } } else { // Initialize new values for (int i = 0; i < attributes.length; i++) { DBDAttributeBinding metaAttr = attributes[i]; try { cells[i] = DBUtils.makeNullValue(session, metaAttr.getValueHandler(), metaAttr.getAttribute()); } catch (DBCException e) { log.warn(e); } } } } } curRow = model.addNewRow(afterCurrent ? rowNum + 1 : rowNum, cells); redrawData(true); updateEditControls(); fireResultSetChange(); } void deleteSelectedRows() { Set<ResultSetRow> rowsToDelete = new LinkedHashSet<>(); if (recordMode) { rowsToDelete.add(curRow); } else { IResultSetSelection selection = getSelection(); if (!selection.isEmpty()) { rowsToDelete.addAll(selection.getSelectedRows()); } } if (rowsToDelete.isEmpty()) { return; } int rowsRemoved = 0; int lastRowNum = -1; for (ResultSetRow row : rowsToDelete) { if (model.deleteRow(row)) { rowsRemoved++; } lastRowNum = row.getVisualNumber(); } redrawData(rowsRemoved > 0); // Move one row down (if we are in grid mode) if (!recordMode && lastRowNum < model.getRowCount() - 1) { activePresentation.scrollToRow(IResultSetPresentation.RowPosition.NEXT); } updateEditControls(); fireResultSetChange(); } ////////////////////////////////// // Virtual identifier management @Nullable DBDRowIdentifier getVirtualEntityIdentifier() { if (!model.isSingleSource() || model.getVisibleAttributeCount() == 0) { return null; } DBDRowIdentifier rowIdentifier = model.getVisibleAttribute(0).getRowIdentifier(); DBSEntityReferrer identifier = rowIdentifier == null ? null : rowIdentifier.getUniqueKey(); if (identifier != null && identifier instanceof DBVEntityConstraint) { return rowIdentifier; } else { return null; } } boolean checkEntityIdentifier() throws DBException { DBSEntity entity = model.getSingleSource(); if (entity == null) { UIUtils.showErrorDialog( null, "Unrecognized entity", "Can't detect source entity"); return false; } final DBCExecutionContext executionContext = getExecutionContext(); if (executionContext == null) { return false; } // Check for value locators // Probably we have only virtual one with empty attribute set final DBDRowIdentifier identifier = getVirtualEntityIdentifier(); if (identifier != null) { if (CommonUtils.isEmpty(identifier.getAttributes())) { // Empty identifier. We have to define it return new UIConfirmation() { @Override public Boolean runTask() { return ValidateUniqueKeyUsageDialog.validateUniqueKey(ResultSetViewer.this, executionContext); } }.confirm(); } } { // Check attributes of non-virtual identifier DBDRowIdentifier rowIdentifier = model.getVisibleAttribute(0).getRowIdentifier(); if (rowIdentifier == null) { // We shouldn't be here ever! // Virtual id should be created if we missing natural one UIUtils.showErrorDialog( null, "No entity identifier", "Entity " + entity.getName() + " has no unique key"); return false; } else if (CommonUtils.isEmpty(rowIdentifier.getAttributes())) { UIUtils.showErrorDialog( null, "No entity identifier", "Attributes of '" + DBUtils.getObjectFullName(rowIdentifier.getUniqueKey(), DBPEvaluationContext.UI) + "' are missing in result set"); return false; } } return true; } boolean editEntityIdentifier(DBRProgressMonitor monitor) throws DBException { DBDRowIdentifier virtualEntityIdentifier = getVirtualEntityIdentifier(); if (virtualEntityIdentifier == null) { log.warn("No virtual identifier"); return false; } DBVEntityConstraint constraint = (DBVEntityConstraint) virtualEntityIdentifier.getUniqueKey(); EditConstraintDialog dialog = new EditConstraintDialog( getControl().getShell(), "Define virtual unique identifier", constraint); if (dialog.open() != IDialogConstants.OK_ID) { return false; } Collection<DBSEntityAttribute> uniqueAttrs = dialog.getSelectedAttributes(); constraint.setAttributes(uniqueAttrs); virtualEntityIdentifier = getVirtualEntityIdentifier(); if (virtualEntityIdentifier == null) { log.warn("No virtual identifier defined"); return false; } virtualEntityIdentifier.reloadAttributes(monitor, model.getAttributes()); persistConfig(); return true; } void clearEntityIdentifier(DBRProgressMonitor monitor) throws DBException { DBDAttributeBinding firstAttribute = model.getVisibleAttribute(0); DBDRowIdentifier rowIdentifier = firstAttribute.getRowIdentifier(); if (rowIdentifier != null) { DBVEntityConstraint virtualKey = (DBVEntityConstraint) rowIdentifier.getUniqueKey(); virtualKey.setAttributes(Collections.<DBSEntityAttribute>emptyList()); rowIdentifier.reloadAttributes(monitor, model.getAttributes()); virtualKey.getParentObject().setProperty(DBVConstants.PROPERTY_USE_VIRTUAL_KEY_QUIET, null); } persistConfig(); } public void fireResultSetChange() { synchronized (listeners) { if (!listeners.isEmpty()) { for (IResultSetListener listener : listeners) { listener.handleResultSetChange(); } } } } public void fireResultSetLoad() { synchronized (listeners) { if (!listeners.isEmpty()) { for (IResultSetListener listener : listeners) { listener.handleResultSetLoad(); } } } } private static class SimpleFilterManager implements IResultSetFilterManager { private final Map<String, List<String>> filterHistory = new HashMap<>(); @NotNull @Override public List<String> getQueryFilterHistory(@NotNull String query) throws DBException { final List<String> filters = filterHistory.get(query); if (filters != null) { return filters; } return Collections.emptyList(); } @Override public void saveQueryFilterValue(@NotNull String query, @NotNull String filterValue) throws DBException { List<String> filters = filterHistory.get(query); if (filters == null) { filters = new ArrayList<>(); filterHistory.put(query, filters); } filters.add(filterValue); } @Override public void deleteQueryFilterValue(@NotNull String query, String filterValue) throws DBException { List<String> filters = filterHistory.get(query); if (filters != null) { filters.add(filterValue); } } } private class EmptySelection extends StructuredSelection implements IResultSetSelection { @NotNull @Override public IResultSetController getController() { return ResultSetViewer.this; } @NotNull @Override public Collection<DBDAttributeBinding> getSelectedAttributes() { return Collections.emptyList(); } @NotNull @Override public Collection<ResultSetRow> getSelectedRows() { return Collections.emptyList(); } @Override public DBDAttributeBinding getElementAttribute(Object element) { return null; } @Override public ResultSetRow getElementRow(Object element) { return null; } } public static class PanelsMenuContributor extends CompoundContributionItem { @Override protected IContributionItem[] getContributionItems() { final ResultSetViewer rsv = (ResultSetViewer) ResultSetCommandHandler.getActiveResultSet( DBeaverUI.getActiveWorkbenchWindow().getActivePage().getActivePart()); if (rsv == null) { return new IContributionItem[0]; } List<IContributionItem> items = rsv.fillPanelsMenu(); return items.toArray(new IContributionItem[items.size()]); } } private class ConfigAction extends Action implements IMenuCreator { public ConfigAction() { super(CoreMessages.controls_resultset_viewer_action_options, IAction.AS_DROP_DOWN_MENU); setImageDescriptor(DBeaverIcons.getImageDescriptor(UIIcon.CONFIGURATION)); } @Override public IMenuCreator getMenuCreator() { return this; } @Override public void runWithEvent(Event event) { Menu menu = getMenu(activePresentation.getControl()); if (menu != null && event.widget instanceof ToolItem) { Rectangle bounds = ((ToolItem) event.widget).getBounds(); Point point = ((ToolItem) event.widget).getParent().toDisplay(bounds.x, bounds.y + bounds.height); menu.setLocation(point.x, point.y); menu.setVisible(true); } } @Override public void dispose() { } @Override public Menu getMenu(Control parent) { MenuManager menuManager = new MenuManager(); menuManager.add(new ShowFiltersAction(false)); menuManager.add(new CustomizeColorsAction()); menuManager.add(new Separator()); menuManager.add(new VirtualKeyEditAction(true)); menuManager.add(new VirtualKeyEditAction(false)); menuManager.add(new DictionaryEditAction()); menuManager.add(new Separator()); menuManager.add(new ToggleModeAction()); activePresentation.fillMenu(menuManager); if (!CommonUtils.isEmpty(availablePresentations) && availablePresentations.size() > 1) { menuManager.add(new Separator()); for (final ResultSetPresentationDescriptor pd : availablePresentations) { Action action = new Action(pd.getLabel(), IAction.AS_RADIO_BUTTON) { @Override public boolean isEnabled() { return !isRefreshInProgress(); } @Override public boolean isChecked() { return pd == activePresentationDescriptor; } @Override public void run() { switchPresentation(pd); } }; if (pd.getIcon() != null) { //action.setImageDescriptor(ImageDescriptor.createFromImage(pd.getIcon())); } menuManager.add(action); } } menuManager.add(new Separator()); menuManager.add(new Action("Preferences") { @Override public void run() { UIUtils.showPreferencesFor( getControl().getShell(), ResultSetViewer.this, PrefPageDatabaseGeneral.PAGE_ID); } }); return menuManager.createContextMenu(parent); } @Nullable @Override public Menu getMenu(Menu parent) { return null; } } private class ShowFiltersAction extends Action { public ShowFiltersAction(boolean context) { super(context ? "Customize ..." : "Order/Filter ...", DBeaverIcons.getImageDescriptor(UIIcon.FILTER)); } @Override public void run() { new FilterSettingsDialog(ResultSetViewer.this).open(); } } private class ToggleServerSideOrderingAction extends Action { public ToggleServerSideOrderingAction() { super(CoreMessages.pref_page_database_resultsets_label_server_side_order); } @Override public int getStyle() { return AS_CHECK_BOX; } @Override public boolean isChecked() { return getPreferenceStore().getBoolean(DBeaverPreferences.RESULT_SET_ORDER_SERVER_SIDE); } @Override public void run() { DBPPreferenceStore preferenceStore = getPreferenceStore(); preferenceStore.setValue( DBeaverPreferences.RESULT_SET_ORDER_SERVER_SIDE, !preferenceStore.getBoolean(DBeaverPreferences.RESULT_SET_ORDER_SERVER_SIDE)); } } private enum FilterByAttributeType { VALUE(UIIcon.FILTER_VALUE) { @Override Object getValue(@NotNull ResultSetViewer viewer, @NotNull DBDAttributeBinding attribute, @NotNull DBCLogicalOperator operator, boolean useDefault) { final ResultSetRow row = viewer.getCurrentRow(); if (attribute == null || row == null) { return null; } Object cellValue = viewer.model.getCellValue(attribute, row); if (operator == DBCLogicalOperator.LIKE && cellValue != null) { cellValue = "%" + cellValue + "%"; } return cellValue; } }, INPUT(UIIcon.FILTER_INPUT) { @Override Object getValue(@NotNull ResultSetViewer viewer, @NotNull DBDAttributeBinding attribute, @NotNull DBCLogicalOperator operator, boolean useDefault) { if (useDefault) { return ".."; } else { ResultSetRow[] rows = null; if (operator.getArgumentCount() < 0) { Collection<ResultSetRow> selectedRows = viewer.getSelection().getSelectedRows(); rows = selectedRows.toArray(new ResultSetRow[selectedRows.size()]); } else { ResultSetRow focusRow = viewer.getCurrentRow(); if (focusRow != null) { rows = new ResultSetRow[] { focusRow }; } } if (rows == null || rows.length == 0) { return null; } FilterValueEditDialog dialog = new FilterValueEditDialog(viewer, attribute, rows, operator); if (dialog.open() == IDialogConstants.OK_ID) { return dialog.getValue(); } else { return null; } } } }, CLIPBOARD(UIIcon.FILTER_CLIPBOARD) { @Override Object getValue(@NotNull ResultSetViewer viewer, @NotNull DBDAttributeBinding attribute, @NotNull DBCLogicalOperator operator, boolean useDefault) { try { return ResultSetUtils.getAttributeValueFromClipboard(attribute); } catch (DBCException e) { log.debug("Error copying from clipboard", e); return null; } } }, NONE(UIIcon.FILTER_VALUE) { @Override Object getValue(@NotNull ResultSetViewer viewer, @NotNull DBDAttributeBinding attribute, @NotNull DBCLogicalOperator operator, boolean useDefault) { return null; } }; final ImageDescriptor icon; FilterByAttributeType(DBPImage icon) { this.icon = DBeaverIcons.getImageDescriptor(icon); } @Nullable abstract Object getValue(@NotNull ResultSetViewer viewer, @NotNull DBDAttributeBinding attribute, @NotNull DBCLogicalOperator operator, boolean useDefault); } private String translateFilterPattern(DBCLogicalOperator operator, FilterByAttributeType type, DBDAttributeBinding attribute) { Object value = type.getValue(this, attribute, operator, true); DBCExecutionContext executionContext = getExecutionContext(); String strValue = executionContext == null ? String.valueOf(value) : attribute.getValueHandler().getValueDisplayString(attribute, value, DBDDisplayFormat.UI); if (operator.getArgumentCount() == 0) { return operator.getStringValue(); } else { return operator.getStringValue() + " " + CommonUtils.truncateString(strValue, 64); } } private class FilterByAttributeAction extends Action { private final DBCLogicalOperator operator; private final FilterByAttributeType type; private final DBDAttributeBinding attribute; public FilterByAttributeAction(DBCLogicalOperator operator, FilterByAttributeType type, DBDAttributeBinding attribute) { super(attribute.getName() + " " + translateFilterPattern(operator, type, attribute), type.icon); this.operator = operator; this.type = type; this.attribute = attribute; } @Override public void run() { Object value = type.getValue(ResultSetViewer.this, attribute, operator, false); if (operator.getArgumentCount() != 0 && value == null) { return; } DBDDataFilter filter = new DBDDataFilter(model.getDataFilter()); DBDAttributeConstraint constraint = filter.getConstraint(attribute); if (constraint != null) { constraint.setOperator(operator); constraint.setValue(value); setDataFilter(filter, true); } } } private class FilterResetAttributeAction extends Action { private final DBDAttributeBinding attribute; public FilterResetAttributeAction(DBDAttributeBinding attribute) { super("Remove filter for '" + attribute.getName() + "'", DBeaverIcons.getImageDescriptor(UIIcon.REVERT)); this.attribute = attribute; } @Override public void run() { DBDDataFilter dataFilter = new DBDDataFilter(model.getDataFilter()); DBDAttributeConstraint constraint = dataFilter.getConstraint(attribute); if (constraint != null) { constraint.setCriteria(null); setDataFilter(dataFilter, true); } } } private abstract class ColorAction extends Action { protected ColorAction(String name) { super(name); } @NotNull protected DBVEntity getVirtualEntity(DBDAttributeBinding binding) { final DBSEntity entity = getModel().getSingleSource(); if (entity == null) { throw new IllegalStateException("No virtual entity for multi-source query"); } final DBVEntity vEntity = DBVUtils.findVirtualEntity(entity, true); assert vEntity != null; return vEntity; } protected void updateColors(DBVEntity entity) { model.updateColorMapping(); redrawData(false); entity.getDataSource().getContainer().persistConfiguration(); } } private class SetRowColorAction extends ColorAction { private final DBDAttributeBinding attribute; private final Object value; public SetRowColorAction(DBDAttributeBinding attr, Object value) { super("Color by " + attr.getName()); this.attribute = attr; this.value = value; } @Override public void run() { RGB color; final Shell shell = UIUtils.createCenteredShell(getControl().getShell()); try { ColorDialog cd = new ColorDialog(shell); color = cd.open(); if (color == null) { return; } } finally { shell.dispose(); } final DBVEntity vEntity = getVirtualEntity(attribute); vEntity.setColorOverride(attribute, value, null, StringConverter.asString(color)); updateColors(vEntity); } } private class ResetRowColorAction extends ColorAction { private final DBDAttributeBinding attribute; public ResetRowColorAction(DBDAttributeBinding attr, Object value) { super("Reset color by " + attr.getName()); this.attribute = attr; } @Override public void run() { final DBVEntity vEntity = getVirtualEntity(attribute); vEntity.removeColorOverride(attribute); updateColors(vEntity); } } private class CustomizeColorsAction extends ColorAction { private final DBDAttributeBinding curAttribute; private final ResultSetRow row; public CustomizeColorsAction() { this(null, null); } public CustomizeColorsAction(DBDAttributeBinding curAttribute, ResultSetRow row) { super("Row colors ..."); this.curAttribute = curAttribute; this.row = row; } @Override public void run() { ColorSettingsDialog dialog = new ColorSettingsDialog(ResultSetViewer.this, curAttribute, row); if (dialog.open() != IDialogConstants.OK_ID) { return; } final DBVEntity vEntity = getVirtualEntity(curAttribute); //vEntity.removeColorOverride(attribute); updateColors(vEntity); } @Override public boolean isEnabled() { return false; } } private class VirtualKeyEditAction extends Action { private boolean define; public VirtualKeyEditAction(boolean define) { super(define ? "Define virtual unique key" : "Clear virtual unique key"); this.define = define; } @Override public boolean isEnabled() { DBDRowIdentifier identifier = getVirtualEntityIdentifier(); return identifier != null && (define || !CommonUtils.isEmpty(identifier.getAttributes())); } @Override public void run() { DBeaverUI.runUIJob("Edit virtual key", new DBRRunnableWithProgress() { @Override public void run(DBRProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { if (define) { editEntityIdentifier(monitor); } else { clearEntityIdentifier(monitor); } } catch (DBException e) { throw new InvocationTargetException(e); } } }); } } private class DictionaryEditAction extends Action { public DictionaryEditAction() { super("Define dictionary"); } @Override public void run() { EditDictionaryDialog dialog = new EditDictionaryDialog( getSite().getShell(), "Edit dictionary", model.getSingleSource()); dialog.open(); } @Override public boolean isEnabled() { final DBSEntity singleSource = model.getSingleSource(); return singleSource != null; } } private class ToggleModeAction extends Action { { setActionDefinitionId(ResultSetCommandHandler.CMD_TOGGLE_MODE); setImageDescriptor(DBeaverIcons.getImageDescriptor(UIIcon.RS_GRID)); } public ToggleModeAction() { super("Toggle mode", Action.AS_CHECK_BOX); } @Override public boolean isChecked() { return isRecordMode(); } @Override public void run() { toggleMode(); } } private class PresentationSwitchCombo extends ContributionItem implements SelectionListener { private ToolItem toolitem; private CImageCombo combo; @Override public void fill(ToolBar parent, int index) { toolitem = new ToolItem(parent, SWT.SEPARATOR, index); Control control = createControl(parent); toolitem.setControl(control); } @Override public void fill(Composite parent) { createControl(parent); } protected Control createControl(Composite parent) { combo = new CImageCombo(parent, SWT.BORDER | SWT.DROP_DOWN | SWT.READ_ONLY); combo.add(DBeaverIcons.getImage(DBIcon.TYPE_UNKNOWN), "", null, null); final int textWidth = parent.getFont().getFontData()[0].getHeight() * 10; combo.setWidthHint(textWidth); if (toolitem != null) { toolitem.setWidth(textWidth); } combo.addSelectionListener(this); combo.setToolTipText(ActionUtils.findCommandDescription(ResultSetCommandHandler.CMD_SWITCH_PRESENTATION, getSite(), false)); return combo; } @Override public void widgetSelected(SelectionEvent e) { ResultSetPresentationDescriptor selectedPresentation = (ResultSetPresentationDescriptor) combo.getData(combo.getSelectionIndex()); if (activePresentationDescriptor == selectedPresentation) { return; } switchPresentation(selectedPresentation); } @Override public void widgetDefaultSelected(SelectionEvent e) { } } class HistoryStateItem { DBSDataContainer dataContainer; DBDDataFilter filter; int rowNumber; public HistoryStateItem(DBSDataContainer dataContainer, @Nullable DBDDataFilter filter, int rowNumber) { this.dataContainer = dataContainer; this.filter = filter; this.rowNumber = rowNumber; } public String describeState() { DBCExecutionContext context = getExecutionContext(); String desc = dataContainer.getName(); if (context != null && filter != null && filter.hasConditions()) { StringBuilder condBuffer = new StringBuilder(); SQLUtils.appendConditionString(filter, context.getDataSource(), null, condBuffer, true); desc += " [" + condBuffer + "]"; } return desc; } } static class PresentationSettings { final Set<String> enabledPanelIds = new LinkedHashSet<>(); String activePanelId; int panelRatio; boolean panelsVisible; } public static void openNewDataEditor(DBNDatabaseNode targetNode, DBDDataFilter newFilter) { IEditorPart entityEditor = NavigatorHandlerObjectOpen.openEntityEditor( targetNode, DatabaseDataEditor.class.getName(), Collections.<String, Object>singletonMap(DatabaseDataEditor.ATTR_DATA_FILTER, newFilter), DBeaverUI.getActiveWorkbenchWindow() ); if (entityEditor instanceof MultiPageEditorPart) { Object selectedPage = ((MultiPageEditorPart) entityEditor).getSelectedPage(); if (selectedPage instanceof IResultSetContainer) { ResultSetViewer rsv = (ResultSetViewer) ((IResultSetContainer) selectedPage).getResultSetController(); if (rsv != null && !rsv.isRefreshInProgress() && !newFilter.equals(rsv.getModel().getDataFilter())) { // Set filter directly rsv.refreshWithFilter(newFilter); } } } } }
#737 RSV row delete - shift down only if row wasn't removed from the list
plugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/ui/controls/resultset/ResultSetViewer.java
#737 RSV row delete - shift down only if row wasn't removed from the list
<ide><path>lugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/ui/controls/resultset/ResultSetViewer.java <ide> } <ide> redrawData(rowsRemoved > 0); <ide> // Move one row down (if we are in grid mode) <del> if (!recordMode && lastRowNum < model.getRowCount() - 1) { <add> if (!recordMode && lastRowNum < model.getRowCount() - 1 && rowsRemoved == 0) { <ide> activePresentation.scrollToRow(IResultSetPresentation.RowPosition.NEXT); <add> } else { <add> activePresentation.scrollToRow(IResultSetPresentation.RowPosition.CURRENT); <ide> } <ide> <ide> updateEditControls();
Java
apache-2.0
e887b5774179d77d49c324abfc4b992d9217f3d8
0
OpenHFT/Chronicle-Network
package net.openhft.chronicle.network; import net.openhft.chronicle.core.Jvm; import net.openhft.chronicle.core.util.Time; import net.openhft.chronicle.network.connection.FatalFailureMonitor; import net.openhft.chronicle.network.connection.SocketAddressSupplier; import net.openhft.chronicle.wire.Marshallable; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import static net.openhft.chronicle.core.io.Closeable.closeQuietly; public interface ConnectionStrategy extends Marshallable { /** * @param name the name of the connection, only used for logging * @param socketAddressSupplier * @param networkStatsListener * @param didLogIn was the last attempt successfull, was a login established * @param fatalFailureMonitor * @return * @throws InterruptedException */ SocketChannel connect(@NotNull String name, @NotNull SocketAddressSupplier socketAddressSupplier, @Nullable NetworkStatsListener<? extends NetworkContext> networkStatsListener, boolean didLogIn, @Nullable FatalFailureMonitor fatalFailureMonitor) throws InterruptedException; /** * the reason for this method is that unlike the selector it uses tick time */ @Nullable default SocketChannel openSocketChannel(@NotNull InetSocketAddress socketAddress, int tcpBufferSize, long timeoutMs) throws IOException, InterruptedException { assert timeoutMs > 0; long start = Time.tickTime(); SocketChannel sc = socketChannel(socketAddress, tcpBufferSize); if (sc != null) return sc; for (; ; ) { if (Thread.currentThread().isInterrupted()) throw new InterruptedException(); if (start + timeoutMs < Time.tickTime()) { Jvm.warn().on(ConnectionStrategy.class, "Timed out attempting to connect to " + socketAddress); return null; } sc = socketChannel(socketAddress, tcpBufferSize); if (sc != null) return sc; Thread.yield(); } } @Nullable static SocketChannel socketChannel(@NotNull InetSocketAddress socketAddress, int tcpBufferSize) throws IOException { final SocketChannel result = SocketChannel.open(); @Nullable Selector selector = null; boolean failed = true; try { result.configureBlocking(false); Socket socket = result.socket(); socket.setTcpNoDelay(true); socket.setReceiveBufferSize(tcpBufferSize); socket.setSendBufferSize(tcpBufferSize); socket.setSoTimeout(0); socket.setSoLinger(false, 0); result.connect(socketAddress); selector = Selector.open(); result.register(selector, SelectionKey.OP_CONNECT); int select = selector.select(1); if (select == 0) { Jvm.debug().on(ConnectionStrategy.class, "Timed out attempting to connect to " + socketAddress); return null; } else { try { if (!result.finishConnect()) return null; } catch (IOException e) { Jvm.debug().on(ConnectionStrategy.class, "Failed to connect to " + socketAddress + " " + e); return null; } } failed = false; return result; } catch (Exception e) { return null; } finally { closeQuietly(selector); if (failed) closeQuietly(result); } } }
src/main/java/net/openhft/chronicle/network/ConnectionStrategy.java
package net.openhft.chronicle.network; import net.openhft.chronicle.core.Jvm; import net.openhft.chronicle.core.util.Time; import net.openhft.chronicle.network.connection.FatalFailureMonitor; import net.openhft.chronicle.network.connection.SocketAddressSupplier; import net.openhft.chronicle.wire.Marshallable; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import static net.openhft.chronicle.core.io.Closeable.closeQuietly; public interface ConnectionStrategy extends Marshallable { /** * @param name the name of the connection, only used for logging * @param socketAddressSupplier * @param networkStatsListener * @param didLogIn was the last attempt successfull, was a login established * @param fatalFailureMonitor * @return * @throws InterruptedException */ SocketChannel connect(@NotNull String name, @NotNull SocketAddressSupplier socketAddressSupplier, @Nullable NetworkStatsListener<? extends NetworkContext> networkStatsListener, boolean didLogIn, @Nullable FatalFailureMonitor fatalFailureMonitor) throws InterruptedException; /** * the reason for this method is that unlike the selector it uses tick time */ @Nullable default SocketChannel openSocketChannel(@NotNull InetSocketAddress socketAddress, int tcpBufferSize, long timeoutMs) throws IOException, InterruptedException { long start = Time.tickTime(); SocketChannel sc = socketChannel(socketAddress, tcpBufferSize); if (sc != null) return sc; for (; ; ) { if (start + timeoutMs < Time.tickTime()) { Jvm.warn().on(ConnectionStrategy.class, "Timed out attempting to connect to " + socketAddress); return null; } sc = socketChannel(socketAddress, tcpBufferSize); if (sc != null) return sc; Thread.yield(); } } @Nullable static SocketChannel socketChannel(@NotNull InetSocketAddress socketAddress, int tcpBufferSize) throws IOException { final SocketChannel result = SocketChannel.open(); @Nullable Selector selector = null; boolean failed = true; try { result.configureBlocking(false); Socket socket = result.socket(); socket.setTcpNoDelay(true); socket.setReceiveBufferSize(tcpBufferSize); socket.setSendBufferSize(tcpBufferSize); socket.setSoTimeout(0); socket.setSoLinger(false, 0); result.connect(socketAddress); selector = Selector.open(); result.register(selector, SelectionKey.OP_CONNECT); int select = selector.select(1); if (select == 0) { Jvm.debug().on(ConnectionStrategy.class, "Timed out attempting to connect to " + socketAddress); return null; } else { try { if (!result.finishConnect()) return null; } catch (IOException e) { Jvm.debug().on(ConnectionStrategy.class, "Failed to connect to " + socketAddress + " " + e); return null; } } failed = false; return result; } catch (Exception e) { return null; } finally { closeQuietly(selector); if (failed) closeQuietly(result); } } }
added support for enqueuing the the fix sendMessage() directly on the out bytes, rather than going via an intermediate buffer
src/main/java/net/openhft/chronicle/network/ConnectionStrategy.java
added support for enqueuing the the fix sendMessage() directly on the out bytes, rather than going via an intermediate buffer
<ide><path>rc/main/java/net/openhft/chronicle/network/ConnectionStrategy.java <ide> default SocketChannel openSocketChannel(@NotNull InetSocketAddress socketAddress, <ide> int tcpBufferSize, <ide> long timeoutMs) throws IOException, InterruptedException { <del> <add> assert timeoutMs > 0; <ide> long start = Time.tickTime(); <ide> SocketChannel sc = socketChannel(socketAddress, tcpBufferSize); <ide> if (sc != null) <ide> return sc; <ide> <ide> for (; ; ) { <add> if (Thread.currentThread().isInterrupted()) <add> throw new InterruptedException(); <ide> if (start + timeoutMs < Time.tickTime()) { <ide> Jvm.warn().on(ConnectionStrategy.class, "Timed out attempting to connect to " + socketAddress); <ide> return null;
Java
apache-2.0
46bc0deb60983549b9e895d51ae130bd5b5786ba
0
rwl/requestfactory-addon
package org.springframework.roo.addon.web.mvc.controller; import java.beans.Introspector; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import java.util.Map.Entry; import java.util.logging.Logger; import org.springframework.roo.addon.beaninfo.BeanInfoMetadata; import org.springframework.roo.addon.beaninfo.BeanInfoUtils; import org.springframework.roo.addon.entity.EntityMetadata; import org.springframework.roo.addon.entity.RooIdentifier; import org.springframework.roo.addon.finder.FinderMetadata; import org.springframework.roo.addon.json.JsonMetadata; import org.springframework.roo.addon.plural.PluralMetadata; import org.springframework.roo.classpath.PhysicalTypeCategory; import org.springframework.roo.classpath.PhysicalTypeDetails; import org.springframework.roo.classpath.PhysicalTypeIdentifier; import org.springframework.roo.classpath.PhysicalTypeIdentifierNamingUtils; import org.springframework.roo.classpath.PhysicalTypeMetadata; import org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails; import org.springframework.roo.classpath.details.FieldMetadata; import org.springframework.roo.classpath.details.MemberFindingUtils; import org.springframework.roo.classpath.details.MethodMetadata; import org.springframework.roo.classpath.details.MethodMetadataBuilder; import org.springframework.roo.classpath.details.annotations.AnnotatedJavaType; import org.springframework.roo.classpath.details.annotations.AnnotationAttributeValue; import org.springframework.roo.classpath.details.annotations.AnnotationMetadata; import org.springframework.roo.classpath.details.annotations.AnnotationMetadataBuilder; import org.springframework.roo.classpath.details.annotations.ArrayAttributeValue; import org.springframework.roo.classpath.details.annotations.BooleanAttributeValue; import org.springframework.roo.classpath.details.annotations.EnumAttributeValue; import org.springframework.roo.classpath.details.annotations.StringAttributeValue; import org.springframework.roo.classpath.itd.AbstractItdTypeDetailsProvidingMetadataItem; import org.springframework.roo.classpath.itd.InvocableMemberBodyBuilder; import org.springframework.roo.classpath.itd.ItdSourceFileComposer; import org.springframework.roo.classpath.scanner.MemberDetailsScanner; import org.springframework.roo.metadata.MetadataIdentificationUtils; import org.springframework.roo.metadata.MetadataService; import org.springframework.roo.model.DataType; import org.springframework.roo.model.EnumDetails; import org.springframework.roo.model.JavaSymbolName; import org.springframework.roo.model.JavaType; import org.springframework.roo.model.ReservedWords; import org.springframework.roo.project.Path; import org.springframework.roo.support.style.ToStringCreator; import org.springframework.roo.support.util.Assert; import org.springframework.roo.support.util.StringUtils; /** * Metadata for {@link RooWebScaffold}. * * @author Stefan Schmidt * @since 1.0 */ public class WebScaffoldMetadata extends AbstractItdTypeDetailsProvidingMetadataItem { private static final String PROVIDES_TYPE_STRING = WebScaffoldMetadata.class.getName(); private static final String PROVIDES_TYPE = MetadataIdentificationUtils.create(PROVIDES_TYPE_STRING); private WebScaffoldAnnotationValues annotationValues; private BeanInfoMetadata beanInfoMetadata; private EntityMetadata entityMetadata; private MetadataService metadataService; private SortedSet<JavaType> specialDomainTypes; private String controllerPath; private String entityName; private Map<JavaSymbolName, DateTimeFormat> dateTypes; private Map<JavaType, String> pluralCache; private JsonMetadata jsonMetadata; private Logger log = Logger.getLogger(getClass().getName()); private MemberDetailsScanner detailsScanner; public WebScaffoldMetadata(String identifier, JavaType aspectName, PhysicalTypeMetadata governorPhysicalTypeMetadata, MetadataService metadataService, MemberDetailsScanner detailsScanner, WebScaffoldAnnotationValues annotationValues, BeanInfoMetadata beanInfoMetadata, EntityMetadata entityMetadata, FinderMetadata finderMetadata, ControllerOperations controllerOperations) { super(identifier, aspectName, governorPhysicalTypeMetadata); Assert.isTrue(isValid(identifier), "Metadata identification string '" + identifier + "' does not appear to be a valid"); Assert.notNull(annotationValues, "Annotation values required"); Assert.notNull(metadataService, "Metadata service required"); Assert.notNull(beanInfoMetadata, "Bean info metadata required"); Assert.notNull(entityMetadata, "Entity metadata required"); Assert.notNull(finderMetadata, "Finder metadata required"); Assert.notNull(controllerOperations, "Controller operations required"); Assert.notNull(detailsScanner, "Member details scanner required"); if (!isValid()) { return; } this.pluralCache = new HashMap<JavaType, String>(); this.annotationValues = annotationValues; this.beanInfoMetadata = beanInfoMetadata; this.entityMetadata = entityMetadata; this.detailsScanner = detailsScanner; this.entityName = uncapitalize(beanInfoMetadata.getJavaBean().getSimpleTypeName()); if (ReservedWords.RESERVED_JAVA_KEYWORDS.contains(this.entityName)) { this.entityName = "_" + entityName; } this.controllerPath = annotationValues.getPath(); this.metadataService = metadataService; specialDomainTypes = getSpecialDomainTypes(beanInfoMetadata.getJavaBean()); dateTypes = getDatePatterns(); if (annotationValues.create) { builder.addMethod(getCreateMethod()); builder.addMethod(getCreateFormMethod()); } builder.addMethod(getShowMethod()); builder.addMethod(getListMethod()); if (annotationValues.update) { builder.addMethod(getUpdateMethod()); builder.addMethod(getUpdateFormMethod()); } if (annotationValues.delete) { builder.addMethod(getDeleteMethod()); } if (annotationValues.exposeFinders) { // No need for null check of entityMetadata.getDynamicFinders as it guarantees non-null (but maybe empty list) for (String finderName : entityMetadata.getDynamicFinders()) { builder.addMethod(getFinderFormMethod(finderMetadata.getDynamicFinderMethod(finderName, beanInfoMetadata.getJavaBean().getSimpleTypeName().toLowerCase()))); builder.addMethod(getFinderMethod(finderMetadata.getDynamicFinderMethod(finderName, beanInfoMetadata.getJavaBean().getSimpleTypeName().toLowerCase()))); } } if (specialDomainTypes.size() > 0) { for (MethodMetadata method : getPopulateMethods()) { builder.addMethod(method); } } if (!dateTypes.isEmpty()) { builder.addMethod(getDateTimeFormatHelperMethod()); } if (annotationValues.isExposeJson()) { // Decide if we want to build json support this.jsonMetadata = (JsonMetadata) metadataService.get(JsonMetadata.createIdentifier(beanInfoMetadata.getJavaBean(), Path.SRC_MAIN_JAVA)); if (jsonMetadata != null) { builder.addMethod(getJsonShowMethod()); builder.addMethod(getJsonListMethod()); builder.addMethod(getJsonCreateMethod()); builder.addMethod(getCreateFromJsonArrayMethod()); builder.addMethod(getJsonUpdateMethod()); builder.addMethod(getUpdateFromJsonArrayMethod()); builder.addMethod(getJsonDeleteMethod()); if (annotationValues.exposeFinders) { for (String finderName : entityMetadata.getDynamicFinders()) { builder.addMethod(getFinderJsonMethod(finderMetadata.getDynamicFinderMethod(finderName, beanInfoMetadata.getJavaBean().getSimpleTypeName().toLowerCase()))); } } } } if (annotationValues.isCreate() || annotationValues.isUpdate()) { builder.addMethod(getEncodeUrlPathSegmentMethod()); } itdTypeDetails = builder.build(); new ItdSourceFileComposer(itdTypeDetails); } public String getIdentifierForBeanInfoMetadata() { return beanInfoMetadata.getId(); } public String getIdentifierForEntityMetadata() { return entityMetadata.getId(); } public WebScaffoldAnnotationValues getAnnotationValues() { return annotationValues; } private MethodMetadata getDeleteMethod() { if (entityMetadata.getFindMethod() == null || entityMetadata.getRemoveMethod() == null) { // Mandatory input is missing (ROO-589) return null; } JavaSymbolName methodName = new JavaSymbolName("delete"); List<AnnotationMetadata> typeAnnotations = new ArrayList<AnnotationMetadata>(); List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>(); attributes.add(new StringAttributeValue(new JavaSymbolName("value"), entityMetadata.getIdentifierField().getFieldName().getSymbolName())); AnnotationMetadataBuilder pathVariableAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.PathVariable"), attributes); typeAnnotations.add(pathVariableAnnotation.build()); List<AnnotationAttributeValue<?>> firstResultAttributes = new ArrayList<AnnotationAttributeValue<?>>(); firstResultAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "page")); firstResultAttributes.add(new BooleanAttributeValue(new JavaSymbolName("required"), false)); List<AnnotationMetadata> firstResultAnnotations = new ArrayList<AnnotationMetadata>(); AnnotationMetadataBuilder firstResultAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestParam"), firstResultAttributes); firstResultAnnotations.add(firstResultAnnotation.build()); List<AnnotationAttributeValue<?>> maxResultsAttributes = new ArrayList<AnnotationAttributeValue<?>>(); maxResultsAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "size")); maxResultsAttributes.add(new BooleanAttributeValue(new JavaSymbolName("required"), false)); List<AnnotationMetadata> maxResultsAnnotations = new ArrayList<AnnotationMetadata>(); AnnotationMetadataBuilder maxResultAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestParam"), maxResultsAttributes); maxResultsAnnotations.add(maxResultAnnotation.build()); List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>(); paramTypes.add(new AnnotatedJavaType(entityMetadata.getIdentifierField().getFieldType(), typeAnnotations)); paramTypes.add(new AnnotatedJavaType(new JavaType(Integer.class.getName()), firstResultAnnotations)); paramTypes.add(new AnnotatedJavaType(new JavaType(Integer.class.getName()), maxResultsAnnotations)); paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.Model"), null)); MethodMetadata method = methodExists(methodName, paramTypes); if (method != null) return method; List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(); paramNames.add(new JavaSymbolName(entityMetadata.getIdentifierField().getFieldName().getSymbolName())); paramNames.add(new JavaSymbolName("page")); paramNames.add(new JavaSymbolName("size")); paramNames.add(new JavaSymbolName("model")); List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "/{" + entityMetadata.getIdentifierField().getFieldName().getSymbolName() + "}")); requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("DELETE")))); AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(requestMapping); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine(beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "." + entityMetadata.getFindMethod().getMethodName() + "(" + entityMetadata.getIdentifierField().getFieldName().getSymbolName() + ")." + entityMetadata.getRemoveMethod().getMethodName() + "();"); bodyBuilder.appendFormalLine("model.addAttribute(\"page\", (page == null) ? \"1\" : page.toString());"); bodyBuilder.appendFormalLine("model.addAttribute(\"size\", (size == null) ? \"10\" : size.toString());"); bodyBuilder.appendFormalLine("return \"redirect:/" + controllerPath + "?page=\" + ((page == null) ? \"1\" : page.toString()) + \"&size=\" + ((size == null) ? \"10\" : size.toString());"); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.STRING_OBJECT, paramTypes, paramNames, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getListMethod() { if (entityMetadata.getFindEntriesMethod() == null || entityMetadata.getCountMethod() == null || entityMetadata.getFindAllMethod() == null) { // Mandatory input is missing (ROO-589) return null; } JavaSymbolName methodName = new JavaSymbolName("list"); List<AnnotationAttributeValue<?>> firstResultAttributes = new ArrayList<AnnotationAttributeValue<?>>(); firstResultAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "page")); firstResultAttributes.add(new BooleanAttributeValue(new JavaSymbolName("required"), false)); List<AnnotationMetadata> firstResultAnnotations = new ArrayList<AnnotationMetadata>(); AnnotationMetadataBuilder firstResultAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestParam"), firstResultAttributes); firstResultAnnotations.add(firstResultAnnotation.build()); List<AnnotationAttributeValue<?>> maxResultsAttributes = new ArrayList<AnnotationAttributeValue<?>>(); maxResultsAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "size")); maxResultsAttributes.add(new BooleanAttributeValue(new JavaSymbolName("required"), false)); List<AnnotationMetadata> maxResultsAnnotations = new ArrayList<AnnotationMetadata>(); AnnotationMetadataBuilder maxResultAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestParam"), maxResultsAttributes); maxResultsAnnotations.add(maxResultAnnotation.build()); List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>(); paramTypes.add(new AnnotatedJavaType(new JavaType(Integer.class.getName()), firstResultAnnotations)); paramTypes.add(new AnnotatedJavaType(new JavaType(Integer.class.getName()), maxResultsAnnotations)); paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.Model"), null)); MethodMetadata method = methodExists(methodName, paramTypes); if (method != null) { return method; } List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(); paramNames.add(new JavaSymbolName("page")); paramNames.add(new JavaSymbolName("size")); paramNames.add(new JavaSymbolName("model")); List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("GET")))); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes)); String plural = getPlural(beanInfoMetadata.getJavaBean()).toLowerCase(); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine("if (page != null || size != null) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine("int sizeNo = size == null ? 10 : size.intValue();"); bodyBuilder.appendFormalLine("model.addAttribute(\"" + plural + "\", " + beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "." + entityMetadata.getFindEntriesMethod().getMethodName() + "(page == null ? 0 : (page.intValue() - 1) * sizeNo, sizeNo));"); bodyBuilder.appendFormalLine("float nrOfPages = (float) " + beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "." + entityMetadata.getCountMethod().getMethodName() + "() / sizeNo;"); bodyBuilder.appendFormalLine("model.addAttribute(\"maxPages\", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("} else {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine("model.addAttribute(\"" + plural + "\", " + beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "." + entityMetadata.getFindAllMethod().getMethodName() + "());"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); if (!dateTypes.isEmpty()) { bodyBuilder.appendFormalLine("addDateTimeFormatPatterns(model);"); } bodyBuilder.appendFormalLine("return \"" + controllerPath + "/list\";"); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.STRING_OBJECT, paramTypes, paramNames, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getShowMethod() { if (entityMetadata.getFindMethod() == null) { // Mandatory input is missing (ROO-589) return null; } JavaSymbolName methodName = new JavaSymbolName("show"); List<AnnotationMetadata> typeAnnotations = new ArrayList<AnnotationMetadata>(); List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>(); attributes.add(new StringAttributeValue(new JavaSymbolName("value"), entityMetadata.getIdentifierField().getFieldName().getSymbolName())); AnnotationMetadataBuilder pathVariableAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.PathVariable"), attributes); typeAnnotations.add(pathVariableAnnotation.build()); List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>(); paramTypes.add(new AnnotatedJavaType(entityMetadata.getIdentifierField().getFieldType(), typeAnnotations)); paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.Model"), null)); MethodMetadata method = methodExists(methodName, paramTypes); if (method != null) return method; List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(); paramNames.add(new JavaSymbolName(entityMetadata.getIdentifierField().getFieldName().getSymbolName())); paramNames.add(new JavaSymbolName("model")); List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "/{" + entityMetadata.getIdentifierField().getFieldName().getSymbolName() + "}")); requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("GET")))); AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(requestMapping); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); if (!dateTypes.isEmpty()) { bodyBuilder.appendFormalLine("addDateTimeFormatPatterns(model);"); } bodyBuilder.appendFormalLine("model.addAttribute(\"" + entityName.toLowerCase() + "\", " + beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "." + entityMetadata.getFindMethod().getMethodName() + "(" + entityMetadata.getIdentifierField().getFieldName().getSymbolName() + "));"); bodyBuilder.appendFormalLine("model.addAttribute(\"itemId\", " + entityMetadata.getIdentifierField().getFieldName().getSymbolName() + ");"); bodyBuilder.appendFormalLine("return \"" + controllerPath + "/show\";"); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.STRING_OBJECT, paramTypes, paramNames, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getCreateMethod() { if (entityMetadata.getPersistMethod() == null) {// || entityMetadata.getFindAllMethod() == null) { // Mandatory input is missing (ROO-589) return null; } JavaSymbolName methodName = new JavaSymbolName("create"); List<AnnotationMetadata> typeAnnotations = new ArrayList<AnnotationMetadata>(); AnnotationMetadataBuilder validAnnotation = new AnnotationMetadataBuilder(new JavaType("javax.validation.Valid")); typeAnnotations.add(validAnnotation.build()); List<AnnotationMetadata> noAnnotations = new ArrayList<AnnotationMetadata>(); List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>(); paramTypes.add(new AnnotatedJavaType(beanInfoMetadata.getJavaBean(), typeAnnotations)); paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.validation.BindingResult"), noAnnotations)); paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.Model"), noAnnotations)); paramTypes.add(new AnnotatedJavaType(new JavaType("javax.servlet.http.HttpServletRequest"), noAnnotations)); MethodMetadata method = methodExists(methodName, paramTypes); if (method != null) return method; List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(); paramNames.add(new JavaSymbolName(entityName)); paramNames.add(new JavaSymbolName("result")); paramNames.add(new JavaSymbolName("model")); paramNames.add(new JavaSymbolName("request")); List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("POST")))); AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(requestMapping); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine("if (result.hasErrors()) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine("model.addAttribute(\"" + entityName + "\", " + entityName + ");"); if (!dateTypes.isEmpty()) { bodyBuilder.appendFormalLine("addDateTimeFormatPatterns(model);"); } bodyBuilder.appendFormalLine("return \"" + controllerPath + "/create\";"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); bodyBuilder.appendFormalLine(entityName + "." + entityMetadata.getPersistMethod().getMethodName() + "();"); bodyBuilder.appendFormalLine("return \"redirect:/" + controllerPath + "/\" + encodeUrlPathSegment(" + entityName + "." + entityMetadata.getIdentifierAccessor().getMethodName() + "().toString(), request);"); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.STRING_OBJECT, paramTypes, paramNames, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getCreateFormMethod() { // if (entityMetadata.getFindAllMethod() == null) { // // Mandatory input is missing (ROO-589) // return null; // } JavaSymbolName methodName = new JavaSymbolName("createForm"); List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>(); paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.Model"), null)); MethodMetadata method = methodExists(methodName, paramTypes); if (method != null) return method; List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(); paramNames.add(new JavaSymbolName("model")); List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("params"), "form")); requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("GET")))); AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(requestMapping); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine("model.addAttribute(\"" + entityName + "\", new " + beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "());"); if (!dateTypes.isEmpty()) { bodyBuilder.appendFormalLine("addDateTimeFormatPatterns(model);"); } boolean listAdded = false; for (MethodMetadata accessorMethod : beanInfoMetadata.getPublicAccessors()) { if (specialDomainTypes.contains(accessorMethod.getReturnType())) { FieldMetadata field = beanInfoMetadata.getFieldForPropertyName(BeanInfoUtils.getPropertyNameForJavaBeanMethod(accessorMethod)); if (null != field && null != MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.validation.constraints.NotNull"))) { EntityMetadata entityMetadata = (EntityMetadata) metadataService.get(EntityMetadata.createIdentifier(accessorMethod.getReturnType(), Path.SRC_MAIN_JAVA)); if (entityMetadata != null) { if (!listAdded) { String listShort = new JavaType("java.util.List").getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()); String arrayListShort = new JavaType("java.util.ArrayList").getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()); bodyBuilder.appendFormalLine(listShort + " dependencies = new " + arrayListShort + "();"); listAdded = true; } bodyBuilder.appendFormalLine("if (" + accessorMethod.getReturnType().getSimpleTypeName() + "." + entityMetadata.getCountMethod().getMethodName().getSymbolName() + "() == 0) {"); bodyBuilder.indent(); // Adding string array which has the fieldName at position 0 and the path at position 1 bodyBuilder.appendFormalLine("dependencies.add(new String[]{\"" + field.getFieldName().getSymbolName() + "\", \"" + entityMetadata.getPlural().toLowerCase() + "\"});"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } } } } if (listAdded) { bodyBuilder.appendFormalLine("model.addAttribute(\"dependencies\", dependencies);"); } bodyBuilder.appendFormalLine("return \"" + controllerPath + "/create\";"); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.STRING_OBJECT, paramTypes, paramNames, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getUpdateMethod() { if (entityMetadata.getMergeMethod() == null) {// || entityMetadata.getFindAllMethod() == null) { // Mandatory input is missing (ROO-589) return null; } JavaSymbolName methodName = new JavaSymbolName("update"); List<AnnotationMetadata> typeAnnotations = new ArrayList<AnnotationMetadata>(); AnnotationMetadataBuilder validAnnotation = new AnnotationMetadataBuilder(new JavaType("javax.validation.Valid")); typeAnnotations.add(validAnnotation.build()); List<AnnotationMetadata> noAnnotations = new ArrayList<AnnotationMetadata>(); List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>(); paramTypes.add(new AnnotatedJavaType(beanInfoMetadata.getJavaBean(), typeAnnotations)); paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.validation.BindingResult"), noAnnotations)); paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.Model"), noAnnotations)); paramTypes.add(new AnnotatedJavaType(new JavaType("javax.servlet.http.HttpServletRequest"), noAnnotations)); MethodMetadata method = methodExists(methodName, paramTypes); if (method != null) return method; List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(); paramNames.add(new JavaSymbolName(entityName)); paramNames.add(new JavaSymbolName("result")); paramNames.add(new JavaSymbolName("model")); paramNames.add(new JavaSymbolName("request")); List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("PUT")))); AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(requestMapping); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine("if (result.hasErrors()) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine("model.addAttribute(\"" + entityName + "\", " + entityName + ");"); if (!dateTypes.isEmpty()) { bodyBuilder.appendFormalLine("addDateTimeFormatPatterns(model);"); } bodyBuilder.appendFormalLine("return \"" + controllerPath + "/update\";"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); bodyBuilder.appendFormalLine(entityName + "." + entityMetadata.getMergeMethod().getMethodName() + "();"); bodyBuilder.appendFormalLine("return \"redirect:/" + controllerPath + "/\" + encodeUrlPathSegment(" + entityName + "." + entityMetadata.getIdentifierAccessor().getMethodName() + "().toString(), request);"); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.STRING_OBJECT, paramTypes, paramNames, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getUpdateFormMethod() { if (entityMetadata.getFindMethod() == null) {// || entityMetadata.getFindAllMethod() == null) { // Mandatory input is missing (ROO-589) return null; } JavaSymbolName methodName = new JavaSymbolName("updateForm"); List<AnnotationMetadata> typeAnnotations = new ArrayList<AnnotationMetadata>(); List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>(); attributes.add(new StringAttributeValue(new JavaSymbolName("value"), entityMetadata.getIdentifierField().getFieldName().getSymbolName())); AnnotationMetadataBuilder pathVariableAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.PathVariable"), attributes); typeAnnotations.add(pathVariableAnnotation.build()); List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>(); paramTypes.add(new AnnotatedJavaType(entityMetadata.getIdentifierField().getFieldType(), typeAnnotations)); paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.Model"), null)); MethodMetadata updateFormMethod = methodExists(methodName, paramTypes); if (updateFormMethod != null) return updateFormMethod; List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(); paramNames.add(new JavaSymbolName(entityMetadata.getIdentifierField().getFieldName().getSymbolName())); paramNames.add(new JavaSymbolName("model")); List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "/{" + entityMetadata.getIdentifierField().getFieldName().getSymbolName() + "}")); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("params"), "form")); requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("GET")))); AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(requestMapping); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine("model.addAttribute(\"" + entityName + "\", " + beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "." + entityMetadata.getFindMethod().getMethodName() + "(" + entityMetadata.getIdentifierField().getFieldName().getSymbolName() + "));"); if (!dateTypes.isEmpty()) { bodyBuilder.appendFormalLine("addDateTimeFormatPatterns(model);"); } bodyBuilder.appendFormalLine("return \"" + controllerPath + "/update\";"); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.STRING_OBJECT, paramTypes, paramNames, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getJsonShowMethod() { JavaSymbolName toJsonMethodName = jsonMetadata.getToJsonMethodName(); if (toJsonMethodName == null || entityMetadata.getFindMethod() == null) { return null; } JavaSymbolName methodName = new JavaSymbolName("showJson"); List<AnnotationMetadata> parameters = new ArrayList<AnnotationMetadata>(); List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>(); attributes.add(new StringAttributeValue(new JavaSymbolName("value"), entityMetadata.getIdentifierField().getFieldName().getSymbolName())); AnnotationMetadataBuilder pathVariableAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.PathVariable"), attributes); parameters.add(pathVariableAnnotation.build()); List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>(); paramTypes.add(new AnnotatedJavaType(entityMetadata.getIdentifierField().getFieldType(), parameters)); MethodMetadata jsonShowMethod = methodExists(methodName, paramTypes); if (jsonShowMethod != null) return jsonShowMethod; List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(); paramNames.add(new JavaSymbolName(entityMetadata.getIdentifierField().getFieldName().getSymbolName())); List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "/{" + entityMetadata.getIdentifierField().getFieldName().getSymbolName() + "}")); requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("GET")))); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("headers"), "Accept=application/json")); AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(requestMapping); annotations.add(new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.ResponseBody"))); String beanShortName = getShortName(beanInfoMetadata.getJavaBean()); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine(beanShortName + " " + beanShortName.toLowerCase() + " = " + beanShortName + "." + entityMetadata.getFindMethod().getMethodName() + "(" + entityMetadata.getIdentifierField().getFieldName().getSymbolName() + ");"); bodyBuilder.appendFormalLine("if (" + beanShortName.toLowerCase() + " == null) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine("return new " + getShortName(new JavaType("org.springframework.http.ResponseEntity")) + "<String>(" + getShortName(new JavaType("org.springframework.http.HttpStatus")) + ".NOT_FOUND);"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); bodyBuilder.appendFormalLine("return " + beanShortName.toLowerCase() + "." + toJsonMethodName.getSymbolName() + "();"); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, new JavaType("java.lang.Object"), paramTypes, paramNames, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getJsonCreateMethod() { JavaSymbolName fromJsonMethodName = jsonMetadata.getFromJsonMethodName(); if (fromJsonMethodName == null || entityMetadata.getPersistMethod() == null) { return null; } JavaSymbolName methodName = new JavaSymbolName("createFromJson"); List<AnnotationMetadata> parameters = new ArrayList<AnnotationMetadata>(); AnnotationMetadataBuilder requestBodyAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestBody")); parameters.add(requestBodyAnnotation.build()); List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>(); paramTypes.add(new AnnotatedJavaType(JavaType.STRING_OBJECT, parameters)); MethodMetadata jsonCreateMethod = methodExists(methodName, paramTypes); if (jsonCreateMethod != null) return jsonCreateMethod; List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(); paramNames.add(new JavaSymbolName("json")); List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("POST")))); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("headers"), "Accept=application/json")); AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(requestMapping); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine(beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "." + fromJsonMethodName.getSymbolName() + "(json)." + entityMetadata.getPersistMethod().getMethodName().getSymbolName() + "();"); bodyBuilder.appendFormalLine("return new ResponseEntity<String>(" + new JavaType("org.springframework.http.HttpStatus").getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + ".CREATED);"); List<JavaType> typeParams = new ArrayList<JavaType>(); typeParams.add(JavaType.STRING_OBJECT); JavaType returnType = new JavaType("org.springframework.http.ResponseEntity", 0, DataType.TYPE, null, typeParams); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, returnType, paramTypes, paramNames, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getCreateFromJsonArrayMethod() { JavaSymbolName fromJsonArrayMethodName = jsonMetadata.getFromJsonArrayMethodName(); if (fromJsonArrayMethodName == null || entityMetadata.getPersistMethod() == null) { return null; } JavaSymbolName methodName = new JavaSymbolName("createFromJsonArray"); List<AnnotationMetadata> parameters = new ArrayList<AnnotationMetadata>(); AnnotationMetadataBuilder requestBodyAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestBody")); parameters.add(requestBodyAnnotation.build()); List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>(); paramTypes.add(new AnnotatedJavaType(JavaType.STRING_OBJECT, parameters)); MethodMetadata existingMethod = methodExists(methodName, paramTypes); if (existingMethod != null) return existingMethod; List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(); paramNames.add(new JavaSymbolName("json")); List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "/jsonArray")); requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("POST")))); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("headers"), "Accept=application/json")); AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(requestMapping); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); String beanName = beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()); List<JavaType> params = new ArrayList<JavaType>(); params.add(beanInfoMetadata.getJavaBean()); bodyBuilder.appendFormalLine("for (" + beanName + " " + entityName + ": " + beanName + "." + fromJsonArrayMethodName.getSymbolName() + "(json)) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(entityName + "." + entityMetadata.getPersistMethod().getMethodName().getSymbolName() + "();"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); bodyBuilder.appendFormalLine("return new ResponseEntity<String>(" + new JavaType("org.springframework.http.HttpStatus").getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + ".CREATED);"); List<JavaType> typeParams = new ArrayList<JavaType>(); typeParams.add(JavaType.STRING_OBJECT); JavaType returnType = new JavaType("org.springframework.http.ResponseEntity", 0, DataType.TYPE, null, typeParams); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, returnType, paramTypes, paramNames, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getJsonListMethod() { JavaSymbolName toJsonArrayMethodName = jsonMetadata.getToJsonArrayMethodName(); if (toJsonArrayMethodName == null || entityMetadata.getFindAllMethod() == null) { return null; } // See if the type itself declared the method JavaSymbolName methodName = new JavaSymbolName("listJson"); MethodMetadata result = MemberFindingUtils.getDeclaredMethod(governorTypeDetails, methodName, null); if (result != null) { return result; } List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("headers"), "Accept=application/json")); AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(requestMapping); annotations.add(new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.ResponseBody"))); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); String entityName = beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()); bodyBuilder.appendFormalLine("return " + entityName + "." + toJsonArrayMethodName.getSymbolName() + "(" + entityName + "." + entityMetadata.getFindAllMethod().getMethodName() + "());"); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.STRING_OBJECT, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getJsonUpdateMethod() { JavaSymbolName fromJsonMethodName = jsonMetadata.getFromJsonMethodName(); if (fromJsonMethodName == null || entityMetadata.getMergeMethod() == null) { return null; } JavaSymbolName methodName = new JavaSymbolName("updateFromJson"); List<AnnotationMetadata> parameters = new ArrayList<AnnotationMetadata>(); AnnotationMetadataBuilder requestBodyAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestBody")); parameters.add(requestBodyAnnotation.build()); List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>(); paramTypes.add(new AnnotatedJavaType(JavaType.STRING_OBJECT, parameters)); MethodMetadata jsonCreateMethod = methodExists(methodName, paramTypes); if (jsonCreateMethod != null) return jsonCreateMethod; List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(); paramNames.add(new JavaSymbolName("json")); List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("PUT")))); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("headers"), "Accept=application/json")); AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(requestMapping); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); String beanShortName = beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()); bodyBuilder.appendFormalLine("if (" + beanShortName + "." + fromJsonMethodName.getSymbolName() + "(json)." + entityMetadata.getMergeMethod().getMethodName().getSymbolName() + "() == null) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine("return new ResponseEntity<String>(" + new JavaType("org.springframework.http.HttpStatus").getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + ".NOT_FOUND);"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); bodyBuilder.appendFormalLine("return new ResponseEntity<String>(" + new JavaType("org.springframework.http.HttpStatus").getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + ".OK);"); List<JavaType> typeParams = new ArrayList<JavaType>(); typeParams.add(JavaType.STRING_OBJECT); JavaType returnType = new JavaType("org.springframework.http.ResponseEntity", 0, DataType.TYPE, null, typeParams); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, returnType, paramTypes, paramNames, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getUpdateFromJsonArrayMethod() { JavaSymbolName fromJsonArrayMethodName = jsonMetadata.getFromJsonArrayMethodName(); if (fromJsonArrayMethodName == null || entityMetadata.getMergeMethod() == null) { return null; } JavaSymbolName methodName = new JavaSymbolName("updateFromJsonArray"); List<AnnotationMetadata> parameters = new ArrayList<AnnotationMetadata>(); AnnotationMetadataBuilder requestBodyAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestBody")); parameters.add(requestBodyAnnotation.build()); List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>(); paramTypes.add(new AnnotatedJavaType(JavaType.STRING_OBJECT, parameters)); MethodMetadata existingMethod = methodExists(methodName, paramTypes); if (existingMethod != null) return existingMethod; List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(); paramNames.add(new JavaSymbolName("json")); List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "/jsonArray")); requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("PUT")))); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("headers"), "Accept=application/json")); AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(requestMapping); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); String beanName = beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()); List<JavaType> params = new ArrayList<JavaType>(); params.add(beanInfoMetadata.getJavaBean()); bodyBuilder.appendFormalLine("for (" + beanName + " " + entityName + ": " + beanName + "." + fromJsonArrayMethodName.getSymbolName() + "(json)) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine("if (" + entityName + "." + entityMetadata.getMergeMethod().getMethodName().getSymbolName() + "() == null) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine("return new ResponseEntity<String>(" + new JavaType("org.springframework.http.HttpStatus").getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + ".NOT_FOUND);"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); bodyBuilder.appendFormalLine("return new ResponseEntity<String>(" + new JavaType("org.springframework.http.HttpStatus").getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + ".OK);"); List<JavaType> typeParams = new ArrayList<JavaType>(); typeParams.add(JavaType.STRING_OBJECT); JavaType returnType = new JavaType("org.springframework.http.ResponseEntity", 0, DataType.TYPE, null, typeParams); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, returnType, paramTypes, paramNames, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getJsonDeleteMethod() { if (entityMetadata.getFindMethod() == null || entityMetadata.getRemoveMethod() == null) { // Mandatory input is missing (ROO-589) return null; } JavaSymbolName methodName = new JavaSymbolName("deleteFromJson"); List<AnnotationMetadata> typeAnnotations = new ArrayList<AnnotationMetadata>(); List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>(); attributes.add(new StringAttributeValue(new JavaSymbolName("value"), entityMetadata.getIdentifierField().getFieldName().getSymbolName())); AnnotationMetadataBuilder pathVariableAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.PathVariable"), attributes); typeAnnotations.add(pathVariableAnnotation.build()); List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>(); paramTypes.add(new AnnotatedJavaType(entityMetadata.getIdentifierField().getFieldType(), typeAnnotations)); MethodMetadata method = methodExists(methodName, paramTypes); if (method != null) return method; List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(); paramNames.add(new JavaSymbolName(entityMetadata.getIdentifierField().getFieldName().getSymbolName())); List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "/{" + entityMetadata.getIdentifierField().getFieldName().getSymbolName() + "}")); requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("DELETE")))); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("headers"), "Accept=application/json")); AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(requestMapping); String beanShortName = beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine(beanShortName + " " + beanShortName.toLowerCase() + " = " + beanShortName + "." + entityMetadata.getFindMethod().getMethodName() + "(" + entityMetadata.getIdentifierField().getFieldName().getSymbolName() + ");"); bodyBuilder.appendFormalLine("if (" + beanShortName.toLowerCase() + " == null) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine("return new " + getShortName(new JavaType("org.springframework.http.ResponseEntity")) + "<String>(" + getShortName(new JavaType("org.springframework.http.HttpStatus")) + ".NOT_FOUND);"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); bodyBuilder.appendFormalLine(beanShortName.toLowerCase() + "." + entityMetadata.getRemoveMethod().getMethodName() + "();"); bodyBuilder.appendFormalLine("return new ResponseEntity<String>(" + new JavaType("org.springframework.http.HttpStatus").getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + ".OK);"); List<JavaType> typeParams = new ArrayList<JavaType>(); typeParams.add(JavaType.STRING_OBJECT); JavaType returnType = new JavaType("org.springframework.http.ResponseEntity", 0, DataType.TYPE, null, typeParams); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, returnType, paramTypes, paramNames, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getFinderJsonMethod(MethodMetadata methodMetadata) { Assert.notNull(methodMetadata, "Method metadata required for finder"); if (jsonMetadata.getToJsonArrayMethodName() == null) { return null; } JavaSymbolName finderMethodName = new JavaSymbolName("json" + StringUtils.capitalize(methodMetadata.getMethodName().getSymbolName())); List<AnnotatedJavaType> annotatedParamTypes = new ArrayList<AnnotatedJavaType>(); List<JavaSymbolName> paramNames = methodMetadata.getParameterNames(); List<JavaType> paramTypes = AnnotatedJavaType.convertFromAnnotatedJavaTypes(methodMetadata.getParameterTypes()); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); StringBuilder methodParams = new StringBuilder(); for (int i = 0; i < paramTypes.size(); i++) { List<AnnotationMetadata> annotations = new ArrayList<AnnotationMetadata>(); List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>(); attributes.add(new StringAttributeValue(new JavaSymbolName("value"), uncapitalize(paramNames.get(i).getSymbolName()))); if (paramTypes.get(i).equals(JavaType.BOOLEAN_PRIMITIVE) || paramTypes.get(i).equals(JavaType.BOOLEAN_OBJECT)) { attributes.add(new BooleanAttributeValue(new JavaSymbolName("required"), false)); } AnnotationMetadataBuilder requestParamAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestParam"), attributes); annotations.add(requestParamAnnotation.build()); if (paramTypes.get(i).equals(new JavaType(Date.class.getName())) || paramTypes.get(i).equals(new JavaType(Calendar.class.getName()))) { JavaSymbolName fieldName = null; if (paramNames.get(i).getSymbolName().startsWith("max") || paramNames.get(i).getSymbolName().startsWith("min")) { fieldName = new JavaSymbolName(uncapitalize(paramNames.get(i).getSymbolName().substring(3))); } else { fieldName = paramNames.get(i); } FieldMetadata field = beanInfoMetadata.getFieldForPropertyName(fieldName); if (field != null) { AnnotationMetadata annotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("org.springframework.format.annotation.DateTimeFormat")); if (annotation != null) { annotations.add(annotation); } } } annotatedParamTypes.add(new AnnotatedJavaType(paramTypes.get(i), annotations)); if (paramTypes.get(i).equals(JavaType.BOOLEAN_OBJECT)) { methodParams.append(paramNames.get(i) + " == null ? new Boolean(false) : " + paramNames.get(i) + ", "); } else { methodParams.append(paramNames.get(i) + ", "); } } if (methodParams.length() > 0) { methodParams.delete(methodParams.length() - 2, methodParams.length()); } annotatedParamTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.Model"), new ArrayList<AnnotationMetadata>())); MethodMetadata existingMethod = methodExists(finderMethodName, annotatedParamTypes); if (existingMethod != null) return existingMethod; List<JavaSymbolName> newParamNames = new ArrayList<JavaSymbolName>(); newParamNames.addAll(paramNames); newParamNames.add(new JavaSymbolName("model")); List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("params"), "find=" + methodMetadata.getMethodName().getSymbolName().replaceFirst("find" + entityMetadata.getPlural(), ""))); requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("GET")))); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("headers"), "Accept=application/json")); AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(requestMapping); String shortBeanName = beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()); bodyBuilder.appendFormalLine("return " + shortBeanName + "." + jsonMetadata.getToJsonArrayMethodName().getSymbolName().toString() + "(" + shortBeanName + "." + methodMetadata.getMethodName().getSymbolName() + "(" + methodParams.toString() + ").getResultList());"); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, finderMethodName, JavaType.STRING_OBJECT, annotatedParamTypes, newParamNames, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getFinderFormMethod(MethodMetadata methodMetadata) { if (entityMetadata.getFindAllMethod() == null) { // Mandatory input is missing (ROO-589) return null; } Assert.notNull(methodMetadata, "Method metadata required for finder"); JavaSymbolName finderFormMethodName = new JavaSymbolName(methodMetadata.getMethodName().getSymbolName() + "Form"); List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>(); List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(); List<JavaType> types = AnnotatedJavaType.convertFromAnnotatedJavaTypes(methodMetadata.getParameterTypes()); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); boolean needmodel = false; for (JavaType javaType : types) { EntityMetadata typeEntityMetadata = null; if (javaType.isCommonCollectionType() && isSpecialType(javaType.getParameters().get(0))) { javaType = javaType.getParameters().get(0); typeEntityMetadata = (EntityMetadata) metadataService.get(EntityMetadata.createIdentifier(javaType, Path.SRC_MAIN_JAVA)); } else if (isEnumType(javaType)) { bodyBuilder.appendFormalLine("model.addAttribute(\"" + getPlural(javaType).toLowerCase() + "\", java.util.Arrays.asList(" + javaType.getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + ".class.getEnumConstants()));"); } else if (isSpecialType(javaType)) { typeEntityMetadata = (EntityMetadata) metadataService.get(EntityMetadata.createIdentifier(javaType, Path.SRC_MAIN_JAVA)); } if (typeEntityMetadata != null) { bodyBuilder.appendFormalLine("model.addAttribute(\"" + getPlural(javaType).toLowerCase() + "\", " + javaType.getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "." + typeEntityMetadata.getFindAllMethod().getMethodName() + "());"); } needmodel = true; } if (types.contains(new JavaType(Date.class.getName())) || types.contains(new JavaType(Calendar.class.getName()))) { bodyBuilder.appendFormalLine("addDateTimeFormatPatterns(model);"); } bodyBuilder.appendFormalLine("return \"" + controllerPath + "/" + methodMetadata.getMethodName().getSymbolName() + "\";"); if (needmodel) { paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.Model"), null)); paramNames.add(new JavaSymbolName("model")); } MethodMetadata existingMethod = methodExists(finderFormMethodName, paramTypes); if (existingMethod != null) return existingMethod; List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); List<StringAttributeValue> arrayValues = new ArrayList<StringAttributeValue>(); arrayValues.add(new StringAttributeValue(new JavaSymbolName("value"), "find=" + methodMetadata.getMethodName().getSymbolName().replaceFirst("find" + entityMetadata.getPlural(), ""))); arrayValues.add(new StringAttributeValue(new JavaSymbolName("value"), "form")); requestMappingAttributes.add(new ArrayAttributeValue<StringAttributeValue>(new JavaSymbolName("params"), arrayValues)); requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("GET")))); AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(requestMapping); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, finderFormMethodName, JavaType.STRING_OBJECT, paramTypes, paramNames, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getFinderMethod(MethodMetadata methodMetadata) { Assert.notNull(methodMetadata, "Method metadata required for finder"); JavaSymbolName finderMethodName = new JavaSymbolName(methodMetadata.getMethodName().getSymbolName()); List<AnnotatedJavaType> annotatedParamTypes = new ArrayList<AnnotatedJavaType>(); List<JavaSymbolName> paramNames = methodMetadata.getParameterNames(); List<JavaType> paramTypes = AnnotatedJavaType.convertFromAnnotatedJavaTypes(methodMetadata.getParameterTypes()); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); StringBuilder methodParams = new StringBuilder(); for (int i = 0; i < paramTypes.size(); i++) { List<AnnotationMetadata> annotations = new ArrayList<AnnotationMetadata>(); List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>(); attributes.add(new StringAttributeValue(new JavaSymbolName("value"), uncapitalize(paramNames.get(i).getSymbolName()))); if (paramTypes.get(i).equals(JavaType.BOOLEAN_PRIMITIVE) || paramTypes.get(i).equals(JavaType.BOOLEAN_OBJECT)) { attributes.add(new BooleanAttributeValue(new JavaSymbolName("required"), false)); } AnnotationMetadataBuilder requestParamAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestParam"), attributes); annotations.add(requestParamAnnotation.build()); if (paramTypes.get(i).equals(new JavaType(Date.class.getName())) || paramTypes.get(i).equals(new JavaType(Calendar.class.getName()))) { JavaSymbolName fieldName = null; if (paramNames.get(i).getSymbolName().startsWith("max") || paramNames.get(i).getSymbolName().startsWith("min")) { fieldName = new JavaSymbolName(uncapitalize(paramNames.get(i).getSymbolName().substring(3))); } else { fieldName = paramNames.get(i); } FieldMetadata field = beanInfoMetadata.getFieldForPropertyName(fieldName); if (field != null) { AnnotationMetadata annotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("org.springframework.format.annotation.DateTimeFormat")); if (annotation != null) { annotations.add(annotation); } } } annotatedParamTypes.add(new AnnotatedJavaType(paramTypes.get(i), annotations)); if (paramTypes.get(i).equals(JavaType.BOOLEAN_OBJECT)) { methodParams.append(paramNames.get(i) + " == null ? new Boolean(false) : " + paramNames.get(i) + ", "); } else { methodParams.append(paramNames.get(i) + ", "); } } if (methodParams.length() > 0) { methodParams.delete(methodParams.length() - 2, methodParams.length()); } annotatedParamTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.Model"), new ArrayList<AnnotationMetadata>())); MethodMetadata existingMethod = methodExists(finderMethodName, annotatedParamTypes); if (existingMethod != null) return existingMethod; List<JavaSymbolName> newParamNames = new ArrayList<JavaSymbolName>(); newParamNames.addAll(paramNames); newParamNames.add(new JavaSymbolName("model")); List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("params"), "find=" + methodMetadata.getMethodName().getSymbolName().replaceFirst("find" + entityMetadata.getPlural(), ""))); requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("GET")))); AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(requestMapping); bodyBuilder.appendFormalLine("model.addAttribute(\"" + getPlural(beanInfoMetadata.getJavaBean()).toLowerCase() + "\", " + beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "." + methodMetadata.getMethodName().getSymbolName() + "(" + methodParams.toString() + ").getResultList());"); if (paramTypes.contains(new JavaType(Date.class.getName())) || paramTypes.contains(new JavaType(Calendar.class.getName()))) { bodyBuilder.appendFormalLine("addDateTimeFormatPatterns(model);"); } bodyBuilder.appendFormalLine("return \"" + controllerPath + "/list\";"); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, finderMethodName, JavaType.STRING_OBJECT, annotatedParamTypes, newParamNames, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getDateTimeFormatHelperMethod() { JavaSymbolName addDateTimeFormatPatterns = new JavaSymbolName("addDateTimeFormatPatterns"); List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>(); paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.Model"), new ArrayList<AnnotationMetadata>())); MethodMetadata addDateTimeFormatPatternsMethod = methodExists(addDateTimeFormatPatterns, paramTypes); if (addDateTimeFormatPatternsMethod != null) return addDateTimeFormatPatternsMethod; List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(); paramNames.add(new JavaSymbolName("model")); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); Iterator<Map.Entry<JavaSymbolName, DateTimeFormat>> it = dateTypes.entrySet().iterator(); while (it.hasNext()) { Entry<JavaSymbolName, DateTimeFormat> entry = it.next(); String pattern; if (entry.getValue().pattern != null) { pattern = "\"" + entry.getValue().pattern + "\""; } else { JavaType dateTimeFormat = new JavaType("org.joda.time.format.DateTimeFormat"); String dateTimeFormatSimple = dateTimeFormat.getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()); JavaType localeContextHolder = new JavaType("org.springframework.context.i18n.LocaleContextHolder"); String localeContextHolderSimple = localeContextHolder.getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()); pattern = dateTimeFormatSimple + ".patternForStyle(\"" + entry.getValue().style + "\", " + localeContextHolderSimple + ".getLocale())"; } bodyBuilder.appendFormalLine("model.addAttribute(\"" + entityName + "_" + entry.getKey().getSymbolName().toLowerCase() + "_date_format\", " + pattern + ");"); } MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), 0, addDateTimeFormatPatterns, JavaType.VOID_PRIMITIVE, paramTypes, paramNames, bodyBuilder); return methodBuilder.build(); } private List<MethodMetadata> getPopulateMethods() { List<MethodMetadata> methods = new ArrayList<MethodMetadata>(); for (JavaType type : specialDomainTypes) { // There is a need to present a populator for self references (see ROO-1112) // if (type.equals(beanInfoMetadata.getJavaBean())) { // continue; // } InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); EntityMetadata typeEntityMetadata = (EntityMetadata) metadataService.get(EntityMetadata.createIdentifier(type, Path.SRC_MAIN_JAVA)); if (typeEntityMetadata != null) { bodyBuilder.appendFormalLine("return " + type.getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "." + typeEntityMetadata.getFindAllMethod().getMethodName() + "();"); } else if (isEnumType(type)) { JavaType arrays = new JavaType("java.util.Arrays"); bodyBuilder.appendFormalLine("return " + arrays.getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + ".asList(" + type.getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + ".class.getEnumConstants());"); } else if (isRooIdentifier(type)) { continue; } else { throw new IllegalStateException("Could not scaffold controller for type " + beanInfoMetadata.getJavaBean().getFullyQualifiedTypeName() + ", the referenced type " + type.getFullyQualifiedTypeName() + " cannot be handled"); } JavaSymbolName populateMethodName = new JavaSymbolName("populate" + getPlural(type)); MethodMetadata addReferenceDataMethod = methodExists(populateMethodName, new ArrayList<AnnotatedJavaType>()); if (addReferenceDataMethod != null) continue; List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>(); attributes.add(new StringAttributeValue(new JavaSymbolName("value"), getPlural(type).toLowerCase())); annotations.add(new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.ModelAttribute"), attributes)); List<JavaType> typeParams = new ArrayList<JavaType>(); typeParams.add(type); JavaType returnType = new JavaType("java.util.Collection", 0, DataType.TYPE, null, typeParams); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, populateMethodName, returnType, bodyBuilder); methodBuilder.setAnnotations(annotations); methods.add(methodBuilder.build()); } return methods; } private MethodMetadata getEncodeUrlPathSegmentMethod() { JavaSymbolName encodeUrlPathSegment = new JavaSymbolName("encodeUrlPathSegment"); List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>(); paramTypes.add(new AnnotatedJavaType(JavaType.STRING_OBJECT, new ArrayList<AnnotationMetadata>())); paramTypes.add(new AnnotatedJavaType(new JavaType("javax.servlet.http.HttpServletRequest"), new ArrayList<AnnotationMetadata>())); MethodMetadata encodeUrlPathSegmentMethod = methodExists(encodeUrlPathSegment, paramTypes); if (encodeUrlPathSegmentMethod != null) return encodeUrlPathSegmentMethod; List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(); paramNames.add(new JavaSymbolName("pathSegment")); paramNames.add(new JavaSymbolName("request")); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine("String enc = request.getCharacterEncoding();"); bodyBuilder.appendFormalLine("if (enc == null) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine("enc = " + new JavaType("org.springframework.web.util.WebUtils").getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + ".DEFAULT_CHARACTER_ENCODING;"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); bodyBuilder.appendFormalLine("try {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine("pathSegment = " + new JavaType("org.springframework.web.util.UriUtils").getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + ".encodePathSegment(pathSegment, enc);"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); bodyBuilder.appendFormalLine("catch (" + new JavaType("java.io.UnsupportedEncodingException").getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + " uee) {}"); bodyBuilder.appendFormalLine("return pathSegment;"); return new MethodMetadataBuilder(getId(), 0, encodeUrlPathSegment, JavaType.STRING_OBJECT, paramTypes, paramNames, bodyBuilder).build(); } private SortedSet<JavaType> getSpecialDomainTypes(JavaType javaType) { SortedSet<JavaType> specialTypes = new TreeSet<JavaType>(); BeanInfoMetadata bim = (BeanInfoMetadata) metadataService.get(BeanInfoMetadata.createIdentifier(javaType, Path.SRC_MAIN_JAVA)); if (bim == null) { // Unable to get metadata so it is not a JavaType in our project anyway. return specialTypes; } EntityMetadata em = (EntityMetadata) metadataService.get(EntityMetadata.createIdentifier(javaType, Path.SRC_MAIN_JAVA)); if (em == null) { // Unable to get entity metadata so it is not a Entity in our project anyway. return specialTypes; } for (MethodMetadata accessor : bim.getPublicAccessors(false)) { // Not interested in identifiers and version fields if (accessor.equals(em.getIdentifierAccessor()) || accessor.equals(em.getVersionAccessor())) { continue; } // Not interested in fields that are not exposed via a mutator or are JPA transient fields FieldMetadata fieldMetadata = bim.getFieldForPropertyName(BeanInfoUtils.getPropertyNameForJavaBeanMethod(accessor)); if (fieldMetadata == null || !hasMutator(fieldMetadata, bim) || isTransientFieldType(fieldMetadata)) { continue; } JavaType type = accessor.getReturnType(); if (type.isCommonCollectionType()) { for (JavaType genericType : type.getParameters()) { if (isSpecialType(genericType)) { specialTypes.add(genericType); } } } else { if (isSpecialType(type) && !isEmbeddedFieldType(fieldMetadata)) { specialTypes.add(type); } } } return specialTypes; } private Map<JavaSymbolName, DateTimeFormat> getDatePatterns() { Map<JavaSymbolName, DateTimeFormat> dates = new HashMap<JavaSymbolName, DateTimeFormat>(); for (MethodMetadata accessor : beanInfoMetadata.getPublicAccessors(false)) { // Not interested in identifiers and version fields if (accessor.equals(entityMetadata.getIdentifierAccessor()) || accessor.equals(entityMetadata.getVersionAccessor())) { continue; } // Not interested in fields that are not exposed via a mutator FieldMetadata fieldMetadata = beanInfoMetadata.getFieldForPropertyName(BeanInfoUtils.getPropertyNameForJavaBeanMethod(accessor)); if (fieldMetadata == null || !hasMutator(fieldMetadata, beanInfoMetadata)) { continue; } JavaType type = accessor.getReturnType(); if (type.getFullyQualifiedTypeName().equals(Date.class.getName()) || type.getFullyQualifiedTypeName().equals(Calendar.class.getName())) { AnnotationMetadata annotation = MemberFindingUtils.getAnnotationOfType(fieldMetadata.getAnnotations(), new JavaType("org.springframework.format.annotation.DateTimeFormat")); JavaSymbolName patternSymbol = new JavaSymbolName("pattern"); JavaSymbolName styleSymbol = new JavaSymbolName("style"); DateTimeFormat dateTimeFormat = null; if (annotation != null) { if (annotation.getAttributeNames().contains(styleSymbol)) { dateTimeFormat = DateTimeFormat.withStyle(annotation.getAttribute(styleSymbol).getValue().toString()); } else if (annotation.getAttributeNames().contains(patternSymbol)) { dateTimeFormat = DateTimeFormat.withPattern(annotation.getAttribute(patternSymbol).getValue().toString()); } } if (dateTimeFormat != null) { dates.put(fieldMetadata.getFieldName(), dateTimeFormat); for (String finder : entityMetadata.getDynamicFinders()) { if (finder.contains(StringUtils.capitalize(fieldMetadata.getFieldName().getSymbolName()) + "Between")) { dates.put(new JavaSymbolName("min" + StringUtils.capitalize(fieldMetadata.getFieldName().getSymbolName())), dateTimeFormat); dates.put(new JavaSymbolName("max" + StringUtils.capitalize(fieldMetadata.getFieldName().getSymbolName())), dateTimeFormat); } } } else { log.warning("It is recommended to use @DateTimeFormat(style=\"S-\") on " + beanInfoMetadata.getJavaBean().getSimpleTypeName() + "." + fieldMetadata.getFieldName() + " to use automatic date conversion in Spring MVC"); } } } return dates; } private MethodMetadata methodExists(JavaSymbolName methodName, List<AnnotatedJavaType> parameters) { return MemberFindingUtils.getMethod(detailsScanner.getMemberDetails(WebScaffoldMetadataProviderImpl.class.getName(), governorTypeDetails), methodName, AnnotatedJavaType.convertFromAnnotatedJavaTypes(parameters)); } private String getShortName(JavaType type) { return type.getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()); } private boolean isEnumType(JavaType type) { PhysicalTypeMetadata physicalTypeMetadata = (PhysicalTypeMetadata) metadataService.get(PhysicalTypeIdentifierNamingUtils.createIdentifier(PhysicalTypeIdentifier.class.getName(), type, Path.SRC_MAIN_JAVA)); if (physicalTypeMetadata != null) { PhysicalTypeDetails details = physicalTypeMetadata.getMemberHoldingTypeDetails(); if (details != null) { if (details.getPhysicalTypeCategory().equals(PhysicalTypeCategory.ENUMERATION)) { return true; } } } return false; } private boolean isRooIdentifier(JavaType type) { PhysicalTypeMetadata physicalTypeMetadata = (PhysicalTypeMetadata) metadataService.get(PhysicalTypeIdentifier.createIdentifier(type, Path.SRC_MAIN_JAVA)); if (physicalTypeMetadata == null) { return false; } ClassOrInterfaceTypeDetails cid = (ClassOrInterfaceTypeDetails) physicalTypeMetadata.getMemberHoldingTypeDetails(); if (cid == null) { return false; } return null != MemberFindingUtils.getAnnotationOfType(cid.getAnnotations(), new JavaType(RooIdentifier.class.getName())); } private boolean hasMutator(FieldMetadata fieldMetadata, BeanInfoMetadata bim) { for (MethodMetadata mutator : bim.getPublicMutators()) { if (fieldMetadata.equals(bim.getFieldForPropertyName(BeanInfoUtils.getPropertyNameForJavaBeanMethod(mutator)))) return true; } return false; } private boolean isSpecialType(JavaType javaType) { // We are only interested if the type is part of our application if (metadataService.get(PhysicalTypeIdentifier.createIdentifier(javaType, Path.SRC_MAIN_JAVA)) != null) { return true; } return false; } private boolean isEmbeddedFieldType(FieldMetadata field) { return MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.persistence.Embedded")) != null; } private boolean isTransientFieldType(FieldMetadata field) { return MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.persistence.Transient")) != null; } private String getPlural(JavaType type) { if (pluralCache.get(type) != null) { return pluralCache.get(type); } PluralMetadata pluralMetadata = (PluralMetadata) metadataService.get(PluralMetadata.createIdentifier(type, Path.SRC_MAIN_JAVA)); Assert.notNull(pluralMetadata, "Could not determine the plural for the '" + type.getFullyQualifiedTypeName() + "' type"); if (!pluralMetadata.getPlural().equals(type.getSimpleTypeName())) { pluralCache.put(type, pluralMetadata.getPlural()); return pluralMetadata.getPlural(); } pluralCache.put(type, pluralMetadata.getPlural() + "Items"); return pluralMetadata.getPlural() + "Items"; } public String toString() { ToStringCreator tsc = new ToStringCreator(this); tsc.append("identifier", getId()); tsc.append("valid", valid); tsc.append("aspectName", aspectName); tsc.append("destinationType", destination); tsc.append("governor", governorPhysicalTypeMetadata.getId()); tsc.append("itdTypeDetails", itdTypeDetails); return tsc.toString(); } public static final String getMetadataIdentiferType() { return PROVIDES_TYPE; } public static final String createIdentifier(JavaType javaType, Path path) { return PhysicalTypeIdentifierNamingUtils.createIdentifier(PROVIDES_TYPE_STRING, javaType, path); } public static final JavaType getJavaType(String metadataIdentificationString) { return PhysicalTypeIdentifierNamingUtils.getJavaType(PROVIDES_TYPE_STRING, metadataIdentificationString); } public static final Path getPath(String metadataIdentificationString) { return PhysicalTypeIdentifierNamingUtils.getPath(PROVIDES_TYPE_STRING, metadataIdentificationString); } public static boolean isValid(String metadataIdentificationString) { return PhysicalTypeIdentifierNamingUtils.isValid(PROVIDES_TYPE_STRING, metadataIdentificationString); } private static class DateTimeFormat { public String style; public String pattern; public static DateTimeFormat withStyle(String style) { DateTimeFormat d = new DateTimeFormat(); d.style = style; return d; } public static DateTimeFormat withPattern(String pattern) { DateTimeFormat d = new DateTimeFormat(); d.pattern = pattern; return d; } } private String uncapitalize(String term) { // [ROO-1790] this is needed to adhere to the JavaBean naming conventions (see JavaBean spec section 8.8) return Introspector.decapitalize(StringUtils.capitalize(term)); } }
addon-web-mvc-controller/src/main/java/org/springframework/roo/addon/web/mvc/controller/WebScaffoldMetadata.java
package org.springframework.roo.addon.web.mvc.controller; import java.beans.Introspector; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import java.util.Map.Entry; import java.util.logging.Logger; import org.springframework.roo.addon.beaninfo.BeanInfoMetadata; import org.springframework.roo.addon.beaninfo.BeanInfoUtils; import org.springframework.roo.addon.entity.EntityMetadata; import org.springframework.roo.addon.entity.RooIdentifier; import org.springframework.roo.addon.finder.FinderMetadata; import org.springframework.roo.addon.json.JsonMetadata; import org.springframework.roo.addon.plural.PluralMetadata; import org.springframework.roo.classpath.PhysicalTypeCategory; import org.springframework.roo.classpath.PhysicalTypeDetails; import org.springframework.roo.classpath.PhysicalTypeIdentifier; import org.springframework.roo.classpath.PhysicalTypeIdentifierNamingUtils; import org.springframework.roo.classpath.PhysicalTypeMetadata; import org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails; import org.springframework.roo.classpath.details.FieldMetadata; import org.springframework.roo.classpath.details.MemberFindingUtils; import org.springframework.roo.classpath.details.MethodMetadata; import org.springframework.roo.classpath.details.MethodMetadataBuilder; import org.springframework.roo.classpath.details.annotations.AnnotatedJavaType; import org.springframework.roo.classpath.details.annotations.AnnotationAttributeValue; import org.springframework.roo.classpath.details.annotations.AnnotationMetadata; import org.springframework.roo.classpath.details.annotations.AnnotationMetadataBuilder; import org.springframework.roo.classpath.details.annotations.ArrayAttributeValue; import org.springframework.roo.classpath.details.annotations.BooleanAttributeValue; import org.springframework.roo.classpath.details.annotations.EnumAttributeValue; import org.springframework.roo.classpath.details.annotations.StringAttributeValue; import org.springframework.roo.classpath.itd.AbstractItdTypeDetailsProvidingMetadataItem; import org.springframework.roo.classpath.itd.InvocableMemberBodyBuilder; import org.springframework.roo.classpath.itd.ItdSourceFileComposer; import org.springframework.roo.classpath.scanner.MemberDetailsScanner; import org.springframework.roo.metadata.MetadataIdentificationUtils; import org.springframework.roo.metadata.MetadataService; import org.springframework.roo.model.DataType; import org.springframework.roo.model.EnumDetails; import org.springframework.roo.model.JavaSymbolName; import org.springframework.roo.model.JavaType; import org.springframework.roo.model.ReservedWords; import org.springframework.roo.project.Path; import org.springframework.roo.support.style.ToStringCreator; import org.springframework.roo.support.util.Assert; import org.springframework.roo.support.util.StringUtils; /** * Metadata for {@link RooWebScaffold}. * * @author Stefan Schmidt * @since 1.0 */ public class WebScaffoldMetadata extends AbstractItdTypeDetailsProvidingMetadataItem { private static final String PROVIDES_TYPE_STRING = WebScaffoldMetadata.class.getName(); private static final String PROVIDES_TYPE = MetadataIdentificationUtils.create(PROVIDES_TYPE_STRING); private WebScaffoldAnnotationValues annotationValues; private BeanInfoMetadata beanInfoMetadata; private EntityMetadata entityMetadata; private MetadataService metadataService; private SortedSet<JavaType> specialDomainTypes; private String controllerPath; private String entityName; private Map<JavaSymbolName, DateTimeFormat> dateTypes; private Map<JavaType, String> pluralCache; private JsonMetadata jsonMetadata; private Logger log = Logger.getLogger(getClass().getName()); private MemberDetailsScanner detailsScanner; public WebScaffoldMetadata(String identifier, JavaType aspectName, PhysicalTypeMetadata governorPhysicalTypeMetadata, MetadataService metadataService, MemberDetailsScanner detailsScanner, WebScaffoldAnnotationValues annotationValues, BeanInfoMetadata beanInfoMetadata, EntityMetadata entityMetadata, FinderMetadata finderMetadata, ControllerOperations controllerOperations) { super(identifier, aspectName, governorPhysicalTypeMetadata); Assert.isTrue(isValid(identifier), "Metadata identification string '" + identifier + "' does not appear to be a valid"); Assert.notNull(annotationValues, "Annotation values required"); Assert.notNull(metadataService, "Metadata service required"); Assert.notNull(beanInfoMetadata, "Bean info metadata required"); Assert.notNull(entityMetadata, "Entity metadata required"); Assert.notNull(finderMetadata, "Finder metadata required"); Assert.notNull(controllerOperations, "Controller operations required"); Assert.notNull(detailsScanner, "Member details scanner required"); if (!isValid()) { return; } this.pluralCache = new HashMap<JavaType, String>(); this.annotationValues = annotationValues; this.beanInfoMetadata = beanInfoMetadata; this.entityMetadata = entityMetadata; this.detailsScanner = detailsScanner; this.entityName = uncapitalize(beanInfoMetadata.getJavaBean().getSimpleTypeName()); if (ReservedWords.RESERVED_JAVA_KEYWORDS.contains(this.entityName)) { this.entityName = "_" + entityName; } this.controllerPath = annotationValues.getPath(); this.metadataService = metadataService; specialDomainTypes = getSpecialDomainTypes(beanInfoMetadata.getJavaBean()); dateTypes = getDatePatterns(); if (annotationValues.create) { builder.addMethod(getCreateMethod()); builder.addMethod(getCreateFormMethod()); } builder.addMethod(getShowMethod()); builder.addMethod(getListMethod()); if (annotationValues.update) { builder.addMethod(getUpdateMethod()); builder.addMethod(getUpdateFormMethod()); } if (annotationValues.delete) { builder.addMethod(getDeleteMethod()); } if (annotationValues.exposeFinders) { // No need for null check of entityMetadata.getDynamicFinders as it guarantees non-null (but maybe empty list) for (String finderName : entityMetadata.getDynamicFinders()) { builder.addMethod(getFinderFormMethod(finderMetadata.getDynamicFinderMethod(finderName, beanInfoMetadata.getJavaBean().getSimpleTypeName().toLowerCase()))); builder.addMethod(getFinderMethod(finderMetadata.getDynamicFinderMethod(finderName, beanInfoMetadata.getJavaBean().getSimpleTypeName().toLowerCase()))); } } if (specialDomainTypes.size() > 0) { for (MethodMetadata method : getPopulateMethods()) { builder.addMethod(method); } } if (!dateTypes.isEmpty()) { builder.addMethod(getDateTimeFormatHelperMethod()); } if (annotationValues.isExposeJson()) { // Decide if we want to build json support this.jsonMetadata = (JsonMetadata) metadataService.get(JsonMetadata.createIdentifier(beanInfoMetadata.getJavaBean(), Path.SRC_MAIN_JAVA)); if (jsonMetadata != null) { builder.addMethod(getJsonShowMethod()); builder.addMethod(getJsonListMethod()); builder.addMethod(getJsonCreateMethod()); builder.addMethod(getCreateFromJsonArrayMethod()); builder.addMethod(getJsonUpdateMethod()); builder.addMethod(getUpdateFromJsonArrayMethod()); builder.addMethod(getJsonDeleteMethod()); if (annotationValues.exposeFinders) { for (String finderName : entityMetadata.getDynamicFinders()) { builder.addMethod(getFinderJsonMethod(finderMetadata.getDynamicFinderMethod(finderName, beanInfoMetadata.getJavaBean().getSimpleTypeName().toLowerCase()))); } } } } if (annotationValues.isCreate() || annotationValues.isUpdate()) { builder.addMethod(getEncodeUrlPathSegmentMethod()); } itdTypeDetails = builder.build(); new ItdSourceFileComposer(itdTypeDetails); } public String getIdentifierForBeanInfoMetadata() { return beanInfoMetadata.getId(); } public String getIdentifierForEntityMetadata() { return entityMetadata.getId(); } public WebScaffoldAnnotationValues getAnnotationValues() { return annotationValues; } private MethodMetadata getDeleteMethod() { if (entityMetadata.getFindMethod() == null || entityMetadata.getRemoveMethod() == null) { // Mandatory input is missing (ROO-589) return null; } JavaSymbolName methodName = new JavaSymbolName("delete"); List<AnnotationMetadata> typeAnnotations = new ArrayList<AnnotationMetadata>(); List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>(); attributes.add(new StringAttributeValue(new JavaSymbolName("value"), entityMetadata.getIdentifierField().getFieldName().getSymbolName())); AnnotationMetadataBuilder pathVariableAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.PathVariable"), attributes); typeAnnotations.add(pathVariableAnnotation.build()); List<AnnotationAttributeValue<?>> firstResultAttributes = new ArrayList<AnnotationAttributeValue<?>>(); firstResultAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "page")); firstResultAttributes.add(new BooleanAttributeValue(new JavaSymbolName("required"), false)); List<AnnotationMetadata> firstResultAnnotations = new ArrayList<AnnotationMetadata>(); AnnotationMetadataBuilder firstResultAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestParam"), firstResultAttributes); firstResultAnnotations.add(firstResultAnnotation.build()); List<AnnotationAttributeValue<?>> maxResultsAttributes = new ArrayList<AnnotationAttributeValue<?>>(); maxResultsAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "size")); maxResultsAttributes.add(new BooleanAttributeValue(new JavaSymbolName("required"), false)); List<AnnotationMetadata> maxResultsAnnotations = new ArrayList<AnnotationMetadata>(); AnnotationMetadataBuilder maxResultAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestParam"), maxResultsAttributes); maxResultsAnnotations.add(maxResultAnnotation.build()); List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>(); paramTypes.add(new AnnotatedJavaType(entityMetadata.getIdentifierField().getFieldType(), typeAnnotations)); paramTypes.add(new AnnotatedJavaType(new JavaType(Integer.class.getName()), firstResultAnnotations)); paramTypes.add(new AnnotatedJavaType(new JavaType(Integer.class.getName()), maxResultsAnnotations)); paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.Model"), null)); MethodMetadata method = methodExists(methodName, paramTypes); if (method != null) return method; List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(); paramNames.add(new JavaSymbolName(entityMetadata.getIdentifierField().getFieldName().getSymbolName())); paramNames.add(new JavaSymbolName("page")); paramNames.add(new JavaSymbolName("size")); paramNames.add(new JavaSymbolName("model")); List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "/{" + entityMetadata.getIdentifierField().getFieldName().getSymbolName() + "}")); requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("DELETE")))); AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(requestMapping); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine(beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "." + entityMetadata.getFindMethod().getMethodName() + "(" + entityMetadata.getIdentifierField().getFieldName().getSymbolName() + ")." + entityMetadata.getRemoveMethod().getMethodName() + "();"); bodyBuilder.appendFormalLine("model.addAttribute(\"page\", (page == null) ? \"1\" : page.toString());"); bodyBuilder.appendFormalLine("model.addAttribute(\"size\", (size == null) ? \"10\" : size.toString());"); bodyBuilder.appendFormalLine("return \"redirect:/" + controllerPath + "?page=\" + ((page == null) ? \"1\" : page.toString()) + \"&size=\" + ((size == null) ? \"10\" : size.toString());"); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.STRING_OBJECT, paramTypes, paramNames, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getListMethod() { if (entityMetadata.getFindEntriesMethod() == null || entityMetadata.getCountMethod() == null || entityMetadata.getFindAllMethod() == null) { // Mandatory input is missing (ROO-589) return null; } JavaSymbolName methodName = new JavaSymbolName("list"); List<AnnotationAttributeValue<?>> firstResultAttributes = new ArrayList<AnnotationAttributeValue<?>>(); firstResultAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "page")); firstResultAttributes.add(new BooleanAttributeValue(new JavaSymbolName("required"), false)); List<AnnotationMetadata> firstResultAnnotations = new ArrayList<AnnotationMetadata>(); AnnotationMetadataBuilder firstResultAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestParam"), firstResultAttributes); firstResultAnnotations.add(firstResultAnnotation.build()); List<AnnotationAttributeValue<?>> maxResultsAttributes = new ArrayList<AnnotationAttributeValue<?>>(); maxResultsAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "size")); maxResultsAttributes.add(new BooleanAttributeValue(new JavaSymbolName("required"), false)); List<AnnotationMetadata> maxResultsAnnotations = new ArrayList<AnnotationMetadata>(); AnnotationMetadataBuilder maxResultAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestParam"), maxResultsAttributes); maxResultsAnnotations.add(maxResultAnnotation.build()); List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>(); paramTypes.add(new AnnotatedJavaType(new JavaType(Integer.class.getName()), firstResultAnnotations)); paramTypes.add(new AnnotatedJavaType(new JavaType(Integer.class.getName()), maxResultsAnnotations)); paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.Model"), null)); MethodMetadata method = methodExists(methodName, paramTypes); if (method != null) { return method; } List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(); paramNames.add(new JavaSymbolName("page")); paramNames.add(new JavaSymbolName("size")); paramNames.add(new JavaSymbolName("model")); List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("GET")))); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes)); String plural = getPlural(beanInfoMetadata.getJavaBean()).toLowerCase(); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine("if (page != null || size != null) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine("int sizeNo = size == null ? 10 : size.intValue();"); bodyBuilder.appendFormalLine("model.addAttribute(\"" + plural + "\", " + beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "." + entityMetadata.getFindEntriesMethod().getMethodName() + "(page == null ? 0 : (page.intValue() - 1) * sizeNo, sizeNo));"); bodyBuilder.appendFormalLine("float nrOfPages = (float) " + beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "." + entityMetadata.getCountMethod().getMethodName() + "() / sizeNo;"); bodyBuilder.appendFormalLine("model.addAttribute(\"maxPages\", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("} else {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine("model.addAttribute(\"" + plural + "\", " + beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "." + entityMetadata.getFindAllMethod().getMethodName() + "());"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); if (!dateTypes.isEmpty()) { bodyBuilder.appendFormalLine("addDateTimeFormatPatterns(model);"); } bodyBuilder.appendFormalLine("return \"" + controllerPath + "/list\";"); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.STRING_OBJECT, paramTypes, paramNames, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getShowMethod() { if (entityMetadata.getFindMethod() == null) { // Mandatory input is missing (ROO-589) return null; } JavaSymbolName methodName = new JavaSymbolName("show"); List<AnnotationMetadata> typeAnnotations = new ArrayList<AnnotationMetadata>(); List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>(); attributes.add(new StringAttributeValue(new JavaSymbolName("value"), entityMetadata.getIdentifierField().getFieldName().getSymbolName())); AnnotationMetadataBuilder pathVariableAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.PathVariable"), attributes); typeAnnotations.add(pathVariableAnnotation.build()); List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>(); paramTypes.add(new AnnotatedJavaType(entityMetadata.getIdentifierField().getFieldType(), typeAnnotations)); paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.Model"), null)); MethodMetadata method = methodExists(methodName, paramTypes); if (method != null) return method; List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(); paramNames.add(new JavaSymbolName(entityMetadata.getIdentifierField().getFieldName().getSymbolName())); paramNames.add(new JavaSymbolName("model")); List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "/{" + entityMetadata.getIdentifierField().getFieldName().getSymbolName() + "}")); requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("GET")))); AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(requestMapping); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); if (!dateTypes.isEmpty()) { bodyBuilder.appendFormalLine("addDateTimeFormatPatterns(model);"); } bodyBuilder.appendFormalLine("model.addAttribute(\"" + entityName.toLowerCase() + "\", " + beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "." + entityMetadata.getFindMethod().getMethodName() + "(" + entityMetadata.getIdentifierField().getFieldName().getSymbolName() + "));"); bodyBuilder.appendFormalLine("model.addAttribute(\"itemId\", " + entityMetadata.getIdentifierField().getFieldName().getSymbolName() + ");"); bodyBuilder.appendFormalLine("return \"" + controllerPath + "/show\";"); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.STRING_OBJECT, paramTypes, paramNames, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getCreateMethod() { if (entityMetadata.getPersistMethod() == null) {// || entityMetadata.getFindAllMethod() == null) { // Mandatory input is missing (ROO-589) return null; } JavaSymbolName methodName = new JavaSymbolName("create"); List<AnnotationMetadata> typeAnnotations = new ArrayList<AnnotationMetadata>(); AnnotationMetadataBuilder validAnnotation = new AnnotationMetadataBuilder(new JavaType("javax.validation.Valid")); typeAnnotations.add(validAnnotation.build()); List<AnnotationMetadata> noAnnotations = new ArrayList<AnnotationMetadata>(); List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>(); paramTypes.add(new AnnotatedJavaType(beanInfoMetadata.getJavaBean(), typeAnnotations)); paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.validation.BindingResult"), noAnnotations)); paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.Model"), noAnnotations)); paramTypes.add(new AnnotatedJavaType(new JavaType("javax.servlet.http.HttpServletRequest"), noAnnotations)); MethodMetadata method = methodExists(methodName, paramTypes); if (method != null) return method; List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(); paramNames.add(new JavaSymbolName(entityName)); paramNames.add(new JavaSymbolName("result")); paramNames.add(new JavaSymbolName("model")); paramNames.add(new JavaSymbolName("request")); List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("POST")))); AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(requestMapping); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine("if (result.hasErrors()) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine("model.addAttribute(\"" + entityName + "\", " + entityName + ");"); if (!dateTypes.isEmpty()) { bodyBuilder.appendFormalLine("addDateTimeFormatPatterns(model);"); } bodyBuilder.appendFormalLine("return \"" + controllerPath + "/create\";"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); bodyBuilder.appendFormalLine(entityName + "." + entityMetadata.getPersistMethod().getMethodName() + "();"); bodyBuilder.appendFormalLine("return \"redirect:/" + controllerPath + "/\" + encodeUrlPathSegment(" + entityName + "." + entityMetadata.getIdentifierAccessor().getMethodName() + "().toString(), request);"); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.STRING_OBJECT, paramTypes, paramNames, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getCreateFormMethod() { // if (entityMetadata.getFindAllMethod() == null) { // // Mandatory input is missing (ROO-589) // return null; // } JavaSymbolName methodName = new JavaSymbolName("createForm"); List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>(); paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.Model"), null)); MethodMetadata method = methodExists(methodName, paramTypes); if (method != null) return method; List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(); paramNames.add(new JavaSymbolName("model")); List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("params"), "form")); requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("GET")))); AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(requestMapping); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine("model.addAttribute(\"" + entityName + "\", new " + beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "());"); if (!dateTypes.isEmpty()) { bodyBuilder.appendFormalLine("addDateTimeFormatPatterns(model);"); } boolean listAdded = false; for (MethodMetadata accessorMethod : beanInfoMetadata.getPublicAccessors()) { if (specialDomainTypes.contains(accessorMethod.getReturnType())) { FieldMetadata field = beanInfoMetadata.getFieldForPropertyName(BeanInfoUtils.getPropertyNameForJavaBeanMethod(accessorMethod)); if (null != field && null != MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.validation.constraints.NotNull"))) { EntityMetadata entityMetadata = (EntityMetadata) metadataService.get(EntityMetadata.createIdentifier(accessorMethod.getReturnType(), Path.SRC_MAIN_JAVA)); if (entityMetadata != null) { if (!listAdded) { String listShort = new JavaType("java.util.List").getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()); String arrayListShort = new JavaType("java.util.ArrayList").getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()); bodyBuilder.appendFormalLine(listShort + " dependencies = new " + arrayListShort + "();"); listAdded = true; } bodyBuilder.appendFormalLine("if (" + accessorMethod.getReturnType().getSimpleTypeName() + "." + entityMetadata.getCountMethod().getMethodName().getSymbolName() + "() == 0) {"); bodyBuilder.indent(); // Adding string array which has the fieldName at position 0 and the path at position 1 bodyBuilder.appendFormalLine("dependencies.add(new String[]{\"" + field.getFieldName().getSymbolName() + "\", \"" + entityMetadata.getPlural().toLowerCase() + "\"});"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } } } } if (listAdded) { bodyBuilder.appendFormalLine("model.addAttribute(\"dependencies\", dependencies);"); } bodyBuilder.appendFormalLine("return \"" + controllerPath + "/create\";"); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.STRING_OBJECT, paramTypes, paramNames, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getUpdateMethod() { if (entityMetadata.getMergeMethod() == null) {// || entityMetadata.getFindAllMethod() == null) { // Mandatory input is missing (ROO-589) return null; } JavaSymbolName methodName = new JavaSymbolName("update"); List<AnnotationMetadata> typeAnnotations = new ArrayList<AnnotationMetadata>(); AnnotationMetadataBuilder validAnnotation = new AnnotationMetadataBuilder(new JavaType("javax.validation.Valid")); typeAnnotations.add(validAnnotation.build()); List<AnnotationMetadata> noAnnotations = new ArrayList<AnnotationMetadata>(); List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>(); paramTypes.add(new AnnotatedJavaType(beanInfoMetadata.getJavaBean(), typeAnnotations)); paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.validation.BindingResult"), noAnnotations)); paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.Model"), noAnnotations)); paramTypes.add(new AnnotatedJavaType(new JavaType("javax.servlet.http.HttpServletRequest"), noAnnotations)); MethodMetadata method = methodExists(methodName, paramTypes); if (method != null) return method; List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(); paramNames.add(new JavaSymbolName(entityName)); paramNames.add(new JavaSymbolName("result")); paramNames.add(new JavaSymbolName("model")); paramNames.add(new JavaSymbolName("request")); List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("PUT")))); AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(requestMapping); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine("if (result.hasErrors()) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine("model.addAttribute(\"" + entityName + "\", " + entityName + ");"); if (!dateTypes.isEmpty()) { bodyBuilder.appendFormalLine("addDateTimeFormatPatterns(model);"); } bodyBuilder.appendFormalLine("return \"" + controllerPath + "/update\";"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); bodyBuilder.appendFormalLine(entityName + "." + entityMetadata.getMergeMethod().getMethodName() + "();"); bodyBuilder.appendFormalLine("return \"redirect:/" + controllerPath + "/\" + encodeUrlPathSegment(" + entityName + "." + entityMetadata.getIdentifierAccessor().getMethodName() + "().toString(), request);"); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.STRING_OBJECT, paramTypes, paramNames, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getUpdateFormMethod() { if (entityMetadata.getFindMethod() == null) {// || entityMetadata.getFindAllMethod() == null) { // Mandatory input is missing (ROO-589) return null; } JavaSymbolName methodName = new JavaSymbolName("updateForm"); List<AnnotationMetadata> typeAnnotations = new ArrayList<AnnotationMetadata>(); List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>(); attributes.add(new StringAttributeValue(new JavaSymbolName("value"), entityMetadata.getIdentifierField().getFieldName().getSymbolName())); AnnotationMetadataBuilder pathVariableAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.PathVariable"), attributes); typeAnnotations.add(pathVariableAnnotation.build()); List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>(); paramTypes.add(new AnnotatedJavaType(entityMetadata.getIdentifierField().getFieldType(), typeAnnotations)); paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.Model"), null)); MethodMetadata updateFormMethod = methodExists(methodName, paramTypes); if (updateFormMethod != null) return updateFormMethod; List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(); paramNames.add(new JavaSymbolName(entityMetadata.getIdentifierField().getFieldName().getSymbolName())); paramNames.add(new JavaSymbolName("model")); List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "/{" + entityMetadata.getIdentifierField().getFieldName().getSymbolName() + "}")); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("params"), "form")); requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("GET")))); AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(requestMapping); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine("model.addAttribute(\"" + entityName + "\", " + beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "." + entityMetadata.getFindMethod().getMethodName() + "(" + entityMetadata.getIdentifierField().getFieldName().getSymbolName() + "));"); if (!dateTypes.isEmpty()) { bodyBuilder.appendFormalLine("addDateTimeFormatPatterns(model);"); } bodyBuilder.appendFormalLine("return \"" + controllerPath + "/update\";"); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.STRING_OBJECT, paramTypes, paramNames, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getJsonShowMethod() { JavaSymbolName toJsonMethodName = jsonMetadata.getToJsonMethodName(); if (toJsonMethodName == null || entityMetadata.getFindMethod() == null) { return null; } JavaSymbolName methodName = new JavaSymbolName("showJson"); List<AnnotationMetadata> parameters = new ArrayList<AnnotationMetadata>(); List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>(); attributes.add(new StringAttributeValue(new JavaSymbolName("value"), entityMetadata.getIdentifierField().getFieldName().getSymbolName())); AnnotationMetadataBuilder pathVariableAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.PathVariable"), attributes); parameters.add(pathVariableAnnotation.build()); List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>(); paramTypes.add(new AnnotatedJavaType(entityMetadata.getIdentifierField().getFieldType(), parameters)); MethodMetadata jsonShowMethod = methodExists(methodName, paramTypes); if (jsonShowMethod != null) return jsonShowMethod; List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(); paramNames.add(new JavaSymbolName(entityMetadata.getIdentifierField().getFieldName().getSymbolName())); List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "/{" + entityMetadata.getIdentifierField().getFieldName().getSymbolName() + "}")); requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("GET")))); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("headers"), "Accept=application/json")); AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(requestMapping); annotations.add(new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.ResponseBody"))); String beanShortName = getShortName(beanInfoMetadata.getJavaBean()); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine(beanShortName + " " + beanShortName.toLowerCase() + " = " + beanShortName + "." + entityMetadata.getFindMethod().getMethodName() + "(" + entityMetadata.getIdentifierField().getFieldName().getSymbolName() + ");"); bodyBuilder.appendFormalLine("if (" + beanShortName.toLowerCase() + " == null) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine("return new " + getShortName(new JavaType("org.springframework.http.ResponseEntity")) + "<String>(" + getShortName(new JavaType("org.springframework.http.HttpStatus")) + ".NOT_FOUND);"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); bodyBuilder.appendFormalLine("return " + beanShortName.toLowerCase() + "." + toJsonMethodName.getSymbolName() + "();"); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, new JavaType("java.lang.Object"), paramTypes, paramNames, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getJsonCreateMethod() { JavaSymbolName fromJsonMethodName = jsonMetadata.getFromJsonMethodName(); if (fromJsonMethodName == null || entityMetadata.getPersistMethod() == null) { return null; } JavaSymbolName methodName = new JavaSymbolName("createFromJson"); List<AnnotationMetadata> parameters = new ArrayList<AnnotationMetadata>(); AnnotationMetadataBuilder requestBodyAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestBody")); parameters.add(requestBodyAnnotation.build()); List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>(); paramTypes.add(new AnnotatedJavaType(JavaType.STRING_OBJECT, parameters)); MethodMetadata jsonCreateMethod = methodExists(methodName, paramTypes); if (jsonCreateMethod != null) return jsonCreateMethod; List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(); paramNames.add(new JavaSymbolName("json")); List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("POST")))); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("headers"), "Accept=application/json")); AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(requestMapping); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine(beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "." + fromJsonMethodName.getSymbolName() + "(json)." + entityMetadata.getPersistMethod().getMethodName().getSymbolName() + "();"); bodyBuilder.appendFormalLine("return new ResponseEntity<String>(" + new JavaType("org.springframework.http.HttpStatus").getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + ".CREATED);"); List<JavaType> typeParams = new ArrayList<JavaType>(); typeParams.add(JavaType.STRING_OBJECT); JavaType returnType = new JavaType("org.springframework.http.ResponseEntity", 0, DataType.TYPE, null, typeParams); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, returnType, paramTypes, paramNames, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getCreateFromJsonArrayMethod() { JavaSymbolName fromJsonArrayMethodName = jsonMetadata.getFromJsonArrayMethodName(); if (fromJsonArrayMethodName == null || entityMetadata.getPersistMethod() == null) { return null; } JavaSymbolName methodName = new JavaSymbolName("createFromJsonArray"); List<AnnotationMetadata> parameters = new ArrayList<AnnotationMetadata>(); AnnotationMetadataBuilder requestBodyAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestBody")); parameters.add(requestBodyAnnotation.build()); List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>(); paramTypes.add(new AnnotatedJavaType(JavaType.STRING_OBJECT, parameters)); MethodMetadata existingMethod = methodExists(methodName, paramTypes); if (existingMethod != null) return existingMethod; List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(); paramNames.add(new JavaSymbolName("json")); List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "/jsonArray")); requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("POST")))); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("headers"), "Accept=application/json")); AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(requestMapping); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); String beanName = beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()); List<JavaType> params = new ArrayList<JavaType>(); params.add(beanInfoMetadata.getJavaBean()); bodyBuilder.appendFormalLine("for (" + beanName + " " + entityName + ": " + beanName + "." + fromJsonArrayMethodName.getSymbolName() + "(json)) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(entityName + "." + entityMetadata.getPersistMethod().getMethodName().getSymbolName() + "();"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); bodyBuilder.appendFormalLine("return new ResponseEntity<String>(" + new JavaType("org.springframework.http.HttpStatus").getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + ".CREATED);"); List<JavaType> typeParams = new ArrayList<JavaType>(); typeParams.add(JavaType.STRING_OBJECT); JavaType returnType = new JavaType("org.springframework.http.ResponseEntity", 0, DataType.TYPE, null, typeParams); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, returnType, paramTypes, paramNames, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getJsonListMethod() { JavaSymbolName toJsonArrayMethodName = jsonMetadata.getToJsonArrayMethodName(); if (toJsonArrayMethodName == null || entityMetadata.getFindAllMethod() == null) { return null; } // See if the type itself declared the method JavaSymbolName methodName = new JavaSymbolName("listJson"); MethodMetadata result = MemberFindingUtils.getDeclaredMethod(governorTypeDetails, methodName, null); if (result != null) { return result; } List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("headers"), "Accept=application/json")); AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(requestMapping); annotations.add(new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.ResponseBody"))); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); String entityName = beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()); bodyBuilder.appendFormalLine("return " + entityName + "." + toJsonArrayMethodName.getSymbolName() + "(" + entityName + "." + entityMetadata.getFindAllMethod().getMethodName() + "());"); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.STRING_OBJECT, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getJsonUpdateMethod() { JavaSymbolName fromJsonMethodName = jsonMetadata.getFromJsonMethodName(); if (fromJsonMethodName == null || entityMetadata.getMergeMethod() == null) { return null; } JavaSymbolName methodName = new JavaSymbolName("updateFromJson"); List<AnnotationMetadata> parameters = new ArrayList<AnnotationMetadata>(); AnnotationMetadataBuilder requestBodyAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestBody")); parameters.add(requestBodyAnnotation.build()); List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>(); paramTypes.add(new AnnotatedJavaType(JavaType.STRING_OBJECT, parameters)); MethodMetadata jsonCreateMethod = methodExists(methodName, paramTypes); if (jsonCreateMethod != null) return jsonCreateMethod; List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(); paramNames.add(new JavaSymbolName("json")); List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("PUT")))); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("headers"), "Accept=application/json")); AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(requestMapping); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); String beanShortName = beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()); bodyBuilder.appendFormalLine("if (" + beanShortName + "." + fromJsonMethodName.getSymbolName() + "(json)." + entityMetadata.getMergeMethod().getMethodName().getSymbolName() + "() == null) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine("return new ResponseEntity<String>(" + new JavaType("org.springframework.http.HttpStatus").getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + ".NOT_FOUND);"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); bodyBuilder.appendFormalLine("return new ResponseEntity<String>(" + new JavaType("org.springframework.http.HttpStatus").getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + ".OK);"); List<JavaType> typeParams = new ArrayList<JavaType>(); typeParams.add(JavaType.STRING_OBJECT); JavaType returnType = new JavaType("org.springframework.http.ResponseEntity", 0, DataType.TYPE, null, typeParams); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, returnType, paramTypes, paramNames, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getUpdateFromJsonArrayMethod() { JavaSymbolName fromJsonArrayMethodName = jsonMetadata.getFromJsonArrayMethodName(); if (fromJsonArrayMethodName == null || entityMetadata.getMergeMethod() == null) { return null; } JavaSymbolName methodName = new JavaSymbolName("updateFromJsonArray"); List<AnnotationMetadata> parameters = new ArrayList<AnnotationMetadata>(); AnnotationMetadataBuilder requestBodyAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestBody")); parameters.add(requestBodyAnnotation.build()); List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>(); paramTypes.add(new AnnotatedJavaType(JavaType.STRING_OBJECT, parameters)); MethodMetadata existingMethod = methodExists(methodName, paramTypes); if (existingMethod != null) return existingMethod; List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(); paramNames.add(new JavaSymbolName("json")); List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "/jsonArray")); requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("PUT")))); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("headers"), "Accept=application/json")); AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(requestMapping); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); String beanName = beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()); List<JavaType> params = new ArrayList<JavaType>(); params.add(beanInfoMetadata.getJavaBean()); bodyBuilder.appendFormalLine("for (" + beanName + " " + entityName + ": " + beanName + "." + fromJsonArrayMethodName.getSymbolName() + "(json)) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine("if (" + entityName + "." + entityMetadata.getMergeMethod().getMethodName().getSymbolName() + "() == null) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine("return new ResponseEntity<String>(" + new JavaType("org.springframework.http.HttpStatus").getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + ".NOT_FOUND);"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); bodyBuilder.appendFormalLine("return new ResponseEntity<String>(" + new JavaType("org.springframework.http.HttpStatus").getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + ".OK);"); List<JavaType> typeParams = new ArrayList<JavaType>(); typeParams.add(JavaType.STRING_OBJECT); JavaType returnType = new JavaType("org.springframework.http.ResponseEntity", 0, DataType.TYPE, null, typeParams); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, returnType, paramTypes, paramNames, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getJsonDeleteMethod() { if (entityMetadata.getFindMethod() == null || entityMetadata.getRemoveMethod() == null) { // Mandatory input is missing (ROO-589) return null; } JavaSymbolName methodName = new JavaSymbolName("deleteFromJson"); List<AnnotationMetadata> typeAnnotations = new ArrayList<AnnotationMetadata>(); List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>(); attributes.add(new StringAttributeValue(new JavaSymbolName("value"), entityMetadata.getIdentifierField().getFieldName().getSymbolName())); AnnotationMetadataBuilder pathVariableAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.PathVariable"), attributes); typeAnnotations.add(pathVariableAnnotation.build()); List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>(); paramTypes.add(new AnnotatedJavaType(entityMetadata.getIdentifierField().getFieldType(), typeAnnotations)); MethodMetadata method = methodExists(methodName, paramTypes); if (method != null) return method; List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(); paramNames.add(new JavaSymbolName(entityMetadata.getIdentifierField().getFieldName().getSymbolName())); List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "/{" + entityMetadata.getIdentifierField().getFieldName().getSymbolName() + "}")); requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("DELETE")))); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("headers"), "Accept=application/json")); AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(requestMapping); String beanShortName = beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine(beanShortName + " " + beanShortName.toLowerCase() + " = " + beanShortName + "." + entityMetadata.getFindMethod().getMethodName() + "(" + entityMetadata.getIdentifierField().getFieldName().getSymbolName() + ");"); bodyBuilder.appendFormalLine("if (" + beanShortName.toLowerCase() + " == null) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine("return new " + getShortName(new JavaType("org.springframework.http.ResponseEntity")) + "<String>(" + getShortName(new JavaType("org.springframework.http.HttpStatus")) + ".NOT_FOUND);"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); bodyBuilder.appendFormalLine(beanShortName.toLowerCase() + "." + entityMetadata.getRemoveMethod().getMethodName() + "();"); bodyBuilder.appendFormalLine("return new ResponseEntity<String>(" + new JavaType("org.springframework.http.HttpStatus").getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + ".OK);"); List<JavaType> typeParams = new ArrayList<JavaType>(); typeParams.add(JavaType.STRING_OBJECT); JavaType returnType = new JavaType("org.springframework.http.ResponseEntity", 0, DataType.TYPE, null, typeParams); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, returnType, paramTypes, paramNames, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getFinderJsonMethod(MethodMetadata methodMetadata) { Assert.notNull(methodMetadata, "Method metadata required for finder"); if (jsonMetadata.getToJsonArrayMethodName() == null) { return null; } JavaSymbolName finderMethodName = new JavaSymbolName("json" + StringUtils.capitalize(methodMetadata.getMethodName().getSymbolName())); List<AnnotatedJavaType> annotatedParamTypes = new ArrayList<AnnotatedJavaType>(); List<JavaSymbolName> paramNames = methodMetadata.getParameterNames(); List<JavaType> paramTypes = AnnotatedJavaType.convertFromAnnotatedJavaTypes(methodMetadata.getParameterTypes()); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); StringBuilder methodParams = new StringBuilder(); for (int i = 0; i < paramTypes.size(); i++) { List<AnnotationMetadata> annotations = new ArrayList<AnnotationMetadata>(); List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>(); attributes.add(new StringAttributeValue(new JavaSymbolName("value"), uncapitalize(paramNames.get(i).getSymbolName()))); if (paramTypes.get(i).equals(JavaType.BOOLEAN_PRIMITIVE) || paramTypes.get(i).equals(JavaType.BOOLEAN_OBJECT)) { attributes.add(new BooleanAttributeValue(new JavaSymbolName("required"), false)); } AnnotationMetadataBuilder requestParamAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestParam"), attributes); annotations.add(requestParamAnnotation.build()); if (paramTypes.get(i).equals(new JavaType(Date.class.getName())) || paramTypes.get(i).equals(new JavaType(Calendar.class.getName()))) { JavaSymbolName fieldName = null; if (paramNames.get(i).getSymbolName().startsWith("max") || paramNames.get(i).getSymbolName().startsWith("min")) { fieldName = new JavaSymbolName(uncapitalize(paramNames.get(i).getSymbolName().substring(3))); } else { fieldName = paramNames.get(i); } FieldMetadata field = beanInfoMetadata.getFieldForPropertyName(fieldName); if (field != null) { AnnotationMetadata annotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("org.springframework.format.annotation.DateTimeFormat")); if (annotation != null) { annotations.add(annotation); } } } annotatedParamTypes.add(new AnnotatedJavaType(paramTypes.get(i), annotations)); if (paramTypes.get(i).equals(JavaType.BOOLEAN_OBJECT)) { methodParams.append(paramNames.get(i) + " == null ? new Boolean(false) : " + paramNames.get(i) + ", "); } else { methodParams.append(paramNames.get(i) + ", "); } } if (methodParams.length() > 0) { methodParams.delete(methodParams.length() - 2, methodParams.length()); } annotatedParamTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.Model"), new ArrayList<AnnotationMetadata>())); MethodMetadata existingMethod = methodExists(finderMethodName, annotatedParamTypes); if (existingMethod != null) return existingMethod; List<JavaSymbolName> newParamNames = new ArrayList<JavaSymbolName>(); newParamNames.addAll(paramNames); newParamNames.add(new JavaSymbolName("model")); List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("params"), "find=" + methodMetadata.getMethodName().getSymbolName().replaceFirst("find" + entityMetadata.getPlural(), ""))); requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("GET")))); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("headers"), "Accept=application/json")); AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(requestMapping); String shortBeanName = beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()); bodyBuilder.appendFormalLine("return " + shortBeanName + "." + jsonMetadata.getToJsonArrayMethodName().getSymbolName().toString() + "(" + shortBeanName + "." + methodMetadata.getMethodName().getSymbolName() + "(" + methodParams.toString() + ").getResultList());"); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, finderMethodName, JavaType.STRING_OBJECT, annotatedParamTypes, newParamNames, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getFinderFormMethod(MethodMetadata methodMetadata) { if (entityMetadata.getFindAllMethod() == null) { // Mandatory input is missing (ROO-589) return null; } Assert.notNull(methodMetadata, "Method metadata required for finder"); JavaSymbolName finderFormMethodName = new JavaSymbolName(methodMetadata.getMethodName().getSymbolName() + "Form"); List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>(); List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(); List<JavaType> types = AnnotatedJavaType.convertFromAnnotatedJavaTypes(methodMetadata.getParameterTypes()); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); boolean needmodel = false; for (JavaType javaType : types) { EntityMetadata typeEntityMetadata = null; if (javaType.isCommonCollectionType() && isSpecialType(javaType.getParameters().get(0))) { javaType = javaType.getParameters().get(0); typeEntityMetadata = (EntityMetadata) metadataService.get(EntityMetadata.createIdentifier(javaType, Path.SRC_MAIN_JAVA)); } else if (isEnumType(javaType)) { bodyBuilder.appendFormalLine("model.addAttribute(\"" + getPlural(javaType).toLowerCase() + "\", java.util.Arrays.asList(" + javaType.getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + ".class.getEnumConstants()));"); } else if (isSpecialType(javaType)) { typeEntityMetadata = (EntityMetadata) metadataService.get(EntityMetadata.createIdentifier(javaType, Path.SRC_MAIN_JAVA)); } if (typeEntityMetadata != null) { bodyBuilder.appendFormalLine("model.addAttribute(\"" + getPlural(javaType).toLowerCase() + "\", " + javaType.getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "." + typeEntityMetadata.getFindAllMethod().getMethodName() + "());"); } needmodel = true; } if (types.contains(new JavaType(Date.class.getName())) || types.contains(new JavaType(Calendar.class.getName()))) { bodyBuilder.appendFormalLine("addDateTimeFormatPatterns(model);"); } bodyBuilder.appendFormalLine("return \"" + controllerPath + "/" + methodMetadata.getMethodName().getSymbolName() + "\";"); if (needmodel) { paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.Model"), null)); paramNames.add(new JavaSymbolName("model")); } MethodMetadata existingMethod = methodExists(finderFormMethodName, paramTypes); if (existingMethod != null) return existingMethod; List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); List<StringAttributeValue> arrayValues = new ArrayList<StringAttributeValue>(); arrayValues.add(new StringAttributeValue(new JavaSymbolName("value"), "find=" + methodMetadata.getMethodName().getSymbolName().replaceFirst("find" + entityMetadata.getPlural(), ""))); arrayValues.add(new StringAttributeValue(new JavaSymbolName("value"), "form")); requestMappingAttributes.add(new ArrayAttributeValue<StringAttributeValue>(new JavaSymbolName("params"), arrayValues)); requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("GET")))); AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(requestMapping); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, finderFormMethodName, JavaType.STRING_OBJECT, paramTypes, paramNames, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getFinderMethod(MethodMetadata methodMetadata) { Assert.notNull(methodMetadata, "Method metadata required for finder"); JavaSymbolName finderMethodName = new JavaSymbolName(methodMetadata.getMethodName().getSymbolName()); List<AnnotatedJavaType> annotatedParamTypes = new ArrayList<AnnotatedJavaType>(); List<JavaSymbolName> paramNames = methodMetadata.getParameterNames(); List<JavaType> paramTypes = AnnotatedJavaType.convertFromAnnotatedJavaTypes(methodMetadata.getParameterTypes()); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); StringBuilder methodParams = new StringBuilder(); for (int i = 0; i < paramTypes.size(); i++) { List<AnnotationMetadata> annotations = new ArrayList<AnnotationMetadata>(); List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>(); attributes.add(new StringAttributeValue(new JavaSymbolName("value"), uncapitalize(paramNames.get(i).getSymbolName()))); if (paramTypes.get(i).equals(JavaType.BOOLEAN_PRIMITIVE) || paramTypes.get(i).equals(JavaType.BOOLEAN_OBJECT)) { attributes.add(new BooleanAttributeValue(new JavaSymbolName("required"), false)); } AnnotationMetadataBuilder requestParamAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestParam"), attributes); annotations.add(requestParamAnnotation.build()); if (paramTypes.get(i).equals(new JavaType(Date.class.getName())) || paramTypes.get(i).equals(new JavaType(Calendar.class.getName()))) { JavaSymbolName fieldName = null; if (paramNames.get(i).getSymbolName().startsWith("max") || paramNames.get(i).getSymbolName().startsWith("min")) { fieldName = new JavaSymbolName(uncapitalize(paramNames.get(i).getSymbolName().substring(3))); } else { fieldName = paramNames.get(i); } FieldMetadata field = beanInfoMetadata.getFieldForPropertyName(fieldName); if (field != null) { AnnotationMetadata annotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("org.springframework.format.annotation.DateTimeFormat")); if (annotation != null) { annotations.add(annotation); } } } annotatedParamTypes.add(new AnnotatedJavaType(paramTypes.get(i), annotations)); if (paramTypes.get(i).equals(JavaType.BOOLEAN_OBJECT)) { methodParams.append(paramNames.get(i) + " == null ? new Boolean(false) : " + paramNames.get(i) + ", "); } else { methodParams.append(paramNames.get(i) + ", "); } } if (methodParams.length() > 0) { methodParams.delete(methodParams.length() - 2, methodParams.length()); } annotatedParamTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.Model"), new ArrayList<AnnotationMetadata>())); MethodMetadata existingMethod = methodExists(finderMethodName, annotatedParamTypes); if (existingMethod != null) return existingMethod; List<JavaSymbolName> newParamNames = new ArrayList<JavaSymbolName>(); newParamNames.addAll(paramNames); newParamNames.add(new JavaSymbolName("model")); List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>(); requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("params"), "find=" + methodMetadata.getMethodName().getSymbolName().replaceFirst("find" + entityMetadata.getPlural(), ""))); requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("GET")))); AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(requestMapping); bodyBuilder.appendFormalLine("model.addAttribute(\"" + getPlural(beanInfoMetadata.getJavaBean()).toLowerCase() + "\", " + beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "." + methodMetadata.getMethodName().getSymbolName() + "(" + methodParams.toString() + ").getResultList());"); if (paramTypes.contains(new JavaType(Date.class.getName())) || paramTypes.contains(new JavaType(Calendar.class.getName()))) { bodyBuilder.appendFormalLine("addDateTimeFormatPatterns(model);"); } bodyBuilder.appendFormalLine("return \"" + controllerPath + "/list\";"); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, finderMethodName, JavaType.STRING_OBJECT, annotatedParamTypes, newParamNames, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder.build(); } private MethodMetadata getDateTimeFormatHelperMethod() { JavaSymbolName addDateTimeFormatPatterns = new JavaSymbolName("addDateTimeFormatPatterns"); List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>(); paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.Model"), new ArrayList<AnnotationMetadata>())); MethodMetadata addDateTimeFormatPatternsMethod = methodExists(addDateTimeFormatPatterns, paramTypes); if (addDateTimeFormatPatternsMethod != null) return addDateTimeFormatPatternsMethod; List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(); paramNames.add(new JavaSymbolName("model")); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); Iterator<Map.Entry<JavaSymbolName, DateTimeFormat>> it = dateTypes.entrySet().iterator(); while (it.hasNext()) { Entry<JavaSymbolName, DateTimeFormat> entry = it.next(); String pattern; if (entry.getValue().pattern != null) { pattern = "\"" + entry.getValue().pattern + "\""; } else { JavaType dateTimeFormat = new JavaType("org.joda.time.format.DateTimeFormat"); String dateTimeFormatSimple = dateTimeFormat.getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()); JavaType localeContextHolder = new JavaType("org.springframework.context.i18n.LocaleContextHolder"); String localeContextHolderSimple = localeContextHolder.getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()); pattern = dateTimeFormatSimple + ".patternForStyle(\"" + entry.getValue().style + "\", " + localeContextHolderSimple + ".getLocale())"; } bodyBuilder.appendFormalLine("model.addAttribute(\"" + entityName + "_" + entry.getKey().getSymbolName().toLowerCase() + "_date_format\", " + pattern + ");"); } MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), 0, addDateTimeFormatPatterns, JavaType.VOID_PRIMITIVE, paramTypes, paramNames, bodyBuilder); return methodBuilder.build(); } private List<MethodMetadata> getPopulateMethods() { List<MethodMetadata> methods = new ArrayList<MethodMetadata>(); for (JavaType type : specialDomainTypes) { // There is a need to present a populator for self references (see ROO-1112) // if (type.equals(beanInfoMetadata.getJavaBean())) { // continue; // } InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); EntityMetadata typeEntityMetadata = (EntityMetadata) metadataService.get(EntityMetadata.createIdentifier(type, Path.SRC_MAIN_JAVA)); if (typeEntityMetadata != null) { bodyBuilder.appendFormalLine("return " + type.getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "." + typeEntityMetadata.getFindAllMethod().getMethodName() + "();"); } else if (isEnumType(type)) { JavaType arrays = new JavaType("java.util.Arrays"); bodyBuilder.appendFormalLine("return " + arrays.getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + ".asList(" + type.getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + ".class.getEnumConstants());"); } else if (isRooIdentifier(type)) { continue; } else { throw new IllegalStateException("Could not scaffold controller for type " + beanInfoMetadata.getJavaBean().getFullyQualifiedTypeName() + ", the referenced type " + type.getFullyQualifiedTypeName() + " cannot be handled"); } JavaSymbolName populateMethodName = new JavaSymbolName("populate" + getPlural(type)); MethodMetadata addReferenceDataMethod = methodExists(populateMethodName, new ArrayList<AnnotatedJavaType>()); if (addReferenceDataMethod != null) continue; List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>(); attributes.add(new StringAttributeValue(new JavaSymbolName("value"), getPlural(type).toLowerCase())); annotations.add(new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.ModelAttribute"), attributes)); List<JavaType> typeParams = new ArrayList<JavaType>(); typeParams.add(type); JavaType returnType = new JavaType("java.util.Collection", 0, DataType.TYPE, null, typeParams); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, populateMethodName, returnType, bodyBuilder); methodBuilder.setAnnotations(annotations); methods.add(methodBuilder.build()); } return methods; } private MethodMetadata getEncodeUrlPathSegmentMethod() { JavaSymbolName encodeUrlPathSegment = new JavaSymbolName("encodeUrlPathSegment"); List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>(); paramTypes.add(new AnnotatedJavaType(JavaType.STRING_OBJECT, new ArrayList<AnnotationMetadata>())); paramTypes.add(new AnnotatedJavaType(new JavaType("javax.servlet.http.HttpServletRequest"), new ArrayList<AnnotationMetadata>())); MethodMetadata encodeUrlPathSegmentMethod = methodExists(encodeUrlPathSegment, paramTypes); if (encodeUrlPathSegmentMethod != null) return encodeUrlPathSegmentMethod; List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(); paramNames.add(new JavaSymbolName("pathSegment")); paramNames.add(new JavaSymbolName("request")); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine("String enc = request.getCharacterEncoding();"); bodyBuilder.appendFormalLine("if (enc == null) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine("enc = " + new JavaType("org.springframework.web.util.WebUtils").getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + ".DEFAULT_CHARACTER_ENCODING;"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); bodyBuilder.appendFormalLine("try {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine("pathSegment = " + new JavaType("org.springframework.web.util.UriUtils").getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + ".encodePathSegment(pathSegment, enc);"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); bodyBuilder.appendFormalLine("catch (" + new JavaType("java.io.UnsupportedEncodingException").getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + " uee) {}"); bodyBuilder.appendFormalLine("return pathSegment;"); return new MethodMetadataBuilder(getId(), 0, encodeUrlPathSegment, JavaType.STRING_OBJECT, paramTypes, paramNames, bodyBuilder).build(); } private SortedSet<JavaType> getSpecialDomainTypes(JavaType javaType) { SortedSet<JavaType> specialTypes = new TreeSet<JavaType>(); BeanInfoMetadata bim = (BeanInfoMetadata) metadataService.get(BeanInfoMetadata.createIdentifier(javaType, Path.SRC_MAIN_JAVA)); if (bim == null) { // Unable to get metadata so it is not a JavaType in our project anyway. return specialTypes; } EntityMetadata em = (EntityMetadata) metadataService.get(EntityMetadata.createIdentifier(javaType, Path.SRC_MAIN_JAVA)); if (em == null) { // Unable to get entity metadata so it is not a Entity in our project anyway. return specialTypes; } for (MethodMetadata accessor : bim.getPublicAccessors(false)) { // Not interested in identifiers and version fields if (accessor.equals(em.getIdentifierAccessor()) || accessor.equals(em.getVersionAccessor())) { continue; } // Not interested in fields that are not exposed via a mutator or are JPA transient fields FieldMetadata fieldMetadata = bim.getFieldForPropertyName(BeanInfoUtils.getPropertyNameForJavaBeanMethod(accessor)); if (fieldMetadata == null || !hasMutator(fieldMetadata, bim) || isTransientFieldType(fieldMetadata)) { continue; } JavaType type = accessor.getReturnType(); if (type.isCommonCollectionType()) { for (JavaType genericType : type.getParameters()) { if (isSpecialType(genericType)) { specialTypes.add(genericType); } } } else { if (isSpecialType(type) && !isEmbeddedFieldType(fieldMetadata)) { specialTypes.add(type); } } } return specialTypes; } private Map<JavaSymbolName, DateTimeFormat> getDatePatterns() { Map<JavaSymbolName, DateTimeFormat> dates = new HashMap<JavaSymbolName, DateTimeFormat>(); for (MethodMetadata accessor : beanInfoMetadata.getPublicAccessors(false)) { // Not interested in identifiers and version fields if (accessor.equals(entityMetadata.getIdentifierAccessor()) || accessor.equals(entityMetadata.getVersionAccessor())) { continue; } // Not interested in fields that are not exposed via a mutator FieldMetadata fieldMetadata = beanInfoMetadata.getFieldForPropertyName(BeanInfoUtils.getPropertyNameForJavaBeanMethod(accessor)); if (fieldMetadata == null || !hasMutator(fieldMetadata, beanInfoMetadata)) { continue; } JavaType type = accessor.getReturnType(); if (type.getFullyQualifiedTypeName().equals(Date.class.getName()) || type.getFullyQualifiedTypeName().equals(Calendar.class.getName())) { AnnotationMetadata annotation = MemberFindingUtils.getAnnotationOfType(fieldMetadata.getAnnotations(), new JavaType("org.springframework.format.annotation.DateTimeFormat")); JavaSymbolName patternSymbol = new JavaSymbolName("pattern"); JavaSymbolName styleSymbol = new JavaSymbolName("style"); DateTimeFormat dateTimeFormat = null; if (annotation != null) { if (annotation.getAttributeNames().contains(styleSymbol)) { dateTimeFormat = DateTimeFormat.withStyle(annotation.getAttribute(styleSymbol).getValue().toString()); } else if (annotation.getAttributeNames().contains(patternSymbol)) { dateTimeFormat = DateTimeFormat.withPattern(annotation.getAttribute(patternSymbol).getValue().toString()); } } if (dateTimeFormat != null) { dates.put(fieldMetadata.getFieldName(), dateTimeFormat); for (String finder : entityMetadata.getDynamicFinders()) { if (finder.contains(StringUtils.capitalize(fieldMetadata.getFieldName().getSymbolName()) + "Between")) { dates.put(new JavaSymbolName("min" + StringUtils.capitalize(fieldMetadata.getFieldName().getSymbolName())), dateTimeFormat); dates.put(new JavaSymbolName("max" + StringUtils.capitalize(fieldMetadata.getFieldName().getSymbolName())), dateTimeFormat); } } } else { log.warning("It is recommended to use @DateTimeFormat(style=\"S-\") on " + beanInfoMetadata.getJavaBean().getSimpleTypeName() + "." + fieldMetadata.getFieldName() + " to use automatic date conversion in Spring MVC"); } } } return dates; } private MethodMetadata methodExists(JavaSymbolName methodName, List<AnnotatedJavaType> parameters) { return MemberFindingUtils.getMethod(detailsScanner.getMemberDetails(getClass().getName(), governorTypeDetails), methodName, AnnotatedJavaType.convertFromAnnotatedJavaTypes(parameters)); } private String getShortName(JavaType type) { return type.getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()); } private boolean isEnumType(JavaType type) { PhysicalTypeMetadata physicalTypeMetadata = (PhysicalTypeMetadata) metadataService.get(PhysicalTypeIdentifierNamingUtils.createIdentifier(PhysicalTypeIdentifier.class.getName(), type, Path.SRC_MAIN_JAVA)); if (physicalTypeMetadata != null) { PhysicalTypeDetails details = physicalTypeMetadata.getMemberHoldingTypeDetails(); if (details != null) { if (details.getPhysicalTypeCategory().equals(PhysicalTypeCategory.ENUMERATION)) { return true; } } } return false; } private boolean isRooIdentifier(JavaType type) { PhysicalTypeMetadata physicalTypeMetadata = (PhysicalTypeMetadata) metadataService.get(PhysicalTypeIdentifier.createIdentifier(type, Path.SRC_MAIN_JAVA)); if (physicalTypeMetadata == null) { return false; } ClassOrInterfaceTypeDetails cid = (ClassOrInterfaceTypeDetails) physicalTypeMetadata.getMemberHoldingTypeDetails(); if (cid == null) { return false; } return null != MemberFindingUtils.getAnnotationOfType(cid.getAnnotations(), new JavaType(RooIdentifier.class.getName())); } private boolean hasMutator(FieldMetadata fieldMetadata, BeanInfoMetadata bim) { for (MethodMetadata mutator : bim.getPublicMutators()) { if (fieldMetadata.equals(bim.getFieldForPropertyName(BeanInfoUtils.getPropertyNameForJavaBeanMethod(mutator)))) return true; } return false; } private boolean isSpecialType(JavaType javaType) { // We are only interested if the type is part of our application if (metadataService.get(PhysicalTypeIdentifier.createIdentifier(javaType, Path.SRC_MAIN_JAVA)) != null) { return true; } return false; } private boolean isEmbeddedFieldType(FieldMetadata field) { return MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.persistence.Embedded")) != null; } private boolean isTransientFieldType(FieldMetadata field) { return MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.persistence.Transient")) != null; } private String getPlural(JavaType type) { if (pluralCache.get(type) != null) { return pluralCache.get(type); } PluralMetadata pluralMetadata = (PluralMetadata) metadataService.get(PluralMetadata.createIdentifier(type, Path.SRC_MAIN_JAVA)); Assert.notNull(pluralMetadata, "Could not determine the plural for the '" + type.getFullyQualifiedTypeName() + "' type"); if (!pluralMetadata.getPlural().equals(type.getSimpleTypeName())) { pluralCache.put(type, pluralMetadata.getPlural()); return pluralMetadata.getPlural(); } pluralCache.put(type, pluralMetadata.getPlural() + "Items"); return pluralMetadata.getPlural() + "Items"; } public String toString() { ToStringCreator tsc = new ToStringCreator(this); tsc.append("identifier", getId()); tsc.append("valid", valid); tsc.append("aspectName", aspectName); tsc.append("destinationType", destination); tsc.append("governor", governorPhysicalTypeMetadata.getId()); tsc.append("itdTypeDetails", itdTypeDetails); return tsc.toString(); } public static final String getMetadataIdentiferType() { return PROVIDES_TYPE; } public static final String createIdentifier(JavaType javaType, Path path) { return PhysicalTypeIdentifierNamingUtils.createIdentifier(PROVIDES_TYPE_STRING, javaType, path); } public static final JavaType getJavaType(String metadataIdentificationString) { return PhysicalTypeIdentifierNamingUtils.getJavaType(PROVIDES_TYPE_STRING, metadataIdentificationString); } public static final Path getPath(String metadataIdentificationString) { return PhysicalTypeIdentifierNamingUtils.getPath(PROVIDES_TYPE_STRING, metadataIdentificationString); } public static boolean isValid(String metadataIdentificationString) { return PhysicalTypeIdentifierNamingUtils.isValid(PROVIDES_TYPE_STRING, metadataIdentificationString); } private static class DateTimeFormat { public String style; public String pattern; public static DateTimeFormat withStyle(String style) { DateTimeFormat d = new DateTimeFormat(); d.style = style; return d; } public static DateTimeFormat withPattern(String pattern) { DateTimeFormat d = new DateTimeFormat(); d.pattern = pattern; return d; } } private String uncapitalize(String term) { // [ROO-1790] this is needed to adhere to the JavaBean naming conventions (see JavaBean spec section 8.8) return Introspector.decapitalize(StringUtils.capitalize(term)); } }
ROO-1918: WebScaffoldMetadata should use its MetadataProvider class name to ensure optimal loop detection semantics
addon-web-mvc-controller/src/main/java/org/springframework/roo/addon/web/mvc/controller/WebScaffoldMetadata.java
ROO-1918: WebScaffoldMetadata should use its MetadataProvider class name to ensure optimal loop detection semantics
<ide><path>ddon-web-mvc-controller/src/main/java/org/springframework/roo/addon/web/mvc/controller/WebScaffoldMetadata.java <ide> } <ide> <ide> private MethodMetadata methodExists(JavaSymbolName methodName, List<AnnotatedJavaType> parameters) { <del> return MemberFindingUtils.getMethod(detailsScanner.getMemberDetails(getClass().getName(), governorTypeDetails), methodName, AnnotatedJavaType.convertFromAnnotatedJavaTypes(parameters)); <add> return MemberFindingUtils.getMethod(detailsScanner.getMemberDetails(WebScaffoldMetadataProviderImpl.class.getName(), governorTypeDetails), methodName, AnnotatedJavaType.convertFromAnnotatedJavaTypes(parameters)); <ide> } <ide> <ide> private String getShortName(JavaType type) {
JavaScript
mit
31b0a09a4ed9d3b5a06cbb8311b15a03e20da148
0
MostlyJS/mostly-feathers-mongoose
import assert from 'assert'; import fp from 'ramda'; import makeDebug from 'debug'; import { Service as BaseService } from 'feathers-mongoose'; import { errorHandler } from 'feathers-mongoose/lib/error-handler'; const debug = makeDebug('mostly:feathers-mongoose:service'); const defaultOptions = { lean: true, paginate: { default: 10, max: 50 } }; const defaultMethods = ['find', 'get', 'create', 'update', 'patch', 'remove']; // prevent accidental multiple operations const assertMultiple = function(id, params, message) { if (!id) { if (params && params.query && (params.$multi || params.query.$multi)) { delete params.query.$multi; } else { throw new Error(message); } } }; const unsetOptions = fp.pipe( fp.dissoc('Model'), fp.dissoc('ModelName') ); const unset_id = function(obj) { if (obj && obj._id) { return fp.pipe( fp.assoc('id', String(obj.id || obj._id)), fp.dissoc('_id'), fp.dissoc('__v') )(obj); } else { return obj; } }; const unsetObj = function(obj) { if (Array.isArray(obj)) { return fp.map(unset_id, obj); } else { return unset_id(obj); } }; // transform the results const transform = function(results) { if (results) { if (results.data) { results.data = unsetObj(results.data); } else { results = unsetObj(results); } } return results; }; export class Service extends BaseService { constructor(options) { options = Object.assign({}, defaultOptions, options); super(options); this.options = unsetOptions(options); this.name = options.name || 'mongoose-service'; } setup(app) { this.app = app; } find(params) { params = params || { query: {} }; // default behaviours for external call if (params.provider && params.query) { // fix id query as _ids if (params.query.id) { params.query._id = params.query.id; delete params.query.id; } // filter destroyed item by default if (!params.query.destroyedAt) { params.query.destroyedAt = null; } // default sort if (!params.query.$sort) { params.query.$sort = { createdAt: -1 }; } } // search by regex Object.keys(params.query || []).forEach(field => { if (params.query[field] && params.query[field].$like !== undefined && field.indexOf('$') === -1) { params.query[field] = { $regex: new RegExp(params.query[field].$like), $options: 'i' }; } }); const action = params.__action; if (!action || action === 'find') { debug('service %s find %j', this.name, params.query); return super.find(params).then(transform); } // TODO secure action call by find if (this[action] && defaultMethods.indexOf(action) < 0) { params = fp.dissoc('__action', params); return this._action(action, null, {}, params); } throw new Error("No such **find** action: " + action); } get(id, params) { if (id === 'null' || id === '0') id = null; params = params || { query: {} }; let action = params.__action; // check if id is action for find if (id && !action) { if (this[id] && defaultMethods.indexOf(id) < 0) { params = fp.assoc('__action', id, params); return this.find(params); } } if (!action || action === 'get') { debug('service %s get %j', this.name, id, params); return super.get(id, params).then(transform); } // TODO secure action call by get if (this[action] && defaultMethods.indexOf(action) < 0) { params = fp.dissoc('__action', params); return this._action(action, id, {}, params); } throw new Error("No such **get** action: " + action); } create(data, params) { params = params || { query: {} }; // add support to create multiple objects if (Array.isArray(data)) { return Promise.all(data.map(current => this.create(current, params))); } const action = params.__action; if (!action || action === 'create') { debug('service %s create %j', this.name, data); return super.create(data, params).then(transform); } // TODO secure action call by get if (this[action] && defaultMethods.indexOf(action) < 0) { params = fp.dissoc('__action', params); return this._action(action, null, data, params); } else { throw new Error("No such **create** action: " + action); } } update(id, data, params) { if (id === 'null') id = null; params = params || {}; assertMultiple(id, params, "Found null id, update must be called with $multi."); const action = params.__action; if (!action || action === 'update') { debug('service %s update %j', this.name, id, data); return super.update(id, data, params).then(transform); } // TODO secure action call by get if (this[action] && defaultMethods.indexOf(action) < 0) { params = fp.dissoc('__action', params); return this._action(action, id, data, params); } else { throw new Error("No such **put** action: " + action); } } patch(id, data, params) { if (id === 'null') id = null; params = params || {}; assertMultiple(id, params, "Found null id, patch must be called with $multi."); const action = params.__action; if (!action || action === 'patch') { return super.patch(id, data, params).then(transform); } // TODO secure action call by get if (this[action] && defaultMethods.indexOf(action) < 0) { debug('service %s patch %j', this.name, id); params = fp.dissoc('__action', params); return this._action(action, id, data, params); } else { throw new Error("No such **patch** action: " + action); } } remove(id, params) { if (id === 'null') id = null; assertMultiple(id, params, "Found null id, remove must be called with $multi."); const action = params.__action; if (!action || action === 'remove') { if (params.query.$soft) { debug('service %s remove soft %j', this.name, id); params = fp.dissocPath(['query', '$soft'], params); return super.patch(id, { destroyedAt: new Date() }, params).then(transform); } else { debug('service %s remove %j', this.name, id); return super.remove(id, params).then(transform); } } // TODO secure action call by get if (id && action === 'restore') { params = fp.dissoc('__action', params); return this.restore(id, params); } else { throw new Error("No such **remove** action: " + action); } } _action(action, id, data, params) { debug(' => %s action %s with %j', this.name, action, id, data); assert(this[action], 'No such action method: ' + action); // delete params.provider; let query = id? this.get(id, params) : Promise.resolve(null); return query.then(origin => { if (origin && origin.data) { origin = origin.data; } if (id && !origin) { throw new Error('Not found record ' + id + ' in ' + this.Model.modelName); } return this[action].call(this, id, data, params, origin); }); } // some reserved actions upsert(data, params) { params = params || {}; let query = params.query || data; // default find by input data return this.Model.findOneAndUpdate(query, data, { upsert: true, new: true }) .lean() .then(transform) .catch(errorHandler); } count(id, data, params) { params = params || id || { query: {} }; params.query.$limit = 0; return super.find(params).then(result => result.total); } first(id, data, params) { params = params || id || { query: {} }; params.query.$limit = 1; params.paginate = false; // disable paginate return this.find(params).then(results => { results = results.data || results; if (Array.isArray(results) && results.length > 0) { return results[0]; } else { return null; } }); } last(id, data, params) { params = params || id || { query: {} }; return this.count(id, data, params).then(total => { params.query.$limit = 1; params.query.$skip = total - 1; return this.find(params).then(results => { results = results.data || results; if (Array.isArray(results) && results.length > 0) { return results[0]; } else { return results; } }); }); } restore(id, data, params) { return super.patch(id, { destroyedAt: null }, params).then(transform); } } export default function init (options) { return new Service(options); } init.Service = Service; init.transform = transform;
src/service.js
import assert from 'assert'; import fp from 'ramda'; import makeDebug from 'debug'; import { Service as BaseService } from 'feathers-mongoose'; import { errorHandler } from 'feathers-mongoose/lib/error-handler'; const debug = makeDebug('mostly:feathers-mongoose:service'); const defaultOptions = { lean: true, paginate: { default: 10, max: 50 } }; const defaultMethods = ['find', 'get', 'create', 'update', 'patch', 'remove']; // prevent accidental multiple operations const assertMultiple = function(id, params, message) { if (!id) { if (params && params.query && (params.$multi || params.query.$multi)) { delete params.query.$multi; } else { throw new Error(message); } } }; const unsetOptions = fp.pipe( fp.dissoc('Model'), fp.dissoc('ModelName') ); const unset_id = function(obj) { if (obj && obj._id) { return fp.pipe( fp.assoc('id', String(obj.id || obj._id)), fp.dissoc('_id'), fp.dissoc('__v') )(obj); } else { return obj; } }; const unsetObj = function(obj) { if (Array.isArray(obj)) { return fp.map(unset_id, obj); } else { return unset_id(obj); } }; // transform the results const transform = function(results) { if (results) { if (results.data) { results.data = unsetObj(results.data); } else { results = unsetObj(results); } } return results; }; export class Service extends BaseService { constructor(options) { options = Object.assign({}, defaultOptions, options); super(options); this.options = unsetOptions(options); this.name = options.name || 'mongoose-service'; } setup(app) { this.app = app; } find(params) { params = params || { query: {} }; // default behaviours for external call if (params.provider && params.query) { // fix id query as _ids if (params.query.id) { params.query._id = params.query.id; delete params.query.id; } // filter destroyed item by default if (!params.query.destroyedAt) { params.query.destroyedAt = null; } // default sort if (!params.query.$sort) { params.query.$sort = { createdAt: -1 }; } } // search by regex Object.keys(params.query || []).forEach(field => { if (params.query[field] && params.query[field].$like !== undefined && field.indexOf('$') === -1) { params.query[field] = { $regex: new RegExp(params.query[field].$like), $options: 'i' }; } }); const action = params.__action; if (!action || action === 'find') { debug('service %s find %j', this.name, params.query); return super.find(params).then(transform); } // TODO secure action call by find if (this[action] && defaultMethods.indexOf(action) < 0) { let params2 = fp.dissoc('__action', params); return this._action(action, null, {}, params2); } throw new Error("No such **find** action: " + action); } get(id, params) { if (id === 'null' || id === '0') id = null; params = params || { query: {} }; let action = params.__action; // check if id is action for find if (id && !action) { if (this[id] && defaultMethods.indexOf(id) < 0) { let params2 = fp.assoc('__action', id, params); return this.find(params2); } } if (!action || action === 'get') { debug('service %s get %j', this.name, id, params); return super.get(id, params).then(transform); } // TODO secure action call by get if (this[action] && defaultMethods.indexOf(action) < 0) { let params2 = fp.dissoc('__action', params); return this._action(action, id, {}, params2); } throw new Error("No such **get** action: " + action); } create(data, params) { params = params || { query: {} }; // add support to create multiple objects if (Array.isArray(data)) { return Promise.all(data.map(current => this.create(current, params))); } const action = params.__action; if (!action || action === 'create') { debug('service %s create %j', this.name, data); return super.create(data, params).then(transform); } // TODO secure action call by get if (this[action] && defaultMethods.indexOf(action) < 0) { let params2 = fp.dissoc('__action', params); return this._action(action, null, data, params2); } else { throw new Error("No such **create** action: " + action); } } update(id, data, params) { if (id === 'null') id = null; params = params || {}; assertMultiple(id, params, "Found null id, update must be called with $multi."); const action = params.__action; if (!action || action === 'update') { debug('service %s update %j', this.name, id, data); return super.update(id, data, params).then(transform); } // TODO secure action call by get if (this[action] && defaultMethods.indexOf(action) < 0) { let params2 = fp.dissoc('__action', params); return this._action(action, id, data, params2); } else { throw new Error("No such **put** action: " + action); } } patch(id, data, params) { if (id === 'null') id = null; params = params || {}; assertMultiple(id, params, "Found null id, patch must be called with $multi."); const action = params.__action; if (!action || action === 'patch') { return super.patch(id, data, params).then(transform); } // TODO secure action call by get if (this[action] && defaultMethods.indexOf(action) < 0) { debug('service %s patch %j', this.name, id); let params2 = fp.dissoc('__action', params); return this._action(action, id, data, params2); } else { throw new Error("No such **patch** action: " + action); } } remove(id, params) { if (id === 'null') id = null; assertMultiple(id, params, "Found null id, remove must be called with $multi."); const action = params.__action; if (!action || action === 'remove') { if (params.query.$soft) { debug('service %s remove soft %j', this.name, id); let params2 = fp.dissocPath(['query', '$soft'], params); return super.patch(id, { destroyedAt: new Date() }, params2).then(transform); } else { debug('service %s remove %j', this.name, id); return super.remove(id, params).then(transform); } } // TODO secure action call by get if (action === 'restore') { let params2 = fp.dissoc('__action', params); return this.restore(id, params2); } else { throw new Error("No such **remove** action: " + action); } } _action(action, id, data, params) { debug(' => %s action %s with %j', this.name, action, id, data); assert(this[action], 'No such action method: ' + action); // delete params.provider; let query = id? this.get(id, params) : Promise.resolve(null); return query.then(origin => { if (origin && origin.data) { origin = origin.data; } if (id && !origin) { throw new Error('Not found record ' + id + ' in ' + this.Model.modelName); } return this[action].call(this, id, data, params, origin); }); } // some reserved actions upsert(data, params) { params = params || {}; let query = params.query || data; // default find by input data return this.Model.findOneAndUpdate(query, data, { upsert: true, new: true }) .lean() .then(transform) .catch(errorHandler); } count(id, data, params) { params = params || id || { query: {} }; params.query.$limit = 0; return super.find(params).then(result => result.total); } first(id, data, params) { params = params || id || { query: {} }; params.query.$limit = 1; params.paginate = false; // disable paginate return this.find(params).then(results => { results = results.data || results; if (Array.isArray(results) && results.length > 0) { return results[0]; } else { return null; } }); } last(id, data, params) { params = params || id || { query: {} }; return this.count(id, data, params).then(total => { params.query.$limit = 1; params.query.$skip = total - 1; return this.find(params).then(results => { results = results.data || results; if (Array.isArray(results) && results.length > 0) { return results[0]; } else { return results; } }); }); } restore(id, data, params) { return super.patch(id, { destroyedAt: null }, params).then(transform); } } export default function init (options) { return new Service(options); } init.Service = Service; init.transform = transform;
minor change
src/service.js
minor change
<ide><path>rc/service.js <ide> <ide> // TODO secure action call by find <ide> if (this[action] && defaultMethods.indexOf(action) < 0) { <del> let params2 = fp.dissoc('__action', params); <del> return this._action(action, null, {}, params2); <add> params = fp.dissoc('__action', params); <add> return this._action(action, null, {}, params); <ide> } <ide> throw new Error("No such **find** action: " + action); <ide> } <ide> // check if id is action for find <ide> if (id && !action) { <ide> if (this[id] && defaultMethods.indexOf(id) < 0) { <del> let params2 = fp.assoc('__action', id, params); <del> return this.find(params2); <add> params = fp.assoc('__action', id, params); <add> return this.find(params); <ide> } <ide> } <ide> <ide> <ide> // TODO secure action call by get <ide> if (this[action] && defaultMethods.indexOf(action) < 0) { <del> let params2 = fp.dissoc('__action', params); <del> return this._action(action, id, {}, params2); <add> params = fp.dissoc('__action', params); <add> return this._action(action, id, {}, params); <ide> } <ide> throw new Error("No such **get** action: " + action); <ide> } <ide> <ide> // TODO secure action call by get <ide> if (this[action] && defaultMethods.indexOf(action) < 0) { <del> let params2 = fp.dissoc('__action', params); <del> return this._action(action, null, data, params2); <add> params = fp.dissoc('__action', params); <add> return this._action(action, null, data, params); <ide> } else { <ide> throw new Error("No such **create** action: " + action); <ide> } <ide> <ide> // TODO secure action call by get <ide> if (this[action] && defaultMethods.indexOf(action) < 0) { <del> let params2 = fp.dissoc('__action', params); <del> return this._action(action, id, data, params2); <add> params = fp.dissoc('__action', params); <add> return this._action(action, id, data, params); <ide> } else { <ide> throw new Error("No such **put** action: " + action); <ide> } <ide> // TODO secure action call by get <ide> if (this[action] && defaultMethods.indexOf(action) < 0) { <ide> debug('service %s patch %j', this.name, id); <del> let params2 = fp.dissoc('__action', params); <del> return this._action(action, id, data, params2); <add> params = fp.dissoc('__action', params); <add> return this._action(action, id, data, params); <ide> } else { <ide> throw new Error("No such **patch** action: " + action); <ide> } <ide> if (!action || action === 'remove') { <ide> if (params.query.$soft) { <ide> debug('service %s remove soft %j', this.name, id); <del> let params2 = fp.dissocPath(['query', '$soft'], params); <del> return super.patch(id, { destroyedAt: new Date() }, params2).then(transform); <add> params = fp.dissocPath(['query', '$soft'], params); <add> return super.patch(id, { destroyedAt: new Date() }, params).then(transform); <ide> } else { <ide> debug('service %s remove %j', this.name, id); <ide> return super.remove(id, params).then(transform); <ide> } <ide> <ide> // TODO secure action call by get <del> if (action === 'restore') { <del> let params2 = fp.dissoc('__action', params); <del> return this.restore(id, params2); <add> if (id && action === 'restore') { <add> params = fp.dissoc('__action', params); <add> return this.restore(id, params); <ide> } else { <ide> throw new Error("No such **remove** action: " + action); <ide> }
JavaScript
mit
fe517b33a5be58f1e7d4ea72a91d8e8bf24b9061
0
bitjson/bitcore,bitpay/bitcore,dashevo/insight-api-dash,bitjson/bitcore,bitpay/bitcore,pnagurny/bitcore-node,martindale/bitcore,martindale/bitcore,netanelkl/bitcore-node,bitpay/bitcore,bitpay/bitcore,maraoz/bitcore-node,martindale/bitcore,martindale/bitcore,bitjson/bitcore,bitjson/bitcore
'use strict'; var TRANSACTION_DISPLAYED = 5; var BLOCKS_DISPLAYED = 5; angular.module('insight.system').controller('IndexController', function($scope, $rootScope, Global, get_socket, Blocks, Block, Transactions, Transaction) { $scope.global = Global; var getTransaction = function(txid) { Transaction.get({ txId: txid }, function(res) { $scope.txs.unshift(res); }); }; var getBlock = function(hash) { Block.get({ blockHash: hash }, function(res) { $scope.blocks.unshift(res); }); }; var socket = get_socket($scope); socket.emit('subscribe', 'inv'); //show errors $scope.flashMessage = $rootScope.flashMessage || null; socket.on('tx', function(tx) { var txStr = tx.txid.toString(); console.log('Transaction received! ' + JSON.stringify(tx)); if (parseInt($scope.txs.length) > parseInt(TRANSACTION_DISPLAYED) - 1) { $scope.txs.pop(); } getTransaction(txStr); }); socket.on('block', function(block) { var blockHash = block.hash.toString(); console.log('Block received! ' + JSON.stringify(block)); if (parseInt($scope.blocks.length) > parseInt(BLOCKS_DISPLAYED) - 1) { $scope.blocks.pop(); } getBlock(blockHash); }); $scope.human_since = function(time) { var m = moment.unix(time); return m.max().fromNow(); }; $scope.index = function() { Blocks.get({ limit: BLOCKS_DISPLAYED }, function(res) { $scope.blocks = res.blocks; $scope.blocksLength = res.lenght; }); Transactions.get({ limit: TRANSACTION_DISPLAYED }, function(res) { $scope.txs = res.txs; }); }; $scope.txs = []; $scope.blocks = []; });
public/js/controllers/index.js
'use strict'; var TRANSACTION_DISPLAYED = 5; var BLOCKS_DISPLAYED = 5; angular.module('insight.system').controller('IndexController', function($scope, $rootScope, Global, get_socket, Blocks, Block, Transactions, Transaction) { $scope.global = Global; var getTransaction = function(txid) { Transaction.get({ txId: txid }, function(res) { $scope.txs.unshift(res); }); }; var getBlock = function(hash) { Block.get({ blockHash: hash }, function(res) { $scope.blocks.unshift(res); }); }; var socket = get_socket($scope); socket.emit('subscribe', 'inv'); //show errors $scope.flashMessage = $rootScope.flashMessage || null; socket.on('tx', function(tx) { var txStr = tx.txid.toString(); console.log('Transaction received! ' + JSON.stringify(tx)); if (parseInt($scope.txs.length) === parseInt(TRANSACTION_DISPLAYED)) { $scope.txs.pop(); } getTransaction(txStr); }); socket.on('block', function(block) { var blockHash = block.hash.toString(); console.log('Block received! ' + JSON.stringify(block)); if (parseInt($scope.blocks.length) === parseInt(BLOCKS_DISPLAYED)) { $scope.blocks.pop(); } getBlock(blockHash); }); $scope.human_since = function(time) { var m = moment.unix(time); return m.max().fromNow(); }; $scope.index = function() { Blocks.get({ limit: BLOCKS_DISPLAYED }, function(res) { $scope.blocks = res.blocks; $scope.blocksLength = res.lenght; }); Transactions.get({ limit: TRANSACTION_DISPLAYED }, function(res) { $scope.txs = res.txs; }); }; $scope.txs = []; $scope.blocks = []; });
homepage: fixed, only show 5 elements (it is!)
public/js/controllers/index.js
homepage: fixed, only show 5 elements (it is!)
<ide><path>ublic/js/controllers/index.js <ide> socket.on('tx', function(tx) { <ide> var txStr = tx.txid.toString(); <ide> console.log('Transaction received! ' + JSON.stringify(tx)); <del> if (parseInt($scope.txs.length) === parseInt(TRANSACTION_DISPLAYED)) { <add> if (parseInt($scope.txs.length) > parseInt(TRANSACTION_DISPLAYED) - 1) { <ide> $scope.txs.pop(); <ide> } <ide> getTransaction(txStr); <ide> socket.on('block', function(block) { <ide> var blockHash = block.hash.toString(); <ide> console.log('Block received! ' + JSON.stringify(block)); <del> if (parseInt($scope.blocks.length) === parseInt(BLOCKS_DISPLAYED)) { <add> if (parseInt($scope.blocks.length) > parseInt(BLOCKS_DISPLAYED) - 1) { <ide> $scope.blocks.pop(); <ide> } <ide> getBlock(blockHash);
Java
apache-2.0
e13e71c062b0e12fb12f856fe30ad8bd8f21849f
0
michaelkourlas/voipms-sms-client
/* * VoIP.ms SMS * Copyright (C) 2015-2016 Michael Kourlas * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.kourlas.voipms_sms.activities; import android.Manifest; import android.annotation.TargetApi; import android.app.Activity; import android.app.NotificationManager; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Outline; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.app.NavUtils; import android.support.v4.content.ContextCompat; import android.support.v4.view.ViewCompat; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.view.ActionMode; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.*; import android.widget.*; import net.kourlas.voipms_sms.*; import net.kourlas.voipms_sms.adapters.ConversationRecyclerViewAdapter; import net.kourlas.voipms_sms.model.Conversation; import net.kourlas.voipms_sms.model.Message; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.Locale; public class ConversationActivity extends AppCompatActivity implements ActionMode.Callback, View.OnLongClickListener, View.OnClickListener, ActivityCompat.OnRequestPermissionsResultCallback { private static final String TAG = "ConversationActivity"; private static final int PERM_REQ_CALL = 0; private String contact; private Menu menu; private RecyclerView recyclerView; private LinearLayoutManager layoutManager; private ConversationRecyclerViewAdapter adapter; private ActionMode actionMode; private boolean actionModeEnabled; private Database database; private Preferences preferences; static void sendMessage(Activity sourceActivity, long databaseId) { Context applicationContext = sourceActivity.getApplicationContext(); Database database = Database.getInstance(applicationContext); Preferences preferences = Preferences.getInstance(applicationContext); Message message = database.getMessageWithDatabaseId( preferences.getDid(), databaseId); SendMessageTask task = new SendMessageTask( sourceActivity.getApplicationContext(), message, sourceActivity); if (preferences.getEmail().equals("") || preferences.getPassword().equals("") || preferences.getDid().equals("")) { // Do not show an error; this method should never be called // unless the email, password and DID are set task.cleanup(false); return; } if (!Utils.isNetworkConnectionAvailable(applicationContext)) { Toast.makeText(applicationContext, applicationContext.getString( R.string.conversation_send_error_network), Toast.LENGTH_SHORT).show(); task.cleanup(false); return; } try { String voipUrl = "https://www.voip.ms/api/v1/rest.php?" + "api_username=" + URLEncoder.encode( preferences.getEmail(), "UTF-8") + "&" + "api_password=" + URLEncoder.encode( preferences.getPassword(), "UTF-8") + "&" + "method=sendSMS" + "&" + "did=" + URLEncoder.encode( preferences.getDid(), "UTF-8") + "&" + "dst=" + URLEncoder.encode( message.getContact(), "UTF-8") + "&" + "message=" + URLEncoder.encode( message.getText(), "UTF-8"); task.start(voipUrl); } catch (UnsupportedEncodingException ex) { // This should never happen since the encoding (UTF-8) is hardcoded throw new Error(ex); } } public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.conversation); database = Database.getInstance(getApplicationContext()); preferences = Preferences.getInstance(getApplicationContext()); contact = getIntent().getStringExtra(getString(R.string.conversation_extra_contact)); if ((contact.length() == 11) && (contact.charAt(0) == '1')) { // Remove the leading one from a North American phone number // (e.g. +1 (123) 555-4567) contact = contact.substring(1); } Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); ViewCompat.setElevation(toolbar, getResources() .getDimension(R.dimen.toolbar_elevation)); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { String contactName = Utils.getContactName(this, contact); if (contactName != null) { actionBar.setTitle(contactName); } else { actionBar.setTitle(Utils.getFormattedPhoneNumber(contact)); } actionBar.setHomeButtonEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); } layoutManager = new LinearLayoutManager(this); layoutManager.setOrientation(LinearLayoutManager.VERTICAL); layoutManager.setStackFromEnd(true); adapter = new ConversationRecyclerViewAdapter(this, layoutManager, contact); recyclerView = (RecyclerView) findViewById(R.id.list); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(adapter); actionMode = null; actionModeEnabled = false; final EditText messageText = (EditText) findViewById(R.id.message_edit_text); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { messageText.setOutlineProvider(new ViewOutlineProvider() { @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public void getOutline(View view, Outline outline) { outline.setRoundRect(0, 0, view.getWidth(), view.getHeight(), 15); } }); messageText.setClipToOutline(true); } messageText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // Do nothing. } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // Do nothing. } @Override public void afterTextChanged(Editable s) { ViewSwitcher viewSwitcher = (ViewSwitcher) findViewById(R.id.view_switcher); if (s.toString().equals("") && viewSwitcher.getDisplayedChild() == 1) { viewSwitcher.setDisplayedChild(0); } else if (viewSwitcher.getDisplayedChild() == 0) { viewSwitcher.setDisplayedChild(1); } } }); messageText.setOnFocusChangeListener((v, hasFocus) -> { if (hasFocus) { adapter.refresh(); } }); String intentMessageText = getIntent().getStringExtra( getString(R.string.conversation_extra_message_text)); if (intentMessageText != null) { messageText.setText(intentMessageText); } boolean intentFocus = getIntent() .getBooleanExtra( getString(R.string.conversation_extra_focus), false); if (intentFocus) { messageText.requestFocus(); } RelativeLayout messageSection = (RelativeLayout) findViewById(R.id.message_section); ViewCompat.setElevation(messageSection, 8); QuickContactBadge photo = (QuickContactBadge) findViewById(R.id.photo); Utils.applyCircularMask(photo); photo.assignContactFromPhone(preferences.getDid(), true); String photoUri = Utils.getContactPhotoUri(getApplicationContext(), preferences.getDid()); if (photoUri != null) { photo.setImageURI(Uri.parse(photoUri)); } else { photo.setImageToDefault(); } final ImageButton sendButton = (ImageButton) findViewById(R.id.send_button); Utils.applyCircularMask(sendButton); sendButton.setOnClickListener(v -> preSendMessage()); } @Override protected void onResume() { super.onResume(); ActivityMonitor.getInstance().setCurrentActivity(this); Integer id = Notifications.getInstance(getApplicationContext()) .getNotificationIds().get(contact); if (id != null) { NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService( Context.NOTIFICATION_SERVICE); notificationManager.cancel(id); } markConversationAsRead(); adapter.refresh(); } @Override protected void onPause() { super.onPause(); ActivityMonitor.getInstance().deleteReferenceToActivity(this); } @Override protected void onDestroy() { super.onDestroy(); ActivityMonitor.getInstance().deleteReferenceToActivity(this); } @Override public void onBackPressed() { if (actionModeEnabled) { actionMode.finish(); } else if (menu != null) { MenuItem searchItem = menu.findItem(R.id.search_button); SearchView searchView = (SearchView) searchItem.getActionView(); if (!searchView.isIconified()) { searchItem.collapseActionView(); } else { super.onBackPressed(); } } } @Override public boolean onCreateOptionsMenu(final Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.conversation, menu); this.menu = menu; if (!getPackageManager() .hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) { MenuItem phoneMenuItem = menu.findItem(R.id.call_button); phoneMenuItem.setVisible(false); } SearchView searchView = (SearchView) menu.findItem(R.id.search_button).getActionView(); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { adapter.refresh(newText); return true; } }); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { switch (item.getItemId()) { case R.id.call_button: return callButtonHandler(); case R.id.delete_button: Conversation conversation = database.getConversation(preferences.getDid(), contact); if (conversation.getMessages().length == 0) { NavUtils.navigateUpFromSameTask(this); } else { List<Long> databaseIds = new ArrayList<>(); for (int i = 0; i < adapter.getItemCount(); i++) { if (adapter.getItem(i).getDatabaseId() != null) { databaseIds .add(adapter.getItem(i).getDatabaseId()); } } Long[] databaseIdsArray = new Long[databaseIds.size()]; databaseIds.toArray(databaseIdsArray); deleteMessages(databaseIdsArray); } return true; } } return super.onOptionsItemSelected(item); } @Override public boolean onCreateActionMode(ActionMode actionMode, Menu menu) { MenuInflater inflater = actionMode.getMenuInflater(); inflater.inflate(R.menu.conversation_secondary, menu); return true; } @Override public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) { return false; } @Override public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) { if (menuItem.getItemId() == R.id.resend_button) { for (int i = 0; i < adapter.getItemCount(); i++) { if (adapter.isItemChecked(i)) { sendMessage(adapter.getItem(i).getDatabaseId()); break; } } actionMode.finish(); return true; } else if (menuItem.getItemId() == R.id.info_button) { Message message = null; for (int i = 0; i < adapter.getItemCount(); i++) { if (adapter.isItemChecked(i)) { message = adapter.getItem(i); break; } } if (message != null) { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()); String dialogText; if (message.getType() == Message.Type.INCOMING) { dialogText = (message.getVoipId() == null ? "" : (getString(R.string.conversation_info_id) + " " + message.getVoipId() + "\n")) + getString(R.string.conversation_info_to) + " " + Utils.getFormattedPhoneNumber(message.getDid()) + "\n" + getString(R.string.conversation_info_from) + " " + Utils.getFormattedPhoneNumber( message.getContact()) + "\n" + getString(R.string.conversation_info_date) + " " + dateFormat.format(message.getDate()); } else { dialogText = (message.getVoipId() == null ? "" : (getString(R.string.conversation_info_id) + " " + message.getVoipId() + "\n")) + getString(R.string.conversation_info_to) + " " + Utils.getFormattedPhoneNumber( message.getContact()) + "\n" + getString(R.string.conversation_info_from) + " " + Utils.getFormattedPhoneNumber(message.getDid()) + "\n" + getString(R.string.conversation_info_date) + " " + dateFormat.format(message.getDate()); } Utils.showAlertDialog(this, getString( R.string.conversation_info_title), dialogText, getString(R.string.ok), null, null, null); } actionMode.finish(); return true; } else if (menuItem.getItemId() == R.id.copy_button) { Message message = null; for (int i = 0; i < adapter.getItemCount(); i++) { if (adapter.isItemChecked(i)) { message = adapter.getItem(i); break; } } if (message != null) { ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("Text message", message.getText()); clipboard.setPrimaryClip(clip); } actionMode.finish(); return true; } else if (menuItem.getItemId() == R.id.share_button) { Message message = null; for (int i = 0; i < adapter.getItemCount(); i++) { if (adapter.isItemChecked(i)) { message = adapter.getItem(i); break; } } if (message != null) { Intent intent = new Intent(android.content.Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(android.content.Intent.EXTRA_TEXT, message.getText()); startActivity(Intent.createChooser(intent, null)); } actionMode.finish(); return true; } else if (menuItem.getItemId() == R.id.delete_button) { List<Long> databaseIds = new ArrayList<>(); for (int i = 0; i < adapter.getItemCount(); i++) { if (adapter.isItemChecked(i)) { databaseIds.add(adapter.getItem(i).getDatabaseId()); } } Long[] databaseIdsArray = new Long[databaseIds.size()]; databaseIds.toArray(databaseIdsArray); deleteMessages(databaseIdsArray); actionMode.finish(); return true; } else { return false; } } @Override public void onDestroyActionMode(ActionMode actionMode) { for (int i = 0; i < adapter.getItemCount(); i++) { adapter.setItemChecked(i, false); } actionModeEnabled = false; } @Override public void onClick(View view) { if (actionModeEnabled) { toggleItem(view); } else { Message message = adapter.getItem(recyclerView.getChildAdapterPosition(view)); if (!message.isDelivered() && !message.isDeliveryInProgress()) { preSendMessage(message.getDatabaseId()); } } } @Override public boolean onLongClick(View view) { toggleItem(view); return true; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == PERM_REQ_CALL) { for (int i = 0; i < permissions.length; i++) { if (permissions[i].equals(Manifest.permission.CALL_PHONE)) { if (grantResults[i] == PackageManager.PERMISSION_GRANTED) { callButtonHandler(); } else { Utils.showPermissionSnackbar( this, R.id.coordinator_layout, getString(R.string.conversation_perm_denied_call)); } } } } } private boolean callButtonHandler() { Intent intent = new Intent(Intent.ACTION_CALL); intent.setData(Uri.parse("tel:" + contact)); if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions( this, new String[] {Manifest.permission.CALL_PHONE}, PERM_REQ_CALL); } else { try { startActivity(intent); } catch (SecurityException ignored) { // Do nothing. } } return true; } private void updateButtons() { MenuItem resendAction = actionMode.getMenu().findItem(R.id.resend_button); MenuItem copyAction = actionMode.getMenu().findItem(R.id.copy_button); MenuItem shareAction = actionMode.getMenu().findItem(R.id.share_button); MenuItem infoAction = actionMode.getMenu().findItem(R.id.info_button); int count = adapter.getCheckedItemCount(); boolean resendVisible = false; if (count == 1) { for (int i = 0; i < adapter.getItemCount(); i++) { if (adapter.isItemChecked(i)) { if (!adapter.getItem(i).isDelivered() && !adapter.getItem(i) .isDeliveryInProgress()) { resendVisible = true; break; } } } } resendAction.setVisible(resendVisible); if (count >= 2) { infoAction.setVisible(false); copyAction.setVisible(false); shareAction.setVisible(false); } else { infoAction.setVisible(true); copyAction.setVisible(true); shareAction.setVisible(true); } } private void toggleItem(View view) { adapter.toggleItemChecked(recyclerView.getChildAdapterPosition(view)); if (adapter.getCheckedItemCount() == 0) { if (actionMode != null) { actionMode.finish(); } actionModeEnabled = false; return; } if (!actionModeEnabled) { actionMode = startSupportActionMode(this); actionModeEnabled = true; } updateButtons(); } private void deleteMessages(final Long[] databaseIds) { Utils.showAlertDialog(this, getString( R.string.conversation_delete_confirm_title), getString( R.string.conversation_delete_confirm_message), getString(R.string.delete), (dialog, which) -> { for (long databaseId : databaseIds) { Message message = database .getMessageWithDatabaseId( preferences.getDid(), databaseId); if (message.getVoipId() == null) { database .removeMessage(databaseId); } else { message.setDeleted(true); database.insertMessage(message); } adapter.refresh(); } }, getString(R.string.cancel), null); } private void preSendMessage() { EditText messageEditText = (EditText) findViewById(R.id.message_edit_text); String messageText = messageEditText.getText().toString(); while (true) { if (messageText.length() > 160) { long databaseId = database .insertMessage(new Message(preferences.getDid(), contact, messageText.substring(0, 160))); messageText = messageText.substring(160); adapter.refresh(); preSendMessage(databaseId); } else { long databaseId = database .insertMessage(new Message(preferences.getDid(), contact, messageText.substring(0, messageText .length()))); adapter.refresh(); preSendMessage(databaseId); break; } } messageEditText.setText(""); } private void preSendMessage(long databaseId) { Message message = database.getMessageWithDatabaseId(preferences.getDid(), databaseId); message.setDelivered(false); message.setDeliveryInProgress(true); database.insertMessage(message); adapter.refresh(); sendMessage(databaseId); } private void postSendMessage(boolean success, long databaseId) { if (success) { database.removeMessage(databaseId); database.synchronize(true, true, this); } else { Message message = database .getMessageWithDatabaseId(preferences.getDid(), databaseId); message.setDelivered(false); message.setDeliveryInProgress(false); database.insertMessage(message); adapter.refresh(); } if (adapter.getItemCount() > 0) { layoutManager.scrollToPosition(adapter.getItemCount() - 1); } } public void postUpdate() { markConversationAsRead(); adapter.refresh(); } public String getContact() { return contact; } private void markConversationAsRead() { for (Message message : database .getConversation(preferences.getDid(), contact).getMessages()) { message.setUnread(false); database.insertMessage(message); } } private void sendMessage(long databaseId) { sendMessage(this, databaseId); } public static class SendMessageTask { private final Context applicationContext; private final Message message; private final Activity sourceActivity; SendMessageTask(Context applicationContext, Message message, Activity sourceActivity) { this.applicationContext = applicationContext; this.message = message; this.sourceActivity = sourceActivity; } void start(String voipUrl) { new SendMessageAsyncTask().execute(voipUrl); } void cleanup(boolean success) { if (sourceActivity instanceof ConversationActivity) { ((ConversationActivity) sourceActivity) .postSendMessage(success, message.getDatabaseId()); } else if (sourceActivity instanceof ConversationQuickReplyActivity) { ((ConversationQuickReplyActivity) sourceActivity) .postSendMessage(success, message.getDatabaseId()); } } private class SendMessageAsyncTask extends AsyncTask<String, String, Boolean> { @Override protected Boolean doInBackground(String... params) { JSONObject resultJson; try { resultJson = Utils.getJson(params[0]); } catch (JSONException ex) { Log.w(TAG, Log.getStackTraceString(ex)); publishProgress(applicationContext.getString( R.string.conversation_send_error_api_parse)); return false; } catch (Exception ex) { Log.w(TAG, Log.getStackTraceString(ex)); publishProgress(applicationContext.getString( R.string.conversation_send_error_api_request)); return false; } String status = resultJson.optString("status"); if (status == null) { publishProgress(applicationContext.getString( R.string.conversation_send_error_api_parse)); return false; } if (!status.equals("success")) { publishProgress(applicationContext.getString( R.string.conversation_send_error_api_error) .replace("{error}", status)); return false; } return true; } @Override protected void onPostExecute(Boolean success) { cleanup(success); } /** * Shows a toast to the user. * * @param message The message to show. This must be a String * array with a single element containing the * message. */ @Override protected void onProgressUpdate(String... message) { Toast.makeText(applicationContext, message[0], Toast.LENGTH_SHORT).show(); } } } }
voipms-sms/src/main/java/net/kourlas/voipms_sms/activities/ConversationActivity.java
/* * VoIP.ms SMS * Copyright (C) 2015-2016 Michael Kourlas * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.kourlas.voipms_sms.activities; import android.Manifest; import android.annotation.TargetApi; import android.app.Activity; import android.app.NotificationManager; import android.content.*; import android.content.pm.PackageManager; import android.graphics.Outline; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.provider.Settings; import android.support.annotation.NonNull; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.Snackbar; import android.support.v4.app.ActivityCompat; import android.support.v4.app.NavUtils; import android.support.v4.content.ContextCompat; import android.support.v4.view.ViewCompat; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.view.ActionMode; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.*; import android.widget.*; import net.kourlas.voipms_sms.*; import net.kourlas.voipms_sms.adapters.ConversationRecyclerViewAdapter; import net.kourlas.voipms_sms.model.Conversation; import net.kourlas.voipms_sms.model.Message; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.Locale; public class ConversationActivity extends AppCompatActivity implements ActionMode.Callback, View.OnLongClickListener, View.OnClickListener, ActivityCompat.OnRequestPermissionsResultCallback { public static final String TAG = "ConversationActivity"; private static final int PERM_REQ_CALL = 0; private final ConversationActivity activity = this; private String contact; private Menu menu; private RecyclerView recyclerView; private LinearLayoutManager layoutManager; private ConversationRecyclerViewAdapter adapter; private ActionMode actionMode; private boolean actionModeEnabled; private Database database; private Preferences preferences; public static void sendMessage(Activity sourceActivity, long databaseId) { Context applicationContext = sourceActivity.getApplicationContext(); Database database = Database.getInstance(applicationContext); Preferences preferences = Preferences.getInstance(applicationContext); Message message = database.getMessageWithDatabaseId(preferences.getDid(), databaseId); SendMessageTask task = new SendMessageTask(sourceActivity.getApplicationContext(), message, sourceActivity); if (preferences.getEmail().equals("") || preferences.getPassword().equals("") || preferences.getDid().equals("")) { // Do not show an error; this method should never be called unless the email, password and DID are set task.cleanup(false); return; } if (!Utils.isNetworkConnectionAvailable(applicationContext)) { Toast.makeText(applicationContext, applicationContext.getString(R.string.conversation_send_error_network), Toast.LENGTH_SHORT).show(); task.cleanup(false); return; } try { String voipUrl = "https://www.voip.ms/api/v1/rest.php?" + "api_username=" + URLEncoder.encode(preferences.getEmail(), "UTF-8") + "&" + "api_password=" + URLEncoder.encode(preferences.getPassword(), "UTF-8") + "&" + "method=sendSMS" + "&" + "did=" + URLEncoder.encode(preferences.getDid(), "UTF-8") + "&" + "dst=" + URLEncoder.encode(message.getContact(), "UTF-8") + "&" + "message=" + URLEncoder.encode(message.getText(), "UTF-8"); task.start(voipUrl); } catch (UnsupportedEncodingException ex) { // This should never happen since the encoding (UTF-8) is hardcoded throw new Error(ex); } } public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.conversation); database = Database.getInstance(getApplicationContext()); preferences = Preferences.getInstance(getApplicationContext()); contact = getIntent().getStringExtra(getString(R.string.conversation_extra_contact)); // Remove the leading one from a North American phone number // (e.g. +1 (123) 555-4567) if ((contact.length() == 11) && (contact.charAt(0) == '1')) { contact = contact.substring(1); } Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); ViewCompat.setElevation(toolbar, getResources().getDimension(R.dimen.toolbar_elevation)); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { String contactName = Utils.getContactName(this, contact); if (contactName != null) { actionBar.setTitle(contactName); } else { actionBar.setTitle(Utils.getFormattedPhoneNumber(contact)); } actionBar.setHomeButtonEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); } layoutManager = new LinearLayoutManager(this); layoutManager.setOrientation(LinearLayoutManager.VERTICAL); layoutManager.setStackFromEnd(true); adapter = new ConversationRecyclerViewAdapter(this, layoutManager, contact); recyclerView = (RecyclerView) findViewById(R.id.list); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(adapter); actionMode = null; actionModeEnabled = false; final EditText messageText = (EditText) findViewById(R.id.message_edit_text); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { messageText.setOutlineProvider(new ViewOutlineProvider() { @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public void getOutline(View view, Outline outline) { outline.setRoundRect(0, 0, view.getWidth(), view.getHeight(), 15); } }); messageText.setClipToOutline(true); } messageText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // Do nothing. } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // Do nothing. } @Override public void afterTextChanged(Editable s) { ViewSwitcher viewSwitcher = (ViewSwitcher) findViewById(R.id.view_switcher); if (s.toString().equals("") && viewSwitcher.getDisplayedChild() == 1) { viewSwitcher.setDisplayedChild(0); } else if (viewSwitcher.getDisplayedChild() == 0) { viewSwitcher.setDisplayedChild(1); } } }); messageText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { adapter.refresh(); } } }); String intentMessageText = getIntent().getStringExtra(getString(R.string.conversation_extra_message_text)); if (intentMessageText != null) { messageText.setText(intentMessageText); } boolean intentFocus = getIntent().getBooleanExtra(getString(R.string.conversation_extra_focus), false); if (intentFocus) { messageText.requestFocus(); } RelativeLayout messageSection = (RelativeLayout) findViewById(R.id.message_section); ViewCompat.setElevation(messageSection, 8); QuickContactBadge photo = (QuickContactBadge) findViewById(R.id.photo); Utils.applyCircularMask(photo); photo.assignContactFromPhone(preferences.getDid(), true); String photoUri = Utils.getContactPhotoUri(getApplicationContext(), preferences.getDid()); if (photoUri != null) { photo.setImageURI(Uri.parse(photoUri)); } else { photo.setImageToDefault(); } final ImageButton sendButton = (ImageButton) findViewById(R.id.send_button); Utils.applyCircularMask(sendButton); sendButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { preSendMessage(); } }); } @Override protected void onResume() { super.onResume(); ActivityMonitor.getInstance().setCurrentActivity(this); Integer id = Notifications.getInstance(getApplicationContext()).getNotificationIds().get(contact); if (id != null) { NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.cancel(id); } markConversationAsRead(); adapter.refresh(); } @Override protected void onPause() { super.onPause(); ActivityMonitor.getInstance().deleteReferenceToActivity(this); } @Override protected void onDestroy() { super.onDestroy(); ActivityMonitor.getInstance().deleteReferenceToActivity(this); } @Override public void onBackPressed() { if (actionModeEnabled) { actionMode.finish(); } else if (menu != null) { MenuItem searchItem = menu.findItem(R.id.search_button); SearchView searchView = (SearchView) searchItem.getActionView(); if (!searchView.isIconified()) { searchItem.collapseActionView(); } else { super.onBackPressed(); } } } @Override public boolean onCreateOptionsMenu(final Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.conversation, menu); this.menu = menu; if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) { MenuItem phoneMenuItem = menu.findItem(R.id.call_button); phoneMenuItem.setVisible(false); } SearchView searchView = (SearchView) menu.findItem(R.id.search_button).getActionView(); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { adapter.refresh(newText); return true; } }); return super.onCreateOptionsMenu(menu); } public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == PERM_REQ_CALL) { for (int i = 0; i < permissions.length; i++) { if (permissions[i].equals(Manifest.permission.CALL_PHONE)) { if (grantResults[i] == PackageManager.PERMISSION_GRANTED) { callButtonHandler(); } else { Utils.showPermissionSnackbar( this, R.id.coordinator_layout, getString(R.string.conversation_perm_denied_call)); } } } } } private boolean callButtonHandler() { Intent intent = new Intent(Intent.ACTION_CALL); intent.setData(Uri.parse("tel:" + contact)); if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions( this, new String[] {Manifest.permission.CALL_PHONE}, PERM_REQ_CALL); } else { try { startActivity(intent); } catch (SecurityException ignored) { // Do nothing. } } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { switch (item.getItemId()) { case R.id.call_button: return callButtonHandler(); case R.id.delete_button: Conversation conversation = database.getConversation(preferences.getDid(), contact); if (conversation.getMessages().length == 0) { NavUtils.navigateUpFromSameTask(this); } else { List<Long> databaseIds = new ArrayList<>(); for (int i = 0; i < adapter.getItemCount(); i++) { if (adapter.getItem(i).getDatabaseId() != null) { databaseIds.add(adapter.getItem(i).getDatabaseId()); } } Long[] databaseIdsArray = new Long[databaseIds.size()]; databaseIds.toArray(databaseIdsArray); deleteMessages(databaseIdsArray); } return true; } } return super.onOptionsItemSelected(item); } @Override public boolean onCreateActionMode(ActionMode actionMode, Menu menu) { MenuInflater inflater = actionMode.getMenuInflater(); inflater.inflate(R.menu.conversation_secondary, menu); return true; } @Override public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) { return false; } @Override public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) { if (menuItem.getItemId() == R.id.resend_button) { for (int i = 0; i < adapter.getItemCount(); i++) { if (adapter.isItemChecked(i)) { sendMessage(adapter.getItem(i).getDatabaseId()); break; } } actionMode.finish(); return true; } else if (menuItem.getItemId() == R.id.info_button) { Message message = null; for (int i = 0; i < adapter.getItemCount(); i++) { if (adapter.isItemChecked(i)) { message = adapter.getItem(i); break; } } if (message != null) { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()); String dialogText; if (message.getType() == Message.Type.INCOMING) { dialogText = (message.getVoipId() == null ? "" : (getString(R.string.conversation_info_id) + " " + message.getVoipId() + "\n")) + getString(R.string.conversation_info_to) + " " + Utils.getFormattedPhoneNumber(message.getDid()) + "\n" + getString(R.string.conversation_info_from) + " " + Utils.getFormattedPhoneNumber(message.getContact()) + "\n" + getString(R.string.conversation_info_date) + " " + dateFormat.format(message.getDate()); } else { dialogText = (message.getVoipId() == null ? "" : (getString(R.string.conversation_info_id) + " " + message.getVoipId() + "\n")) + getString(R.string.conversation_info_to) + " " + Utils.getFormattedPhoneNumber(message.getContact()) + "\n" + getString(R.string.conversation_info_from) + " " + Utils.getFormattedPhoneNumber(message.getDid()) + "\n" + getString(R.string.conversation_info_date) + " " + dateFormat.format(message.getDate()); } Utils.showAlertDialog(this, getString(R.string.conversation_info_title), dialogText, getString(R.string.ok), null, null, null); } actionMode.finish(); return true; } else if (menuItem.getItemId() == R.id.copy_button) { Message message = null; for (int i = 0; i < adapter.getItemCount(); i++) { if (adapter.isItemChecked(i)) { message = adapter.getItem(i); break; } } if (message != null) { ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("Text message", message.getText()); clipboard.setPrimaryClip(clip); } actionMode.finish(); return true; } else if (menuItem.getItemId() == R.id.share_button) { Message message = null; for (int i = 0; i < adapter.getItemCount(); i++) { if (adapter.isItemChecked(i)) { message = adapter.getItem(i); break; } } if (message != null) { Intent intent = new Intent(android.content.Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(android.content.Intent.EXTRA_TEXT, message.getText()); startActivity(Intent.createChooser(intent, null)); } actionMode.finish(); return true; } else if (menuItem.getItemId() == R.id.delete_button) { List<Long> databaseIds = new ArrayList<>(); for (int i = 0; i < adapter.getItemCount(); i++) { if (adapter.isItemChecked(i)) { databaseIds.add(adapter.getItem(i).getDatabaseId()); } } Long[] databaseIdsArray = new Long[databaseIds.size()]; databaseIds.toArray(databaseIdsArray); deleteMessages(databaseIdsArray); actionMode.finish(); return true; } else { return false; } } @Override public void onDestroyActionMode(ActionMode actionMode) { for (int i = 0; i < adapter.getItemCount(); i++) { adapter.setItemChecked(i, false); } actionModeEnabled = false; } private void updateButtons() { MenuItem resendAction = actionMode.getMenu().findItem(R.id.resend_button); MenuItem copyAction = actionMode.getMenu().findItem(R.id.copy_button); MenuItem shareAction = actionMode.getMenu().findItem(R.id.share_button); MenuItem infoAction = actionMode.getMenu().findItem(R.id.info_button); int count = adapter.getCheckedItemCount(); boolean resendVisible = false; if (count == 1) { for (int i = 0; i < adapter.getItemCount(); i++) { if (adapter.isItemChecked(i)) { if (!adapter.getItem(i).isDelivered() && !adapter.getItem(i).isDeliveryInProgress()) { resendVisible = true; break; } } } } resendAction.setVisible(resendVisible); if (count >= 2) { infoAction.setVisible(false); copyAction.setVisible(false); shareAction.setVisible(false); } else { infoAction.setVisible(true); copyAction.setVisible(true); shareAction.setVisible(true); } } @Override public void onClick(View view) { if (actionModeEnabled) { toggleItem(view); } else { Message message = adapter.getItem(recyclerView.getChildAdapterPosition(view)); if (!message.isDelivered() && !message.isDeliveryInProgress()) { preSendMessage(message.getDatabaseId()); } } } @Override public boolean onLongClick(View view) { toggleItem(view); return true; } private void toggleItem(View view) { adapter.toggleItemChecked(recyclerView.getChildAdapterPosition(view)); if (adapter.getCheckedItemCount() == 0) { if (actionMode != null) { actionMode.finish(); } actionModeEnabled = false; return; } if (!actionModeEnabled) { actionMode = startSupportActionMode(this); actionModeEnabled = true; } updateButtons(); } public void deleteMessages(final Long[] databaseIds) { Utils.showAlertDialog(this, getString(R.string.conversation_delete_confirm_title), getString(R.string.conversation_delete_confirm_message), getString(R.string.delete), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { for (long databaseId : databaseIds) { Message message = database.getMessageWithDatabaseId(preferences.getDid(), databaseId); if (message.getVoipId() == null) { database.removeMessage(databaseId); } else { message.setDeleted(true); database.insertMessage(message); } adapter.refresh(); } } }, getString(R.string.cancel), null); } public void preSendMessage() { EditText messageEditText = (EditText) findViewById(R.id.message_edit_text); String messageText = messageEditText.getText().toString(); while (true) { if (messageText.length() > 160) { long databaseId = database.insertMessage(new Message(preferences.getDid(), contact, messageText.substring(0, 160))); messageText = messageText.substring(160); adapter.refresh(); preSendMessage(databaseId); } else { long databaseId = database.insertMessage(new Message(preferences.getDid(), contact, messageText.substring(0, messageText.length()))); adapter.refresh(); preSendMessage(databaseId); break; } } messageEditText.setText(""); } public void preSendMessage(long databaseId) { Message message = database.getMessageWithDatabaseId(preferences.getDid(), databaseId); message.setDelivered(false); message.setDeliveryInProgress(true); database.insertMessage(message); adapter.refresh(); sendMessage(databaseId); } public void postSendMessage(boolean success, long databaseId) { if (success) { database.removeMessage(databaseId); database.synchronize(true, true, this); } else { Message message = database.getMessageWithDatabaseId(preferences.getDid(), databaseId); message.setDelivered(false); message.setDeliveryInProgress(false); database.insertMessage(message); adapter.refresh(); } if (adapter.getItemCount() > 0) { layoutManager.scrollToPosition(adapter.getItemCount() - 1); } } public void postUpdate() { markConversationAsRead(); adapter.refresh(); } public String getContact() { return contact; } public void markConversationAsRead() { for (Message message : database.getConversation(preferences.getDid(), contact).getMessages()) { message.setUnread(false); database.insertMessage(message); } } public void sendMessage(long databaseId) { sendMessage(this, databaseId); } public static class SendMessageTask { private final Context applicationContext; private final Message message; private final Activity sourceActivity; public SendMessageTask(Context applicationContext, Message message, Activity sourceActivity) { this.applicationContext = applicationContext; this.message = message; this.sourceActivity = sourceActivity; } public void start(String voipUrl) { new SendMessageAsyncTask().execute(voipUrl); } public void cleanup(boolean success) { if (sourceActivity instanceof ConversationActivity) { ((ConversationActivity) sourceActivity).postSendMessage(success, message.getDatabaseId()); } else if (sourceActivity instanceof ConversationQuickReplyActivity) { ((ConversationQuickReplyActivity) sourceActivity).postSendMessage(success, message.getDatabaseId()); } } private class SendMessageAsyncTask extends AsyncTask<String, String, Boolean> { @Override protected Boolean doInBackground(String... params) { JSONObject resultJson; try { resultJson = Utils.getJson(params[0]); } catch (JSONException ex) { Log.w(TAG, Log.getStackTraceString(ex)); publishProgress(applicationContext.getString(R.string.conversation_send_error_api_parse)); return false; } catch (Exception ex) { Log.w(TAG, Log.getStackTraceString(ex)); publishProgress(applicationContext.getString(R.string.conversation_send_error_api_request)); return false; } String status = resultJson.optString("status"); if (status == null) { publishProgress(applicationContext.getString(R.string.conversation_send_error_api_parse)); return false; } if (!status.equals("success")) { publishProgress(applicationContext.getString( R.string.conversation_send_error_api_error).replace("{error}", status)); return false; } return true; } @Override protected void onPostExecute(Boolean success) { cleanup(success); } /** * Shows a toast to the user. * * @param message The message to show. This must be a String array with a single element containing the * message. */ @Override protected void onProgressUpdate(String... message) { Toast.makeText(applicationContext, message[0], Toast.LENGTH_SHORT).show(); } } } }
Cleanup ConversationActivity
voipms-sms/src/main/java/net/kourlas/voipms_sms/activities/ConversationActivity.java
Cleanup ConversationActivity
<ide><path>oipms-sms/src/main/java/net/kourlas/voipms_sms/activities/ConversationActivity.java <ide> import android.annotation.TargetApi; <ide> import android.app.Activity; <ide> import android.app.NotificationManager; <del>import android.content.*; <add>import android.content.ClipData; <add>import android.content.ClipboardManager; <add>import android.content.Context; <add>import android.content.Intent; <ide> import android.content.pm.PackageManager; <ide> import android.graphics.Outline; <ide> import android.net.Uri; <ide> import android.os.AsyncTask; <ide> import android.os.Build; <ide> import android.os.Bundle; <del>import android.provider.Settings; <ide> import android.support.annotation.NonNull; <del>import android.support.design.widget.CoordinatorLayout; <del>import android.support.design.widget.Snackbar; <ide> import android.support.v4.app.ActivityCompat; <ide> import android.support.v4.app.NavUtils; <ide> import android.support.v4.content.ContextCompat; <ide> import java.util.Locale; <ide> <ide> public class ConversationActivity <del> extends AppCompatActivity <del> implements ActionMode.Callback, View.OnLongClickListener, <del> View.OnClickListener, <del> ActivityCompat.OnRequestPermissionsResultCallback <add> extends AppCompatActivity <add> implements ActionMode.Callback, View.OnLongClickListener, <add> View.OnClickListener, <add> ActivityCompat.OnRequestPermissionsResultCallback <ide> { <del> public static final String TAG = "ConversationActivity"; <add> private static final String TAG = "ConversationActivity"; <ide> private static final int PERM_REQ_CALL = 0; <ide> <del> private final ConversationActivity activity = this; <del> <ide> private String contact; <del> <ide> private Menu menu; <ide> <ide> private RecyclerView recyclerView; <ide> private Database database; <ide> private Preferences preferences; <ide> <del> public static void sendMessage(Activity sourceActivity, long databaseId) { <add> static void sendMessage(Activity sourceActivity, long databaseId) { <ide> Context applicationContext = sourceActivity.getApplicationContext(); <ide> Database database = Database.getInstance(applicationContext); <ide> Preferences preferences = Preferences.getInstance(applicationContext); <ide> <del> Message message = database.getMessageWithDatabaseId(preferences.getDid(), databaseId); <del> SendMessageTask task = new SendMessageTask(sourceActivity.getApplicationContext(), message, sourceActivity); <del> <del> if (preferences.getEmail().equals("") || preferences.getPassword().equals("") || <del> preferences.getDid().equals("")) { <del> // Do not show an error; this method should never be called unless the email, password and DID are set <add> Message message = database.getMessageWithDatabaseId( <add> preferences.getDid(), databaseId); <add> SendMessageTask task = new SendMessageTask( <add> sourceActivity.getApplicationContext(), message, <add> sourceActivity); <add> <add> if (preferences.getEmail().equals("") <add> || preferences.getPassword().equals("") <add> || preferences.getDid().equals("")) <add> { <add> // Do not show an error; this method should never be called <add> // unless the email, password and DID are set <ide> task.cleanup(false); <ide> return; <ide> } <ide> <ide> if (!Utils.isNetworkConnectionAvailable(applicationContext)) { <del> Toast.makeText(applicationContext, applicationContext.getString(R.string.conversation_send_error_network), <del> Toast.LENGTH_SHORT).show(); <add> Toast.makeText(applicationContext, <add> applicationContext.getString( <add> R.string.conversation_send_error_network), <add> Toast.LENGTH_SHORT).show(); <ide> task.cleanup(false); <ide> return; <ide> } <ide> <ide> try { <del> String voipUrl = "https://www.voip.ms/api/v1/rest.php?" + <del> "api_username=" + URLEncoder.encode(preferences.getEmail(), "UTF-8") + "&" + <del> "api_password=" + URLEncoder.encode(preferences.getPassword(), "UTF-8") + "&" + <del> "method=sendSMS" + "&" + <del> "did=" + URLEncoder.encode(preferences.getDid(), "UTF-8") + "&" + <del> "dst=" + URLEncoder.encode(message.getContact(), "UTF-8") + "&" + <del> "message=" + URLEncoder.encode(message.getText(), "UTF-8"); <add> String voipUrl = "https://www.voip.ms/api/v1/rest.php?" <add> + "api_username=" + URLEncoder.encode( <add> preferences.getEmail(), "UTF-8") + "&" <add> + "api_password=" + URLEncoder.encode( <add> preferences.getPassword(), "UTF-8") + "&" <add> + "method=sendSMS" + "&" <add> + "did=" + URLEncoder.encode( <add> preferences.getDid(), "UTF-8") + "&" <add> + "dst=" + URLEncoder.encode( <add> message.getContact(), "UTF-8") + "&" <add> + "message=" + URLEncoder.encode( <add> message.getText(), "UTF-8"); <ide> task.start(voipUrl); <ide> } catch (UnsupportedEncodingException ex) { <ide> // This should never happen since the encoding (UTF-8) is hardcoded <ide> preferences = Preferences.getInstance(getApplicationContext()); <ide> <ide> contact = getIntent().getStringExtra(getString(R.string.conversation_extra_contact)); <del> // Remove the leading one from a North American phone number <del> // (e.g. +1 (123) 555-4567) <ide> if ((contact.length() == 11) && (contact.charAt(0) == '1')) { <add> // Remove the leading one from a North American phone number <add> // (e.g. +1 (123) 555-4567) <ide> contact = contact.substring(1); <ide> } <ide> <ide> Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); <del> ViewCompat.setElevation(toolbar, getResources().getDimension(R.dimen.toolbar_elevation)); <add> ViewCompat.setElevation(toolbar, getResources() <add> .getDimension(R.dimen.toolbar_elevation)); <ide> setSupportActionBar(toolbar); <ide> ActionBar actionBar = getSupportActionBar(); <ide> if (actionBar != null) { <ide> String contactName = Utils.getContactName(this, contact); <ide> if (contactName != null) { <ide> actionBar.setTitle(contactName); <del> } <del> else { <add> } else { <ide> actionBar.setTitle(Utils.getFormattedPhoneNumber(contact)); <ide> } <ide> actionBar.setHomeButtonEnabled(true); <ide> layoutManager = new LinearLayoutManager(this); <ide> layoutManager.setOrientation(LinearLayoutManager.VERTICAL); <ide> layoutManager.setStackFromEnd(true); <del> adapter = new ConversationRecyclerViewAdapter(this, layoutManager, contact); <add> adapter = new ConversationRecyclerViewAdapter(this, layoutManager, <add> contact); <ide> recyclerView = (RecyclerView) findViewById(R.id.list); <ide> recyclerView.setHasFixedSize(true); <ide> recyclerView.setLayoutManager(layoutManager); <ide> actionMode = null; <ide> actionModeEnabled = false; <ide> <del> final EditText messageText = (EditText) findViewById(R.id.message_edit_text); <add> final EditText messageText = <add> (EditText) findViewById(R.id.message_edit_text); <ide> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { <ide> messageText.setOutlineProvider(new ViewOutlineProvider() { <ide> @TargetApi(Build.VERSION_CODES.LOLLIPOP) <ide> @Override <ide> public void getOutline(View view, Outline outline) { <del> outline.setRoundRect(0, 0, view.getWidth(), view.getHeight(), 15); <add> outline.setRoundRect(0, 0, view.getWidth(), <add> view.getHeight(), 15); <ide> } <ide> }); <ide> messageText.setClipToOutline(true); <ide> } <ide> messageText.addTextChangedListener(new TextWatcher() { <ide> @Override <del> public void beforeTextChanged(CharSequence s, int start, int count, int after) { <add> public void beforeTextChanged(CharSequence s, int start, int count, <add> int after) <add> { <ide> // Do nothing. <ide> } <ide> <ide> @Override <del> public void onTextChanged(CharSequence s, int start, int before, int count) { <add> public void onTextChanged(CharSequence s, int start, int before, <add> int count) <add> { <ide> // Do nothing. <ide> } <ide> <ide> @Override <ide> public void afterTextChanged(Editable s) { <del> ViewSwitcher viewSwitcher = (ViewSwitcher) findViewById(R.id.view_switcher); <del> if (s.toString().equals("") && viewSwitcher.getDisplayedChild() == 1) { <add> ViewSwitcher viewSwitcher = <add> (ViewSwitcher) findViewById(R.id.view_switcher); <add> if (s.toString().equals("") <add> && viewSwitcher.getDisplayedChild() == 1) <add> { <ide> viewSwitcher.setDisplayedChild(0); <del> } <del> else if (viewSwitcher.getDisplayedChild() == 0) { <add> } else if (viewSwitcher.getDisplayedChild() == 0) { <ide> viewSwitcher.setDisplayedChild(1); <ide> } <ide> } <ide> }); <del> messageText.setOnFocusChangeListener(new View.OnFocusChangeListener() { <del> @Override <del> public void onFocusChange(View v, boolean hasFocus) { <del> if (hasFocus) { <del> adapter.refresh(); <del> } <add> messageText.setOnFocusChangeListener((v, hasFocus) -> { <add> if (hasFocus) { <add> adapter.refresh(); <ide> } <ide> }); <del> String intentMessageText = getIntent().getStringExtra(getString(R.string.conversation_extra_message_text)); <add> String intentMessageText = getIntent().getStringExtra( <add> getString(R.string.conversation_extra_message_text)); <ide> if (intentMessageText != null) { <ide> messageText.setText(intentMessageText); <ide> } <del> boolean intentFocus = getIntent().getBooleanExtra(getString(R.string.conversation_extra_focus), false); <add> boolean intentFocus = getIntent() .getBooleanExtra( <add> getString(R.string.conversation_extra_focus), false); <ide> if (intentFocus) { <ide> messageText.requestFocus(); <ide> } <ide> <del> RelativeLayout messageSection = (RelativeLayout) findViewById(R.id.message_section); <add> RelativeLayout messageSection = <add> (RelativeLayout) findViewById(R.id.message_section); <ide> ViewCompat.setElevation(messageSection, 8); <ide> <ide> QuickContactBadge photo = (QuickContactBadge) findViewById(R.id.photo); <ide> Utils.applyCircularMask(photo); <ide> photo.assignContactFromPhone(preferences.getDid(), true); <del> String photoUri = Utils.getContactPhotoUri(getApplicationContext(), preferences.getDid()); <add> String photoUri = Utils.getContactPhotoUri(getApplicationContext(), <add> preferences.getDid()); <ide> if (photoUri != null) { <ide> photo.setImageURI(Uri.parse(photoUri)); <del> } <del> else { <add> } else { <ide> photo.setImageToDefault(); <ide> } <ide> <del> final ImageButton sendButton = (ImageButton) findViewById(R.id.send_button); <add> final ImageButton sendButton = <add> (ImageButton) findViewById(R.id.send_button); <ide> Utils.applyCircularMask(sendButton); <del> sendButton.setOnClickListener(new View.OnClickListener() { <del> @Override <del> public void onClick(View v) { <del> preSendMessage(); <del> } <del> }); <add> sendButton.setOnClickListener(v -> preSendMessage()); <ide> } <ide> <ide> @Override <ide> super.onResume(); <ide> ActivityMonitor.getInstance().setCurrentActivity(this); <ide> <del> Integer id = Notifications.getInstance(getApplicationContext()).getNotificationIds().get(contact); <add> Integer id = Notifications.getInstance(getApplicationContext()) <add> .getNotificationIds().get(contact); <ide> if (id != null) { <ide> NotificationManager notificationManager = (NotificationManager) <del> getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE); <add> getApplicationContext().getSystemService( <add> Context.NOTIFICATION_SERVICE); <ide> notificationManager.cancel(id); <ide> } <ide> <ide> public void onBackPressed() { <ide> if (actionModeEnabled) { <ide> actionMode.finish(); <del> } <del> else if (menu != null) { <add> } else if (menu != null) { <ide> MenuItem searchItem = menu.findItem(R.id.search_button); <ide> SearchView searchView = (SearchView) searchItem.getActionView(); <ide> if (!searchView.isIconified()) { <ide> searchItem.collapseActionView(); <del> } <del> else { <add> } else { <ide> super.onBackPressed(); <ide> } <ide> } <ide> inflater.inflate(R.menu.conversation, menu); <ide> this.menu = menu; <ide> <del> if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) { <add> if (!getPackageManager() <add> .hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) <add> { <ide> MenuItem phoneMenuItem = menu.findItem(R.id.call_button); <ide> phoneMenuItem.setVisible(false); <ide> } <ide> <del> SearchView searchView = (SearchView) menu.findItem(R.id.search_button).getActionView(); <add> SearchView searchView = <add> (SearchView) menu.findItem(R.id.search_button).getActionView(); <ide> searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { <ide> @Override <ide> public boolean onQueryTextSubmit(String query) { <ide> return super.onCreateOptionsMenu(menu); <ide> } <ide> <add> @Override <add> public boolean onOptionsItemSelected(MenuItem item) { <add> ActionBar actionBar = getSupportActionBar(); <add> if (actionBar != null) { <add> switch (item.getItemId()) { <add> case R.id.call_button: <add> return callButtonHandler(); <add> case R.id.delete_button: <add> Conversation conversation = <add> database.getConversation(preferences.getDid(), contact); <add> if (conversation.getMessages().length == 0) { <add> NavUtils.navigateUpFromSameTask(this); <add> } else { <add> List<Long> databaseIds = new ArrayList<>(); <add> for (int i = 0; i < adapter.getItemCount(); i++) { <add> if (adapter.getItem(i).getDatabaseId() != null) { <add> databaseIds <add> .add(adapter.getItem(i).getDatabaseId()); <add> } <add> } <add> <add> Long[] databaseIdsArray = new Long[databaseIds.size()]; <add> databaseIds.toArray(databaseIdsArray); <add> deleteMessages(databaseIdsArray); <add> } <add> return true; <add> } <add> } <add> <add> return super.onOptionsItemSelected(item); <add> } <add> <add> @Override <add> public boolean onCreateActionMode(ActionMode actionMode, Menu menu) { <add> MenuInflater inflater = actionMode.getMenuInflater(); <add> inflater.inflate(R.menu.conversation_secondary, menu); <add> return true; <add> } <add> <add> @Override <add> public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) { <add> return false; <add> } <add> <add> @Override <add> public boolean onActionItemClicked(ActionMode actionMode, <add> MenuItem menuItem) <add> { <add> if (menuItem.getItemId() == R.id.resend_button) { <add> for (int i = 0; i < adapter.getItemCount(); i++) { <add> if (adapter.isItemChecked(i)) { <add> sendMessage(adapter.getItem(i).getDatabaseId()); <add> break; <add> } <add> } <add> <add> actionMode.finish(); <add> return true; <add> } else if (menuItem.getItemId() == R.id.info_button) { <add> Message message = null; <add> for (int i = 0; i < adapter.getItemCount(); i++) { <add> if (adapter.isItemChecked(i)) { <add> message = adapter.getItem(i); <add> break; <add> } <add> } <add> <add> if (message != null) { <add> DateFormat dateFormat = <add> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", <add> Locale.getDefault()); <add> String dialogText; <add> if (message.getType() == Message.Type.INCOMING) { <add> dialogText = (message.getVoipId() == null ? "" : <add> (getString(R.string.conversation_info_id) + <add> " " + message.getVoipId() + "\n")) <add> + getString(R.string.conversation_info_to) <add> + " " + <add> Utils.getFormattedPhoneNumber(message.getDid()) <add> + "\n" + <add> getString(R.string.conversation_info_from) <add> + " " + <add> Utils.getFormattedPhoneNumber( <add> message.getContact()) + "\n" + <add> getString(R.string.conversation_info_date) <add> + " " + dateFormat.format(message.getDate()); <add> } else { <add> dialogText = (message.getVoipId() == null ? "" : <add> (getString(R.string.conversation_info_id) + <add> " " + message.getVoipId() + "\n")) <add> + getString(R.string.conversation_info_to) <add> + " " + <add> Utils.getFormattedPhoneNumber( <add> message.getContact()) + "\n" + <add> getString(R.string.conversation_info_from) <add> + " " + <add> Utils.getFormattedPhoneNumber(message.getDid()) <add> + "\n" + <add> getString(R.string.conversation_info_date) <add> + " " + dateFormat.format(message.getDate()); <add> } <add> Utils.showAlertDialog(this, getString( <add> R.string.conversation_info_title), dialogText, <add> getString(R.string.ok), null, null, null); <add> } <add> <add> actionMode.finish(); <add> return true; <add> } else if (menuItem.getItemId() == R.id.copy_button) { <add> Message message = null; <add> for (int i = 0; i < adapter.getItemCount(); i++) { <add> if (adapter.isItemChecked(i)) { <add> message = adapter.getItem(i); <add> break; <add> } <add> } <add> <add> if (message != null) { <add> ClipboardManager clipboard = <add> (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); <add> ClipData clip = <add> ClipData.newPlainText("Text message", message.getText()); <add> clipboard.setPrimaryClip(clip); <add> } <add> <add> actionMode.finish(); <add> return true; <add> } else if (menuItem.getItemId() == R.id.share_button) { <add> Message message = null; <add> for (int i = 0; i < adapter.getItemCount(); i++) { <add> if (adapter.isItemChecked(i)) { <add> message = adapter.getItem(i); <add> break; <add> } <add> } <add> <add> if (message != null) { <add> Intent intent = new Intent(android.content.Intent.ACTION_SEND); <add> intent.setType("text/plain"); <add> intent.putExtra(android.content.Intent.EXTRA_TEXT, <add> message.getText()); <add> startActivity(Intent.createChooser(intent, null)); <add> } <add> <add> actionMode.finish(); <add> return true; <add> } else if (menuItem.getItemId() == R.id.delete_button) { <add> List<Long> databaseIds = new ArrayList<>(); <add> for (int i = 0; i < adapter.getItemCount(); i++) { <add> if (adapter.isItemChecked(i)) { <add> databaseIds.add(adapter.getItem(i).getDatabaseId()); <add> } <add> } <add> <add> Long[] databaseIdsArray = new Long[databaseIds.size()]; <add> databaseIds.toArray(databaseIdsArray); <add> deleteMessages(databaseIdsArray); <add> <add> actionMode.finish(); <add> return true; <add> } else { <add> return false; <add> } <add> } <add> <add> @Override <add> public void onDestroyActionMode(ActionMode actionMode) { <add> for (int i = 0; i < adapter.getItemCount(); i++) { <add> adapter.setItemChecked(i, false); <add> } <add> actionModeEnabled = false; <add> } <add> <add> @Override <add> public void onClick(View view) { <add> if (actionModeEnabled) { <add> toggleItem(view); <add> } else { <add> Message message = <add> adapter.getItem(recyclerView.getChildAdapterPosition(view)); <add> if (!message.isDelivered() && !message.isDeliveryInProgress()) { <add> preSendMessage(message.getDatabaseId()); <add> } <add> } <add> } <add> <add> @Override <add> public boolean onLongClick(View view) { <add> toggleItem(view); <add> return true; <add> } <add> <add> @Override <ide> public void onRequestPermissionsResult(int requestCode, <ide> @NonNull String permissions[], <ide> @NonNull int[] grantResults) <ide> return true; <ide> } <ide> <del> @Override <del> public boolean onOptionsItemSelected(MenuItem item) { <del> ActionBar actionBar = getSupportActionBar(); <del> if (actionBar != null) { <del> switch (item.getItemId()) { <del> case R.id.call_button: <del> return callButtonHandler(); <del> case R.id.delete_button: <del> Conversation conversation = database.getConversation(preferences.getDid(), contact); <del> if (conversation.getMessages().length == 0) { <del> NavUtils.navigateUpFromSameTask(this); <del> } <del> else { <del> List<Long> databaseIds = new ArrayList<>(); <del> for (int i = 0; i < adapter.getItemCount(); i++) { <del> if (adapter.getItem(i).getDatabaseId() != null) { <del> databaseIds.add(adapter.getItem(i).getDatabaseId()); <del> } <del> } <del> <del> Long[] databaseIdsArray = new Long[databaseIds.size()]; <del> databaseIds.toArray(databaseIdsArray); <del> deleteMessages(databaseIdsArray); <del> } <del> return true; <del> } <del> } <del> <del> return super.onOptionsItemSelected(item); <del> } <del> <del> @Override <del> public boolean onCreateActionMode(ActionMode actionMode, Menu menu) { <del> MenuInflater inflater = actionMode.getMenuInflater(); <del> inflater.inflate(R.menu.conversation_secondary, menu); <del> return true; <del> } <del> <del> @Override <del> public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) { <del> return false; <del> } <del> <del> @Override <del> public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) { <del> if (menuItem.getItemId() == R.id.resend_button) { <del> for (int i = 0; i < adapter.getItemCount(); i++) { <del> if (adapter.isItemChecked(i)) { <del> sendMessage(adapter.getItem(i).getDatabaseId()); <del> break; <del> } <del> } <del> <del> actionMode.finish(); <del> return true; <del> } <del> else if (menuItem.getItemId() == R.id.info_button) { <del> Message message = null; <del> for (int i = 0; i < adapter.getItemCount(); i++) { <del> if (adapter.isItemChecked(i)) { <del> message = adapter.getItem(i); <del> break; <del> } <del> } <del> <del> if (message != null) { <del> DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()); <del> String dialogText; <del> if (message.getType() == Message.Type.INCOMING) { <del> dialogText = (message.getVoipId() == null ? "" : (getString(R.string.conversation_info_id) + <del> " " + message.getVoipId() + "\n")) + getString(R.string.conversation_info_to) + " " + <del> Utils.getFormattedPhoneNumber(message.getDid()) + "\n" + <del> getString(R.string.conversation_info_from) + " " + <del> Utils.getFormattedPhoneNumber(message.getContact()) + "\n" + <del> getString(R.string.conversation_info_date) + " " + dateFormat.format(message.getDate()); <del> } <del> else { <del> dialogText = (message.getVoipId() == null ? "" : (getString(R.string.conversation_info_id) + <del> " " + message.getVoipId() + "\n")) + getString(R.string.conversation_info_to) + " " + <del> Utils.getFormattedPhoneNumber(message.getContact()) + "\n" + <del> getString(R.string.conversation_info_from) + " " + <del> Utils.getFormattedPhoneNumber(message.getDid()) + "\n" + <del> getString(R.string.conversation_info_date) + " " + dateFormat.format(message.getDate()); <del> } <del> Utils.showAlertDialog(this, getString(R.string.conversation_info_title), dialogText, <del> getString(R.string.ok), null, null, null); <del> } <del> <del> actionMode.finish(); <del> return true; <del> } <del> else if (menuItem.getItemId() == R.id.copy_button) { <del> Message message = null; <del> for (int i = 0; i < adapter.getItemCount(); i++) { <del> if (adapter.isItemChecked(i)) { <del> message = adapter.getItem(i); <del> break; <del> } <del> } <del> <del> if (message != null) { <del> ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); <del> ClipData clip = ClipData.newPlainText("Text message", message.getText()); <del> clipboard.setPrimaryClip(clip); <del> } <del> <del> actionMode.finish(); <del> return true; <del> } <del> else if (menuItem.getItemId() == R.id.share_button) { <del> Message message = null; <del> for (int i = 0; i < adapter.getItemCount(); i++) { <del> if (adapter.isItemChecked(i)) { <del> message = adapter.getItem(i); <del> break; <del> } <del> } <del> <del> if (message != null) { <del> Intent intent = new Intent(android.content.Intent.ACTION_SEND); <del> intent.setType("text/plain"); <del> intent.putExtra(android.content.Intent.EXTRA_TEXT, message.getText()); <del> startActivity(Intent.createChooser(intent, null)); <del> } <del> <del> actionMode.finish(); <del> return true; <del> } <del> else if (menuItem.getItemId() == R.id.delete_button) { <del> List<Long> databaseIds = new ArrayList<>(); <del> for (int i = 0; i < adapter.getItemCount(); i++) { <del> if (adapter.isItemChecked(i)) { <del> databaseIds.add(adapter.getItem(i).getDatabaseId()); <del> } <del> } <del> <del> Long[] databaseIdsArray = new Long[databaseIds.size()]; <del> databaseIds.toArray(databaseIdsArray); <del> deleteMessages(databaseIdsArray); <del> <del> actionMode.finish(); <del> return true; <del> } <del> else { <del> return false; <del> } <del> } <del> <del> @Override <del> public void onDestroyActionMode(ActionMode actionMode) { <del> for (int i = 0; i < adapter.getItemCount(); i++) { <del> adapter.setItemChecked(i, false); <del> } <del> actionModeEnabled = false; <del> } <del> <ide> private void updateButtons() { <del> MenuItem resendAction = actionMode.getMenu().findItem(R.id.resend_button); <add> MenuItem resendAction = <add> actionMode.getMenu().findItem(R.id.resend_button); <ide> MenuItem copyAction = actionMode.getMenu().findItem(R.id.copy_button); <ide> MenuItem shareAction = actionMode.getMenu().findItem(R.id.share_button); <ide> MenuItem infoAction = actionMode.getMenu().findItem(R.id.info_button); <ide> if (count == 1) { <ide> for (int i = 0; i < adapter.getItemCount(); i++) { <ide> if (adapter.isItemChecked(i)) { <del> if (!adapter.getItem(i).isDelivered() && !adapter.getItem(i).isDeliveryInProgress()) { <add> if (!adapter.getItem(i).isDelivered() && !adapter.getItem(i) <add> .isDeliveryInProgress()) <add> { <ide> resendVisible = true; <ide> break; <ide> } <ide> infoAction.setVisible(false); <ide> copyAction.setVisible(false); <ide> shareAction.setVisible(false); <del> } <del> else { <add> } else { <ide> infoAction.setVisible(true); <ide> copyAction.setVisible(true); <ide> shareAction.setVisible(true); <ide> } <ide> } <ide> <del> @Override <del> public void onClick(View view) { <del> if (actionModeEnabled) { <del> toggleItem(view); <del> } <del> else { <del> Message message = adapter.getItem(recyclerView.getChildAdapterPosition(view)); <del> if (!message.isDelivered() && !message.isDeliveryInProgress()) { <del> preSendMessage(message.getDatabaseId()); <del> } <del> } <del> } <del> <del> @Override <del> public boolean onLongClick(View view) { <del> toggleItem(view); <del> return true; <del> } <del> <ide> private void toggleItem(View view) { <ide> adapter.toggleItemChecked(recyclerView.getChildAdapterPosition(view)); <ide> <ide> updateButtons(); <ide> } <ide> <del> public void deleteMessages(final Long[] databaseIds) { <del> Utils.showAlertDialog(this, getString(R.string.conversation_delete_confirm_title), <del> getString(R.string.conversation_delete_confirm_message), <del> getString(R.string.delete), new DialogInterface.OnClickListener() { <del> @Override <del> public void onClick(DialogInterface dialog, int which) { <del> for (long databaseId : databaseIds) { <del> Message message = database.getMessageWithDatabaseId(preferences.getDid(), databaseId); <del> if (message.getVoipId() == null) { <del> database.removeMessage(databaseId); <del> } <del> else { <del> message.setDeleted(true); <del> database.insertMessage(message); <del> } <del> adapter.refresh(); <del> } <del> } <del> }, <del> getString(R.string.cancel), null); <del> } <del> <del> public void preSendMessage() { <del> EditText messageEditText = (EditText) findViewById(R.id.message_edit_text); <add> private void deleteMessages(final Long[] databaseIds) { <add> Utils.showAlertDialog(this, getString( <add> R.string.conversation_delete_confirm_title), <add> getString( <add> R.string.conversation_delete_confirm_message), <add> getString(R.string.delete), <add> (dialog, which) -> { <add> for (long databaseId : databaseIds) { <add> Message message = database <add> .getMessageWithDatabaseId( <add> preferences.getDid(), <add> databaseId); <add> if (message.getVoipId() == null) { <add> database <add> .removeMessage(databaseId); <add> } else { <add> message.setDeleted(true); <add> database.insertMessage(message); <add> } <add> adapter.refresh(); <add> } <add> }, <add> getString(R.string.cancel), null); <add> } <add> <add> private void preSendMessage() { <add> EditText messageEditText = <add> (EditText) findViewById(R.id.message_edit_text); <ide> String messageText = messageEditText.getText().toString(); <ide> while (true) { <ide> if (messageText.length() > 160) { <del> long databaseId = database.insertMessage(new Message(preferences.getDid(), contact, <del> messageText.substring(0, 160))); <add> long databaseId = database <add> .insertMessage(new Message(preferences.getDid(), contact, <add> messageText.substring(0, 160))); <ide> messageText = messageText.substring(160); <ide> adapter.refresh(); <ide> preSendMessage(databaseId); <del> } <del> else { <del> long databaseId = database.insertMessage(new Message(preferences.getDid(), contact, <del> messageText.substring(0, messageText.length()))); <add> } else { <add> long databaseId = database <add> .insertMessage(new Message(preferences.getDid(), contact, <add> messageText.substring(0, <add> messageText <add> .length()))); <ide> adapter.refresh(); <ide> preSendMessage(databaseId); <ide> break; <ide> messageEditText.setText(""); <ide> } <ide> <del> public void preSendMessage(long databaseId) { <del> Message message = database.getMessageWithDatabaseId(preferences.getDid(), databaseId); <add> private void preSendMessage(long databaseId) { <add> Message message = <add> database.getMessageWithDatabaseId(preferences.getDid(), databaseId); <ide> message.setDelivered(false); <ide> message.setDeliveryInProgress(true); <ide> database.insertMessage(message); <ide> sendMessage(databaseId); <ide> } <ide> <del> public void postSendMessage(boolean success, long databaseId) { <add> private void postSendMessage(boolean success, long databaseId) { <ide> if (success) { <ide> database.removeMessage(databaseId); <ide> database.synchronize(true, true, this); <del> } <del> else { <del> Message message = database.getMessageWithDatabaseId(preferences.getDid(), databaseId); <add> } else { <add> Message message = database <add> .getMessageWithDatabaseId(preferences.getDid(), databaseId); <ide> message.setDelivered(false); <ide> message.setDeliveryInProgress(false); <ide> database.insertMessage(message); <ide> return contact; <ide> } <ide> <del> public void markConversationAsRead() { <del> for (Message message : database.getConversation(preferences.getDid(), contact).getMessages()) { <add> private void markConversationAsRead() { <add> for (Message message : database <add> .getConversation(preferences.getDid(), contact).getMessages()) { <ide> message.setUnread(false); <ide> database.insertMessage(message); <ide> } <ide> } <ide> <del> public void sendMessage(long databaseId) { <add> private void sendMessage(long databaseId) { <ide> sendMessage(this, databaseId); <ide> } <ide> <ide> private final Message message; <ide> private final Activity sourceActivity; <ide> <del> public SendMessageTask(Context applicationContext, Message message, Activity sourceActivity) { <add> SendMessageTask(Context applicationContext, Message message, <add> Activity sourceActivity) <add> { <ide> this.applicationContext = applicationContext; <ide> <ide> this.message = message; <ide> this.sourceActivity = sourceActivity; <ide> } <ide> <del> public void start(String voipUrl) { <add> void start(String voipUrl) { <ide> new SendMessageAsyncTask().execute(voipUrl); <ide> } <ide> <del> public void cleanup(boolean success) { <add> void cleanup(boolean success) { <ide> if (sourceActivity instanceof ConversationActivity) { <del> ((ConversationActivity) sourceActivity).postSendMessage(success, message.getDatabaseId()); <del> } <del> else if (sourceActivity instanceof ConversationQuickReplyActivity) { <del> ((ConversationQuickReplyActivity) sourceActivity).postSendMessage(success, message.getDatabaseId()); <del> } <del> } <del> <del> private class SendMessageAsyncTask extends AsyncTask<String, String, Boolean> { <add> ((ConversationActivity) sourceActivity) <add> .postSendMessage(success, message.getDatabaseId()); <add> } else if (sourceActivity instanceof <add> ConversationQuickReplyActivity) { <add> ((ConversationQuickReplyActivity) sourceActivity) <add> .postSendMessage(success, message.getDatabaseId()); <add> } <add> } <add> <add> private class SendMessageAsyncTask <add> extends AsyncTask<String, String, Boolean> <add> { <ide> @Override <ide> protected Boolean doInBackground(String... params) { <ide> JSONObject resultJson; <ide> resultJson = Utils.getJson(params[0]); <ide> } catch (JSONException ex) { <ide> Log.w(TAG, Log.getStackTraceString(ex)); <del> publishProgress(applicationContext.getString(R.string.conversation_send_error_api_parse)); <add> publishProgress(applicationContext.getString( <add> R.string.conversation_send_error_api_parse)); <ide> return false; <ide> } catch (Exception ex) { <ide> Log.w(TAG, Log.getStackTraceString(ex)); <del> publishProgress(applicationContext.getString(R.string.conversation_send_error_api_request)); <add> publishProgress(applicationContext.getString( <add> R.string.conversation_send_error_api_request)); <ide> return false; <ide> } <ide> <ide> String status = resultJson.optString("status"); <ide> if (status == null) { <del> publishProgress(applicationContext.getString(R.string.conversation_send_error_api_parse)); <add> publishProgress(applicationContext.getString( <add> R.string.conversation_send_error_api_parse)); <ide> return false; <ide> } <ide> if (!status.equals("success")) { <ide> publishProgress(applicationContext.getString( <del> R.string.conversation_send_error_api_error).replace("{error}", status)); <add> R.string.conversation_send_error_api_error) <add> .replace("{error}", <add> status)); <ide> return false; <ide> } <ide> <ide> /** <ide> * Shows a toast to the user. <ide> * <del> * @param message The message to show. This must be a String array with a single element containing the <add> * @param message The message to show. This must be a String <add> * array with a single element containing the <ide> * message. <ide> */ <ide> @Override <ide> protected void onProgressUpdate(String... message) { <del> Toast.makeText(applicationContext, message[0], Toast.LENGTH_SHORT).show(); <add> Toast.makeText(applicationContext, message[0], <add> Toast.LENGTH_SHORT).show(); <ide> } <ide> } <ide> }
Java
mit
8259c51415d6bec2eb8a67b5ac02ce16a88955d5
0
CS2103JAN2017-T16-B2/main,CS2103JAN2017-T16-B2/main
package seedu.address.logic; import java.util.logging.Logger; import javafx.collections.ObservableList; import seedu.address.commons.core.ComponentManager; import seedu.address.commons.core.LogsCenter; import seedu.address.logic.commands.Command; import seedu.address.logic.commands.CommandResult; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.logic.parser.DateTimeParser; import seedu.address.logic.parser.DateTimeParserManager; import seedu.address.logic.parser.Parser; import seedu.address.model.Model; import seedu.address.model.task.ReadOnlyTask; import seedu.address.storage.Storage; /** * The main LogicManager of the app. */ public class LogicManager extends ComponentManager implements Logic { private final Logger logger = LogsCenter.getLogger(LogicManager.class); private final Model model; private final Parser parser; private final DateTimeParser dtParser; public static UndoManager undoCommandHistory = new UndoManager(); public LogicManager(Model model, Storage storage) { this.model = model; this.parser = new Parser(); dtParser = new DateTimeParserManager(); } @Override public CommandResult execute(String commandText) throws CommandException { logger.info("----------------[USER COMMAND][" + commandText + "]"); Command command = parser.parseCommand(commandText); command.setData(model); command.setDateParser(dtParser); return command.execute(); } @Override public ObservableList<ReadOnlyTask> getFilteredTaskList() { return model.getFilteredTaskList(); } }
src/main/java/seedu/address/logic/LogicManager.java
package seedu.address.logic; import java.util.logging.Logger; import javafx.collections.ObservableList; import seedu.address.commons.core.ComponentManager; import seedu.address.commons.core.LogsCenter; import seedu.address.logic.commands.Command; import seedu.address.logic.commands.CommandResult; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.logic.parser.Parser; import seedu.address.model.Model; import seedu.address.model.task.ReadOnlyTask; import seedu.address.storage.Storage; /** * The main LogicManager of the app. */ public class LogicManager extends ComponentManager implements Logic { private final Logger logger = LogsCenter.getLogger(LogicManager.class); private final Model model; private final Parser parser; public LogicManager(Model model, Storage storage) { this.model = model; this.parser = new Parser(); } @Override public CommandResult execute(String commandText) throws CommandException { logger.info("----------------[USER COMMAND][" + commandText + "]"); Command command = parser.parseCommand(commandText); command.setData(model); return command.execute(); } @Override public ObservableList<ReadOnlyTask> getFilteredTaskList() { return model.getFilteredTaskList(); } }
Add undo manager initialisation in Logic Manager class
src/main/java/seedu/address/logic/LogicManager.java
Add undo manager initialisation in Logic Manager class
<ide><path>rc/main/java/seedu/address/logic/LogicManager.java <ide> import seedu.address.logic.commands.Command; <ide> import seedu.address.logic.commands.CommandResult; <ide> import seedu.address.logic.commands.exceptions.CommandException; <add>import seedu.address.logic.parser.DateTimeParser; <add>import seedu.address.logic.parser.DateTimeParserManager; <ide> import seedu.address.logic.parser.Parser; <ide> import seedu.address.model.Model; <ide> import seedu.address.model.task.ReadOnlyTask; <ide> <ide> private final Model model; <ide> private final Parser parser; <add> private final DateTimeParser dtParser; <add> public static UndoManager undoCommandHistory = new UndoManager(); <ide> <ide> public LogicManager(Model model, Storage storage) { <ide> this.model = model; <ide> this.parser = new Parser(); <add> dtParser = new DateTimeParserManager(); <ide> } <ide> <ide> @Override <ide> logger.info("----------------[USER COMMAND][" + commandText + "]"); <ide> Command command = parser.parseCommand(commandText); <ide> command.setData(model); <add> command.setDateParser(dtParser); <ide> return command.execute(); <ide> } <ide>
JavaScript
mit
b9bf26316931fa4f06c3fe908fa282848ebbef93
0
phase/flower-site,flower/flower.github.io,phase/flower-site,flower/flower.github.io
jQuery.githubUser = function(username, callback) { jQuery.getJSON('https://api.github.com/users/'+username+'/repos?callback=?',callback) } jQuery.fn.loadRepositories = function(username) { this.html("<span>Querying GitHub for " + username +"'s repositories...</span>"); var target = this; $.githubUser(username, function(data) { var repos = data.data; // JSON Parsing sortByName(repos); var list = $('<dl/>'); target.empty().append(list); $(repos).each(function() { if (this.name != (username.toLowerCase()+'.github.com')) { list.append('<dt><a href="'+ (this.homepage?this.homepage:this.html_url) +'">' + this.name + '</a> <em>'+(this.language?('('+this.language+')'):'')+'</em></dt>'); list.append('<dd>' + this.description +'</dd>'); } }); }); function sortByName(repos) { repos.sort(function(a,b) { return a.name - b.name; }); } };
js/github.js
jQuery.githubUser = function(username, callback){ jQuery.getJSON("http://github.com/api/v1/json/" + username + "?callback=?", callback); } jQuery.fn.loadRepositories = function(username) { this.html("<span>Querying GitHub for repositories...</span>"); var target = this; $.githubUser(username, function(data) { var repos = data.user.repositories; sortByNumberOfWatchers(repos); var list = $('<dl/>'); target.empty().append(list); $(repos).each(function() { list.append('<dt><a href="'+ this.url +'">' + this.name + '</a></dt>'); list.append('<dd>' + this.description + '</dd>'); }); }); function sortByNumberOfWatchers(repos) { repos.sort(function(a,b) { return b.watchers - a.watchers; }); } };
Use newer version
js/github.js
Use newer version
<ide><path>s/github.js <del>jQuery.githubUser = function(username, callback){ <del> jQuery.getJSON("http://github.com/api/v1/json/" + username + "?callback=?", callback); <add>jQuery.githubUser = function(username, callback) { <add> jQuery.getJSON('https://api.github.com/users/'+username+'/repos?callback=?',callback) <ide> } <ide> <ide> jQuery.fn.loadRepositories = function(username) { <del> this.html("<span>Querying GitHub for repositories...</span>"); <del> <del> var target = this; <del> $.githubUser(username, function(data) { <del> var repos = data.user.repositories; <del> sortByNumberOfWatchers(repos); <del> <del> var list = $('<dl/>'); <del> target.empty().append(list); <del> $(repos).each(function() { <del> list.append('<dt><a href="'+ this.url +'">' + this.name + '</a></dt>'); <del> list.append('<dd>' + this.description + '</dd>'); <del> }); <del> }); <del> <del> function sortByNumberOfWatchers(repos) { <del> repos.sort(function(a,b) { <del> return b.watchers - a.watchers; <del> }); <del> } <add> this.html("<span>Querying GitHub for " + username +"'s repositories...</span>"); <add> <add> var target = this; <add> $.githubUser(username, function(data) { <add> var repos = data.data; // JSON Parsing <add> sortByName(repos); <add> <add> var list = $('<dl/>'); <add> target.empty().append(list); <add> $(repos).each(function() { <add> if (this.name != (username.toLowerCase()+'.github.com')) { <add> list.append('<dt><a href="'+ (this.homepage?this.homepage:this.html_url) +'">' + this.name + '</a> <em>'+(this.language?('('+this.language+')'):'')+'</em></dt>'); <add> list.append('<dd>' + this.description +'</dd>'); <add> } <add> }); <add> }); <add> <add> function sortByName(repos) { <add> repos.sort(function(a,b) { <add> return a.name - b.name; <add> }); <add> } <ide> };
JavaScript
mit
3a84aa9577bf3d381bbeb9197d03be143ef4618d
0
EdgeCaseBerg/GreenUp,EdgeCaseBerg/green-web,EdgeCaseBerg/green-web,EdgeCaseBerg/GreenUp,EdgeCaseBerg/GreenUp,EdgeCaseBerg/GreenUp,EdgeCaseBerg/GreenUp,EdgeCaseBerg/GreenUp,EdgeCaseBerg/GreenUp,EdgeCaseBerg/green-web,EdgeCaseBerg/green-web
var map, pointarray, heatmap, pickupMarker, markerFlag; var markerType = -1; var markerEvent; var HELP_TRASH = 1; var TRASH_DROP = 2; var COMMENT_LOC = 3; var MOUSEDOWN_TIME; var MOUSEUP_TIME; var heatmapData = [ {location: new google.maps.LatLng(37.782, -122.447), weight: 0.5}, {location: new google.maps.LatLng(37.782, -122.445), weight: 1}, {location: new google.maps.LatLng(37.782, -122.443), weight: 2}, {location: new google.maps.LatLng(37.782, -122.441), weight: 3}, {location: new google.maps.LatLng(37.782, -122.439), weight: 2}, {location: new google.maps.LatLng(37.782, -122.437), weight: 1}, {location: new google.maps.LatLng(37.782, -122.435), weight: 0.5}, {location: new google.maps.LatLng(37.785, -122.447), weight: 3}, {location: new google.maps.LatLng(37.785, -122.445), weight: 2}, {location: new google.maps.LatLng(37.785, -122.443), weight: 1}, {location: new google.maps.LatLng(37.785, -122.441), weight: 0.5}, {location: new google.maps.LatLng(37.785, -122.439), weight: 1}, {location: new google.maps.LatLng(37.785, -122.437), weight: 2}, {location: new google.maps.LatLng(37.785, -122.435), weight: 3} ]; function initialize() { var mapOptions = { zoom: 13, center: new google.maps.LatLng(37.774546, -122.433523), mapTypeId: google.maps.MapTypeId.SATELLITE }; map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions); var pointArray = new google.maps.MVCArray(heatmapData); heatmap = new google.maps.visualization.HeatmapLayer({ data: pointArray, dissipating: true, radius: 5 }); heatmap.setMap(null); google.maps.event.addListener(map, 'mousedown', markerSelectDown); google.maps.event.addListener(map, 'mouseup', markerSelectUp); } // end initialize function initIcons(){ var pickupIcon = "img/icons/greenCircle.png"; pickupMarker = new google.maps.Marker({ position: new google.maps.LatLng(37.785, -122.435), map: map, icon: pickupIcon }); pickupMarker.setVisible(false); markerFlag = false; } function toggleHeatmap() { heatmap.setMap(heatmap.getMap() ? null : map); } function toggleIcons(){ if(markerFlag){ pickupMarker.setVisible(false); markerFlag = false; }else{ pickupMarker.setVisible(true); markerFlag = true; }; } // add an icon for a pickup function addPickupMarker(){ var marker = new google.maps.Marker({ position: markerEvent.latLng, map: map, icon: "img/icons/greenCircle.png" }); } // add an icon for a Comment location function addCommentMarker(){ var marker = new google.maps.Marker({ position: markerEvent.latLng, map: map, icon: "img/icons/blueCircle.png" }); // var marker = new MarkerWithLabel({ // position: markerEvent.latLng, // draggable: true, // raiseOnDrag: true, // map: map, // labelContent: "$425K", // labelAnchor: new google.maps.Point(22, 0), // labelClass: "labels", // the CSS class for the label // labelStyle: {opacity: 0.75} // }); } // add an icon to indicate where trash was found function addTrashMarker(){ var marker = new google.maps.Marker({ position: markerEvent.latLng, map: map, icon: "img/icons/redCircle.png" }); } function markerSelectUp(event){ markerEvent = event; MOUSEUP_TIME = new Date().getTime() / 1000; if((MOUSEUP_TIME - MOUSEDOWN_TIME) < 0.3){ // alert((MOUSEUP_TIME - MOUSEDOWN_TIME)); $('#markerTypeDialog').toggle(); MOUSEDOWN_TIME =0; MOUSEDOWN_TIME =0; }else{ MOUSEDOWN_TIME =0; MOUSEDOWN_TIME =0; } } function markerSelectDown(event){ markerEvent = event; MOUSEDOWN_TIME = new Date().getTime() / 1000; // if((MOUSEUP_TIME - MOUSEDOWN_TIME) < 2){ // $('#markerTypeDialog').toggle(); // MOUSEDOWN_TIME =0; // MOUSEDOWN_TIME =0; // }else{ // MOUSEDOWN_TIME =0; // MOUSEDOWN_TIME =0; // } } function changeRadius() { heatmap.setOptions({radius: heatmap.get('radius') ? null : 20}); } function changeOpacity() { heatmap.setOptions({opacity: heatmap.get('opacity') ? null : 0.2}); } google.maps.event.addDomListener(window, 'load', initialize); google.maps.event.addDomListener(window, 'load', initIcons); $(document).ready(function(){ // loadScript(); $('#toggleHeat').click(function(){ toggleHeatmap(); }); $('#toggleIcons').click(function(){ toggleIcons(); }); $('#selectPickup').click(function(){ $('#markerTypeDialog').toggle(); addPickupMarker(); // alert("hello"); }); $('#selectComment').click(function(){ $('#markerTypeDialog').toggle(); addCommentMarker(); // alert("hello"); }); $('#selectTrash').click(function(){ $('#markerTypeDialog').toggle(); addTrashMarker(); // alert("hello"); }); $('#pr1').click(function(){ $('#container').removeClass("panel1Center"); $('#container').removeClass("panel3Center"); $('#container').addClass("panel2Center"); }); $('#prr1').click(function(){ $('#container').removeClass("panel1Center"); $('#container').removeClass("panel2Center"); $('#container').addClass("panel3Center"); }); $('#pr2').click(function(){ $('#container').removeClass("panel1Center"); $('#container').removeClass("panel2Center"); $('#container').addClass("panel3Center"); }); $('#pl2').click(function(){ $('#container').removeClass("panel3Center"); $('#container').removeClass("panel2Center"); $('#container').addClass("panel1Center"); }); $('#pl3').click(function(){ $('#container').removeClass("panel3Center"); $('#container').removeClass("panel1Center"); $('#container').addClass("panel2Center"); }); $('#pll3').click(function(){ $('#container').removeClass("panel3Center"); $('#container').removeClass("panel2Center"); $('#container').addClass("panel1Center"); }); // $('#map-canvas').mousedown(function(){ // MOUSEDOWN_TIME = new Date().getTime() / 1000; // }); // $('#map-canvas').mouseup(function(){ // MOUSEUP_TIME = new Date().getTime() / 1000; // }); });
client/js/mapsUI.js
var map, pointarray, heatmap, pickupMarker, markerFlag; var markerType = -1; var markerEvent; var HELP_TRASH = 1; var TRASH_DROP = 2; var COMMENT_LOC = 3; var MOUSEDOWN_TIME; var MOUSEUP_TIME; var heatmapData = [ {location: new google.maps.LatLng(37.782, -122.447), weight: 0.5}, {location: new google.maps.LatLng(37.782, -122.445), weight: 1}, {location: new google.maps.LatLng(37.782, -122.443), weight: 2}, {location: new google.maps.LatLng(37.782, -122.441), weight: 3}, {location: new google.maps.LatLng(37.782, -122.439), weight: 2}, {location: new google.maps.LatLng(37.782, -122.437), weight: 1}, {location: new google.maps.LatLng(37.782, -122.435), weight: 0.5}, {location: new google.maps.LatLng(37.785, -122.447), weight: 3}, {location: new google.maps.LatLng(37.785, -122.445), weight: 2}, {location: new google.maps.LatLng(37.785, -122.443), weight: 1}, {location: new google.maps.LatLng(37.785, -122.441), weight: 0.5}, {location: new google.maps.LatLng(37.785, -122.439), weight: 1}, {location: new google.maps.LatLng(37.785, -122.437), weight: 2}, {location: new google.maps.LatLng(37.785, -122.435), weight: 3} ]; function initialize() { var mapOptions = { zoom: 13, center: new google.maps.LatLng(37.774546, -122.433523), mapTypeId: google.maps.MapTypeId.SATELLITE }; map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions); var pointArray = new google.maps.MVCArray(heatmapData); heatmap = new google.maps.visualization.HeatmapLayer({ data: pointArray, dissipating: true, radius: 5 }); heatmap.setMap(map); google.maps.event.addListener(map, 'mousedown', markerSelectDown); google.maps.event.addListener(map, 'mouseup', markerSelectUp); } // end initialize function initIcons(){ var pickupIcon = "img/icons/greenCircle.png"; pickupMarker = new google.maps.Marker({ position: new google.maps.LatLng(37.785, -122.435), map: map, icon: pickupIcon }); markerFlag = true; } function toggleHeatmap() { heatmap.setMap(heatmap.getMap() ? null : map); } function toggleIcons(){ if(markerFlag){ pickupMarker.setVisible(false); markerFlag = false; }else{ pickupMarker.setVisible(true); markerFlag = true; }; } // add an icon for a pickup function addPickupMarker(){ var marker = new google.maps.Marker({ position: markerEvent.latLng, map: map, icon: "img/icons/greenCircle.png" }); } // add an icon for a Comment location function addCommentMarker(){ var marker = new google.maps.Marker({ position: markerEvent.latLng, map: map, icon: "img/icons/blueCircle.png" }); // var marker = new MarkerWithLabel({ // position: markerEvent.latLng, // draggable: true, // raiseOnDrag: true, // map: map, // labelContent: "$425K", // labelAnchor: new google.maps.Point(22, 0), // labelClass: "labels", // the CSS class for the label // labelStyle: {opacity: 0.75} // }); } // add an icon to indicate where trash was found function addTrashMarker(){ var marker = new google.maps.Marker({ position: markerEvent.latLng, map: map, icon: "img/icons/redCircle.png" }); } function markerSelectUp(event){ markerEvent = event; MOUSEUP_TIME = new Date().getTime() / 1000; if((MOUSEUP_TIME - MOUSEDOWN_TIME) < 0.3){ // alert((MOUSEUP_TIME - MOUSEDOWN_TIME)); $('#markerTypeDialog').toggle(); MOUSEDOWN_TIME =0; MOUSEDOWN_TIME =0; }else{ MOUSEDOWN_TIME =0; MOUSEDOWN_TIME =0; } } function markerSelectDown(event){ markerEvent = event; MOUSEDOWN_TIME = new Date().getTime() / 1000; // if((MOUSEUP_TIME - MOUSEDOWN_TIME) < 2){ // $('#markerTypeDialog').toggle(); // MOUSEDOWN_TIME =0; // MOUSEDOWN_TIME =0; // }else{ // MOUSEDOWN_TIME =0; // MOUSEDOWN_TIME =0; // } } function changeRadius() { heatmap.setOptions({radius: heatmap.get('radius') ? null : 20}); } function changeOpacity() { heatmap.setOptions({opacity: heatmap.get('opacity') ? null : 0.2}); } google.maps.event.addDomListener(window, 'load', initialize); google.maps.event.addDomListener(window, 'load', initIcons); $(document).ready(function(){ // loadScript(); $('#toggleHeat').click(function(){ toggleHeatmap(); }); $('#toggleIcons').click(function(){ toggleIcons(); }); $('#selectPickup').click(function(){ $('#markerTypeDialog').toggle(); addPickupMarker(); // alert("hello"); }); $('#selectComment').click(function(){ $('#markerTypeDialog').toggle(); addCommentMarker(); // alert("hello"); }); $('#selectTrash').click(function(){ $('#markerTypeDialog').toggle(); addTrashMarker(); // alert("hello"); }); $('#pr1').click(function(){ $('#container').removeClass("panel1Center"); $('#container').removeClass("panel3Center"); $('#container').addClass("panel2Center"); }); $('#prr1').click(function(){ $('#container').removeClass("panel1Center"); $('#container').removeClass("panel2Center"); $('#container').addClass("panel3Center"); }); $('#pr2').click(function(){ $('#container').removeClass("panel1Center"); $('#container').removeClass("panel2Center"); $('#container').addClass("panel3Center"); }); $('#pl2').click(function(){ $('#container').removeClass("panel3Center"); $('#container').removeClass("panel2Center"); $('#container').addClass("panel1Center"); }); $('#pl3').click(function(){ $('#container').removeClass("panel3Center"); $('#container').removeClass("panel1Center"); $('#container').addClass("panel2Center"); }); $('#pll3').click(function(){ $('#container').removeClass("panel3Center"); $('#container').removeClass("panel2Center"); $('#container').addClass("panel1Center"); }); // $('#map-canvas').mousedown(function(){ // MOUSEDOWN_TIME = new Date().getTime() / 1000; // }); // $('#map-canvas').mouseup(function(){ // MOUSEUP_TIME = new Date().getTime() / 1000; // }); });
Set the layers to be disabled by default to match the checkbox state
client/js/mapsUI.js
Set the layers to be disabled by default to match the checkbox state
<ide><path>lient/js/mapsUI.js <ide> radius: 5 <ide> }); <ide> <del> heatmap.setMap(map); <add> heatmap.setMap(null); <ide> <ide> google.maps.event.addListener(map, 'mousedown', markerSelectDown); <ide> google.maps.event.addListener(map, 'mouseup', markerSelectUp); <ide> map: map, <ide> icon: pickupIcon <ide> }); <del> markerFlag = true; <add> pickupMarker.setVisible(false); <add> markerFlag = false; <ide> } <ide> <ide> function toggleHeatmap() {
Java
artistic-2.0
5fcb4d930aff5412f3202338cc3af46649fd24d4
0
aliyun/aliyun-emapreduce-sdk,uncleGen/aliyun-emapreduce-sdk,aliyun/aliyun-spark-sdk,aliyun/aliyun-emapreduce-sdk,aliyun/aliyun-emapreduce-sdk
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aliyun.fs.oss.utils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import java.io.File; public class Utils { private static Log LOG = LogFactory.getLog(Utils.class); public static synchronized File getTempBufferDir(Configuration conf) { String[] dataDirs = conf.get("dfs.datanode.data.dir", "file:///tmp/").split(","); double minUsage = Double.MAX_VALUE; int n = 0; for(int i=0; i<dataDirs.length; i++) { File file = new File(new Path(dataDirs[i]).toUri().getPath()); double diskUsage = 1.0 * (file.getTotalSpace() - file.getFreeSpace()) / file.getTotalSpace(); if (diskUsage < minUsage) { n = i; minUsage = diskUsage; } i++; } String diskPath = new Path(dataDirs[n]).toUri().getPath(); LOG.debug("choose oss buffer dir: "+diskPath+", and this disk usage is: "+minUsage); return new File(diskPath, "data/oss"); } public static void main(String[] args) { Configuration conf = new Configuration(); conf.set("dfs.datanode.data.dir", "file:///mnt/disk1,file:///mnt/disk4"); System.out.println(Utils.getTempBufferDir(conf)); } }
core/src/main/java/com/aliyun/fs/oss/utils/Utils.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aliyun.fs.oss.utils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import java.io.File; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Random; public class Utils { private static int idx = Math.abs(new Random(System.currentTimeMillis()).nextInt()); public static synchronized File getTempBufferDir(Configuration conf) { boolean confirmExists = conf.getBoolean("fs.oss.buffer.dirs.exists", false); String[] bufferDirs = conf.get("fs.oss.buffer.dirs", "file:///tmp/").split(","); List<String> bufferPaths = new ArrayList<String>(); for(int i = 0; i < bufferDirs.length; i++) { URI uri = new Path(bufferDirs[i]).toUri(); String path = uri.getPath(); Boolean fileExists = new File(path).exists(); if (confirmExists && !fileExists) { continue; } bufferPaths.add(path); } if (bufferPaths.size() == 0) { bufferPaths.add("/tmp/"); } idx = (idx + 1) % bufferPaths.size(); return new File(bufferPaths.get(Math.abs(idx)), "oss"); } public static void main(String[] args) { Configuration conf = new Configuration(); conf.set("dfs.datanode.data.dir", "file:///mnt/disk1,file:///mnt/disk4"); System.out.println(Utils.getTempBufferDir(conf)); } }
fix disk usage imbalance
core/src/main/java/com/aliyun/fs/oss/utils/Utils.java
fix disk usage imbalance
<ide><path>ore/src/main/java/com/aliyun/fs/oss/utils/Utils.java <ide> */ <ide> package com.aliyun.fs.oss.utils; <ide> <add>import org.apache.commons.logging.Log; <add>import org.apache.commons.logging.LogFactory; <ide> import org.apache.hadoop.conf.Configuration; <ide> import org.apache.hadoop.fs.Path; <ide> <ide> import java.io.File; <del>import java.net.URI; <del>import java.util.ArrayList; <del>import java.util.List; <del>import java.util.Random; <ide> <ide> public class Utils { <del> private static int idx = Math.abs(new Random(System.currentTimeMillis()).nextInt()); <add> private static Log LOG = LogFactory.getLog(Utils.class); <ide> public static synchronized File getTempBufferDir(Configuration conf) { <del> boolean confirmExists = conf.getBoolean("fs.oss.buffer.dirs.exists", false); <del> String[] bufferDirs = conf.get("fs.oss.buffer.dirs", "file:///tmp/").split(","); <del> List<String> bufferPaths = new ArrayList<String>(); <del> for(int i = 0; i < bufferDirs.length; i++) { <del> URI uri = new Path(bufferDirs[i]).toUri(); <del> String path = uri.getPath(); <del> Boolean fileExists = new File(path).exists(); <del> if (confirmExists && !fileExists) { <del> continue; <add> String[] dataDirs = conf.get("dfs.datanode.data.dir", "file:///tmp/").split(","); <add> double minUsage = Double.MAX_VALUE; <add> int n = 0; <add> for(int i=0; i<dataDirs.length; i++) { <add> File file = new File(new Path(dataDirs[i]).toUri().getPath()); <add> double diskUsage = 1.0 * (file.getTotalSpace() - file.getFreeSpace()) / file.getTotalSpace(); <add> if (diskUsage < minUsage) { <add> n = i; <add> minUsage = diskUsage; <ide> } <del> bufferPaths.add(path); <add> i++; <ide> } <del> if (bufferPaths.size() == 0) { <del> bufferPaths.add("/tmp/"); <del> } <del> idx = (idx + 1) % bufferPaths.size(); <del> return new File(bufferPaths.get(Math.abs(idx)), "oss"); <add> <add> String diskPath = new Path(dataDirs[n]).toUri().getPath(); <add> LOG.debug("choose oss buffer dir: "+diskPath+", and this disk usage is: "+minUsage); <add> return new File(diskPath, "data/oss"); <ide> } <ide> <ide> public static void main(String[] args) {
Java
mit
error: pathspec 'Java/Queue.java' did not match any file(s) known to git
0c9b813f7ea1bb76149a5be7e1fee3fff2931339
1
saru95/DSA,saru95/DSA,saru95/DSA,saru95/DSA,saru95/DSA
import java.util.ArrayList; public class Queue <T>{ private ArrayList <T> queue; Queue() { queue = new ArrayList<T>(); } public void enqueue(T element){ queue.add(element); } public boolean isEmpty(){ return (queue.size() < 1); } public T dequeue() throws EmptyQueueException{ if(isEmpty()){ throw new EmptyQueueException("Dequeue"); } else{ T element = queue.get(0); queue.remove(0); return element; } } } class EmptyQueueException extends Exception{ public EmptyQueueException(String action){ super("Queue is empty. Underflow.Cannot perform action " + action); } }
Java/Queue.java
Adding Queue in Java
Java/Queue.java
Adding Queue in Java
<ide><path>ava/Queue.java <add>import java.util.ArrayList; <add> <add>public class Queue <T>{ <add> private ArrayList <T> queue; <add> Queue() { <add> queue = new ArrayList<T>(); <add> } <add> <add> public void enqueue(T element){ <add> queue.add(element); <add> } <add> <add> public boolean isEmpty(){ <add> return (queue.size() < 1); <add> } <add> <add> public T dequeue() throws EmptyQueueException{ <add> if(isEmpty()){ <add> throw new EmptyQueueException("Dequeue"); <add> } <add> else{ <add> T element = queue.get(0); <add> queue.remove(0); <add> return element; <add> } <add> } <add> <add>} <add> <add>class EmptyQueueException extends Exception{ <add> <add> public EmptyQueueException(String action){ <add> super("Queue is empty. Underflow.Cannot perform action " + action); <add> } <add>}
JavaScript
mit
004c806efab91c721b66ce2c16bf88610567965d
0
foolywk/perfect-pitch
// dependencies var fs = require('fs'); var http = require('http'); var express = require('express'); var routes = require('./routes'); var path = require('path'); var app = express(); var config = require('./oauth.js'); var User = require('./user.js'); var Video = require('./video.js'); var mongoose = require('mongoose'); var passport = require('passport'); var fbAuth = require('./authentication.js') var LocalStrategy = require('passport-local').Strategy; var FacebookStrategy = require('passport-facebook').Strategy; var googleapis = require('googleapis'); var request = require('request'); var clientSecrets = require('./client_secrets.json'); var OAuth2 = googleapis.auth.OAuth2; // var youtube = require('youtube-video'); var oauth2Client = new OAuth2( clientSecrets.web.client_id, clientSecrets.web.client_secret, "http://127.0.0.1:1337/auth/google/callback"); var access_token; var refresh_token; // connect to the database mongoose.connect('mongodb://localhost/passport-example'); // set access and refresh token from database (stored in admin's account) User.findOne({ oauthID: '706352243' }, function(err, user) { if(err) { console.log(err); } if (!err && user != null) { access_token = user.accessToken; refresh_token = user.refreshToken; console.log("## Access, Refresh tokens set to ", access_token, refresh_token); } }); app.configure(function () { app.set('port', process.env.PORT || 1337); app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); // app.use(express.logger()); /* app.use(express.bodyParser({ keepExtensions: true, uploadloadDir: __dirname +'/temp' })); */ app.use(express.multipart()); app.use(express.cookieParser()); app.use(express.json()); app.use(express.urlencoded()); app.use(express.methodOverride()); app.use(express.session({ secret: 'my_precious' })); app.use(passport.initialize()); app.use(passport.session()); app.use(app.router); app.use(express.static(__dirname + '/public')); }); // routes app.get('/', function (req, res) { res.render('index', { user: req.user }); }); app.get('/account', ensureAuthenticated, function (req, res) { User.findById(req.session.passport.user, function (err, user) { if (err) { console.log(err); } else { res.render('login', { user: user }); }; }); }); app.get('/login', function (req, res) { res.render('login', { user: req.user }); }); app.get('/logout', function (req, res) { var username = JSON.stringify(req.user.name) req.logout(); console.log("## User " + username + " has been logged out."); res.redirect('/'); }); // fb app.get('/auth/facebook', passport.authenticate('facebook'), function (req, res) {}); app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/' }), function (req, res) { res.redirect('/account'); }); // google app.get('/auth/google', function (req, res) { var url = oauth2Client.generateAuthUrl({ access_type: 'offline', approval_prompt: 'force', scope: 'https://www.googleapis.com/auth/youtube.upload' }); res.redirect(url); }); app.get('/auth/google/callback', function (req, res) { console.log('Google callback.', { query: req.query, body: req.body }) console.log('session...', req.session) oauth2Client.getToken(req.query.code || '', function (err, tokens) { console.log('ACCESS TOKENS......', { err: err, tokens: tokens }); authTokens = tokens; User.findOne({ oauthID: '706352243' }, function(err, user) { if(err) { console.log(err); } if (!err && user != null) { user.accessToken = authTokens.access_token; user.refreshToken = authTokens.refresh_token; user.save(function(err) { if(err) { console.log(err); } else { console.log("saving access, refresh token to user ..."); }; }); }; }); }); res.redirect('/'); }); app.post("/upload", function (req, res) { //get the file name console.log("## /upload called for file: " + JSON.stringify(req.files) + " with title " + req.body.title); var filename = req.files.file.name; var extensionAllowed = [".MOV", ".MPEG4", ".AVI", ".WMV"]; var maxSizeOfFile = 10000; var msg = ""; var i = filename.lastIndexOf('.'); // get the temporary location of the file var tmp_path = req.files.file.path; // set where the file should actually exists - in this case it is in the "images" directory var target_path = __dirname + '/upload/' + req.files.file.name; var file_extension = (i < 0) ? '' : filename.substr(i); if ((file_extension in oc(extensionAllowed)) && ((req.files.file.size / 1024) < maxSizeOfFile)) { fs.rename(tmp_path, target_path, function (err) { if (err) throw err; // delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files fs.unlink(tmp_path, function () { if (err) throw err; }); }); // handle upload to youtube googleapis.discover('youtube', 'v3').execute(function (err, client) { var metadata = { snippet: { title: req.body.title, description: req.body.description }, status: { privacyStatus: 'private' } }; // pass auth, refresh tokens oauth2Client.credentials = { access_token: access_token, refresh_token: refresh_token } client.youtube.videos.insert({ part: 'snippet,status' }, metadata) .withMedia('video/MOV', fs.readFileSync(target_path)) .withAuthClient(oauth2Client).execute(function (err, result) { if (err) console.log(err); else console.log(JSON.stringify(result, null, ' ')); // save uploaded video to db var video = new Video({ id: result.id, title: result.snippet.title, publishedAt: result.snippet.publishedAt, owner: req.user }); video.save(function(err) { if(err) { console.log(err); } else { console.log("saved new video: ", JSON.stringify(video, null, "\t")); // done(null, video); }; }); // save upload video to its owner, update year & major User.findOne({ oauthID: req.user.oauthID}, function(err, user) { if(err) { console.log(err); } if (!err && user != null) { user.videos.push(video); user.major = req.body.major; user.year = req.body.year; user.save(function(err) { if(err) { console.log(err); } else { console.log("saving uploaded video to user..."); }; }); }; }); }); }); msg = "File " + JSON.stringify(req.files.file.name) + " successfully uploaded to youtube!" } else { // delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files fs.unlink(tmp_path, function (err) { if (err) throw err; }); msg = "File upload failed. File extension not allowed and size must be less than " + maxSizeOfFile; } res.end(msg); }); function oc(a) { var o = {}; for (var i = 0; i < a.length; i++) { o[a[i]] = ''; } return o; } app.get('/uploadVideo', function (req, res) { console.log('## uploadVideo called for ' + JSON.stringify(req.file.files)); googleapis.discover('youtube', 'v3').execute(function (err, client) { var metadata = { snippet: { title: 'Perfect Pitch Test Upload', description: 'Test Description' }, status: { privacyStatus: 'private' } }; console.log('## AuthTokens:', authTokens); oauth2Client.credentials = { access_token: authTokens.access_token } client.youtube.videos.insert({ part: 'snippet,status' }, metadata) .withMedia('video/MOV', fs.readFileSync(req.files.file.path)) .withAuthClient(oauth2Client).execute(function (err, result) { if (err) console.log(err); else console.log(JSON.stringify(result, null, ' ')); }); }); res.redirect('/'); }); // port http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); }); // test authentication function ensureAuthenticated(req, res, next) { if (req.isAuthenticated()) { return next(); } res.redirect('/') }
app.js
// dependencies var fs = require('fs'); var http = require('http'); var express = require('express'); var routes = require('./routes'); var path = require('path'); var app = express(); var config = require('./oauth.js'); var User = require('./user.js'); var Video = require('./video.js'); var mongoose = require('mongoose'); var passport = require('passport'); var fbAuth = require('./authentication.js') var LocalStrategy = require('passport-local').Strategy; var FacebookStrategy = require('passport-facebook').Strategy; var googleapis = require('googleapis'); var request = require('request'); var clientSecrets = require('./client_secrets.json'); var OAuth2 = googleapis.auth.OAuth2; // var youtube = require('youtube-video'); var oauth2Client = new OAuth2( clientSecrets.web.client_id, clientSecrets.web.client_secret, "http://127.0.0.1:1337/auth/google/callback"); var access_token; var refresh_token; // connect to the database mongoose.connect('mongodb://localhost/passport-example'); // set access and refresh token from database (stored in admin's account) User.findOne({ oauthID: '706352243' }, function(err, user) { if(err) { console.log(err); } if (!err && user != null) { access_token = user.accessToken; refresh_token = user.refreshToken; console.log("## Access, Refresh tokens set to ", access_token, refresh_token); } }); app.configure(function () { app.set('port', process.env.PORT || 1337); app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); // app.use(express.logger()); /* app.use(express.bodyParser({ keepExtensions: true, uploadloadDir: __dirname +'/temp' })); */ app.use(express.multipart()); app.use(express.cookieParser()); app.use(express.json()); app.use(express.urlencoded()); app.use(express.methodOverride()); app.use(express.session({ secret: 'my_precious' })); app.use(passport.initialize()); app.use(passport.session()); app.use(app.router); app.use(express.static(__dirname + '/public')); }); // routes app.get('/', function (req, res) { res.render('index', { user: req.user }); }); app.get('/account', ensureAuthenticated, function (req, res) { User.findById(req.session.passport.user, function (err, user) { if (err) { console.log(err); } else { res.render('login', { user: user }); }; }); }); app.get('/login', function (req, res) { res.render('login', { user: req.user }); }); app.get('/logout', function (req, res) { var username = JSON.stringify(req.user.name) req.logout(); console.log("## User " + username + " has been logged out."); res.redirect('/'); }); // fb app.get('/auth/facebook', passport.authenticate('facebook'), function (req, res) {}); app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/' }), function (req, res) { res.redirect('/account'); }); // google app.get('/auth/google', function (req, res) { var url = oauth2Client.generateAuthUrl({ access_type: 'offline', approval_prompt: 'force', scope: 'https://www.googleapis.com/auth/youtube.upload' }); res.redirect(url); }); app.get('/auth/google/callback', function (req, res) { console.log('Google callback.', { query: req.query, body: req.body }) console.log('session...', req.session) oauth2Client.getToken(req.query.code || '', function (err, tokens) { console.log('ACCESS TOKENS......', { err: err, tokens: tokens }); authTokens = tokens; User.findOne({ oauthID: '706352243' }, function(err, user) { if(err) { console.log(err); } if (!err && user != null) { user.accessToken = authTokens.access_token; user.refreshToken = authTokens.refresh_token; user.save(function(err) { if(err) { console.log(err); } else { console.log("saving access, refresh token to user ..."); }; }); }; }); }); res.redirect('/'); }); app.post("/upload", function (req, res) { //get the file name console.log("## /upload called for file: " + JSON.stringify(req.files) + " with title " + req.body.title); var filename = req.files.file.name; var extensionAllowed = [".MOV", ".MPEG4", ".AVI", ".WMV"]; var maxSizeOfFile = 10000; var msg = ""; var i = filename.lastIndexOf('.'); // get the temporary location of the file var tmp_path = req.files.file.path; // set where the file should actually exists - in this case it is in the "images" directory var target_path = __dirname + '/upload/' + req.files.file.name; var file_extension = (i < 0) ? '' : filename.substr(i); if ((file_extension in oc(extensionAllowed)) && ((req.files.file.size / 1024) < maxSizeOfFile)) { fs.rename(tmp_path, target_path, function (err) { if (err) throw err; // delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files fs.unlink(tmp_path, function () { if (err) throw err; }); }); // handle upload to youtube googleapis.discover('youtube', 'v3').execute(function (err, client) { var metadata = { snippet: { title: req.body.title, description: req.body.description }, status: { privacyStatus: 'private' } }; // pass auth, refresh tokens oauth2Client.credentials = { access_token: access_token, refresh_token: refresh_token } client.youtube.videos.insert({ part: 'snippet,status' }, metadata) .withMedia('video/MOV', fs.readFileSync(target_path)) .withAuthClient(oauth2Client).execute(function (err, result) { if (err) console.log(err); else console.log(JSON.stringify(result, null, ' ')); // save uploaded video to db var video = new Video({ id: result.id, title: result.snippet.title, publishedAt: result.snippet.publishedAt, owner: req.user }); video.save(function(err) { if(err) { console.log(err); } else { console.log("saved new video: ", JSON.stringify(video, null, "\t")); // done(null, video); }; }); // save upload video to its owner, update year & major User.findOne({ oauthID: req.user.oauthID}, function(err, user) { if(err) { console.log(err); } if (!err && user != null) { user.videos.push(video); user.major = req.body.major; user.year = req.body.year; user.save(function(err) { if(err) { console.log(err); } else { console.log("saving uploaded video to user..."); }; }); }; }); }); }); msg = "File " + JSON.stringify(req.files.file.name) + " successfully uploaded to youtube!" } else { // delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files fs.unlink(tmp_path, function (err) { if (err) throw err; }); msg = "File upload failed. File extension not allowed and size must be less than " + maxSizeOfFile; } res.end(msg); }); function oc(a) { var o = {}; for (var i = 0; i < a.length; i++) { o[a[i]] = ''; } return o; } app.get('/uploadVideo', function (req, res) { console.log('## uploadVideo called for ' + JSON.stringify(req.file.files)); googleapis.discover('youtube', 'v3').execute(function (err, client) { var metadata = { snippet: { title: 'Perfect Pitch Test Upload', description: 'Test Description' }, status: { privacyStatus: 'private' } }; console.log('## AuthTokens:', authTokens); oauth2Client.credentials = { access_token: authTokens.access_token } client.youtube.videos.insert({ part: 'snippet,status' }, metadata) .withMedia('video/MOV', fs.readFileSync(req.files.file.path)) .withAuthClient(oauth2Client).execute(function (err, result) { if (err) console.log(err); else console.log(JSON.stringify(result, null, ' ')); }); }); res.redirect('/'); }); // port http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); }); // test authentication function ensureAuthenticated(req, res, next) { if (req.isAuthenticated()) { return next(); } res.redirect('/') }
updaing views
app.js
updaing views
<ide><path>pp.js <ide> app.set('view engine', 'jade'); <ide> // app.use(express.logger()); <ide> /* app.use(express.bodyParser({ <del> keepExtensions: true, <add> keepExtensions: true, <ide> uploadloadDir: __dirname +'/temp' })); */ <ide> app.use(express.multipart()); <ide> app.use(express.cookieParser());
Java
bsd-3-clause
cd994c726e363cf53b8791ef7456b886ad1ab414
0
agmip/translator-dssat,MengZhang/translator-dssat
package org.agmip.translators.dssat; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import static org.agmip.translators.dssat.DssatCommonInput.copyItem; import static org.agmip.util.MapUtil.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * DSSAT Experiment Data I/O API Class * * @author Meng Zhang * @version 1.0 */ public class DssatXFileOutput extends DssatCommonOutput { private static final Logger LOG = LoggerFactory.getLogger(DssatXFileOutput.class); // public static final DssatCRIDHelper crHelper = new DssatCRIDHelper(); /** * DSSAT Experiment Data Output method * * @param arg0 file output path * @param result data holder object */ @Override public void writeFile(String arg0, Map result) { // Initial variables HashMap expData = (HashMap) result; ArrayList<HashMap> soilArr = readSWData(expData, "soil"); ArrayList<HashMap> wthArr = readSWData(expData, "weather"); HashMap soilData; HashMap wthData; BufferedWriter bwX; // output object StringBuilder sbGenData = new StringBuilder(); // construct the data info in the output StringBuilder sbNotesData = new StringBuilder(); // construct the data info in the output StringBuilder sbData = new StringBuilder(); // construct the data info in the output StringBuilder eventPart2 = new StringBuilder(); // output string for second part of event data HashMap secData; ArrayList subDataArr; // Arraylist for event data holder HashMap subData; ArrayList secDataArr; // Arraylist for section data holder HashMap sqData; ArrayList<HashMap> evtArr; // Arraylist for section data holder HashMap evtData; // int trmnNum; // total numbers of treatment in the data holder int cuNum; // total numbers of cultivars in the data holder int flNum; // total numbers of fields in the data holder int saNum; // total numbers of soil analysis in the data holder int icNum; // total numbers of initial conditions in the data holder int mpNum; // total numbers of plaintings in the data holder int miNum; // total numbers of irrigations in the data holder int mfNum; // total numbers of fertilizers in the data holder int mrNum; // total numbers of residues in the data holder int mcNum; // total numbers of chemical in the data holder int mtNum; // total numbers of tillage in the data holder int meNum; // total numbers of enveronment modification in the data holder int mhNum; // total numbers of harvest in the data holder int smNum; // total numbers of simulation controll record ArrayList<HashMap> sqArr; // array for treatment record ArrayList cuArr = new ArrayList(); // array for cultivars record ArrayList flArr = new ArrayList(); // array for fields record ArrayList saArr = new ArrayList(); // array for soil analysis record ArrayList icArr = new ArrayList(); // array for initial conditions record ArrayList mpArr = new ArrayList(); // array for plaintings record ArrayList miArr = new ArrayList(); // array for irrigations record ArrayList mfArr = new ArrayList(); // array for fertilizers record ArrayList mrArr = new ArrayList(); // array for residues record ArrayList mcArr = new ArrayList(); // array for chemical record ArrayList mtArr = new ArrayList(); // array for tillage record ArrayList meArr = new ArrayList(); // array for enveronment modification record ArrayList mhArr = new ArrayList(); // array for harvest record ArrayList smArr = new ArrayList(); // array for simulation control record // String exName; try { // Set default value for missing data if (expData == null || expData.isEmpty()) { return; } // decompressData((HashMap) result); setDefVal(); // Initial BufferedWriter String fileName = getFileName(result, "X"); arg0 = revisePath(arg0); outputFile = new File(arg0 + fileName); bwX = new BufferedWriter(new FileWriter(outputFile)); // Output XFile // EXP.DETAILS Section sbGenData.append(String.format("*EXP.DETAILS: %1$-10s %2$s\r\n\r\n", getFileName(result, "").replaceAll("\\.", ""), getObjectOr(expData, "local_name", defValBlank).toString())); // GENERAL Section sbGenData.append("*GENERAL\r\n"); // People if (!getObjectOr(expData, "person_notes", "").equals("")) { sbGenData.append(String.format("@PEOPLE\r\n %1$s\r\n", getObjectOr(expData, "person_notes", defValBlank).toString())); } // Address if (getObjectOr(expData, "institution", "").equals("")) { // if (!getObjectOr(expData, "fl_loc_1", "").equals("") // && getObjectOr(expData, "fl_loc_2", "").equals("") // && getObjectOr(expData, "fl_loc_3", "").equals("")) { // sbGenData.append(String.format("@ADDRESS\r\n %3$s, %2$s, %1$s\r\n", // getObjectOr(expData, "fl_loc_1", defValBlank).toString(), // getObjectOr(expData, "fl_loc_2", defValBlank).toString(), // getObjectOr(expData, "fl_loc_3", defValBlank).toString())); // } } else { sbGenData.append(String.format("@ADDRESS\r\n %1$s\r\n", getObjectOr(expData, "institution", defValBlank).toString())); } // Site if (!getObjectOr(expData, "site_name", "").equals("")) { sbGenData.append(String.format("@SITE\r\n %1$s\r\n", getObjectOr(expData, "site_name", defValBlank).toString())); } // Plot Info if (isPlotInfoExist(expData)) { sbGenData.append("@ PAREA PRNO PLEN PLDR PLSP PLAY HAREA HRNO HLEN HARM.........\r\n"); sbGenData.append(String.format(" %1$6s %2$5s %3$5s %4$5s %5$5s %6$-5s %7$5s %8$5s %9$5s %10$-15s\r\n", formatNumStr(6, expData, "plta", defValR), formatNumStr(5, expData, "pltr#", defValI), formatNumStr(5, expData, "pltln", defValR), formatNumStr(5, expData, "pldr", defValI), formatNumStr(5, expData, "pltsp", defValI), getObjectOr(expData, "pllay", defValC).toString(), formatNumStr(5, expData, "pltha", defValR), formatNumStr(5, expData, "plth#", defValI), formatNumStr(5, expData, "plthl", defValR), getObjectOr(expData, "plthm", defValC).toString())); } // Notes if (!getObjectOr(expData, "tr_notes", "").equals("")) { sbNotesData.append("@NOTES\r\n"); String notes = getObjectOr(expData, "tr_notes", defValC).toString(); notes = notes.replaceAll("\\\\r\\\\n", "\r\n"); // If notes contain newline code, then write directly if (notes.indexOf("\r\n") >= 0) { // sbData.append(String.format(" %1$s\r\n", notes)); sbNotesData.append(notes); } // Otherwise, add newline for every 75-bits charactors else { while (notes.length() > 75) { sbNotesData.append(" ").append(notes.substring(0, 75)).append("\r\n"); notes = notes.substring(75); } sbNotesData.append(" ").append(notes).append("\r\n"); } } sbData.append("\r\n"); // TREATMENT Section sqArr = getDataList(expData, "dssat_sequence", "data"); evtArr = getDataList(expData, "management", "events"); ArrayList<HashMap> rootArr = getObjectOr(expData, "dssat_root", new ArrayList()); ArrayList<HashMap> meOrgArr = getDataList(expData, "dssat_environment_modification", "data"); ArrayList<HashMap> smOrgArr = getDataList(expData, "dssat_simulation_control", "data"); String seqId; String em; String sm; sbData.append("*TREATMENTS -------------FACTOR LEVELS------------\r\n"); sbData.append("@N R O C TNAME.................... CU FL SA IC MP MI MF MR MC MT ME MH SM\r\n"); // if there is no sequence info, create dummy data if (sqArr.isEmpty()) { sqArr.add(new HashMap()); } // Set sequence related block info for (int i = 0; i < sqArr.size(); i++) { sqData = sqArr.get(i); seqId = getValueOr(sqData, "seqid", defValBlank); em = getValueOr(sqData, "em", defValBlank); sm = getValueOr(sqData, "sm", defValBlank); if (i < soilArr.size()) { soilData = soilArr.get(i); } else if (soilArr.isEmpty()) { soilData = new HashMap(); } else { soilData = soilArr.get(0); } if (soilData == null) { soilData = new HashMap(); } if (i < wthArr.size()) { wthData = wthArr.get(i); } else if (wthArr.isEmpty()) { wthData = new HashMap(); } else { wthData = wthArr.get(0); } if (wthData == null) { wthData = new HashMap(); } HashMap cuData = new HashMap(); HashMap flData = new HashMap(); HashMap mpData = new HashMap(); ArrayList<HashMap> miSubArr = new ArrayList<HashMap>(); ArrayList<HashMap> mfSubArr = new ArrayList<HashMap>(); ArrayList<HashMap> mrSubArr = new ArrayList<HashMap>(); ArrayList<HashMap> mcSubArr = new ArrayList<HashMap>(); ArrayList<HashMap> mtSubArr = new ArrayList<HashMap>(); ArrayList<HashMap> meSubArr = new ArrayList<HashMap>(); ArrayList<HashMap> mhSubArr = new ArrayList<HashMap>(); HashMap smData = new HashMap(); HashMap rootData; // Set exp root info if (i < rootArr.size()) { rootData = rootArr.get(i); } else { rootData = expData; } // Set field info copyItem(flData, rootData, "id_field"); flData.put("wst_id", getWthFileName(rootData)); // if (i < rootArr.size()) { // // copyItem(flData, expData, "wst_id"); // flData.put("wst_id", getWthFileName(rootData)); // } else { // flData.put("wst_id", getWthFileName(wthData)); // } copyItem(flData, rootData, "flsl"); copyItem(flData, rootData, "flob"); copyItem(flData, rootData, "fl_drntype"); copyItem(flData, rootData, "fldrd"); copyItem(flData, rootData, "fldrs"); copyItem(flData, rootData, "flst"); if (soilData.get("sltx") != null) { copyItem(flData, soilData, "sltx"); } else { copyItem(flData, rootData, "sltx"); } copyItem(flData, soilData, "sldp"); copyItem(flData, rootData, "soil_id"); copyItem(flData, rootData, "fl_name"); copyItem(flData, rootData, "fl_lat"); copyItem(flData, rootData, "fl_long"); copyItem(flData, rootData, "flele"); copyItem(flData, rootData, "farea"); copyItem(flData, rootData, "fllwr"); copyItem(flData, rootData, "flsla"); copyItem(flData, getObjectOr(rootData, "dssat_info", new HashMap()), "flhst"); copyItem(flData, getObjectOr(rootData, "dssat_info", new HashMap()), "fhdur"); // remove the "_trno" in the soil_id when soil analysis is available String soilId = getValueOr(flData, "soil_id", ""); if (soilId.length() > 10 && soilId.matches("\\w+_\\d+")) { flData.put("soil_id", getSoilID(flData)); } flNum = setSecDataArr(flData, flArr); // Set initial condition info icNum = setSecDataArr(getObjectOr(rootData, "initial_conditions", new HashMap()), icArr); // Set environment modification info for (int j = 0; j < meOrgArr.size(); j++) { if (em.equals(meOrgArr.get(j).get("em"))) { HashMap tmp = new HashMap(); tmp.putAll(meOrgArr.get(j)); tmp.remove("em"); meSubArr.add(tmp); } } // Set soil analysis info // ArrayList<HashMap> icSubArr = getDataList(expData, "initial_condition", "soilLayer"); ArrayList<HashMap> soilLarys = getObjectOr(soilData, "soilLayer", new ArrayList()); // // If it is stored in the initial condition block // if (isSoilAnalysisExist(icSubArr)) { // HashMap saData = new HashMap(); // ArrayList<HashMap> saSubArr = new ArrayList<HashMap>(); // HashMap saSubData; // for (int i = 0; i < icSubArr.size(); i++) { // saSubData = new HashMap(); // copyItem(saSubData, icSubArr.get(i), "sabl", "icbl", false); // copyItem(saSubData, icSubArr.get(i), "sasc", "slsc", false); // saSubArr.add(saSubData); // } // copyItem(saData, soilData, "sadat"); // saData.put("soilLayer", saSubArr); // saNum = setSecDataArr(saData, saArr); // } else // If it is stored in the soil block if (isSoilAnalysisExist(soilLarys)) { HashMap saData = new HashMap(); ArrayList<HashMap> saSubArr = new ArrayList<HashMap>(); HashMap saSubData; for (int j = 0; j < soilLarys.size(); j++) { saSubData = new HashMap(); copyItem(saSubData, soilLarys.get(j), "sabl", "sllb", false); copyItem(saSubData, soilLarys.get(j), "sasc", "slsc", false); saSubArr.add(saSubData); } copyItem(saData, soilData, "sadat"); saData.put("soilLayer", saSubArr); saNum = setSecDataArr(saData, saArr); } else { saNum = 0; } // Set simulation control info for (int j = 0; j < smOrgArr.size(); j++) { if (sm.equals(smOrgArr.get(j).get("sm"))) { smData.putAll(smOrgArr.get(j)); smData.remove("sm"); break; } } // if (smData.isEmpty()) { // smData.put("fertilizer", mfSubArr); // smData.put("irrigation", miSubArr); // smData.put("planting", mpData); // } copyItem(smData, rootData, "sdat"); copyItem(smData, getObjectOr(wthData, "weather", new HashMap()), "co2y"); // Loop all event data for (int j = 0; j < evtArr.size(); j++) { evtData = new HashMap(); evtData.putAll(evtArr.get(j)); // Check if it has same sequence number if (getValueOr(evtData, "seqid", defValBlank).equals(seqId)) { evtData.remove("seqid"); // Planting event if (getValueOr(evtData, "event", defValBlank).equals("planting")) { // Set cultivals info copyItem(cuData, evtData, "cul_name"); copyItem(cuData, evtData, "crid"); copyItem(cuData, evtData, "cul_id"); copyItem(cuData, evtData, "dssat_cul_id"); copyItem(cuData, evtData, "rm"); copyItem(cuData, evtData, "cul_notes"); translateTo2BitCrid(cuData); // Set planting info mpData.putAll(evtData); mpData.remove("cul_name"); } // irrigation event else if (getValueOr(evtData, "event", "").equals("irrigation")) { miSubArr.add(evtData); } // fertilizer event else if (getValueOr(evtData, "event", "").equals("fertilizer")) { mfSubArr.add(evtData); } // organic_matter event else if (getValueOr(evtData, "event", "").equals("organic_matter")) { // P.S. change event name to organic-materials; Back to organic_matter again. mrSubArr.add(evtData); } // chemical event else if (getValueOr(evtData, "event", "").equals("chemical")) { mcSubArr.add(evtData); } // tillage event else if (getValueOr(evtData, "event", "").equals("tillage")) { mtSubArr.add(evtData); // } // environment_modification event // else if (getValueOr(evtData, "event", "").equals("environment_modification")) { // meSubArr.add(evtData); } // harvest event else if (getValueOr(evtData, "event", "").equals("harvest")) { mhSubArr.add(evtData); copyItem(smData, evtData, "hadat", "date", false); } else { } } else { } } // If alternative fields are avaiable for fertilizer data if (mfSubArr.isEmpty()) { if (!getObjectOr(result, "fen_tot", "").equals("") || !getObjectOr(result, "fep_tot", "").equals("") || !getObjectOr(result, "fek_tot", "").equals("")) { mfSubArr.add(new HashMap()); } } cuNum = setSecDataArr(cuData, cuArr); mpNum = setSecDataArr(mpData, mpArr); miNum = setSecDataArr(miSubArr, miArr); mfNum = setSecDataArr(mfSubArr, mfArr); mrNum = setSecDataArr(mrSubArr, mrArr); mcNum = setSecDataArr(mcSubArr, mcArr); mtNum = setSecDataArr(mtSubArr, mtArr); meNum = setSecDataArr(meSubArr, meArr); mhNum = setSecDataArr(mhSubArr, mhArr); smNum = setSecDataArr(smData, smArr); if (smNum == 0) { smNum = 1; } sbData.append(String.format("%1$-3s%2$1s %3$1s %4$1s %5$-25s %6$2s %7$2s %8$2s %9$2s %10$2s %11$2s %12$2s %13$2s %14$2s %15$2s %16$2s %17$2s %18$2s\r\n", String.format("%2s", getValueOr(sqData, "trno", "1")), // For 3-bit treatment number getValueOr(sqData, "sq", "1").toString(), // P.S. default value here is based on document DSSAT vol2.pdf getValueOr(sqData, "op", "1").toString(), getValueOr(sqData, "co", "0").toString(), formatStr(25, sqData, "trt_name", getValueOr(rootData, "trt_name", getValueOr(rootData, "exname", defValC))), cuNum, //getObjectOr(data, "ge", defValI).toString(), flNum, //getObjectOr(data, "fl", defValI).toString(), saNum, //getObjectOr(data, "sa", defValI).toString(), icNum, //getObjectOr(data, "ic", defValI).toString(), mpNum, //getObjectOr(data, "pl", defValI).toString(), miNum, //getObjectOr(data, "ir", defValI).toString(), mfNum, //getObjectOr(data, "fe", defValI).toString(), mrNum, //getObjectOr(data, "om", defValI).toString(), mcNum, //getObjectOr(data, "ch", defValI).toString(), mtNum, //getObjectOr(data, "ti", defValI).toString(), meNum, //getObjectOr(data, "em", defValI).toString(), mhNum, //getObjectOr(data, "ha", defValI).toString(), smNum)); // 1 } sbData.append("\r\n"); // CULTIVARS Section if (!cuArr.isEmpty()) { sbData.append("*CULTIVARS\r\n"); sbData.append("@C CR INGENO CNAME\r\n"); for (int idx = 0; idx < cuArr.size(); idx++) { secData = (HashMap) cuArr.get(idx); // String cul_id = defValC; String crid = getObjectOr(secData, "crid", ""); // Checl if necessary data is missing if (crid.equals("")) { sbError.append("! Warning: Incompleted record because missing data : [crid]\r\n"); // } else { // // Set cultivar id a default value deponds on the crop id // if (crid.equals("MZ")) { // cul_id = "990002"; // } else { // cul_id = "999999"; // } // } // if (getObjectOr(secData, "cul_id", "").equals("")) { // sbError.append("! Warning: Incompleted record because missing data : [cul_id], and will use default value '").append(cul_id).append("'\r\n"); } sbData.append(String.format("%1$2s %2$-2s %3$-6s %4$s\r\n", idx + 1, //getObjectOr(secData, "ge", defValI).toString(), formatStr(2, secData, "crid", defValBlank), // P.S. if missing, default value use blank string formatStr(6, secData, "dssat_cul_id", getObjectOr(secData, "cul_id", defValC)), // P.S. Set default value which is deponds on crid(Cancelled) getObjectOr(secData, "cul_name", defValC).toString())); if (!getObjectOr(secData, "rm", "").equals("") || !getObjectOr(secData, "cul_notes", "").equals("")) { if (sbNotesData.toString().equals("")) { sbNotesData.append("@NOTES\r\n"); } sbNotesData.append(" Cultivar Additional Info\r\n"); sbNotesData.append(" C RM CNAME CUL_NOTES\r\n"); sbNotesData.append(String.format("%1$2s %2$4s %3$s\r\n", idx + 1, //getObjectOr(secData, "ge", defValI).toString(), getObjectOr(secData, "rm", defValC).toString(), getObjectOr(secData, "cul_notes", defValC).toString())); } } sbData.append("\r\n"); } else { sbError.append("! Warning: There is no cultivar data in the experiment.\r\n"); } // FIELDS Section if (!flArr.isEmpty()) { sbData.append("*FIELDS\r\n"); sbData.append("@L ID_FIELD WSTA.... FLSA FLOB FLDT FLDD FLDS FLST SLTX SLDP ID_SOIL FLNAME\r\n"); eventPart2 = new StringBuilder(); eventPart2.append("@L ...........XCRD ...........YCRD .....ELEV .............AREA .SLEN .FLWR .SLAS FLHST FHDUR\r\n"); } else { sbError.append("! Warning: There is no field data in the experiment.\r\n"); } for (int idx = 0; idx < flArr.size(); idx++) { secData = (HashMap) flArr.get(idx); // Check if the necessary is missing if (getObjectOr(secData, "wst_id", "").equals("")) { sbError.append("! Warning: Incompleted record because missing data : [wst_id]\r\n"); } String soil_id = getValueOr(result, "soil_id", defValC); if (soil_id.equals("")) { sbError.append("! Warning: Incompleted record because missing data : [soil_id]\r\n"); } else if (soil_id.length() > 10) { sbError.append("! Warning: Oversized data : [soil_id] ").append(soil_id).append("\r\n"); } sbData.append(String.format("%1$2s %2$-8s %3$-8s %4$5s %5$5s %6$-5s %7$5s %8$5s %9$-5s %10$-5s%11$5s %12$-10s %13$s\r\n", // P.S. change length definition to match current way idx + 1, //getObjectOr(secData, "fl", defValI).toString(), formatStr(8, secData, "id_field", defValC), formatStr(8, secData, "wst_id", defValC), formatStr(4, secData, "flsl", defValC), formatNumStr(5, secData, "flob", defValR), formatStr(5, secData, "fl_drntype", defValC), formatNumStr(5, secData, "fldrd", defValR), formatNumStr(5, secData, "fldrs", defValR), formatStr(5, secData, "flst", defValC), formatStr(5, secData, "sltx", defValC), formatNumStr(5, secData, "sldp", defValR), soil_id, getObjectOr(secData, "fl_name", defValC).toString())); eventPart2.append(String.format("%1$2s %2$15s %3$15s %4$9s %5$17s %6$5s %7$5s %8$5s %9$5s %10$5s\r\n", idx + 1, //getObjectOr(secData, "fl", defValI).toString(), formatNumStr(15, secData, "fl_long", defValR), formatNumStr(15, secData, "fl_lat", defValR), formatNumStr(9, secData, "flele", defValR), formatNumStr(17, secData, "farea", defValR), "-99", // P.S. SLEN keeps -99 formatNumStr(5, secData, "fllwr", defValR), formatNumStr(5, secData, "flsla", defValR), formatStr(5, secData, "flhst", defValC), formatNumStr(5, secData, "fhdur", defValR))); } if (!flArr.isEmpty()) { sbData.append(eventPart2.toString()).append("\r\n"); } // SOIL ANALYSIS Section if (!saArr.isEmpty()) { sbData.append("*SOIL ANALYSIS\r\n"); for (int idx = 0; idx < saArr.size(); idx++) { secData = (HashMap) saArr.get(idx); sbData.append("@A SADAT SMHB SMPX SMKE SANAME\r\n"); sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$s\r\n", idx + 1, //getObjectOr(secData, "sa", defValI).toString(), formatDateStr(getObjectOr(secData, "sadat", defValD).toString()), getObjectOr(secData, "samhb", defValC).toString(), getObjectOr(secData, "sampx", defValC).toString(), getObjectOr(secData, "samke", defValC).toString(), getObjectOr(secData, "sa_name", defValC).toString())); subDataArr = (ArrayList) getObjectOr(secData, "soilLayer", new ArrayList()); if (!subDataArr.isEmpty()) { sbData.append("@A SABL SADM SAOC SANI SAPHW SAPHB SAPX SAKE SASC\r\n"); } for (int j = 0; j < subDataArr.size(); j++) { subData = (HashMap) subDataArr.get(j); sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s\r\n", idx + 1, //getObjectOr(subData, "sa", defValI).toString(), formatNumStr(5, subData, "sabl", defValR), formatNumStr(5, subData, "sabdm", defValR), formatNumStr(5, subData, "saoc", defValR), formatNumStr(5, subData, "sani", defValR), formatNumStr(5, subData, "saphw", defValR), formatNumStr(5, subData, "saphb", defValR), formatNumStr(5, subData, "sapx", defValR), formatNumStr(5, subData, "sake", defValR), formatNumStr(5, subData, "sasc", defValR))); } } sbData.append("\r\n"); } // INITIAL CONDITIONS Section if (!icArr.isEmpty()) { sbData.append("*INITIAL CONDITIONS\r\n"); for (int idx = 0; idx < icArr.size(); idx++) { secData = (HashMap) icArr.get(idx); translateTo2BitCrid(secData, "icpcr"); sbData.append("@C PCR ICDAT ICRT ICND ICRN ICRE ICWD ICRES ICREN ICREP ICRIP ICRID ICNAME\r\n"); sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$5s %13$5s %14$s\r\n", idx + 1, //getObjectOr(secData, "ic", defValI).toString(), getObjectOr(secData, "icpcr", defValC).toString(), formatDateStr(getObjectOr(secData, "icdat", getPdate(result)).toString()), formatNumStr(5, secData, "icrt", defValR), formatNumStr(5, secData, "icnd", defValR), formatNumStr(5, secData, "icrz#", defValR), formatNumStr(5, secData, "icrze", defValR), formatNumStr(5, secData, "icwt", defValR), formatNumStr(5, secData, "icrag", defValR), formatNumStr(5, secData, "icrn", defValR), formatNumStr(5, secData, "icrp", defValR), formatNumStr(5, secData, "icrip", defValR), formatNumStr(5, secData, "icrdp", defValR), getObjectOr(secData, "ic_name", defValC).toString())); subDataArr = (ArrayList) getObjectOr(secData, "soilLayer", new ArrayList()); if (!subDataArr.isEmpty()) { sbData.append("@C ICBL SH2O SNH4 SNO3\r\n"); } for (int j = 0; j < subDataArr.size(); j++) { subData = (HashMap) subDataArr.get(j); sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s\r\n", idx + 1, //getObjectOr(subData, "ic", defValI).toString(), formatNumStr(5, subData, "icbl", defValR), formatNumStr(5, subData, "ich2o", defValR), formatNumStr(5, subData, "icnh4", defValR), formatNumStr(5, subData, "icno3", defValR))); } } sbData.append("\r\n"); } // PLANTING DETAILS Section if (!mpArr.isEmpty()) { sbData.append("*PLANTING DETAILS\r\n"); sbData.append("@P PDATE EDATE PPOP PPOE PLME PLDS PLRS PLRD PLDP PLWT PAGE PENV PLPH SPRL PLNAME\r\n"); for (int idx = 0; idx < mpArr.size(); idx++) { secData = (HashMap) mpArr.get(idx); // Check if necessary data is missing String pdate = getObjectOr(secData, "date", ""); if (pdate.equals("")) { sbError.append("! Warning: Incompleted record because missing data : [pdate]\r\n"); } else if (formatDateStr(pdate).equals(defValD)) { sbError.append("! Warning: Incompleted record because variable [pdate] with invalid value [").append(pdate).append("]\r\n"); } if (getObjectOr(secData, "plpop", getObjectOr(secData, "plpoe", "")).equals("")) { sbError.append("! Warning: Incompleted record because missing data : [plpop] and [plpoe]\r\n"); } if (getObjectOr(secData, "plrs", "").equals("")) { sbError.append("! Warning: Incompleted record because missing data : [plrs]\r\n"); } // if (getObjectOr(secData, "plma", "").equals("")) { // sbError.append("! Warning: missing data : [plma], and will automatically use default value 'S'\r\n"); // } // if (getObjectOr(secData, "plds", "").equals("")) { // sbError.append("! Warning: missing data : [plds], and will automatically use default value 'R'\r\n"); // } // if (getObjectOr(secData, "pldp", "").equals("")) { // sbError.append("! Warning: missing data : [pldp], and will automatically use default value '7'\r\n"); // } // mm -> cm String pldp = getObjectOr(secData, "pldp", ""); if (!pldp.equals("")) { try { BigDecimal pldpBD = new BigDecimal(pldp); pldpBD = pldpBD.divide(new BigDecimal("10")); secData.put("pldp", pldpBD.toString()); } catch (NumberFormatException e) { } } sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$5s %13$5s %14$5s %15$5s %16$s\r\n", idx + 1, //getObjectOr(data, "pl", defValI).toString(), formatDateStr(getObjectOr(secData, "date", defValD).toString()), formatDateStr(getObjectOr(secData, "pldae", defValD).toString()), formatNumStr(5, secData, "plpop", getObjectOr(secData, "plpoe", defValR)), formatNumStr(5, secData, "plpoe", getObjectOr(secData, "plpop", defValR)), getObjectOr(secData, "plma", defValC).toString(), // P.S. Set default value as "S"(Cancelled) getObjectOr(secData, "plds", defValC).toString(), // P.S. Set default value as "R"(Cancelled) formatNumStr(5, secData, "plrs", defValR), formatNumStr(5, secData, "plrd", defValR), formatNumStr(5, secData, "pldp", defValR), // P.S. Set default value as "7"(Cancelled) formatNumStr(5, secData, "plmwt", defValR), formatNumStr(5, secData, "page", defValR), formatNumStr(5, secData, "plenv", defValR), formatNumStr(5, secData, "plph", defValR), formatNumStr(5, secData, "plspl", defValR), getObjectOr(secData, "pl_name", defValC).toString())); } sbData.append("\r\n"); } else { sbError.append("! Warning: There is no plainting data in the experiment.\r\n"); } // IRRIGATION AND WATER MANAGEMENT Section if (!miArr.isEmpty()) { sbData.append("*IRRIGATION AND WATER MANAGEMENT\r\n"); for (int idx = 0; idx < miArr.size(); idx++) { // secData = (ArrayList) miArr.get(idx); subDataArr = (ArrayList) miArr.get(idx); if (!subDataArr.isEmpty()) { subData = (HashMap) subDataArr.get(0); } else { subData = new HashMap(); } sbData.append("@I EFIR IDEP ITHR IEPT IOFF IAME IAMT IRNAME\r\n"); sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$s\r\n", idx + 1, //getObjectOr(data, "ir", defValI).toString(), formatNumStr(5, subData, "ireff", defValR), formatNumStr(5, subData, "irmdp", defValR), formatNumStr(5, subData, "irthr", defValR), formatNumStr(5, subData, "irept", defValR), getObjectOr(subData, "irstg", defValC).toString(), getObjectOr(subData, "iame", defValC).toString(), formatNumStr(5, subData, "iamt", defValR), getObjectOr(subData, "ir_name", defValC).toString())); if (!subDataArr.isEmpty()) { sbData.append("@I IDATE IROP IRVAL\r\n"); } for (int j = 0; j < subDataArr.size(); j++) { subData = (HashMap) subDataArr.get(j); sbData.append(String.format("%1$2s %2$5s %3$-5s %4$5s\r\n", idx + 1, //getObjectOr(subData, "ir", defValI).toString(), formatDateStr(getObjectOr(subData, "date", defValD).toString()), // P.S. idate -> date getObjectOr(subData, "irop", defValC).toString(), formatNumStr(5, subData, "irval", defValR))); } } sbData.append("\r\n"); } // FERTILIZERS (INORGANIC) Section if (!mfArr.isEmpty()) { sbData.append("*FERTILIZERS (INORGANIC)\r\n"); sbData.append("@F FDATE FMCD FACD FDEP FAMN FAMP FAMK FAMC FAMO FOCD FERNAME\r\n"); // String fen_tot = getObjectOr(result, "fen_tot", defValR); // String fep_tot = getObjectOr(result, "fep_tot", defValR); // String fek_tot = getObjectOr(result, "fek_tot", defValR); // String pdate = getPdate(result); // if (pdate.equals("")) { // pdate = defValD; // } for (int idx = 0; idx < mfArr.size(); idx++) { secDataArr = (ArrayList) mfArr.get(idx); for (int i = 0; i < secDataArr.size(); i++) { secData = (HashMap) secDataArr.get(i); // if (getObjectOr(secData, "fdate", "").equals("")) { // sbError.append("! Warning: missing data : [fdate], and will automatically use planting value '").append(pdate).append("'\r\n"); // } // if (getObjectOr(secData, "fecd", "").equals("")) { // sbError.append("! Warning: missing data : [fecd], and will automatically use default value 'FE001'\r\n"); // } // if (getObjectOr(secData, "feacd", "").equals("")) { // sbError.append("! Warning: missing data : [feacd], and will automatically use default value 'AP002'\r\n"); // } // if (getObjectOr(secData, "fedep", "").equals("")) { // sbError.append("! Warning: missing data : [fedep], and will automatically use default value '10'\r\n"); // } // if (getObjectOr(secData, "feamn", "").equals("")) { // sbError.append("! Warning: missing data : [feamn], and will automatically use the value of FEN_TOT, '").append(fen_tot).append("'\r\n"); // } // if (getObjectOr(secData, "feamp", "").equals("")) { // sbError.append("! Warning: missing data : [feamp], and will automatically use the value of FEP_TOT, '").append(fep_tot).append("'\r\n"); // } // if (getObjectOr(secData, "feamk", "").equals("")) { // sbError.append("! Warning: missing data : [feamk], and will automatically use the value of FEK_TOT, '").append(fek_tot).append("'\r\n"); // } sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$s\r\n", idx + 1, //getObjectOr(data, "fe", defValI).toString(), formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. fdate -> date getObjectOr(secData, "fecd", defValC).toString(), // P.S. Set default value as "FE005"(Cancelled) getObjectOr(secData, "feacd", defValC).toString(), // P.S. Set default value as "AP002"(Cancelled) formatNumStr(5, secData, "fedep", defValR), // P.S. Set default value as "10"(Cancelled) formatNumStr(5, secData, "feamn", defValR), // P.S. Set default value to use the value of FEN_TOT in meta data(Cancelled) formatNumStr(5, secData, "feamp", defValR), // P.S. Set default value to use the value of FEP_TOT in meta data(Cancelled) formatNumStr(5, secData, "feamk", defValR), // P.S. Set default value to use the value of FEK_TOT in meta data(Cancelled) formatNumStr(5, secData, "feamc", defValR), formatNumStr(5, secData, "feamo", defValR), getObjectOr(secData, "feocd", defValC).toString(), getObjectOr(secData, "fe_name", defValC).toString())); } } sbData.append("\r\n"); } // RESIDUES AND ORGANIC FERTILIZER Section if (!mrArr.isEmpty()) { sbData.append("*RESIDUES AND ORGANIC FERTILIZER\r\n"); sbData.append("@R RDATE RCOD RAMT RESN RESP RESK RINP RDEP RMET RENAME\r\n"); for (int idx = 0; idx < mrArr.size(); idx++) { secDataArr = (ArrayList) mrArr.get(idx); for (int i = 0; i < secDataArr.size(); i++) { secData = (HashMap) secDataArr.get(i); sbData.append(String.format("%1$2s %2$5s %3$-5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$s\r\n", idx + 1, //getObjectOr(secData, "om", defValI).toString(), formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. omdat -> date getObjectOr(secData, "omcd", defValC).toString(), formatNumStr(5, secData, "omamt", defValR), formatNumStr(5, secData, "omn%", defValR), formatNumStr(5, secData, "omp%", defValR), formatNumStr(5, secData, "omk%", defValR), formatNumStr(5, secData, "ominp", defValR), formatNumStr(5, secData, "omdep", defValR), formatNumStr(5, secData, "omacd", defValR), getObjectOr(secData, "om_name", defValC).toString())); } } sbData.append("\r\n"); } // CHEMICAL APPLICATIONS Section if (!mcArr.isEmpty()) { sbData.append("*CHEMICAL APPLICATIONS\r\n"); sbData.append("@C CDATE CHCOD CHAMT CHME CHDEP CHT..CHNAME\r\n"); for (int idx = 0; idx < mcArr.size(); idx++) { secDataArr = (ArrayList) mcArr.get(idx); for (int i = 0; i < secDataArr.size(); i++) { secData = (HashMap) secDataArr.get(i); sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$s\r\n", idx + 1, //getObjectOr(secData, "ch", defValI).toString(), formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. cdate -> date getObjectOr(secData, "chcd", defValC).toString(), formatNumStr(5, secData, "chamt", defValR), getObjectOr(secData, "chacd", defValC).toString(), getObjectOr(secData, "chdep", defValC).toString(), getObjectOr(secData, "ch_targets", defValC).toString(), getObjectOr(secData, "ch_name", defValC).toString())); } } sbData.append("\r\n"); } // TILLAGE Section if (!mtArr.isEmpty()) { sbData.append("*TILLAGE AND ROTATIONS\r\n"); sbData.append("@T TDATE TIMPL TDEP TNAME\r\n"); for (int idx = 0; idx < mtArr.size(); idx++) { secDataArr = (ArrayList) mtArr.get(idx); for (int i = 0; i < secDataArr.size(); i++) { secData = (HashMap) secDataArr.get(i); sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$s\r\n", idx + 1, //getObjectOr(secData, "ti", defValI).toString(), formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. tdate -> date getObjectOr(secData, "tiimp", defValC).toString(), formatNumStr(5, secData, "tidep", defValR), getObjectOr(secData, "ti_name", defValC).toString())); } } sbData.append("\r\n"); } // ENVIRONMENT MODIFICATIONS Section if (!meArr.isEmpty()) { sbData.append("*ENVIRONMENT MODIFICATIONS\r\n"); sbData.append("@E ODATE EDAY ERAD EMAX EMIN ERAIN ECO2 EDEW EWIND ENVNAME\r\n"); for (int idx = 0, cnt = 1; idx < meArr.size(); idx++) { secDataArr = (ArrayList) meArr.get(idx); for (int i = 0; i < secDataArr.size(); i++) { secData = (HashMap) secDataArr.get(i); sbData.append(String.format("%1$2s%2$s\r\n", cnt, secData.get("em_data"))); // sbData.append(String.format("%1$2s%2$s\r\n", // idx + 1, // (String) secDataArr.get(i))); // sbData.append(String.format("%1$2s %2$5s %3$-1s%4$4s %5$-1s%6$4s %7$-1s%8$4s %9$-1s%10$4s %11$-1s%12$4s %13$-1s%14$4s %15$-1s%16$4s %17$-1s%18$4s %19$s\r\n", // idx + 1, //getObjectOr(secData, "em", defValI).toString(), // formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. emday -> date // getObjectOr(secData, "ecdyl", defValBlank).toString(), // formatNumStr(4, getObjectOr(secData, "emdyl", defValR), // getObjectOr(secData, "ecrad", defValBlank).toString(), // formatNumStr(4, getObjectOr(secData, "emrad", defValR), // getObjectOr(secData, "ecmax", defValBlank).toString(), // formatNumStr(4, getObjectOr(secData, "emmax", defValR), // getObjectOr(secData, "ecmin", defValBlank).toString(), // formatNumStr(4, getObjectOr(secData, "emmin", defValR), // getObjectOr(secData, "ecrai", defValBlank).toString(), // formatNumStr(4, getObjectOr(secData, "emrai", defValR), // getObjectOr(secData, "ecco2", defValBlank).toString(), // formatNumStr(4, getObjectOr(secData, "emco2", defValR), // getObjectOr(secData, "ecdew", defValBlank).toString(), // formatNumStr(4, getObjectOr(secData, "emdew", defValR), // getObjectOr(secData, "ecwnd", defValBlank).toString(), // formatNumStr(4, getObjectOr(secData, "emwnd", defValR), // getObjectOr(secData, "em_name", defValC).toString())); } } sbData.append("\r\n"); } // HARVEST DETAILS Section if (!mhArr.isEmpty()) { sbData.append("*HARVEST DETAILS\r\n"); sbData.append("@H HDATE HSTG HCOM HSIZE HPC HBPC HNAME\r\n"); for (int idx = 0; idx < mhArr.size(); idx++) { secDataArr = (ArrayList) mhArr.get(idx); for (int i = 0; i < secDataArr.size(); i++) { secData = (HashMap) secDataArr.get(i); sbData.append(String.format("%1$2s %2$5s %3$-5s %4$-5s %5$-5s %6$5s %7$5s %8$s\r\n", idx + 1, //getObjectOr(secData, "ha", defValI).toString(), formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. hdate -> date getObjectOr(secData, "hastg", defValC).toString(), getObjectOr(secData, "hacom", defValC).toString(), getObjectOr(secData, "hasiz", defValC).toString(), formatNumStr(5, secData, "hap%", defValR), formatNumStr(5, secData, "hab%", defValR), getObjectOr(secData, "ha_name", defValC).toString())); } } sbData.append("\r\n"); } // SIMULATION CONTROLS and AUTOMATIC MANAGEMENT Section if (!smArr.isEmpty()) { // Set Title list ArrayList smTitles = new ArrayList(); smTitles.add("@N GENERAL NYERS NREPS START SDATE RSEED SNAME.................... SMODEL\r\n"); smTitles.add("@N OPTIONS WATER NITRO SYMBI PHOSP POTAS DISES CHEM TILL CO2\r\n"); smTitles.add("@N METHODS WTHER INCON LIGHT EVAPO INFIL PHOTO HYDRO NSWIT MESOM MESEV MESOL\r\n"); smTitles.add("@N MANAGEMENT PLANT IRRIG FERTI RESID HARVS\r\n"); smTitles.add("@N OUTPUTS FNAME OVVEW SUMRY FROPT GROUT CAOUT WAOUT NIOUT MIOUT DIOUT VBOSE CHOUT OPOUT\r\n"); smTitles.add("@ AUTOMATIC MANAGEMENT\r\n@N PLANTING PFRST PLAST PH2OL PH2OU PH2OD PSTMX PSTMN\r\n"); smTitles.add("@N IRRIGATION IMDEP ITHRL ITHRU IROFF IMETH IRAMT IREFF\r\n"); smTitles.add("@N NITROGEN NMDEP NMTHR NAMNT NCODE NAOFF\r\n"); smTitles.add("@N RESIDUES RIPCN RTIME RIDEP\r\n"); smTitles.add("@N HARVEST HFRST HLAST HPCNP HPCNR\r\n"); String[] keys = new String[10]; keys[0] = "sm_general"; keys[1] = "sm_options"; keys[2] = "sm_methods"; keys[3] = "sm_management"; keys[4] = "sm_outputs"; keys[5] = "sm_planting"; keys[6] = "sm_irrigation"; keys[7] = "sm_nitrogen"; keys[8] = "sm_residues"; keys[9] = "sm_harvests"; // Loop all the simulation control records sbData.append("*SIMULATION CONTROLS\r\n"); for (int idx = 0; idx < smArr.size(); idx++) { secData = (HashMap) smArr.get(idx); if (secData.containsKey("sm_general")) { secData.remove("sm"); // Object[] keys = secData.keySet().toArray(); for (int i = 0; i < keys.length; i++) { sbData.append(smTitles.get(i)); sbData.append(String.format("%2s ", idx + 1)).append(((String) secData.get(keys[i]))).append("\r\n"); if (i == 4) { sbData.append("\r\n"); } } sbData.append("\r\n"); } else { sbData.append(createSMMAStr(idx + 1, secData)); } } } else { sbData.append("*SIMULATION CONTROLS\r\n"); sbData.append(createSMMAStr(1, new HashMap())); } // Output finish bwX.write(sbError.toString()); bwX.write(sbGenData.toString()); bwX.write(sbNotesData.toString()); bwX.write(sbData.toString()); bwX.close(); } catch (IOException e) { LOG.error(DssatCommonOutput.getStackTrace(e)); } } /** * Create string of Simulation Control and Automatic Management Section * * @param smid simulation index number * @param trData date holder for one treatment data * @return date string with format of "yyddd" */ private String createSMMAStr(int smid, HashMap trData) { StringBuilder sb = new StringBuilder(); String nitro = "Y"; String water = "Y"; String co2 = "M"; String harOpt = "M"; String sdate; String sm = String.format("%2d", smid); ArrayList<HashMap> dataArr; HashMap subData; // // Check if the meta data of fertilizer is not "N" ("Y" or null) // if (!getValueOr(expData, "fertilizer", "").equals("N")) { // // // Check if necessary data is missing in all the event records // // P.S. rule changed since all the necessary data has a default value for it // dataArr = (ArrayList) getObjectOr(trData, "fertilizer", new ArrayList()); // if (dataArr.isEmpty()) { // nitro = "N"; // } //// for (int i = 0; i < dataArr.size(); i++) { //// subData = dataArr.get(i); //// if (getValueOr(subData, "date", "").equals("") //// || getValueOr(subData, "fecd", "").equals("") //// || getValueOr(subData, "feacd", "").equals("") //// || getValueOr(subData, "feamn", "").equals("")) { //// nitro = "N"; //// break; //// } //// } // } // // Check if the meta data of irrigation is not "N" ("Y" or null) // if (!getValueOr(expData, "irrigation", "").equals("N")) { // // // Check if necessary data is missing in all the event records // dataArr = (ArrayList) getObjectOr(trData, "irrigation", new ArrayList()); // for (int i = 0; i < dataArr.size(); i++) { // subData = dataArr.get(i); // if (getValueOr(subData, "date", "").equals("") // || getValueOr(subData, "irval", "").equals("")) { // water = "N"; // break; // } // } // } // Check if CO2Y value is provided and the value is positive, then set CO2 switch to W String co2y = getValueOr(trData, "co2y", "").trim(); if (!co2y.equals("") && !co2y.startsWith("-")) { co2 = "W"; } sdate = getValueOr(trData, "sdat", "").toString(); if (sdate.equals("")) { subData = (HashMap) getObjectOr(trData, "planting", new HashMap()); sdate = getValueOr(subData, "date", defValD); } sdate = formatDateStr(sdate); sdate = String.format("%5s", sdate); if (!getValueOr(trData, "hadat", "").trim().equals("")) { LOG.info(getValueOr(trData, "hadat", "")); harOpt = "R"; } else { LOG.info("NO HARVEST DATE FOUND"); } sb.append("@N GENERAL NYERS NREPS START SDATE RSEED SNAME....................\r\n"); sb.append(sm).append(" GE 1 1 S ").append(sdate).append(" 2150 DEFAULT SIMULATION CONTROL\r\n"); sb.append("@N OPTIONS WATER NITRO SYMBI PHOSP POTAS DISES CHEM TILL CO2\r\n"); sb.append(sm).append(" OP ").append(water).append(" ").append(nitro).append(" Y N N N N Y ").append(co2).append("\r\n"); sb.append("@N METHODS WTHER INCON LIGHT EVAPO INFIL PHOTO HYDRO NSWIT MESOM MESEV MESOL\r\n"); sb.append(sm).append(" ME M M E R S L R 1 P S 2\r\n"); // P.S. 2012/09/02 MESOM "G" -> "P" sb.append("@N MANAGEMENT PLANT IRRIG FERTI RESID HARVS\r\n"); sb.append(sm).append(" MA R R R R ").append(harOpt).append("\r\n"); sb.append("@N OUTPUTS FNAME OVVEW SUMRY FROPT GROUT CAOUT WAOUT NIOUT MIOUT DIOUT VBOSE CHOUT OPOUT\r\n"); sb.append(sm).append(" OU N Y Y 1 Y Y N N N N N N N\r\n\r\n"); sb.append("@ AUTOMATIC MANAGEMENT\r\n"); sb.append("@N PLANTING PFRST PLAST PH2OL PH2OU PH2OD PSTMX PSTMN\r\n"); sb.append(sm).append(" PL 82050 82064 40 100 30 40 10\r\n"); sb.append("@N IRRIGATION IMDEP ITHRL ITHRU IROFF IMETH IRAMT IREFF\r\n"); sb.append(sm).append(" IR 30 50 100 GS000 IR001 10 1.00\r\n"); sb.append("@N NITROGEN NMDEP NMTHR NAMNT NCODE NAOFF\r\n"); sb.append(sm).append(" NI 30 50 25 FE001 GS000\r\n"); sb.append("@N RESIDUES RIPCN RTIME RIDEP\r\n"); sb.append(sm).append(" RE 100 1 20\r\n"); sb.append("@N HARVEST HFRST HLAST HPCNP HPCNR\r\n"); sb.append(sm).append(" HA 0 83057 100 0\r\n\r\n"); return sb.toString(); } /** * Get index value of the record and set new id value in the array * * @param m sub data * @param arr array of sub data * @return current index value of the sub data */ private int setSecDataArr(HashMap m, ArrayList arr) { if (!m.isEmpty()) { for (int j = 0; j < arr.size(); j++) { if (arr.get(j).equals(m)) { return j + 1; } } arr.add(m); return arr.size(); } else { return 0; } } /** * Get index value of the record and set new id value in the array * * @param inArr sub array of data * @param outArr array of sub data * @return current index value of the sub data */ private int setSecDataArr(ArrayList inArr, ArrayList outArr) { if (!inArr.isEmpty()) { for (int j = 0; j < outArr.size(); j++) { if (outArr.get(j).equals(inArr)) { return j + 1; } } outArr.add(inArr); return outArr.size(); } else { return 0; } } /** * To check if there is plot info data existed in the experiment * * @param expData experiment data holder * @return the boolean value for if plot info exists */ private boolean isPlotInfoExist(Map expData) { String[] plotIds = {"plta", "pltr#", "pltln", "pldr", "pltsp", "pllay", "pltha", "plth#", "plthl", "plthm"}; for (int i = 0; i < plotIds.length; i++) { if (!getValueOr(expData, plotIds[i], "").equals("")) { return true; } } return false; } /** * To check if there is soil analysis info data existed in the experiment * * @param expData initial condition layer data array * @return the boolean value for if soil analysis info exists */ private boolean isSoilAnalysisExist(ArrayList<HashMap> icSubArr) { for (int i = 0; i < icSubArr.size(); i++) { if (!getValueOr(icSubArr.get(i), "slsc", "").equals("")) { return true; } } return false; } /** * Get sub data array from experiment data object * * @param expData experiment data holder * @param blockName top level block name * @param dataListName sub array name * @return sub data array */ private ArrayList<HashMap> getDataList(Map expData, String blockName, String dataListName) { HashMap dataBlock = getObjectOr(expData, blockName, new HashMap()); return getObjectOr(dataBlock, dataListName, new ArrayList<HashMap>()); } /** * Try to translate 3-bit crid to 2-bit version stored in the map * * @param cuData the cultivar data record * @param id the field id for contain crop id info */ private void translateTo2BitCrid(HashMap cuData, String id) { String crid = getObjectOr(cuData, id, ""); if (!crid.equals("")) { // DssatCRIDHelper crids = new DssatCRIDHelper(); cuData.put(id, DssatCRIDHelper.get2BitCrid(crid)); } } /** * Try to translate 3-bit crid to 2-bit version stored in the map * * @param cuData the cultivar data record */ private void translateTo2BitCrid(HashMap cuData) { translateTo2BitCrid(cuData, "crid"); } /** * Get soil/weather data from data holder * * @param expData The experiment data holder * @param key The key name for soil/weather section * @return */ private ArrayList readSWData(HashMap expData, String key) { ArrayList ret; Object soil = expData.get(key); if (soil != null) { if (soil instanceof ArrayList) { ret = (ArrayList) soil; } else { ret = new ArrayList(); ret.add(soil); } } else { ret = new ArrayList(); } return ret; } }
src/main/java/org/agmip/translators/dssat/DssatXFileOutput.java
package org.agmip.translators.dssat; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import static org.agmip.translators.dssat.DssatCommonInput.copyItem; import static org.agmip.util.MapUtil.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * DSSAT Experiment Data I/O API Class * * @author Meng Zhang * @version 1.0 */ public class DssatXFileOutput extends DssatCommonOutput { private static final Logger LOG = LoggerFactory.getLogger(DssatXFileOutput.class); // public static final DssatCRIDHelper crHelper = new DssatCRIDHelper(); /** * DSSAT Experiment Data Output method * * @param arg0 file output path * @param result data holder object */ @Override public void writeFile(String arg0, Map result) { // Initial variables HashMap expData = (HashMap) result; ArrayList<HashMap> soilArr = readSWData(expData, "soil"); ArrayList<HashMap> wthArr = readSWData(expData, "weather"); HashMap soilData; HashMap wthData; BufferedWriter bwX; // output object StringBuilder sbGenData = new StringBuilder(); // construct the data info in the output StringBuilder sbNotesData = new StringBuilder(); // construct the data info in the output StringBuilder sbData = new StringBuilder(); // construct the data info in the output StringBuilder eventPart2 = new StringBuilder(); // output string for second part of event data HashMap secData; ArrayList subDataArr; // Arraylist for event data holder HashMap subData; ArrayList secDataArr; // Arraylist for section data holder HashMap sqData; ArrayList<HashMap> evtArr; // Arraylist for section data holder HashMap evtData; // int trmnNum; // total numbers of treatment in the data holder int cuNum; // total numbers of cultivars in the data holder int flNum; // total numbers of fields in the data holder int saNum; // total numbers of soil analysis in the data holder int icNum; // total numbers of initial conditions in the data holder int mpNum; // total numbers of plaintings in the data holder int miNum; // total numbers of irrigations in the data holder int mfNum; // total numbers of fertilizers in the data holder int mrNum; // total numbers of residues in the data holder int mcNum; // total numbers of chemical in the data holder int mtNum; // total numbers of tillage in the data holder int meNum; // total numbers of enveronment modification in the data holder int mhNum; // total numbers of harvest in the data holder int smNum; // total numbers of simulation controll record ArrayList<HashMap> sqArr; // array for treatment record ArrayList cuArr = new ArrayList(); // array for cultivars record ArrayList flArr = new ArrayList(); // array for fields record ArrayList saArr = new ArrayList(); // array for soil analysis record ArrayList icArr = new ArrayList(); // array for initial conditions record ArrayList mpArr = new ArrayList(); // array for plaintings record ArrayList miArr = new ArrayList(); // array for irrigations record ArrayList mfArr = new ArrayList(); // array for fertilizers record ArrayList mrArr = new ArrayList(); // array for residues record ArrayList mcArr = new ArrayList(); // array for chemical record ArrayList mtArr = new ArrayList(); // array for tillage record ArrayList meArr = new ArrayList(); // array for enveronment modification record ArrayList mhArr = new ArrayList(); // array for harvest record ArrayList smArr = new ArrayList(); // array for simulation control record // String exName; try { // Set default value for missing data if (expData == null || expData.isEmpty()) { return; } // decompressData((HashMap) result); setDefVal(); // Initial BufferedWriter String fileName = getFileName(result, "X"); arg0 = revisePath(arg0); outputFile = new File(arg0 + fileName); bwX = new BufferedWriter(new FileWriter(outputFile)); // Output XFile // EXP.DETAILS Section sbGenData.append(String.format("*EXP.DETAILS: %1$-10s %2$s\r\n\r\n", getFileName(result, "").replaceAll("\\.", ""), getObjectOr(expData, "local_name", defValBlank).toString())); // GENERAL Section sbGenData.append("*GENERAL\r\n"); // People if (!getObjectOr(expData, "person_notes", "").equals("")) { sbGenData.append(String.format("@PEOPLE\r\n %1$s\r\n", getObjectOr(expData, "person_notes", defValBlank).toString())); } // Address if (getObjectOr(expData, "institution", "").equals("")) { // if (!getObjectOr(expData, "fl_loc_1", "").equals("") // && getObjectOr(expData, "fl_loc_2", "").equals("") // && getObjectOr(expData, "fl_loc_3", "").equals("")) { // sbGenData.append(String.format("@ADDRESS\r\n %3$s, %2$s, %1$s\r\n", // getObjectOr(expData, "fl_loc_1", defValBlank).toString(), // getObjectOr(expData, "fl_loc_2", defValBlank).toString(), // getObjectOr(expData, "fl_loc_3", defValBlank).toString())); // } } else { sbGenData.append(String.format("@ADDRESS\r\n %1$s\r\n", getObjectOr(expData, "institution", defValBlank).toString())); } // Site if (!getObjectOr(expData, "site_name", "").equals("")) { sbGenData.append(String.format("@SITE\r\n %1$s\r\n", getObjectOr(expData, "site_name", defValBlank).toString())); } // Plot Info if (isPlotInfoExist(expData)) { sbGenData.append("@ PAREA PRNO PLEN PLDR PLSP PLAY HAREA HRNO HLEN HARM.........\r\n"); sbGenData.append(String.format(" %1$6s %2$5s %3$5s %4$5s %5$5s %6$-5s %7$5s %8$5s %9$5s %10$-15s\r\n", formatNumStr(6, expData, "plta", defValR), formatNumStr(5, expData, "pltr#", defValI), formatNumStr(5, expData, "pltln", defValR), formatNumStr(5, expData, "pldr", defValI), formatNumStr(5, expData, "pltsp", defValI), getObjectOr(expData, "pllay", defValC).toString(), formatNumStr(5, expData, "pltha", defValR), formatNumStr(5, expData, "plth#", defValI), formatNumStr(5, expData, "plthl", defValR), getObjectOr(expData, "plthm", defValC).toString())); } // Notes if (!getObjectOr(expData, "tr_notes", "").equals("")) { sbNotesData.append("@NOTES\r\n"); String notes = getObjectOr(expData, "tr_notes", defValC).toString(); notes = notes.replaceAll("\\\\r\\\\n", "\r\n"); // If notes contain newline code, then write directly if (notes.indexOf("\r\n") >= 0) { // sbData.append(String.format(" %1$s\r\n", notes)); sbNotesData.append(notes); } // Otherwise, add newline for every 75-bits charactors else { while (notes.length() > 75) { sbNotesData.append(" ").append(notes.substring(0, 75)).append("\r\n"); notes = notes.substring(75); } sbNotesData.append(" ").append(notes).append("\r\n"); } } sbData.append("\r\n"); // TREATMENT Section sqArr = getDataList(expData, "dssat_sequence", "data"); evtArr = getDataList(expData, "management", "events"); ArrayList<HashMap> rootArr = getObjectOr(expData, "dssat_root", new ArrayList()); ArrayList<HashMap> meOrgArr = getDataList(expData, "dssat_environment_modification", "data"); ArrayList<HashMap> smOrgArr = getDataList(expData, "dssat_simulation_control", "data"); String seqId; String em; String sm; sbData.append("*TREATMENTS -------------FACTOR LEVELS------------\r\n"); sbData.append("@N R O C TNAME.................... CU FL SA IC MP MI MF MR MC MT ME MH SM\r\n"); // if there is no sequence info, create dummy data if (sqArr.isEmpty()) { sqArr.add(new HashMap()); } // Set sequence related block info for (int i = 0; i < sqArr.size(); i++) { sqData = sqArr.get(i); seqId = getValueOr(sqData, "seqid", defValBlank); em = getValueOr(sqData, "em", defValBlank); sm = getValueOr(sqData, "sm", defValBlank); if (i < soilArr.size()) { soilData = soilArr.get(i); } else if (soilArr.isEmpty()) { soilData = new HashMap(); } else { soilData = soilArr.get(0); } if (soilData == null) { soilData = new HashMap(); } if (i < wthArr.size()) { wthData = wthArr.get(i); } else if (wthArr.isEmpty()) { wthData = new HashMap(); } else { wthData = wthArr.get(0); } if (wthData == null) { wthData = new HashMap(); } HashMap cuData = new HashMap(); HashMap flData = new HashMap(); HashMap mpData = new HashMap(); ArrayList<HashMap> miSubArr = new ArrayList<HashMap>(); ArrayList<HashMap> mfSubArr = new ArrayList<HashMap>(); ArrayList<HashMap> mrSubArr = new ArrayList<HashMap>(); ArrayList<HashMap> mcSubArr = new ArrayList<HashMap>(); ArrayList<HashMap> mtSubArr = new ArrayList<HashMap>(); ArrayList<HashMap> meSubArr = new ArrayList<HashMap>(); ArrayList<HashMap> mhSubArr = new ArrayList<HashMap>(); HashMap smData = new HashMap(); HashMap rootData; // Set exp root info if (i < rootArr.size()) { rootData = rootArr.get(i); } else { rootData = expData; } // Set field info copyItem(flData, rootData, "id_field"); flData.put("wst_id", getWthFileName(rootData)); // if (i < rootArr.size()) { // // copyItem(flData, expData, "wst_id"); // flData.put("wst_id", getWthFileName(rootData)); // } else { // flData.put("wst_id", getWthFileName(wthData)); // } copyItem(flData, rootData, "flsl"); copyItem(flData, rootData, "flob"); copyItem(flData, rootData, "fl_drntype"); copyItem(flData, rootData, "fldrd"); copyItem(flData, rootData, "fldrs"); copyItem(flData, rootData, "flst"); if (soilData.get("sltx") != null) { copyItem(flData, soilData, "sltx"); } else { copyItem(flData, rootData, "sltx"); } copyItem(flData, soilData, "sldp"); copyItem(flData, rootData, "soil_id"); copyItem(flData, rootData, "fl_name"); copyItem(flData, rootData, "fl_lat"); copyItem(flData, rootData, "fl_long"); copyItem(flData, rootData, "flele"); copyItem(flData, rootData, "farea"); copyItem(flData, rootData, "fllwr"); copyItem(flData, rootData, "flsla"); copyItem(flData, getObjectOr(rootData, "dssat_info", new HashMap()), "flhst"); copyItem(flData, getObjectOr(rootData, "dssat_info", new HashMap()), "fhdur"); // remove the "_trno" in the soil_id when soil analysis is available String soilId = getValueOr(flData, "soil_id", ""); if (soilId.length() > 10 && soilId.matches("\\w+_\\d+")) { flData.put("soil_id", getSoilID(flData)); } flNum = setSecDataArr(flData, flArr); // Set initial condition info icNum = setSecDataArr(getObjectOr(rootData, "initial_conditions", new HashMap()), icArr); // Set environment modification info for (int j = 0; j < meOrgArr.size(); j++) { if (em.equals(meOrgArr.get(j).get("em"))) { HashMap tmp = new HashMap(); tmp.putAll(meOrgArr.get(j)); tmp.remove("em"); meSubArr.add(tmp); } } // Set soil analysis info // ArrayList<HashMap> icSubArr = getDataList(expData, "initial_condition", "soilLayer"); ArrayList<HashMap> soilLarys = getObjectOr(soilData, "soilLayer", new ArrayList()); // // If it is stored in the initial condition block // if (isSoilAnalysisExist(icSubArr)) { // HashMap saData = new HashMap(); // ArrayList<HashMap> saSubArr = new ArrayList<HashMap>(); // HashMap saSubData; // for (int i = 0; i < icSubArr.size(); i++) { // saSubData = new HashMap(); // copyItem(saSubData, icSubArr.get(i), "sabl", "icbl", false); // copyItem(saSubData, icSubArr.get(i), "sasc", "slsc", false); // saSubArr.add(saSubData); // } // copyItem(saData, soilData, "sadat"); // saData.put("soilLayer", saSubArr); // saNum = setSecDataArr(saData, saArr); // } else // If it is stored in the soil block if (isSoilAnalysisExist(soilLarys)) { HashMap saData = new HashMap(); ArrayList<HashMap> saSubArr = new ArrayList<HashMap>(); HashMap saSubData; for (int j = 0; j < soilLarys.size(); j++) { saSubData = new HashMap(); copyItem(saSubData, soilLarys.get(j), "sabl", "sllb", false); copyItem(saSubData, soilLarys.get(j), "sasc", "slsc", false); saSubArr.add(saSubData); } copyItem(saData, soilData, "sadat"); saData.put("soilLayer", saSubArr); saNum = setSecDataArr(saData, saArr); } else { saNum = 0; } // Set simulation control info for (int j = 0; j < smOrgArr.size(); j++) { if (sm.equals(smOrgArr.get(j).get("sm"))) { smData.putAll(smOrgArr.get(j)); smData.remove("sm"); break; } } // if (smData.isEmpty()) { // smData.put("fertilizer", mfSubArr); // smData.put("irrigation", miSubArr); // smData.put("planting", mpData); // } copyItem(smData, rootData, "sdat"); copyItem(smData, getObjectOr(wthData, "weather", new HashMap()), "co2y"); // Loop all event data for (int j = 0; j < evtArr.size(); j++) { evtData = new HashMap(); evtData.putAll(evtArr.get(j)); // Check if it has same sequence number if (getValueOr(evtData, "seqid", defValBlank).equals(seqId)) { evtData.remove("seqid"); // Planting event if (getValueOr(evtData, "event", defValBlank).equals("planting")) { // Set cultivals info copyItem(cuData, evtData, "cul_name"); copyItem(cuData, evtData, "crid"); copyItem(cuData, evtData, "cul_id"); copyItem(cuData, evtData, "dssat_cul_id"); copyItem(cuData, evtData, "rm"); copyItem(cuData, evtData, "cul_notes"); translateTo2BitCrid(cuData); // Set planting info mpData.putAll(evtData); mpData.remove("cul_name"); } // irrigation event else if (getValueOr(evtData, "event", "").equals("irrigation")) { miSubArr.add(evtData); } // fertilizer event else if (getValueOr(evtData, "event", "").equals("fertilizer")) { mfSubArr.add(evtData); } // organic_matter event else if (getValueOr(evtData, "event", "").equals("organic_matter")) { // P.S. change event name to organic-materials; Back to organic_matter again. mrSubArr.add(evtData); } // chemical event else if (getValueOr(evtData, "event", "").equals("chemical")) { mcSubArr.add(evtData); } // tillage event else if (getValueOr(evtData, "event", "").equals("tillage")) { mtSubArr.add(evtData); // } // environment_modification event // else if (getValueOr(evtData, "event", "").equals("environment_modification")) { // meSubArr.add(evtData); } // harvest event else if (getValueOr(evtData, "event", "").equals("harvest")) { mhSubArr.add(evtData); } else { } } else { } } // If alternative fields are avaiable for fertilizer data if (mfSubArr.isEmpty()) { if (!getObjectOr(result, "fen_tot", "").equals("") || !getObjectOr(result, "fep_tot", "").equals("") || !getObjectOr(result, "fek_tot", "").equals("")) { mfSubArr.add(new HashMap()); } } cuNum = setSecDataArr(cuData, cuArr); mpNum = setSecDataArr(mpData, mpArr); miNum = setSecDataArr(miSubArr, miArr); mfNum = setSecDataArr(mfSubArr, mfArr); mrNum = setSecDataArr(mrSubArr, mrArr); mcNum = setSecDataArr(mcSubArr, mcArr); mtNum = setSecDataArr(mtSubArr, mtArr); meNum = setSecDataArr(meSubArr, meArr); mhNum = setSecDataArr(mhSubArr, mhArr); smNum = setSecDataArr(smData, smArr); if (smNum == 0) { smNum = 1; } sbData.append(String.format("%1$-3s%2$1s %3$1s %4$1s %5$-25s %6$2s %7$2s %8$2s %9$2s %10$2s %11$2s %12$2s %13$2s %14$2s %15$2s %16$2s %17$2s %18$2s\r\n", String.format("%2s", getValueOr(sqData, "trno", "1")), // For 3-bit treatment number getValueOr(sqData, "sq", "1").toString(), // P.S. default value here is based on document DSSAT vol2.pdf getValueOr(sqData, "op", "1").toString(), getValueOr(sqData, "co", "0").toString(), formatStr(25, sqData, "trt_name", getValueOr(rootData, "trt_name", getValueOr(rootData, "exname", defValC))), cuNum, //getObjectOr(data, "ge", defValI).toString(), flNum, //getObjectOr(data, "fl", defValI).toString(), saNum, //getObjectOr(data, "sa", defValI).toString(), icNum, //getObjectOr(data, "ic", defValI).toString(), mpNum, //getObjectOr(data, "pl", defValI).toString(), miNum, //getObjectOr(data, "ir", defValI).toString(), mfNum, //getObjectOr(data, "fe", defValI).toString(), mrNum, //getObjectOr(data, "om", defValI).toString(), mcNum, //getObjectOr(data, "ch", defValI).toString(), mtNum, //getObjectOr(data, "ti", defValI).toString(), meNum, //getObjectOr(data, "em", defValI).toString(), mhNum, //getObjectOr(data, "ha", defValI).toString(), smNum)); // 1 } sbData.append("\r\n"); // CULTIVARS Section if (!cuArr.isEmpty()) { sbData.append("*CULTIVARS\r\n"); sbData.append("@C CR INGENO CNAME\r\n"); for (int idx = 0; idx < cuArr.size(); idx++) { secData = (HashMap) cuArr.get(idx); // String cul_id = defValC; String crid = getObjectOr(secData, "crid", ""); // Checl if necessary data is missing if (crid.equals("")) { sbError.append("! Warning: Incompleted record because missing data : [crid]\r\n"); // } else { // // Set cultivar id a default value deponds on the crop id // if (crid.equals("MZ")) { // cul_id = "990002"; // } else { // cul_id = "999999"; // } // } // if (getObjectOr(secData, "cul_id", "").equals("")) { // sbError.append("! Warning: Incompleted record because missing data : [cul_id], and will use default value '").append(cul_id).append("'\r\n"); } sbData.append(String.format("%1$2s %2$-2s %3$-6s %4$s\r\n", idx + 1, //getObjectOr(secData, "ge", defValI).toString(), formatStr(2, secData, "crid", defValBlank), // P.S. if missing, default value use blank string formatStr(6, secData, "dssat_cul_id", getObjectOr(secData, "cul_id", defValC)), // P.S. Set default value which is deponds on crid(Cancelled) getObjectOr(secData, "cul_name", defValC).toString())); if (!getObjectOr(secData, "rm", "").equals("") || !getObjectOr(secData, "cul_notes", "").equals("")) { if (sbNotesData.toString().equals("")) { sbNotesData.append("@NOTES\r\n"); } sbNotesData.append(" Cultivar Additional Info\r\n"); sbNotesData.append(" C RM CNAME CUL_NOTES\r\n"); sbNotesData.append(String.format("%1$2s %2$4s %3$s\r\n", idx + 1, //getObjectOr(secData, "ge", defValI).toString(), getObjectOr(secData, "rm", defValC).toString(), getObjectOr(secData, "cul_notes", defValC).toString())); } } sbData.append("\r\n"); } else { sbError.append("! Warning: There is no cultivar data in the experiment.\r\n"); } // FIELDS Section if (!flArr.isEmpty()) { sbData.append("*FIELDS\r\n"); sbData.append("@L ID_FIELD WSTA.... FLSA FLOB FLDT FLDD FLDS FLST SLTX SLDP ID_SOIL FLNAME\r\n"); eventPart2 = new StringBuilder(); eventPart2.append("@L ...........XCRD ...........YCRD .....ELEV .............AREA .SLEN .FLWR .SLAS FLHST FHDUR\r\n"); } else { sbError.append("! Warning: There is no field data in the experiment.\r\n"); } for (int idx = 0; idx < flArr.size(); idx++) { secData = (HashMap) flArr.get(idx); // Check if the necessary is missing if (getObjectOr(secData, "wst_id", "").equals("")) { sbError.append("! Warning: Incompleted record because missing data : [wst_id]\r\n"); } String soil_id = getValueOr(result, "soil_id", defValC); if (soil_id.equals("")) { sbError.append("! Warning: Incompleted record because missing data : [soil_id]\r\n"); } else if (soil_id.length() > 10) { sbError.append("! Warning: Oversized data : [soil_id] ").append(soil_id).append("\r\n"); } sbData.append(String.format("%1$2s %2$-8s %3$-8s %4$5s %5$5s %6$-5s %7$5s %8$5s %9$-5s %10$-5s%11$5s %12$-10s %13$s\r\n", // P.S. change length definition to match current way idx + 1, //getObjectOr(secData, "fl", defValI).toString(), formatStr(8, secData, "id_field", defValC), formatStr(8, secData, "wst_id", defValC), formatStr(4, secData, "flsl", defValC), formatNumStr(5, secData, "flob", defValR), formatStr(5, secData, "fl_drntype", defValC), formatNumStr(5, secData, "fldrd", defValR), formatNumStr(5, secData, "fldrs", defValR), formatStr(5, secData, "flst", defValC), formatStr(5, secData, "sltx", defValC), formatNumStr(5, secData, "sldp", defValR), soil_id, getObjectOr(secData, "fl_name", defValC).toString())); eventPart2.append(String.format("%1$2s %2$15s %3$15s %4$9s %5$17s %6$5s %7$5s %8$5s %9$5s %10$5s\r\n", idx + 1, //getObjectOr(secData, "fl", defValI).toString(), formatNumStr(15, secData, "fl_long", defValR), formatNumStr(15, secData, "fl_lat", defValR), formatNumStr(9, secData, "flele", defValR), formatNumStr(17, secData, "farea", defValR), "-99", // P.S. SLEN keeps -99 formatNumStr(5, secData, "fllwr", defValR), formatNumStr(5, secData, "flsla", defValR), formatStr(5, secData, "flhst", defValC), formatNumStr(5, secData, "fhdur", defValR))); } if (!flArr.isEmpty()) { sbData.append(eventPart2.toString()).append("\r\n"); } // SOIL ANALYSIS Section if (!saArr.isEmpty()) { sbData.append("*SOIL ANALYSIS\r\n"); for (int idx = 0; idx < saArr.size(); idx++) { secData = (HashMap) saArr.get(idx); sbData.append("@A SADAT SMHB SMPX SMKE SANAME\r\n"); sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$s\r\n", idx + 1, //getObjectOr(secData, "sa", defValI).toString(), formatDateStr(getObjectOr(secData, "sadat", defValD).toString()), getObjectOr(secData, "samhb", defValC).toString(), getObjectOr(secData, "sampx", defValC).toString(), getObjectOr(secData, "samke", defValC).toString(), getObjectOr(secData, "sa_name", defValC).toString())); subDataArr = (ArrayList) getObjectOr(secData, "soilLayer", new ArrayList()); if (!subDataArr.isEmpty()) { sbData.append("@A SABL SADM SAOC SANI SAPHW SAPHB SAPX SAKE SASC\r\n"); } for (int j = 0; j < subDataArr.size(); j++) { subData = (HashMap) subDataArr.get(j); sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s\r\n", idx + 1, //getObjectOr(subData, "sa", defValI).toString(), formatNumStr(5, subData, "sabl", defValR), formatNumStr(5, subData, "sabdm", defValR), formatNumStr(5, subData, "saoc", defValR), formatNumStr(5, subData, "sani", defValR), formatNumStr(5, subData, "saphw", defValR), formatNumStr(5, subData, "saphb", defValR), formatNumStr(5, subData, "sapx", defValR), formatNumStr(5, subData, "sake", defValR), formatNumStr(5, subData, "sasc", defValR))); } } sbData.append("\r\n"); } // INITIAL CONDITIONS Section if (!icArr.isEmpty()) { sbData.append("*INITIAL CONDITIONS\r\n"); for (int idx = 0; idx < icArr.size(); idx++) { secData = (HashMap) icArr.get(idx); translateTo2BitCrid(secData, "icpcr"); sbData.append("@C PCR ICDAT ICRT ICND ICRN ICRE ICWD ICRES ICREN ICREP ICRIP ICRID ICNAME\r\n"); sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$5s %13$5s %14$s\r\n", idx + 1, //getObjectOr(secData, "ic", defValI).toString(), getObjectOr(secData, "icpcr", defValC).toString(), formatDateStr(getObjectOr(secData, "icdat", getPdate(result)).toString()), formatNumStr(5, secData, "icrt", defValR), formatNumStr(5, secData, "icnd", defValR), formatNumStr(5, secData, "icrz#", defValR), formatNumStr(5, secData, "icrze", defValR), formatNumStr(5, secData, "icwt", defValR), formatNumStr(5, secData, "icrag", defValR), formatNumStr(5, secData, "icrn", defValR), formatNumStr(5, secData, "icrp", defValR), formatNumStr(5, secData, "icrip", defValR), formatNumStr(5, secData, "icrdp", defValR), getObjectOr(secData, "ic_name", defValC).toString())); subDataArr = (ArrayList) getObjectOr(secData, "soilLayer", new ArrayList()); if (!subDataArr.isEmpty()) { sbData.append("@C ICBL SH2O SNH4 SNO3\r\n"); } for (int j = 0; j < subDataArr.size(); j++) { subData = (HashMap) subDataArr.get(j); sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s\r\n", idx + 1, //getObjectOr(subData, "ic", defValI).toString(), formatNumStr(5, subData, "icbl", defValR), formatNumStr(5, subData, "ich2o", defValR), formatNumStr(5, subData, "icnh4", defValR), formatNumStr(5, subData, "icno3", defValR))); } } sbData.append("\r\n"); } // PLANTING DETAILS Section if (!mpArr.isEmpty()) { sbData.append("*PLANTING DETAILS\r\n"); sbData.append("@P PDATE EDATE PPOP PPOE PLME PLDS PLRS PLRD PLDP PLWT PAGE PENV PLPH SPRL PLNAME\r\n"); for (int idx = 0; idx < mpArr.size(); idx++) { secData = (HashMap) mpArr.get(idx); // Check if necessary data is missing String pdate = getObjectOr(secData, "date", ""); if (pdate.equals("")) { sbError.append("! Warning: Incompleted record because missing data : [pdate]\r\n"); } else if (formatDateStr(pdate).equals(defValD)) { sbError.append("! Warning: Incompleted record because variable [pdate] with invalid value [").append(pdate).append("]\r\n"); } if (getObjectOr(secData, "plpop", getObjectOr(secData, "plpoe", "")).equals("")) { sbError.append("! Warning: Incompleted record because missing data : [plpop] and [plpoe]\r\n"); } if (getObjectOr(secData, "plrs", "").equals("")) { sbError.append("! Warning: Incompleted record because missing data : [plrs]\r\n"); } // if (getObjectOr(secData, "plma", "").equals("")) { // sbError.append("! Warning: missing data : [plma], and will automatically use default value 'S'\r\n"); // } // if (getObjectOr(secData, "plds", "").equals("")) { // sbError.append("! Warning: missing data : [plds], and will automatically use default value 'R'\r\n"); // } // if (getObjectOr(secData, "pldp", "").equals("")) { // sbError.append("! Warning: missing data : [pldp], and will automatically use default value '7'\r\n"); // } // mm -> cm String pldp = getObjectOr(secData, "pldp", ""); if (!pldp.equals("")) { try { BigDecimal pldpBD = new BigDecimal(pldp); pldpBD = pldpBD.divide(new BigDecimal("10")); secData.put("pldp", pldpBD.toString()); } catch (NumberFormatException e) { } } sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$5s %13$5s %14$5s %15$5s %16$s\r\n", idx + 1, //getObjectOr(data, "pl", defValI).toString(), formatDateStr(getObjectOr(secData, "date", defValD).toString()), formatDateStr(getObjectOr(secData, "pldae", defValD).toString()), formatNumStr(5, secData, "plpop", getObjectOr(secData, "plpoe", defValR)), formatNumStr(5, secData, "plpoe", getObjectOr(secData, "plpop", defValR)), getObjectOr(secData, "plma", defValC).toString(), // P.S. Set default value as "S"(Cancelled) getObjectOr(secData, "plds", defValC).toString(), // P.S. Set default value as "R"(Cancelled) formatNumStr(5, secData, "plrs", defValR), formatNumStr(5, secData, "plrd", defValR), formatNumStr(5, secData, "pldp", defValR), // P.S. Set default value as "7"(Cancelled) formatNumStr(5, secData, "plmwt", defValR), formatNumStr(5, secData, "page", defValR), formatNumStr(5, secData, "plenv", defValR), formatNumStr(5, secData, "plph", defValR), formatNumStr(5, secData, "plspl", defValR), getObjectOr(secData, "pl_name", defValC).toString())); } sbData.append("\r\n"); } else { sbError.append("! Warning: There is no plainting data in the experiment.\r\n"); } // IRRIGATION AND WATER MANAGEMENT Section if (!miArr.isEmpty()) { sbData.append("*IRRIGATION AND WATER MANAGEMENT\r\n"); for (int idx = 0; idx < miArr.size(); idx++) { // secData = (ArrayList) miArr.get(idx); subDataArr = (ArrayList) miArr.get(idx); if (!subDataArr.isEmpty()) { subData = (HashMap) subDataArr.get(0); } else { subData = new HashMap(); } sbData.append("@I EFIR IDEP ITHR IEPT IOFF IAME IAMT IRNAME\r\n"); sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$s\r\n", idx + 1, //getObjectOr(data, "ir", defValI).toString(), formatNumStr(5, subData, "ireff", defValR), formatNumStr(5, subData, "irmdp", defValR), formatNumStr(5, subData, "irthr", defValR), formatNumStr(5, subData, "irept", defValR), getObjectOr(subData, "irstg", defValC).toString(), getObjectOr(subData, "iame", defValC).toString(), formatNumStr(5, subData, "iamt", defValR), getObjectOr(subData, "ir_name", defValC).toString())); if (!subDataArr.isEmpty()) { sbData.append("@I IDATE IROP IRVAL\r\n"); } for (int j = 0; j < subDataArr.size(); j++) { subData = (HashMap) subDataArr.get(j); sbData.append(String.format("%1$2s %2$5s %3$-5s %4$5s\r\n", idx + 1, //getObjectOr(subData, "ir", defValI).toString(), formatDateStr(getObjectOr(subData, "date", defValD).toString()), // P.S. idate -> date getObjectOr(subData, "irop", defValC).toString(), formatNumStr(5, subData, "irval", defValR))); } } sbData.append("\r\n"); } // FERTILIZERS (INORGANIC) Section if (!mfArr.isEmpty()) { sbData.append("*FERTILIZERS (INORGANIC)\r\n"); sbData.append("@F FDATE FMCD FACD FDEP FAMN FAMP FAMK FAMC FAMO FOCD FERNAME\r\n"); // String fen_tot = getObjectOr(result, "fen_tot", defValR); // String fep_tot = getObjectOr(result, "fep_tot", defValR); // String fek_tot = getObjectOr(result, "fek_tot", defValR); // String pdate = getPdate(result); // if (pdate.equals("")) { // pdate = defValD; // } for (int idx = 0; idx < mfArr.size(); idx++) { secDataArr = (ArrayList) mfArr.get(idx); for (int i = 0; i < secDataArr.size(); i++) { secData = (HashMap) secDataArr.get(i); // if (getObjectOr(secData, "fdate", "").equals("")) { // sbError.append("! Warning: missing data : [fdate], and will automatically use planting value '").append(pdate).append("'\r\n"); // } // if (getObjectOr(secData, "fecd", "").equals("")) { // sbError.append("! Warning: missing data : [fecd], and will automatically use default value 'FE001'\r\n"); // } // if (getObjectOr(secData, "feacd", "").equals("")) { // sbError.append("! Warning: missing data : [feacd], and will automatically use default value 'AP002'\r\n"); // } // if (getObjectOr(secData, "fedep", "").equals("")) { // sbError.append("! Warning: missing data : [fedep], and will automatically use default value '10'\r\n"); // } // if (getObjectOr(secData, "feamn", "").equals("")) { // sbError.append("! Warning: missing data : [feamn], and will automatically use the value of FEN_TOT, '").append(fen_tot).append("'\r\n"); // } // if (getObjectOr(secData, "feamp", "").equals("")) { // sbError.append("! Warning: missing data : [feamp], and will automatically use the value of FEP_TOT, '").append(fep_tot).append("'\r\n"); // } // if (getObjectOr(secData, "feamk", "").equals("")) { // sbError.append("! Warning: missing data : [feamk], and will automatically use the value of FEK_TOT, '").append(fek_tot).append("'\r\n"); // } sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$s\r\n", idx + 1, //getObjectOr(data, "fe", defValI).toString(), formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. fdate -> date getObjectOr(secData, "fecd", defValC).toString(), // P.S. Set default value as "FE005"(Cancelled) getObjectOr(secData, "feacd", defValC).toString(), // P.S. Set default value as "AP002"(Cancelled) formatNumStr(5, secData, "fedep", defValR), // P.S. Set default value as "10"(Cancelled) formatNumStr(5, secData, "feamn", defValR), // P.S. Set default value to use the value of FEN_TOT in meta data(Cancelled) formatNumStr(5, secData, "feamp", defValR), // P.S. Set default value to use the value of FEP_TOT in meta data(Cancelled) formatNumStr(5, secData, "feamk", defValR), // P.S. Set default value to use the value of FEK_TOT in meta data(Cancelled) formatNumStr(5, secData, "feamc", defValR), formatNumStr(5, secData, "feamo", defValR), getObjectOr(secData, "feocd", defValC).toString(), getObjectOr(secData, "fe_name", defValC).toString())); } } sbData.append("\r\n"); } // RESIDUES AND ORGANIC FERTILIZER Section if (!mrArr.isEmpty()) { sbData.append("*RESIDUES AND ORGANIC FERTILIZER\r\n"); sbData.append("@R RDATE RCOD RAMT RESN RESP RESK RINP RDEP RMET RENAME\r\n"); for (int idx = 0; idx < mrArr.size(); idx++) { secDataArr = (ArrayList) mrArr.get(idx); for (int i = 0; i < secDataArr.size(); i++) { secData = (HashMap) secDataArr.get(i); sbData.append(String.format("%1$2s %2$5s %3$-5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$s\r\n", idx + 1, //getObjectOr(secData, "om", defValI).toString(), formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. omdat -> date getObjectOr(secData, "omcd", defValC).toString(), formatNumStr(5, secData, "omamt", defValR), formatNumStr(5, secData, "omn%", defValR), formatNumStr(5, secData, "omp%", defValR), formatNumStr(5, secData, "omk%", defValR), formatNumStr(5, secData, "ominp", defValR), formatNumStr(5, secData, "omdep", defValR), formatNumStr(5, secData, "omacd", defValR), getObjectOr(secData, "om_name", defValC).toString())); } } sbData.append("\r\n"); } // CHEMICAL APPLICATIONS Section if (!mcArr.isEmpty()) { sbData.append("*CHEMICAL APPLICATIONS\r\n"); sbData.append("@C CDATE CHCOD CHAMT CHME CHDEP CHT..CHNAME\r\n"); for (int idx = 0; idx < mcArr.size(); idx++) { secDataArr = (ArrayList) mcArr.get(idx); for (int i = 0; i < secDataArr.size(); i++) { secData = (HashMap) secDataArr.get(i); sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$s\r\n", idx + 1, //getObjectOr(secData, "ch", defValI).toString(), formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. cdate -> date getObjectOr(secData, "chcd", defValC).toString(), formatNumStr(5, secData, "chamt", defValR), getObjectOr(secData, "chacd", defValC).toString(), getObjectOr(secData, "chdep", defValC).toString(), getObjectOr(secData, "ch_targets", defValC).toString(), getObjectOr(secData, "ch_name", defValC).toString())); } } sbData.append("\r\n"); } // TILLAGE Section if (!mtArr.isEmpty()) { sbData.append("*TILLAGE AND ROTATIONS\r\n"); sbData.append("@T TDATE TIMPL TDEP TNAME\r\n"); for (int idx = 0; idx < mtArr.size(); idx++) { secDataArr = (ArrayList) mtArr.get(idx); for (int i = 0; i < secDataArr.size(); i++) { secData = (HashMap) secDataArr.get(i); sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$s\r\n", idx + 1, //getObjectOr(secData, "ti", defValI).toString(), formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. tdate -> date getObjectOr(secData, "tiimp", defValC).toString(), formatNumStr(5, secData, "tidep", defValR), getObjectOr(secData, "ti_name", defValC).toString())); } } sbData.append("\r\n"); } // ENVIRONMENT MODIFICATIONS Section if (!meArr.isEmpty()) { sbData.append("*ENVIRONMENT MODIFICATIONS\r\n"); sbData.append("@E ODATE EDAY ERAD EMAX EMIN ERAIN ECO2 EDEW EWIND ENVNAME\r\n"); for (int idx = 0, cnt = 1; idx < meArr.size(); idx++) { secDataArr = (ArrayList) meArr.get(idx); for (int i = 0; i < secDataArr.size(); i++) { secData = (HashMap) secDataArr.get(i); sbData.append(String.format("%1$2s%2$s\r\n", cnt, secData.get("em_data"))); // sbData.append(String.format("%1$2s%2$s\r\n", // idx + 1, // (String) secDataArr.get(i))); // sbData.append(String.format("%1$2s %2$5s %3$-1s%4$4s %5$-1s%6$4s %7$-1s%8$4s %9$-1s%10$4s %11$-1s%12$4s %13$-1s%14$4s %15$-1s%16$4s %17$-1s%18$4s %19$s\r\n", // idx + 1, //getObjectOr(secData, "em", defValI).toString(), // formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. emday -> date // getObjectOr(secData, "ecdyl", defValBlank).toString(), // formatNumStr(4, getObjectOr(secData, "emdyl", defValR), // getObjectOr(secData, "ecrad", defValBlank).toString(), // formatNumStr(4, getObjectOr(secData, "emrad", defValR), // getObjectOr(secData, "ecmax", defValBlank).toString(), // formatNumStr(4, getObjectOr(secData, "emmax", defValR), // getObjectOr(secData, "ecmin", defValBlank).toString(), // formatNumStr(4, getObjectOr(secData, "emmin", defValR), // getObjectOr(secData, "ecrai", defValBlank).toString(), // formatNumStr(4, getObjectOr(secData, "emrai", defValR), // getObjectOr(secData, "ecco2", defValBlank).toString(), // formatNumStr(4, getObjectOr(secData, "emco2", defValR), // getObjectOr(secData, "ecdew", defValBlank).toString(), // formatNumStr(4, getObjectOr(secData, "emdew", defValR), // getObjectOr(secData, "ecwnd", defValBlank).toString(), // formatNumStr(4, getObjectOr(secData, "emwnd", defValR), // getObjectOr(secData, "em_name", defValC).toString())); } } sbData.append("\r\n"); } // HARVEST DETAILS Section if (!mhArr.isEmpty()) { sbData.append("*HARVEST DETAILS\r\n"); sbData.append("@H HDATE HSTG HCOM HSIZE HPC HBPC HNAME\r\n"); for (int idx = 0; idx < mhArr.size(); idx++) { secDataArr = (ArrayList) mhArr.get(idx); for (int i = 0; i < secDataArr.size(); i++) { secData = (HashMap) secDataArr.get(i); sbData.append(String.format("%1$2s %2$5s %3$-5s %4$-5s %5$-5s %6$5s %7$5s %8$s\r\n", idx + 1, //getObjectOr(secData, "ha", defValI).toString(), formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. hdate -> date getObjectOr(secData, "hastg", defValC).toString(), getObjectOr(secData, "hacom", defValC).toString(), getObjectOr(secData, "hasiz", defValC).toString(), formatNumStr(5, secData, "hap%", defValR), formatNumStr(5, secData, "hab%", defValR), getObjectOr(secData, "ha_name", defValC).toString())); } } sbData.append("\r\n"); } // SIMULATION CONTROLS and AUTOMATIC MANAGEMENT Section if (!smArr.isEmpty()) { // Set Title list ArrayList smTitles = new ArrayList(); smTitles.add("@N GENERAL NYERS NREPS START SDATE RSEED SNAME.................... SMODEL\r\n"); smTitles.add("@N OPTIONS WATER NITRO SYMBI PHOSP POTAS DISES CHEM TILL CO2\r\n"); smTitles.add("@N METHODS WTHER INCON LIGHT EVAPO INFIL PHOTO HYDRO NSWIT MESOM MESEV MESOL\r\n"); smTitles.add("@N MANAGEMENT PLANT IRRIG FERTI RESID HARVS\r\n"); smTitles.add("@N OUTPUTS FNAME OVVEW SUMRY FROPT GROUT CAOUT WAOUT NIOUT MIOUT DIOUT VBOSE CHOUT OPOUT\r\n"); smTitles.add("@ AUTOMATIC MANAGEMENT\r\n@N PLANTING PFRST PLAST PH2OL PH2OU PH2OD PSTMX PSTMN\r\n"); smTitles.add("@N IRRIGATION IMDEP ITHRL ITHRU IROFF IMETH IRAMT IREFF\r\n"); smTitles.add("@N NITROGEN NMDEP NMTHR NAMNT NCODE NAOFF\r\n"); smTitles.add("@N RESIDUES RIPCN RTIME RIDEP\r\n"); smTitles.add("@N HARVEST HFRST HLAST HPCNP HPCNR\r\n"); String[] keys = new String[10]; keys[0] = "sm_general"; keys[1] = "sm_options"; keys[2] = "sm_methods"; keys[3] = "sm_management"; keys[4] = "sm_outputs"; keys[5] = "sm_planting"; keys[6] = "sm_irrigation"; keys[7] = "sm_nitrogen"; keys[8] = "sm_residues"; keys[9] = "sm_harvests"; // Loop all the simulation control records sbData.append("*SIMULATION CONTROLS\r\n"); for (int idx = 0; idx < smArr.size(); idx++) { secData = (HashMap) smArr.get(idx); if (secData.containsKey("sm_general")) { secData.remove("sm"); // Object[] keys = secData.keySet().toArray(); for (int i = 0; i < keys.length; i++) { sbData.append(smTitles.get(i)); sbData.append(String.format("%2s ", idx + 1)).append(((String) secData.get(keys[i]))).append("\r\n"); if (i == 4) { sbData.append("\r\n"); } } sbData.append("\r\n"); } else { sbData.append(createSMMAStr(idx + 1, secData)); } } } else { sbData.append("*SIMULATION CONTROLS\r\n"); sbData.append(createSMMAStr(1, new HashMap())); } // Output finish bwX.write(sbError.toString()); bwX.write(sbGenData.toString()); bwX.write(sbNotesData.toString()); bwX.write(sbData.toString()); bwX.close(); } catch (IOException e) { LOG.error(DssatCommonOutput.getStackTrace(e)); } } /** * Create string of Simulation Control and Automatic Management Section * * @param smid simulation index number * @param trData date holder for one treatment data * @return date string with format of "yyddd" */ private String createSMMAStr(int smid, HashMap trData) { StringBuilder sb = new StringBuilder(); String nitro = "Y"; String water = "Y"; String co2 = "M"; String sdate; String sm = String.format("%2d", smid); ArrayList<HashMap> dataArr; HashMap subData; // // Check if the meta data of fertilizer is not "N" ("Y" or null) // if (!getValueOr(expData, "fertilizer", "").equals("N")) { // // // Check if necessary data is missing in all the event records // // P.S. rule changed since all the necessary data has a default value for it // dataArr = (ArrayList) getObjectOr(trData, "fertilizer", new ArrayList()); // if (dataArr.isEmpty()) { // nitro = "N"; // } //// for (int i = 0; i < dataArr.size(); i++) { //// subData = dataArr.get(i); //// if (getValueOr(subData, "date", "").equals("") //// || getValueOr(subData, "fecd", "").equals("") //// || getValueOr(subData, "feacd", "").equals("") //// || getValueOr(subData, "feamn", "").equals("")) { //// nitro = "N"; //// break; //// } //// } // } // // Check if the meta data of irrigation is not "N" ("Y" or null) // if (!getValueOr(expData, "irrigation", "").equals("N")) { // // // Check if necessary data is missing in all the event records // dataArr = (ArrayList) getObjectOr(trData, "irrigation", new ArrayList()); // for (int i = 0; i < dataArr.size(); i++) { // subData = dataArr.get(i); // if (getValueOr(subData, "date", "").equals("") // || getValueOr(subData, "irval", "").equals("")) { // water = "N"; // break; // } // } // } // Check if CO2Y value is provided and the value is positive, then set CO2 switch to W String co2y = getValueOr(trData, "co2y", "").trim(); if (!co2y.equals("") && !co2y.startsWith("-")) { co2 = "W"; } sdate = getValueOr(trData, "sdat", "").toString(); if (sdate.equals("")) { subData = (HashMap) getObjectOr(trData, "planting", new HashMap()); sdate = getValueOr(subData, "date", defValD); } sdate = formatDateStr(sdate); sdate = String.format("%5s", sdate); sb.append("@N GENERAL NYERS NREPS START SDATE RSEED SNAME....................\r\n"); sb.append(sm).append(" GE 1 1 S ").append(sdate).append(" 2150 DEFAULT SIMULATION CONTROL\r\n"); sb.append("@N OPTIONS WATER NITRO SYMBI PHOSP POTAS DISES CHEM TILL CO2\r\n"); sb.append(sm).append(" OP ").append(water).append(" ").append(nitro).append(" Y N N N N Y ").append(co2).append("\r\n"); sb.append("@N METHODS WTHER INCON LIGHT EVAPO INFIL PHOTO HYDRO NSWIT MESOM MESEV MESOL\r\n"); sb.append(sm).append(" ME M M E R S L R 1 P S 2\r\n"); // P.S. 2012/09/02 MESOM "G" -> "P" sb.append("@N MANAGEMENT PLANT IRRIG FERTI RESID HARVS\r\n"); sb.append(sm).append(" MA R R R R M\r\n"); sb.append("@N OUTPUTS FNAME OVVEW SUMRY FROPT GROUT CAOUT WAOUT NIOUT MIOUT DIOUT VBOSE CHOUT OPOUT\r\n"); sb.append(sm).append(" OU N Y Y 1 Y Y N N N N N N N\r\n\r\n"); sb.append("@ AUTOMATIC MANAGEMENT\r\n"); sb.append("@N PLANTING PFRST PLAST PH2OL PH2OU PH2OD PSTMX PSTMN\r\n"); sb.append(sm).append(" PL 82050 82064 40 100 30 40 10\r\n"); sb.append("@N IRRIGATION IMDEP ITHRL ITHRU IROFF IMETH IRAMT IREFF\r\n"); sb.append(sm).append(" IR 30 50 100 GS000 IR001 10 1.00\r\n"); sb.append("@N NITROGEN NMDEP NMTHR NAMNT NCODE NAOFF\r\n"); sb.append(sm).append(" NI 30 50 25 FE001 GS000\r\n"); sb.append("@N RESIDUES RIPCN RTIME RIDEP\r\n"); sb.append(sm).append(" RE 100 1 20\r\n"); sb.append("@N HARVEST HFRST HLAST HPCNP HPCNR\r\n"); sb.append(sm).append(" HA 0 83057 100 0\r\n\r\n"); return sb.toString(); } /** * Get index value of the record and set new id value in the array * * @param m sub data * @param arr array of sub data * @return current index value of the sub data */ private int setSecDataArr(HashMap m, ArrayList arr) { if (!m.isEmpty()) { for (int j = 0; j < arr.size(); j++) { if (arr.get(j).equals(m)) { return j + 1; } } arr.add(m); return arr.size(); } else { return 0; } } /** * Get index value of the record and set new id value in the array * * @param inArr sub array of data * @param outArr array of sub data * @return current index value of the sub data */ private int setSecDataArr(ArrayList inArr, ArrayList outArr) { if (!inArr.isEmpty()) { for (int j = 0; j < outArr.size(); j++) { if (outArr.get(j).equals(inArr)) { return j + 1; } } outArr.add(inArr); return outArr.size(); } else { return 0; } } /** * To check if there is plot info data existed in the experiment * * @param expData experiment data holder * @return the boolean value for if plot info exists */ private boolean isPlotInfoExist(Map expData) { String[] plotIds = {"plta", "pltr#", "pltln", "pldr", "pltsp", "pllay", "pltha", "plth#", "plthl", "plthm"}; for (int i = 0; i < plotIds.length; i++) { if (!getValueOr(expData, plotIds[i], "").equals("")) { return true; } } return false; } /** * To check if there is soil analysis info data existed in the experiment * * @param expData initial condition layer data array * @return the boolean value for if soil analysis info exists */ private boolean isSoilAnalysisExist(ArrayList<HashMap> icSubArr) { for (int i = 0; i < icSubArr.size(); i++) { if (!getValueOr(icSubArr.get(i), "slsc", "").equals("")) { return true; } } return false; } /** * Get sub data array from experiment data object * * @param expData experiment data holder * @param blockName top level block name * @param dataListName sub array name * @return sub data array */ private ArrayList<HashMap> getDataList(Map expData, String blockName, String dataListName) { HashMap dataBlock = getObjectOr(expData, blockName, new HashMap()); return getObjectOr(dataBlock, dataListName, new ArrayList<HashMap>()); } /** * Try to translate 3-bit crid to 2-bit version stored in the map * * @param cuData the cultivar data record * @param id the field id for contain crop id info */ private void translateTo2BitCrid(HashMap cuData, String id) { String crid = getObjectOr(cuData, id, ""); if (!crid.equals("")) { // DssatCRIDHelper crids = new DssatCRIDHelper(); cuData.put(id, DssatCRIDHelper.get2BitCrid(crid)); } } /** * Try to translate 3-bit crid to 2-bit version stored in the map * * @param cuData the cultivar data record */ private void translateTo2BitCrid(HashMap cuData) { translateTo2BitCrid(cuData, "crid"); } /** * Get soil/weather data from data holder * * @param expData The experiment data holder * @param key The key name for soil/weather section * @return */ private ArrayList readSWData(HashMap expData, String key) { ArrayList ret; Object soil = expData.get(key); if (soil != null) { if (soil instanceof ArrayList) { ret = (ArrayList) soil; } else { ret = new ArrayList(); ret.add(soil); } } else { ret = new ArrayList(); } return ret; } }
Add handling for harvest option in simulation control. If harvest date is valid in the data, then use R, otherwise use M.
src/main/java/org/agmip/translators/dssat/DssatXFileOutput.java
Add handling for harvest option in simulation control. If harvest date is valid in the data, then use R, otherwise use M.
<ide><path>rc/main/java/org/agmip/translators/dssat/DssatXFileOutput.java <ide> } // harvest event <ide> else if (getValueOr(evtData, "event", "").equals("harvest")) { <ide> mhSubArr.add(evtData); <add> copyItem(smData, evtData, "hadat", "date", false); <ide> } else { <ide> } <ide> } else { <ide> String nitro = "Y"; <ide> String water = "Y"; <ide> String co2 = "M"; <add> String harOpt = "M"; <ide> String sdate; <ide> String sm = String.format("%2d", smid); <ide> ArrayList<HashMap> dataArr; <ide> } <ide> sdate = formatDateStr(sdate); <ide> sdate = String.format("%5s", sdate); <add> <add> if (!getValueOr(trData, "hadat", "").trim().equals("")) { <add> LOG.info(getValueOr(trData, "hadat", "")); <add> harOpt = "R"; <add> } else { <add> LOG.info("NO HARVEST DATE FOUND"); <add> } <ide> <ide> sb.append("@N GENERAL NYERS NREPS START SDATE RSEED SNAME....................\r\n"); <ide> sb.append(sm).append(" GE 1 1 S ").append(sdate).append(" 2150 DEFAULT SIMULATION CONTROL\r\n"); <ide> sb.append("@N METHODS WTHER INCON LIGHT EVAPO INFIL PHOTO HYDRO NSWIT MESOM MESEV MESOL\r\n"); <ide> sb.append(sm).append(" ME M M E R S L R 1 P S 2\r\n"); // P.S. 2012/09/02 MESOM "G" -> "P" <ide> sb.append("@N MANAGEMENT PLANT IRRIG FERTI RESID HARVS\r\n"); <del> sb.append(sm).append(" MA R R R R M\r\n"); <add> sb.append(sm).append(" MA R R R R ").append(harOpt).append("\r\n"); <ide> sb.append("@N OUTPUTS FNAME OVVEW SUMRY FROPT GROUT CAOUT WAOUT NIOUT MIOUT DIOUT VBOSE CHOUT OPOUT\r\n"); <ide> sb.append(sm).append(" OU N Y Y 1 Y Y N N N N N N N\r\n\r\n"); <ide> sb.append("@ AUTOMATIC MANAGEMENT\r\n");
Java
apache-2.0
a375fdcafb9bde5297f2d46933f71cee437b314d
0
subutai-io/base,subutai-io/base,subutai-io/Subutai,subutai-io/base,subutai-io/Subutai,subutai-io/Subutai,subutai-io/Subutai,subutai-io/Subutai,subutai-io/base,subutai-io/Subutai
package org.safehaus.subutai.core.broker.impl; import javax.jms.BytesMessage; import javax.jms.Connection; import javax.jms.DeliveryMode; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TopicSubscriber; import org.safehaus.subutai.core.broker.api.Broker; import org.safehaus.subutai.core.broker.api.BrokerException; import org.safehaus.subutai.core.broker.api.ByteMessageListener; import org.safehaus.subutai.core.broker.api.MessageListener; import org.safehaus.subutai.core.broker.api.TextMessageListener; import org.safehaus.subutai.core.broker.api.Topic; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.pool.PooledConnectionFactory; import com.google.common.base.Preconditions; import com.google.common.base.Strings; /** * Broker implementation */ public class BrokerImpl implements Broker { private static final Logger LOG = LoggerFactory.getLogger( BrokerImpl.class.getName() ); protected MessageRoutingListener messageRouter; protected PooledConnectionFactory pool; private final String brokerUrl; private final int maxBrokerConnections; private final boolean isPersistent; private final int messageTimeout; private final int idleConnectionTimeout; public BrokerImpl( final String brokerUrl, final int maxBrokerConnections, final boolean isPersistent, final int messageTimeout, final int idleConnectionTimeout ) { Preconditions.checkArgument( !Strings.isNullOrEmpty( brokerUrl ), "Invalid broker URL" ); Preconditions.checkArgument( maxBrokerConnections > 0, "Max broker connections number must be greater than 0" ); Preconditions.checkArgument( messageTimeout >= 0, "Message timeout must be greater than or equal to 0" ); Preconditions.checkArgument( idleConnectionTimeout > 0, "Idle connection timeout must be greater than 0" ); this.brokerUrl = brokerUrl; this.maxBrokerConnections = maxBrokerConnections; this.isPersistent = isPersistent; this.messageTimeout = messageTimeout; this.idleConnectionTimeout = idleConnectionTimeout; this.messageRouter = new MessageRoutingListener(); } @Override public void sendTextMessage( final String topic, final String message ) throws BrokerException { Preconditions.checkArgument( !Strings.isNullOrEmpty( topic ), "Invalid topic" ); Preconditions.checkArgument( !Strings.isNullOrEmpty( message ), "Message is empty" ); sendMessage( topic, message ); } @Override public void sendByteMessage( final String topic, final byte[] message ) throws BrokerException { Preconditions.checkArgument( !Strings.isNullOrEmpty( topic ), "Invalid topic" ); Preconditions.checkArgument( message != null && message.length > 0, "Message is empty" ); sendMessage( topic, message ); } @Override public void addByteMessageListener( final ByteMessageListener listener ) throws BrokerException { Preconditions.checkNotNull( listener ); Preconditions.checkNotNull( listener.getTopic() ); messageRouter.addListener( listener ); } @Override public void addTextMessageListener( final TextMessageListener listener ) throws BrokerException { Preconditions.checkNotNull( listener ); Preconditions.checkNotNull( listener.getTopic() ); messageRouter.addListener( listener ); } @Override public void removeMessageListener( final MessageListener listener ) { Preconditions.checkNotNull( listener ); messageRouter.removeListener( listener ); } public void init() throws BrokerException { ActiveMQConnectionFactory amqFactory = new ActiveMQConnectionFactory( brokerUrl ); amqFactory.setWatchTopicAdvisories( false ); amqFactory.setCheckForDuplicates( true ); setupConnectionPool( amqFactory ); setupRouter( amqFactory ); } public void dispose() { if ( pool != null ) { pool.stop(); } } protected void setupRouter( ActiveMQConnectionFactory amqFactory ) throws BrokerException { try { for ( Topic topic : Topic.values() ) { Connection connection = amqFactory.createConnection(); connection.setClientID( String.format( "%s-subutai-client", topic.name() ) ); connection.start(); Session session = connection.createSession( false, Session.CLIENT_ACKNOWLEDGE ); javax.jms.Topic topicDestination = session.createTopic( topic.name() ); TopicSubscriber topicSubscriber = session.createDurableSubscriber( topicDestination, String.format( "%s-subutai-subscriber", topic.name() ) ); topicSubscriber.setMessageListener( messageRouter ); } } catch ( JMSException e ) { LOG.error( "Error in setupRouter", e ); throw new BrokerException( e ); } } private void setupConnectionPool( ActiveMQConnectionFactory amqFactory ) { pool = new PooledConnectionFactory( amqFactory ); pool.setMaxConnections( maxBrokerConnections ); pool.setIdleTimeout( idleConnectionTimeout * 1000 ); pool.start(); } private void sendMessage( String topic, Object message ) throws BrokerException { Connection connection = null; Session session = null; MessageProducer producer = null; try { connection = pool.createConnection(); connection.start(); session = connection.createSession( false, Session.AUTO_ACKNOWLEDGE ); Destination destination = session.createTopic( topic ); producer = session.createProducer( destination ); producer.setDeliveryMode( isPersistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT ); producer.setTimeToLive( messageTimeout * 1000 ); Message msg; if ( message instanceof String ) { msg = session.createTextMessage( ( String ) message ); } else { msg = session.createBytesMessage(); ( ( BytesMessage ) msg ).writeBytes( ( byte[] ) message ); } producer.send( msg ); } catch ( Exception e ) { LOG.error( "Error in sendMessage", e ); throw new BrokerException( e ); } finally { if ( producer != null ) { try { producer.close(); } catch ( JMSException e ) { //ignore } } if ( session != null ) { try { session.close(); } catch ( JMSException e ) { //ignore } } if ( connection != null ) { try { connection.close(); } catch ( JMSException e ) { //ignore } } } } }
management/server/core/broker/broker-impl/src/main/java/org/safehaus/subutai/core/broker/impl/BrokerImpl.java
package org.safehaus.subutai.core.broker.impl; import javax.jms.BytesMessage; import javax.jms.Connection; import javax.jms.DeliveryMode; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TopicSubscriber; import org.safehaus.subutai.core.broker.api.Broker; import org.safehaus.subutai.core.broker.api.BrokerException; import org.safehaus.subutai.core.broker.api.ByteMessageListener; import org.safehaus.subutai.core.broker.api.MessageListener; import org.safehaus.subutai.core.broker.api.TextMessageListener; import org.safehaus.subutai.core.broker.api.Topic; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.pool.PooledConnectionFactory; import com.google.common.base.Preconditions; import com.google.common.base.Strings; /** * Broker implementation */ public class BrokerImpl implements Broker { private static final Logger LOG = LoggerFactory.getLogger( BrokerImpl.class.getName() ); protected MessageRoutingListener messageRouter; protected PooledConnectionFactory pool; private final String brokerUrl; private final int maxBrokerConnections; private final boolean isPersistent; private final int messageTimeout; private final int idleConnectionTimeout; public BrokerImpl( final String brokerUrl, final int maxBrokerConnections, final boolean isPersistent, final int messageTimeout, final int idleConnectionTimeout ) { Preconditions.checkArgument( !Strings.isNullOrEmpty( brokerUrl ), "Invalid broker URL" ); Preconditions.checkArgument( maxBrokerConnections > 0, "Max broker connections number must be greater than 0" ); Preconditions.checkArgument( messageTimeout >= 0, "Message timeout must be greater than or equal to 0" ); Preconditions.checkArgument( idleConnectionTimeout > 0, "Idle connection timeout must be greater than 0" ); this.brokerUrl = brokerUrl; this.maxBrokerConnections = maxBrokerConnections; this.isPersistent = isPersistent; this.messageTimeout = messageTimeout; this.idleConnectionTimeout = idleConnectionTimeout; this.messageRouter = new MessageRoutingListener(); } @Override public void sendTextMessage( final String topic, final String message ) throws BrokerException { Preconditions.checkArgument( !Strings.isNullOrEmpty( topic ), "Invalid topic" ); Preconditions.checkArgument( !Strings.isNullOrEmpty( message ), "Message is empty" ); sendMessage( topic, message ); } @Override public void sendByteMessage( final String topic, final byte[] message ) throws BrokerException { Preconditions.checkArgument( !Strings.isNullOrEmpty( topic ), "Invalid topic" ); Preconditions.checkArgument( message != null && message.length > 0, "Message is empty" ); sendMessage( topic, message ); } @Override public void addByteMessageListener( final ByteMessageListener listener ) throws BrokerException { Preconditions.checkNotNull( listener ); Preconditions.checkNotNull( listener.getTopic() ); messageRouter.addListener( listener ); } @Override public void addTextMessageListener( final TextMessageListener listener ) throws BrokerException { Preconditions.checkNotNull( listener ); Preconditions.checkNotNull( listener.getTopic() ); messageRouter.addListener( listener ); } @Override public void removeMessageListener( final MessageListener listener ) { Preconditions.checkNotNull( listener ); messageRouter.removeListener( listener ); } public void init() throws BrokerException { ActiveMQConnectionFactory amqFactory = new ActiveMQConnectionFactory( brokerUrl ); amqFactory.setWatchTopicAdvisories( false ); amqFactory.setCheckForDuplicates( true ); setupConnectionPool( amqFactory ); setupRouter( amqFactory ); } public void dispose() { if ( pool != null ) { pool.stop(); } } protected void setupRouter( ActiveMQConnectionFactory amqFactory ) throws BrokerException { try { Connection connection = amqFactory.createConnection(); connection.setClientID( "subutai" ); connection.start(); for ( Topic topic : Topic.values() ) { Session session = connection.createSession( false, Session.CLIENT_ACKNOWLEDGE ); javax.jms.Topic topicDestination = session.createTopic( topic.name() ); TopicSubscriber topicSubscriber = session.createDurableSubscriber( topicDestination, String.format( "%s-subutai-subscriber", topic.name() ) ); topicSubscriber.setMessageListener( messageRouter ); } } catch ( JMSException e ) { LOG.error( "Error in setupRouter", e ); throw new BrokerException( e ); } } private void setupConnectionPool( ActiveMQConnectionFactory amqFactory ) { pool = new PooledConnectionFactory( amqFactory ); pool.setMaxConnections( maxBrokerConnections ); pool.setIdleTimeout( idleConnectionTimeout * 1000 ); pool.start(); } private void sendMessage( String topic, Object message ) throws BrokerException { Connection connection = null; Session session = null; MessageProducer producer = null; try { connection = pool.createConnection(); connection.start(); session = connection.createSession( false, Session.AUTO_ACKNOWLEDGE ); Destination destination = session.createTopic( topic ); producer = session.createProducer( destination ); producer.setDeliveryMode( isPersistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT ); producer.setTimeToLive( messageTimeout * 1000 ); Message msg; if ( message instanceof String ) { msg = session.createTextMessage( ( String ) message ); } else { msg = session.createBytesMessage(); ( ( BytesMessage ) msg ).writeBytes( ( byte[] ) message ); } producer.send( msg ); } catch ( Exception e ) { LOG.error( "Error in sendMessage", e ); throw new BrokerException( e ); } finally { if ( producer != null ) { try { producer.close(); } catch ( JMSException e ) { //ignore } } if ( session != null ) { try { session.close(); } catch ( JMSException e ) { //ignore } } if ( connection != null ) { try { connection.close(); } catch ( JMSException e ) { //ignore } } } } }
changed to use multiple connections to topics
management/server/core/broker/broker-impl/src/main/java/org/safehaus/subutai/core/broker/impl/BrokerImpl.java
changed to use multiple connections to topics
<ide><path>anagement/server/core/broker/broker-impl/src/main/java/org/safehaus/subutai/core/broker/impl/BrokerImpl.java <ide> { <ide> try <ide> { <del> <del> Connection connection = amqFactory.createConnection(); <del> connection.setClientID( "subutai" ); <del> connection.start(); <del> <ide> for ( Topic topic : Topic.values() ) <ide> { <add> Connection connection = amqFactory.createConnection(); <add> connection.setClientID( String.format( "%s-subutai-client", topic.name() ) ); <add> connection.start(); <ide> Session session = connection.createSession( false, Session.CLIENT_ACKNOWLEDGE ); <ide> javax.jms.Topic topicDestination = session.createTopic( topic.name() ); <ide> TopicSubscriber topicSubscriber = session.createDurableSubscriber( topicDestination,
Java
apache-2.0
error: pathspec 'community/kernel/src/main/java/org/neo4j/helpers/NamedThreadFactory.java' did not match any file(s) known to git
06d74978909fa1e73c067d2aee668b886fe95756
1
HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j
/** * Copyright (c) 2002-2012 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.helpers; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; public class NamedThreadFactory implements ThreadFactory { private final ThreadGroup group; private final AtomicInteger threadCounter = new AtomicInteger( 1 ); private String threadNamePrefix; public NamedThreadFactory( String threadNamePrefix ) { this.threadNamePrefix = threadNamePrefix; SecurityManager securityManager = System.getSecurityManager(); group = (securityManager != null) ? securityManager.getThreadGroup() : Thread.currentThread().getThreadGroup(); } public Thread newThread( Runnable runnable ) { Thread result = new Thread( group, runnable, threadNamePrefix + "-" + threadCounter.getAndIncrement() ); result.setDaemon( false ); result.setPriority( Thread.NORM_PRIORITY ); return result; } }
community/kernel/src/main/java/org/neo4j/helpers/NamedThreadFactory.java
A little helper for naming threads
community/kernel/src/main/java/org/neo4j/helpers/NamedThreadFactory.java
A little helper for naming threads
<ide><path>ommunity/kernel/src/main/java/org/neo4j/helpers/NamedThreadFactory.java <add>/** <add> * Copyright (c) 2002-2012 "Neo Technology," <add> * Network Engine for Objects in Lund AB [http://neotechnology.com] <add> * <add> * This file is part of Neo4j. <add> * <add> * Neo4j is free software: you can redistribute it and/or modify <add> * it under the terms of the GNU General Public License as published by <add> * the Free Software Foundation, either version 3 of the License, or <add> * (at your option) any later version. <add> * <add> * This program is distributed in the hope that it will be useful, <add> * but WITHOUT ANY WARRANTY; without even the implied warranty of <add> * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the <add> * GNU General Public License for more details. <add> * <add> * You should have received a copy of the GNU General Public License <add> * along with this program. If not, see <http://www.gnu.org/licenses/>. <add> */ <add>package org.neo4j.helpers; <add> <add>import java.util.concurrent.ThreadFactory; <add>import java.util.concurrent.atomic.AtomicInteger; <add> <add>public class NamedThreadFactory implements ThreadFactory <add>{ <add> private final ThreadGroup group; <add> private final AtomicInteger threadCounter = new AtomicInteger( 1 ); <add> private String threadNamePrefix; <add> <add> public NamedThreadFactory( String threadNamePrefix ) <add> { <add> this.threadNamePrefix = threadNamePrefix; <add> SecurityManager securityManager = System.getSecurityManager(); <add> group = (securityManager != null) ? <add> securityManager.getThreadGroup() : <add> Thread.currentThread().getThreadGroup(); <add> } <add> <add> public Thread newThread( Runnable runnable ) <add> { <add> Thread result = new Thread( group, runnable, threadNamePrefix + "-" + threadCounter.getAndIncrement() ); <add> result.setDaemon( false ); <add> result.setPriority( Thread.NORM_PRIORITY ); <add> return result; <add> } <add>}
Java
apache-2.0
2601fd3d86c8d01260384536bb1641049b8de5af
0
mixi-inc/triaina,akkm/triaina,mixi-inc/triaina,vishyrich/triaina,vishyrich/triaina,mixi-inc/triaina,akkm/triaina,akkm/triaina,mixi-inc/triaina,vishyrich/triaina
package triaina.webview; 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 com.google.inject.Inject; import triaina.commons.utils.SystemUtils; import triaina.injector.TriainaEnvironment; import triaina.injector.fragment.TriainaFragment; import triaina.webview.annotation.Bridge; import triaina.webview.config.WebViewBridgeConfigurator; import triaina.webview.entity.Params; import triaina.webview.entity.device.EnvironmentSetParams; import triaina.webview.entity.device.FormPictureSelectParams; import triaina.webview.entity.device.FormPictureSelectResult; import triaina.webview.entity.device.NetBrowserOpenParams; public abstract class AbstractWebViewBridgeFragment extends TriainaFragment { private static final String TAG = AbstractWebViewBridgeFragment.class.getSimpleName(); private WebViewBridge mWebViewBridge; @Inject private WebViewBridgeConfigurator mConfigurator; @Inject private WebViewRestoreManager mRestoreManager; @Inject private TriainaEnvironment mEnvironment; private boolean mIsRestored; private Bundle mWebViewStateOnDestroyView; final public String[] getDomains() { return mWebViewBridge.getDomainConfig().getDomains(); } public void call(String channel, Params params) { mWebViewBridge.call(channel, params); } public void call(String channel, Params params, Callback<?> callback) { mWebViewBridge.call(channel, params, callback); } final public WebViewBridge getWebViewBridge() { return mWebViewBridge; } final public WebViewBridgeConfigurator getConfigurator() { return mConfigurator; } @Bridge("system.environment.set") public void doEnvironmentSet(EnvironmentSetParams params) { mEnvironment.set(params.getName(), params.getValue()); } @Bridge("system.form.picture.select") public void doFormPictureSelect(FormPictureSelectParams params, Callback<FormPictureSelectResult> callback) { // TODO need to implement Triaina Framework original logic } @Bridge("system.net.browser.open") public void doNetBrowserOpen(NetBrowserOpenParams params) { SystemUtils.launchExternalBrowser(getActivity(), Uri.parse(params.getUrl())); } @Bridge("system.web.error") public void doWebError() { // ignore } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View inflatedView = mConfigurator.loadInflatedView(this, inflater, container); mWebViewBridge = mConfigurator.loadWebViewBridge(this, inflatedView); mWebViewStateOnDestroyView = null; mConfigurator.configure(mWebViewBridge); mConfigurator.registerBridge(mWebViewBridge, this); configureSettings(); configureClients(); return inflatedView; } protected void configureSettings() { mConfigurator.configureSetting(mWebViewBridge); } protected void configureClients() { mWebViewBridge.setWebChromeClient(new TriainaWebChromeClient(getActivity())); mWebViewBridge.setWebViewClient(new TriainaWebViewClient()); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mIsRestored = mRestoreManager.restoreWebView(mWebViewBridge, savedInstanceState); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mWebViewStateOnDestroyView != null) outState.putAll(mWebViewStateOnDestroyView); // XXX if (mWebViewBridge != null) storeWebView(outState); } protected void storeWebView(Bundle outState) { mRestoreManager.storeWebView(mWebViewBridge, outState, getActivity().getTaskId()); } @Override public void onResume() { super.onResume(); mWebViewBridge.resume(); } @Override public void onPause() { mWebViewBridge.pause(); super.onPause(); } @Override public void onDestroyView() { mWebViewStateOnDestroyView = new Bundle(); storeWebView(mWebViewStateOnDestroyView); try { mWebViewBridge.destroy(); } catch (Exception exp) { Log.w(TAG, exp.getMessage() + "", exp); } mWebViewBridge = null; super.onDestroyView(); } public boolean isRestored() { return mIsRestored; } }
android/WebViewBridge/src/triaina/webview/AbstractWebViewBridgeFragment.java
package triaina.webview; 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 com.google.inject.Inject; import triaina.commons.utils.SystemUtils; import triaina.injector.TriainaEnvironment; import triaina.injector.fragment.TriainaFragment; import triaina.webview.annotation.Bridge; import triaina.webview.config.WebViewBridgeConfigurator; import triaina.webview.entity.Params; import triaina.webview.entity.device.EnvironmentSetParams; import triaina.webview.entity.device.FormPictureSelectParams; import triaina.webview.entity.device.FormPictureSelectResult; import triaina.webview.entity.device.NetBrowserOpenParams; public abstract class AbstractWebViewBridgeFragment extends TriainaFragment { private static final String TAG = AbstractWebViewBridgeFragment.class.getSimpleName(); private WebViewBridge mWebViewBridge; @Inject private WebViewBridgeConfigurator mConfigurator; @Inject private WebViewRestoreManager mRestoreManager; @Inject private TriainaEnvironment mEnvironment; private boolean mIsRestored; private Bundle mWebViewStateOnDestroyView; final public String[] getDomains() { return mWebViewBridge.getDomainConfig().getDomains(); } public void call(String channel, Params params) { mWebViewBridge.call(channel, params); } public void call(String channel, Params params, Callback<?> callback) { mWebViewBridge.call(channel, params, callback); } final public WebViewBridge getWebViewBridge() { return mWebViewBridge; } final public WebViewBridgeConfigurator getConfigurator() { return mConfigurator; } @Bridge("system.environment.set") public void doEnvironmentSet(EnvironmentSetParams params) { mEnvironment.set(params.getName(), params.getValue()); } @Bridge("system.form.picture.select") public void doFormPictureSelect(FormPictureSelectParams params, Callback<FormPictureSelectResult> callback) { // TODO need to implement Triaina Framework original logic } @Bridge("system.net.browser.open") public void doNetBrowserOpen(NetBrowserOpenParams params) { SystemUtils.launchExternalBrowser(getActivity(), Uri.parse(params.getUrl())); } @Bridge("system.web.error") public void doWebError() { // ignore } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View inflatedView = mConfigurator.loadInflatedView(this, inflater, container); mWebViewBridge = mConfigurator.loadWebViewBridge(this, inflatedView); mWebViewStateOnDestroyView = null; mConfigurator.configure(mWebViewBridge); mConfigurator.registerBridge(mWebViewBridge, this); configureSettings(); configureClients(); return inflatedView; } protected void configureSettings() { mConfigurator.configureSetting(mWebViewBridge); } protected void configureClients() { mWebViewBridge.setWebChromeClient(new TriainaWebChromeClient(getActivity())); mWebViewBridge.setWebViewClient(new TriainaWebViewClient()); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mIsRestored = mRestoreManager.restoreWebView(mWebViewBridge, savedInstanceState); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mWebViewStateOnDestroyView != null) outState.putAll(mWebViewStateOnDestroyView); // XXX if (mWebViewBridge != null) storeWebView(outState); } protected void storeWebView(Bundle outState) { mRestoreManager.storeWebView(mWebViewBridge, outState, getActivity().getTaskId()); } @Override public void onResume() { super.onResume(); mWebViewBridge.resume(); } @Override public void onPause() { mWebViewBridge.pause(); super.onPause(); } @Override public void onDestroyView() { mWebViewStateOnDestroyView = new Bundle(); try { storeWebView(mWebViewStateOnDestroyView); mWebViewBridge.destroy(); } catch (Exception exp) { Log.w(TAG, exp.getMessage() + "", exp); } super.onDestroyView(); } public boolean isRestored() { return mIsRestored; } }
Fix not clearing webview afeter destroy
android/WebViewBridge/src/triaina/webview/AbstractWebViewBridgeFragment.java
Fix not clearing webview afeter destroy
<ide><path>ndroid/WebViewBridge/src/triaina/webview/AbstractWebViewBridgeFragment.java <ide> @Override <ide> public void onDestroyView() { <ide> mWebViewStateOnDestroyView = new Bundle(); <add> storeWebView(mWebViewStateOnDestroyView); <ide> try { <del> storeWebView(mWebViewStateOnDestroyView); <ide> mWebViewBridge.destroy(); <ide> } catch (Exception exp) { <ide> Log.w(TAG, exp.getMessage() + "", exp); <ide> } <add> mWebViewBridge = null; <ide> super.onDestroyView(); <ide> } <ide>
Java
mit
6e12c9d9ba10dac36898c214d35f795cf7927081
0
FTC10794/robolib,FTC10794/robocode
package org.firstinspires.ftc.robotcontroller.libs; import com.qualcomm.robotcore.util.Range; /** * Created by Team 10794 on 10/22/16. * This is a library class that controls the motors */ public class MotorFunctions { //These are the control variables for the function. They are set in the constructor. private static int motorMin, motorMax, servoMin, servoMax; private static double servoDelta; /** * Constructor initializing the library class with the desired max and min ranges and servo * delta * @param pMotorMin the minimum value of the DC motor * @param pMotorMax the maximum value of the DC motor * @param pServoMin the minimum value of the servo * @param pServoMax the maximum value of the servo * @param pServoDelta the amount by which to change the servo position */ public MotorFunctions(int pMotorMin, int pMotorMax, int pServoMin, int pServoMax, double pServoDelta) { motorMin = pMotorMin; motorMax = pMotorMax; servoMin = pServoMin; servoMax = pServoMax; servoDelta = pServoDelta; } /** * Normalizes the power level from the joystick value * @param joystickValue The value of the joystick * @return float power level */ public static float dcMotor(float joystickValue) { joystickValue = Range.clip(joystickValue, motorMin, motorMax); joystickValue = (float)scaleInput(joystickValue); return joystickValue; } /** * Normalizes the power level from the joystick value * @param joystickValue The value of the joystick * @param minRange The minimum value of the joystick * @param maxRange The maximum value of the joystick * @return float power level */ public static float dcMotor(float joystickValue, int minRange, int maxRange) { joystickValue = Range.clip(joystickValue, minRange, maxRange); joystickValue = (float)scaleInput(joystickValue); return joystickValue; } /** * Normalizes the servo position * @param position The current servo position * @return double servo position */ public static double servo(double position) { position += servoDelta; position = Range.clip(position, servoMin, servoMax); return position; } /** * Normalizes the servo position * @param position The current servo position * @param servoDelta the amount the current servo changes * @return double servo position */ public static double servo(double position, double servoDelta) { position += servoDelta; position = Range.clip(position, servoMin, servoMax); return position; } /** * Normalizes the servo position * @param position The current servo position * @param minRange The minimum servo position * @param maxRange The maximum servo position * @return double servo position */ public static double servo(double position, int minRange, int maxRange ) { position += servoDelta; position = Range.clip(position, minRange, maxRange); return position; } /** * Normalizes the servo position * @param position The current servo position * @param servoDelta The amount the current servo changes * @param minRange The minimum servo position * @param maxRange The maximum servo position * @return double servo position */ public static double servo(double position, double servoDelta, int minRange, int maxRange) { position += servoDelta; position = Range.clip(position, minRange, maxRange); return position; } /* * This method scales the joystick input so for low joystick values, the * scaled value is less than linear. This is to make it easier to drive * the robot more precisely at slower speeds. */ private static double scaleInput(double dVal) { double[] scaleArray = { 0.0, 0.05, 0.09, 0.10, 0.12, 0.15, 0.18, 0.24, 0.30, 0.36, 0.43, 0.50, 0.60, 0.72, 0.85, 1.00, 1.00 }; // get the corresponding index for the scaleInput array. int index = (int) (dVal * 16.0); // index should be positive. if (index < 0) { index = -index; } // index cannot exceed size of array minus 1. if (index > 16) { index = 16; } // get value from the array. double dScale = 0.0; if (dVal < 0) { dScale = -scaleArray[index]; } else { dScale = scaleArray[index]; } // return scaled value. return dScale; } }
FtcRobotController/src/main/java/org/firstinspires/ftc/robotcontroller/libs/MotorFunctions.java
package org.firstinspires.ftc.robotcontroller.libs; import com.qualcomm.robotcore.util.Range; /** * Created by Team 10794 on 10/22/16. * This is a library class that controls the motors */ public class MotorFunctions { //These are the control variables for the function. They are set in the constructor. private static int motorMin, motorMax, servoMin, servoMax; private static double servoDelta; /** * Constructor initializing the library class with the desired max and min ranges and servo * delta * @param motorMin the minimum value of the DC motor * @param motorMax the maximum value of the DC motor * @param servoMin the minimum value of the servo * @param servoMax the maximum value of the servo * @param servoDelta the amount by which to change the servo position */ public MotorFunctions(int motorMin, int motorMax, int servoMin, int servoMax, double servoDelta) { this.motorMin = motorMin; this.motorMax = motorMax; this.servoMin = servoMin; this.servoMax = servoMax; this.servoDelta = servoDelta; } /** * Normalizes the power level from the joystick value * @param joystickValue The value of the joystick * @return float power level */ public static float dcMotor(float joystickValue) { joystickValue = Range.clip(joystickValue, motorMin, motorMax); joystickValue = (float)scaleInput(joystickValue); return joystickValue; } /** * Normalizes the power level from the joystick value * @param joystickValue The value of the joystick * @param minRange The minimum value of the joystick * @param maxRange The maximum value of the joystick * @return float power level */ public static float dcMotor(float joystickValue, int minRange, int maxRange) { joystickValue = Range.clip(joystickValue, minRange, maxRange); joystickValue = (float)scaleInput(joystickValue); return joystickValue; } /** * Normalizes the servo position * @param position The current servo position * @return double servo position */ public static double servo(double position) { position += servoDelta; position = Range.clip(position, servoMin, servoMax); return position; } /** * Normalizes the servo position * @param position The current servo position * @param servoDelta the amount the current servo changes * @return double servo position */ public static double servo(double position, double servoDelta) { position += servoDelta; position = Range.clip(position, servoMin, servoMax); return position; } /** * Normalizes the servo position * @param position The current servo position * @param minRange The minimum servo position * @param maxRange The maximum servo position * @return double servo position */ public static double servo(double position, int minRange, int maxRange ) { position += servoDelta; position = Range.clip(position, minRange, maxRange); return position; } /** * Normalizes the servo position * @param position The current servo position * @param servoDelta The amount the current servo changes * @param minRange The minimum servo position * @param maxRange The maximum servo position * @return double servo position */ public static double servo(double position, double servoDelta, int minRange, int maxRange) { position += servoDelta; position = Range.clip(position, minRange, maxRange); return position; } /* * This method scales the joystick input so for low joystick values, the * scaled value is less than linear. This is to make it easier to drive * the robot more precisely at slower speeds. */ private static double scaleInput(double dVal) { double[] scaleArray = { 0.0, 0.05, 0.09, 0.10, 0.12, 0.15, 0.18, 0.24, 0.30, 0.36, 0.43, 0.50, 0.60, 0.72, 0.85, 1.00, 1.00 }; // get the corresponding index for the scaleInput array. int index = (int) (dVal * 16.0); // index should be positive. if (index < 0) { index = -index; } // index cannot exceed size of array minus 1. if (index > 16) { index = 16; } // get value from the array. double dScale = 0.0; if (dVal < 0) { dScale = -scaleArray[index]; } else { dScale = scaleArray[index]; } // return scaled value. return dScale; } }
Changed param names to account for static vars
FtcRobotController/src/main/java/org/firstinspires/ftc/robotcontroller/libs/MotorFunctions.java
Changed param names to account for static vars
<ide><path>tcRobotController/src/main/java/org/firstinspires/ftc/robotcontroller/libs/MotorFunctions.java <ide> /** <ide> * Constructor initializing the library class with the desired max and min ranges and servo <ide> * delta <del> * @param motorMin the minimum value of the DC motor <del> * @param motorMax the maximum value of the DC motor <del> * @param servoMin the minimum value of the servo <del> * @param servoMax the maximum value of the servo <del> * @param servoDelta the amount by which to change the servo position <add> * @param pMotorMin the minimum value of the DC motor <add> * @param pMotorMax the maximum value of the DC motor <add> * @param pServoMin the minimum value of the servo <add> * @param pServoMax the maximum value of the servo <add> * @param pServoDelta the amount by which to change the servo position <ide> */ <del> public MotorFunctions(int motorMin, int motorMax, int servoMin, int servoMax, double servoDelta) { <del> this.motorMin = motorMin; <del> this.motorMax = motorMax; <del> this.servoMin = servoMin; <del> this.servoMax = servoMax; <add> public MotorFunctions(int pMotorMin, int pMotorMax, int pServoMin, int pServoMax, double <add> pServoDelta) { <add> motorMin = pMotorMin; <add> motorMax = pMotorMax; <add> servoMin = pServoMin; <add> servoMax = pServoMax; <ide> <del> this.servoDelta = servoDelta; <add> servoDelta = pServoDelta; <ide> } <ide> <ide> /**
Java
apache-2.0
e543c08f134159e2b57425beeebd42464be0ced8
0
tiffchou/odo,tiffchou/odo,groupon/odo,groupon/odo
/* SOURCE: https://raw.github.com/lightbody/browsermob-proxy/7f0a6ec2663bace3f64c878e7f006090c38fbfdc/src/main/java/net/lightbody/bmp/proxy/BrowserMobProxyHandler.java ORIGINAL LICENSE: Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. GROUPON LICENSE: Copyright 2014 Groupon, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.groupon.odo.bmp; import com.groupon.odo.proxylib.Constants; import com.groupon.odo.proxylib.ServerRedirectService; import java.io.File; import java.io.IOException; import java.net.BindException; import java.net.ConnectException; import java.net.InetAddress; import java.net.Socket; import java.net.URL; import java.net.UnknownHostException; import java.security.cert.X509Certificate; import java.util.Date; import java.util.Enumeration; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import com.squareup.okhttp.RequestBody; import com.squareup.okhttp.MediaType; import net.lightbody.bmp.proxy.FirefoxErrorConstants; import net.lightbody.bmp.proxy.FirefoxErrorContent; import net.lightbody.bmp.proxy.http.BadURIException; import net.lightbody.bmp.proxy.jetty.http.EOFException; import net.lightbody.bmp.proxy.jetty.http.HttpConnection; import net.lightbody.bmp.proxy.jetty.http.HttpException; import net.lightbody.bmp.proxy.jetty.http.HttpFields; import net.lightbody.bmp.proxy.jetty.http.HttpListener; import net.lightbody.bmp.proxy.jetty.http.HttpMessage; import net.lightbody.bmp.proxy.jetty.http.HttpRequest; import net.lightbody.bmp.proxy.jetty.http.HttpResponse; import net.lightbody.bmp.proxy.jetty.http.HttpServer; import net.lightbody.bmp.proxy.jetty.http.HttpTunnel; import net.lightbody.bmp.proxy.jetty.http.SocketListener; import net.lightbody.bmp.proxy.jetty.http.SslListener; import net.lightbody.bmp.proxy.jetty.jetty.Server; import net.lightbody.bmp.proxy.jetty.util.InetAddrPort; import net.lightbody.bmp.proxy.jetty.util.URI; import net.lightbody.bmp.proxy.selenium.KeyStoreManager; import net.lightbody.bmp.proxy.selenium.LauncherUtils; import net.lightbody.bmp.proxy.selenium.SeleniumProxyHandler; import net.lightbody.bmp.proxy.util.Log; import okio.BufferedSink; import org.apache.commons.io.IOUtils; import org.apache.http.NoHttpResponseException; import org.apache.http.conn.ConnectTimeoutException; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLProtocolException; import java.security.cert.CertificateException; public class BrowserMobProxyHandler extends SeleniumProxyHandler { private static final Log LOG = new Log(); private static final int HEADER_BUFFER_DEFAULT = 2; private static final long serialVersionUID = 1L; private final String localIP = "127.0.0.1"; private Server jettyServer; private int headerBufferMultiplier = HEADER_BUFFER_DEFAULT; protected final Set<SslRelay> sslRelays = new HashSet<SslRelay>(); // BEGIN ODO CHANGES // Map to hold onto listeners per hostname protected final Map<String, SslRelayOdo> _sslMap = new LinkedHashMap<String, SslRelayOdo>(); protected final Map<String, Date> _certExpirationMap = new LinkedHashMap<String, Date>(); // END ODO CHANGES public BrowserMobProxyHandler() { super(true, "", "", false, false); setShutdownLock(new Object()); // set the tunnel timeout to something larger than the default 30 seconds // we're doing this because SSL connections taking longer than this timeout // will result in a socket connection close that does NOT get handled by the // normal socket connection closing reportError(). Further, it has been seen // that Firefox will actually retry the connection, causing very strange // behavior observed in case http://browsermob.assistly.com/agent/case/27843 // // You can also reproduce it by simply finding some slow loading SSL site // that takes greater than 30 seconds to response. // // Finally, it should be noted that we're setting this timeout to some value // that we anticipate will be larger than any reasonable response time of a // real world request. We don't set it to -1 because the underlying ProxyHandler // will not use it if it's <= 0. We also don't set it to Long.MAX_VALUE because // we don't yet know if this will cause a serious resource drain, so we're // going to try something like 5 minutes for now. setTunnelTimeoutMs(300000); } // BEGIN ODO CHANGES private static final ThreadLocal<String> requestOriginalHostName = new ThreadLocal<String>(); private static final ThreadLocal<URI> requestOriginalURI = new ThreadLocal<URI>(); @Override /** * This is the original handleConnect from BrowserMobProxyHandler with the following changes: * * 1. Store the original URI in a ThreadLocal so that we can determine the host addr later * 2. Store the original hostname in a ThreadLocal so we don't need to do the same string processing again later * 2. Set the URI to 127.0.0.1 to pass into Odo * 3. Call the original handleConnect from SeleniumProxyHandler(copied to handle an Odo SslRelay) */ public void handleConnect(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws HttpException, IOException { URI uri = request.getURI(); String original = uri.toString(); LOG.info("Hostname: " + original); String host = original; int colon = original.indexOf(':'); if (colon != -1) { host = original.substring(0, colon); } // store the original host name requestOriginalHostName.set(host); // make a copy of the URI(have to create a new URI otherwise things are copied by reference and get changed) URI realURI = new URI(request.getURI()); requestOriginalURI.set(realURI); // send requests to Odo HTTPS port int httpsPort = com.groupon.odo.proxylib.Utils.getSystemPort(Constants.SYS_HTTPS_PORT); uri.setURI("127.0.0.1:" + httpsPort); uri.setPort(httpsPort); handleConnectOriginal(pathInContext, pathParams, request, response); } // END ODO CHANGES // BEGIN ODO CHANGES /** * Copied from original SeleniumProxyHandler * Changed SslRelay to SslListener and getSslRelayOrCreateNew to getSslRelayOrCreateNewOdo * No other changes to the function * * @param pathInContext * @param pathParams * @param request * @param response * @throws HttpException * @throws IOException */ public void handleConnectOriginal(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws HttpException, IOException { URI uri = request.getURI(); try { LOG.fine("CONNECT: " + uri); InetAddrPort addrPort; // When logging, we'll attempt to send messages to hosts that don't exist if (uri.toString().endsWith(".selenium.doesnotexist:443")) { // so we have to do set the host to be localhost (you can't new up an IAP with a non-existent hostname) addrPort = new InetAddrPort(443); } else { addrPort = new InetAddrPort(uri.toString()); } if (isForbidden(HttpMessage.__SSL_SCHEME, addrPort.getHost(), addrPort.getPort(), false)) { sendForbid(request, response, uri); } else { HttpConnection http_connection = request.getHttpConnection(); http_connection.forceClose(); HttpServer server = http_connection.getHttpServer(); SslListener listener = getSslRelayOrCreateNewOdo(uri, addrPort, server); int port = listener.getPort(); // Get the timeout int timeoutMs = 30000; Object maybesocket = http_connection.getConnection(); if (maybesocket instanceof Socket) { Socket s = (Socket) maybesocket; timeoutMs = s.getSoTimeout(); } // Create the tunnel HttpTunnel tunnel = newHttpTunnel(request, response, InetAddress.getByName(null), port, timeoutMs); if (tunnel != null) { // TODO - need to setup semi-busy loop for IE. if (_tunnelTimeoutMs > 0) { tunnel.getSocket().setSoTimeout(_tunnelTimeoutMs); if (maybesocket instanceof Socket) { Socket s = (Socket) maybesocket; s.setSoTimeout(_tunnelTimeoutMs); } } tunnel.setTimeoutMs(timeoutMs); customizeConnection(pathInContext, pathParams, request, tunnel.getSocket()); request.getHttpConnection().setHttpTunnel(tunnel); response.setStatus(HttpResponse.__200_OK); response.setContentLength(0); } request.setHandled(true); } } catch (Exception e) { LOG.fine("error during handleConnect", e); response.sendError(HttpResponse.__500_Internal_Server_Error, e.toString()); } } // END ODO CHANGES // BEGIN ODO CHANGES /** * This function wires up a SSL Listener with the cyber villians root CA and cert with the correct CNAME for the request * * @param host * @param listener */ protected X509Certificate wireUpSslWithCyberVilliansCAOdo(String host, SslListener listener) { host = requestOriginalHostName.get(); // Add cybervillians CA(from browsermob) try { // see https://github.com/webmetrics/browsermob-proxy/issues/105 String escapedHost = host.replace('*', '_'); KeyStoreManager keyStoreManager = Utils.getKeyStoreManager(escapedHost); keyStoreManager.getKeyStore().deleteEntry(KeyStoreManager._caPrivKeyAlias); keyStoreManager.persist(); listener.setKeystore(new File("seleniumSslSupport" + File.separator + escapedHost + File.separator + "cybervillainsCA.jks").getAbsolutePath()); return keyStoreManager.getCertificateByAlias(escapedHost); } catch (Exception e) { throw new RuntimeException(e); } } private SslRelayOdo getSslRelayOrCreateNewOdo(URI uri, InetAddrPort addrPort, HttpServer server) throws Exception { URI realURI = requestOriginalURI.get(); InetAddrPort realPort = new InetAddrPort(realURI.toString()); LOG.info("GETSSLRELAY: {}, {}", realURI, realPort); String host = new URL("https://" + realURI.toString()).getHost(); // create a host and port string so the listener sslMap can be keyed off the combination String hostAndPort = host.concat(String.valueOf(realPort.getPort())); LOG.info("getSSLRelay host: {}", hostAndPort); SslRelayOdo listener = null; synchronized (_sslMap) { listener = _sslMap.get(hostAndPort); // check the certificate expiration to see if we need to reload it if (listener != null) { Date exprDate = _certExpirationMap.get(hostAndPort); if (exprDate.before(new Date())) { // destroy the listener if (listener.getHttpServer() != null && listener.isStarted()) { listener.getHttpServer().removeListener(listener); } listener = null; } } // create the listener if it didn't exist if (listener == null) { listener = new SslRelayOdo(addrPort); listener.setNukeDirOrFile(null); _certExpirationMap.put(hostAndPort, wireUpSslWithCyberVilliansCAOdo(host, listener).getNotAfter()); listener.setPassword("password"); listener.setKeyPassword("password"); if (!listener.isStarted()) { server.addListener(listener); startRelayWithPortTollerance(server, listener, 1); } _sslMap.put(hostAndPort, listener); } } return listener; } // END ODO CHANGES // BEGIN ODO CHANGES // Changed method signature from SslRelay to SslListener // END ODO CHANGES private void startRelayWithPortTollerance(HttpServer server, SslListener relay, int tries) throws Exception { if (tries >= 5) { throw new BindException("Unable to bind to several ports, most recently " + relay.getPort() + ". Giving up"); } try { if (server.isStarted()) { relay.start(); } else { throw new RuntimeException("Can't start SslRelay: server is not started (perhaps it was just shut down?)"); } } catch (BindException e) { // doh - the port is being used up, let's pick a new port LOG.info("Unable to bind to port %d, going to try port %d now", relay.getPort(), relay.getPort() + 1); relay.setPort(relay.getPort() + 1); startRelayWithPortTollerance(server, relay, tries + 1); } } @Override protected HttpTunnel newHttpTunnel(HttpRequest httpRequest, HttpResponse httpResponse, InetAddress inetAddress, int i, int i1) throws IOException { // we're opening up a new tunnel, so let's make sure that the associated SslRelay (which may or may not be new) has the proper buffer settings adjustListenerBuffers(); return super.newHttpTunnel(httpRequest, httpResponse, inetAddress, i, i1); } /** * Returns a OkHttpClient that ignores SSL cert errors * @return */ private static OkHttpClient getUnsafeOkHttpClient() { try { // Create a trust manager that does not validate certificate chains final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { } @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } } }; // Install the all-trusting trust manager final SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); // Create an ssl socket factory with our all-trusting manager final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.setSslSocketFactory(sslSocketFactory); okHttpClient.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); return okHttpClient; } catch (Exception e) { throw new RuntimeException(e); } } // ODO VERSION protected long proxyPlainTextRequest(final URL url, String pathInContext, String pathParams, HttpRequest request, final HttpResponse response) throws IOException { try { String urlStr = url.toString(); if (urlStr.toLowerCase().startsWith(Constants.ODO_INTERNAL_WEBAPP_URL)) { urlStr = "http://localhost:" + com.groupon.odo.proxylib.Utils.getSystemPort(Constants.SYS_HTTP_PORT) + "/odo"; } // setup okhttp to ignore ssl issues OkHttpClient okHttpClient = getUnsafeOkHttpClient(); okHttpClient.setFollowRedirects(false); okHttpClient.setFollowSslRedirects(false); Request.Builder okRequestBuilder = new Request.Builder(); if (urlStr.startsWith("http://")) { int httpPort = com.groupon.odo.proxylib.Utils.getSystemPort(Constants.SYS_HTTP_PORT); urlStr = urlStr.replace(getHostNameFromURL(urlStr), localIP + ":" + httpPort); } okRequestBuilder = okRequestBuilder.url(urlStr); // copy request headers Enumeration<?> enm = request.getFieldNames(); boolean isGet = "GET".equals(request.getMethod()); boolean hasContent = false; boolean usedContentLength = false; long contentLength = 0; while (enm.hasMoreElements()) { String hdr = (String) enm.nextElement(); if (!isGet && HttpFields.__ContentType.equals(hdr)) { hasContent = true; } if (!isGet && HttpFields.__ContentLength.equals(hdr)) { contentLength = Long.parseLong(request.getField(hdr)); usedContentLength = true; } Enumeration<?> vals = request.getFieldValues(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { if (!isGet && HttpFields.__ContentLength.equals(hdr) && Integer.parseInt(val) > 0) { hasContent = true; } if (!_DontProxyHeaders.containsKey(hdr)) { okRequestBuilder = okRequestBuilder.addHeader(hdr, val); //httpReq.addRequestHeader(hdr, val); } } } } if ("GET".equals(request.getMethod())) { // don't need to do anything else } else if ("POST".equals(request.getMethod()) || "PUT".equals(request.getMethod()) || "DELETE".equals(request.getMethod())) { RequestBody okRequestBody = null; if (hasContent) { final String contentType = request.getContentType(); final byte[] bytes = IOUtils.toByteArray(request.getInputStream()); okRequestBody = new RequestBody() { @Override public MediaType contentType() { MediaType.parse(contentType); return null; } @Override public void writeTo(BufferedSink bufferedSink) throws IOException { bufferedSink.write(bytes); } }; // we need to add some ODO specific headers to give ODO a hint for content-length vs transfer-encoding // since okHTTP will automatically chunk even if the request was not chunked // this allows Odo to set the appropriate headers when the server request is made if (usedContentLength) { okRequestBuilder = okRequestBuilder.addHeader("ODO-POST-TYPE", "content-length:" + contentLength); } } else { okRequestBody = RequestBody.create(null, new byte[0]); } if ("POST".equals(request.getMethod())) { okRequestBuilder = okRequestBuilder.post(okRequestBody); } else if ("PUT".equals(request.getMethod())) { okRequestBuilder = okRequestBuilder.put(okRequestBody); } else if ("DELETE".equals(request.getMethod())) { okRequestBuilder = okRequestBuilder.delete(okRequestBody); } } else if ("OPTIONS".equals(request.getMethod())) { // NOT SUPPORTED } else if ("HEAD".equals(request.getMethod())) { okRequestBuilder = okRequestBuilder.head(); } else { LOG.warn("Unexpected request method %s, giving up", request.getMethod()); request.setHandled(true); return -1; } Request okRequest = okRequestBuilder.build(); Response okResponse = okHttpClient.newCall(okRequest).execute(); // Set status and response message response.setStatus(okResponse.code()); response.setReason(okResponse.message()); // copy response headers for (int headerNum = 0; headerNum < okResponse.headers().size(); headerNum++) { String headerName = okResponse.headers().name(headerNum); if (!_DontProxyHeaders.containsKey(headerName) && !_ProxyAuthHeaders.containsKey(headerName)) { response.addField(headerName, okResponse.headers().value(headerNum)); } } // write output to response output stream try { IOUtils.copy(okResponse.body().byteStream(), response.getOutputStream()); } catch (Exception e) { // ignoring this until we refactor the proxy // The copy occasionally fails due to an issue where okResponse has more data in the body than it's supposed to // The client still gets all of the data it was expecting } request.setHandled(true); return okResponse.body().contentLength(); } catch (Exception e) { LOG.warn("Caught exception proxying: ", e); reportError(e, url, response); request.setHandled(true); return -1; } } private static void reportError(Exception e, URL url, HttpResponse response) { FirefoxErrorContent error = FirefoxErrorContent.GENERIC; if (e instanceof UnknownHostException) { error = FirefoxErrorContent.DNS_NOT_FOUND; } else if (e instanceof ConnectException) { error = FirefoxErrorContent.CONN_FAILURE; } else if (e instanceof ConnectTimeoutException) { error = FirefoxErrorContent.NET_TIMEOUT; } else if (e instanceof NoHttpResponseException) { error = FirefoxErrorContent.NET_RESET; } else if (e instanceof EOFException) { error = FirefoxErrorContent.NET_INTERRUPT; } else if (e instanceof IllegalArgumentException && e.getMessage().startsWith("Host name may not be null")) { error = FirefoxErrorContent.DNS_NOT_FOUND; } else if (e instanceof BadURIException) { error = FirefoxErrorContent.MALFORMED_URI; } else if (e instanceof SSLProtocolException) { return; } String shortDesc = String.format(error.getShortDesc(), url.getHost()); String text = String.format(FirefoxErrorConstants.ERROR_PAGE, error.getTitle(), shortDesc, error.getLongDesc()); try { response.setStatus(HttpResponse.__502_Bad_Gateway); response.setContentLength(text.length()); response.getOutputStream().write(text.getBytes()); } catch (IOException e1) { LOG.warn("IOException while trying to report an HTTP error"); } } public void setJettyServer(Server jettyServer) { this.jettyServer = jettyServer; } public void adjustListenerBuffers() { // configure the listeners to have larger buffers. We do this because we've seen cases where the header is // too large. Normally this would happen on "meaningless" JS includes for ad networks, but we eventually saw // it in a way that caused a Selenium script not to work due to too many headers (see [email protected]) HttpListener[] listeners = jettyServer.getListeners(); for (HttpListener listener : listeners) { if (listener instanceof SocketListener) { SocketListener sl = (SocketListener) listener; if (sl.getBufferReserve() != 512 * headerBufferMultiplier) { sl.setBufferReserve(512 * headerBufferMultiplier); } if (sl.getBufferSize() != 8192 * headerBufferMultiplier) { sl.setBufferSize(8192 * headerBufferMultiplier); } } } } // BEGIN ODO CHANGES /** * Cleanup function to remove all allocated listeners */ public void cleanup() { synchronized (_sslMap) { for (SslRelayOdo relay : _sslMap.values()) { if (relay.getHttpServer() != null && relay.isStarted()) { relay.getHttpServer().removeListener(relay); } } sslRelays.clear(); } } // END ODO CHANGES // BEGIN ODO CHANGES // Copied from SeleniumProxyHandler(renamed to SslRelayOdo from SslRelay; no other changes) public static class SslRelayOdo extends SslListener { InetAddrPort _addr; File nukeDirOrFile; private static final long serialVersionUID = 1L; SslRelayOdo(InetAddrPort addr) { _addr = addr; } public void setNukeDirOrFile(File nukeDirOrFile) { this.nukeDirOrFile = nukeDirOrFile; } protected void customizeRequest(Socket socket, HttpRequest request) { super.customizeRequest(socket, request); URI uri = request.getURI(); // Convert the URI to a proxy URL // // NOTE: Don't just add a host + port to the request URI, since this causes the URI to // get "dirty" and be rewritten, potentially breaking the proxy slightly. Instead, // create a brand new URI that includes the protocol, the host, and the port, but leaves // intact the path + query string "as is" so that it does not get rewritten. request.setURI(new URI("https://" + _addr.getHost() + ":" + _addr.getPort() + uri.toString())); } public void stop() throws InterruptedException { super.stop(); if (nukeDirOrFile != null) { if (nukeDirOrFile.isDirectory()) { LauncherUtils.recursivelyDeleteDir(nukeDirOrFile); } else { nukeDirOrFile.delete(); } } } } /** * @param url full url containing hostname * @return hostname */ public static String getHostNameFromURL(String url) { int urlLeftPos = url.indexOf("//"); String hostName = url.substring(urlLeftPos + 2); int urlRightPos = hostName.indexOf("/"); if (urlRightPos != -1) { hostName = hostName.substring(0, urlRightPos); } // now look for a port int portPos = hostName.indexOf(":"); if (portPos != -1) { hostName = hostName.substring(0, portPos); } return hostName; } // END ODO CHANGES }
browsermob-proxy/src/main/java/com/groupon/odo/bmp/BrowserMobProxyHandler.java
/* SOURCE: https://raw.github.com/lightbody/browsermob-proxy/7f0a6ec2663bace3f64c878e7f006090c38fbfdc/src/main/java/net/lightbody/bmp/proxy/BrowserMobProxyHandler.java ORIGINAL LICENSE: Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. GROUPON LICENSE: Copyright 2014 Groupon, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.groupon.odo.bmp; import com.groupon.odo.proxylib.Constants; import com.groupon.odo.proxylib.ServerRedirectService; import java.io.File; import java.io.IOException; import java.net.BindException; import java.net.ConnectException; import java.net.InetAddress; import java.net.Socket; import java.net.URL; import java.net.UnknownHostException; import java.security.cert.X509Certificate; import java.util.Date; import java.util.Enumeration; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import com.squareup.okhttp.RequestBody; import com.squareup.okhttp.MediaType; import net.lightbody.bmp.proxy.FirefoxErrorConstants; import net.lightbody.bmp.proxy.FirefoxErrorContent; import net.lightbody.bmp.proxy.http.BadURIException; import net.lightbody.bmp.proxy.jetty.http.EOFException; import net.lightbody.bmp.proxy.jetty.http.HttpConnection; import net.lightbody.bmp.proxy.jetty.http.HttpException; import net.lightbody.bmp.proxy.jetty.http.HttpFields; import net.lightbody.bmp.proxy.jetty.http.HttpListener; import net.lightbody.bmp.proxy.jetty.http.HttpMessage; import net.lightbody.bmp.proxy.jetty.http.HttpRequest; import net.lightbody.bmp.proxy.jetty.http.HttpResponse; import net.lightbody.bmp.proxy.jetty.http.HttpServer; import net.lightbody.bmp.proxy.jetty.http.HttpTunnel; import net.lightbody.bmp.proxy.jetty.http.SocketListener; import net.lightbody.bmp.proxy.jetty.http.SslListener; import net.lightbody.bmp.proxy.jetty.jetty.Server; import net.lightbody.bmp.proxy.jetty.util.InetAddrPort; import net.lightbody.bmp.proxy.jetty.util.URI; import net.lightbody.bmp.proxy.selenium.KeyStoreManager; import net.lightbody.bmp.proxy.selenium.LauncherUtils; import net.lightbody.bmp.proxy.selenium.SeleniumProxyHandler; import net.lightbody.bmp.proxy.util.Log; import okio.BufferedSink; import org.apache.commons.io.IOUtils; import org.apache.http.NoHttpResponseException; import org.apache.http.conn.ConnectTimeoutException; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLProtocolException; import java.security.cert.CertificateException; public class BrowserMobProxyHandler extends SeleniumProxyHandler { private static final Log LOG = new Log(); private static final int HEADER_BUFFER_DEFAULT = 2; private static final long serialVersionUID = 1L; private Server jettyServer; private int headerBufferMultiplier = HEADER_BUFFER_DEFAULT; protected final Set<SslRelay> sslRelays = new HashSet<SslRelay>(); // BEGIN ODO CHANGES // Map to hold onto listeners per hostname protected final Map<String, SslRelayOdo> _sslMap = new LinkedHashMap<String, SslRelayOdo>(); protected final Map<String, Date> _certExpirationMap = new LinkedHashMap<String, Date>(); // END ODO CHANGES public BrowserMobProxyHandler() { super(true, "", "", false, false); setShutdownLock(new Object()); // set the tunnel timeout to something larger than the default 30 seconds // we're doing this because SSL connections taking longer than this timeout // will result in a socket connection close that does NOT get handled by the // normal socket connection closing reportError(). Further, it has been seen // that Firefox will actually retry the connection, causing very strange // behavior observed in case http://browsermob.assistly.com/agent/case/27843 // // You can also reproduce it by simply finding some slow loading SSL site // that takes greater than 30 seconds to response. // // Finally, it should be noted that we're setting this timeout to some value // that we anticipate will be larger than any reasonable response time of a // real world request. We don't set it to -1 because the underlying ProxyHandler // will not use it if it's <= 0. We also don't set it to Long.MAX_VALUE because // we don't yet know if this will cause a serious resource drain, so we're // going to try something like 5 minutes for now. setTunnelTimeoutMs(300000); } // BEGIN ODO CHANGES private static final ThreadLocal<String> requestOriginalHostName = new ThreadLocal<String>(); private static final ThreadLocal<URI> requestOriginalURI = new ThreadLocal<URI>(); @Override /** * This is the original handleConnect from BrowserMobProxyHandler with the following changes: * * 1. Store the original URI in a ThreadLocal so that we can determine the host addr later * 2. Store the original hostname in a ThreadLocal so we don't need to do the same string processing again later * 2. Set the URI to 127.0.0.1 to pass into Odo * 3. Call the original handleConnect from SeleniumProxyHandler(copied to handle an Odo SslRelay) */ public void handleConnect(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws HttpException, IOException { URI uri = request.getURI(); String original = uri.toString(); LOG.info("Hostname: " + original); String host = original; int colon = original.indexOf(':'); if (colon != -1) { host = original.substring(0, colon); } // store the original host name requestOriginalHostName.set(host); // make a copy of the URI(have to create a new URI otherwise things are copied by reference and get changed) URI realURI = new URI(request.getURI()); requestOriginalURI.set(realURI); // send requests to Odo HTTPS port int httpsPort = com.groupon.odo.proxylib.Utils.getSystemPort(Constants.SYS_HTTPS_PORT); uri.setURI("127.0.0.1:" + httpsPort); uri.setPort(httpsPort); handleConnectOriginal(pathInContext, pathParams, request, response); } // END ODO CHANGES // BEGIN ODO CHANGES /** * Copied from original SeleniumProxyHandler * Changed SslRelay to SslListener and getSslRelayOrCreateNew to getSslRelayOrCreateNewOdo * No other changes to the function * * @param pathInContext * @param pathParams * @param request * @param response * @throws HttpException * @throws IOException */ public void handleConnectOriginal(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws HttpException, IOException { URI uri = request.getURI(); try { LOG.fine("CONNECT: " + uri); InetAddrPort addrPort; // When logging, we'll attempt to send messages to hosts that don't exist if (uri.toString().endsWith(".selenium.doesnotexist:443")) { // so we have to do set the host to be localhost (you can't new up an IAP with a non-existent hostname) addrPort = new InetAddrPort(443); } else { addrPort = new InetAddrPort(uri.toString()); } if (isForbidden(HttpMessage.__SSL_SCHEME, addrPort.getHost(), addrPort.getPort(), false)) { sendForbid(request, response, uri); } else { HttpConnection http_connection = request.getHttpConnection(); http_connection.forceClose(); HttpServer server = http_connection.getHttpServer(); SslListener listener = getSslRelayOrCreateNewOdo(uri, addrPort, server); int port = listener.getPort(); // Get the timeout int timeoutMs = 30000; Object maybesocket = http_connection.getConnection(); if (maybesocket instanceof Socket) { Socket s = (Socket) maybesocket; timeoutMs = s.getSoTimeout(); } // Create the tunnel HttpTunnel tunnel = newHttpTunnel(request, response, InetAddress.getByName(null), port, timeoutMs); if (tunnel != null) { // TODO - need to setup semi-busy loop for IE. if (_tunnelTimeoutMs > 0) { tunnel.getSocket().setSoTimeout(_tunnelTimeoutMs); if (maybesocket instanceof Socket) { Socket s = (Socket) maybesocket; s.setSoTimeout(_tunnelTimeoutMs); } } tunnel.setTimeoutMs(timeoutMs); customizeConnection(pathInContext, pathParams, request, tunnel.getSocket()); request.getHttpConnection().setHttpTunnel(tunnel); response.setStatus(HttpResponse.__200_OK); response.setContentLength(0); } request.setHandled(true); } } catch (Exception e) { LOG.fine("error during handleConnect", e); response.sendError(HttpResponse.__500_Internal_Server_Error, e.toString()); } } // END ODO CHANGES // BEGIN ODO CHANGES /** * This function wires up a SSL Listener with the cyber villians root CA and cert with the correct CNAME for the request * * @param host * @param listener */ protected X509Certificate wireUpSslWithCyberVilliansCAOdo(String host, SslListener listener) { host = requestOriginalHostName.get(); // Add cybervillians CA(from browsermob) try { // see https://github.com/webmetrics/browsermob-proxy/issues/105 String escapedHost = host.replace('*', '_'); KeyStoreManager keyStoreManager = Utils.getKeyStoreManager(escapedHost); keyStoreManager.getKeyStore().deleteEntry(KeyStoreManager._caPrivKeyAlias); keyStoreManager.persist(); listener.setKeystore(new File("seleniumSslSupport" + File.separator + escapedHost + File.separator + "cybervillainsCA.jks").getAbsolutePath()); return keyStoreManager.getCertificateByAlias(escapedHost); } catch (Exception e) { throw new RuntimeException(e); } } private SslRelayOdo getSslRelayOrCreateNewOdo(URI uri, InetAddrPort addrPort, HttpServer server) throws Exception { URI realURI = requestOriginalURI.get(); InetAddrPort realPort = new InetAddrPort(realURI.toString()); LOG.info("GETSSLRELAY: {}, {}", realURI, realPort); String host = new URL("https://" + realURI.toString()).getHost(); // create a host and port string so the listener sslMap can be keyed off the combination String hostAndPort = host.concat(String.valueOf(realPort.getPort())); LOG.info("getSSLRelay host: {}", hostAndPort); SslRelayOdo listener = null; synchronized (_sslMap) { listener = _sslMap.get(hostAndPort); // check the certificate expiration to see if we need to reload it if (listener != null) { Date exprDate = _certExpirationMap.get(hostAndPort); if (exprDate.before(new Date())) { // destroy the listener if (listener.getHttpServer() != null && listener.isStarted()) { listener.getHttpServer().removeListener(listener); } listener = null; } } // create the listener if it didn't exist if (listener == null) { listener = new SslRelayOdo(addrPort); listener.setNukeDirOrFile(null); _certExpirationMap.put(hostAndPort, wireUpSslWithCyberVilliansCAOdo(host, listener).getNotAfter()); listener.setPassword("password"); listener.setKeyPassword("password"); if (!listener.isStarted()) { server.addListener(listener); startRelayWithPortTollerance(server, listener, 1); } _sslMap.put(hostAndPort, listener); } } return listener; } // END ODO CHANGES // BEGIN ODO CHANGES // Changed method signature from SslRelay to SslListener // END ODO CHANGES private void startRelayWithPortTollerance(HttpServer server, SslListener relay, int tries) throws Exception { if (tries >= 5) { throw new BindException("Unable to bind to several ports, most recently " + relay.getPort() + ". Giving up"); } try { if (server.isStarted()) { relay.start(); } else { throw new RuntimeException("Can't start SslRelay: server is not started (perhaps it was just shut down?)"); } } catch (BindException e) { // doh - the port is being used up, let's pick a new port LOG.info("Unable to bind to port %d, going to try port %d now", relay.getPort(), relay.getPort() + 1); relay.setPort(relay.getPort() + 1); startRelayWithPortTollerance(server, relay, tries + 1); } } @Override protected HttpTunnel newHttpTunnel(HttpRequest httpRequest, HttpResponse httpResponse, InetAddress inetAddress, int i, int i1) throws IOException { // we're opening up a new tunnel, so let's make sure that the associated SslRelay (which may or may not be new) has the proper buffer settings adjustListenerBuffers(); return super.newHttpTunnel(httpRequest, httpResponse, inetAddress, i, i1); } /** * Returns a OkHttpClient that ignores SSL cert errors * @return */ private static OkHttpClient getUnsafeOkHttpClient() { try { // Create a trust manager that does not validate certificate chains final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { } @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } } }; // Install the all-trusting trust manager final SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); // Create an ssl socket factory with our all-trusting manager final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.setSslSocketFactory(sslSocketFactory); okHttpClient.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); return okHttpClient; } catch (Exception e) { throw new RuntimeException(e); } } // ODO VERSION protected long proxyPlainTextRequest(final URL url, String pathInContext, String pathParams, HttpRequest request, final HttpResponse response) throws IOException { try { String urlStr = url.toString(); if (urlStr.toLowerCase().startsWith(Constants.ODO_INTERNAL_WEBAPP_URL)) { urlStr = "http://localhost:" + com.groupon.odo.proxylib.Utils.getSystemPort(Constants.SYS_HTTP_PORT) + "/odo"; } // setup okhttp to ignore ssl issues OkHttpClient okHttpClient = getUnsafeOkHttpClient(); okHttpClient.setFollowRedirects(false); okHttpClient.setFollowSslRedirects(false); Request.Builder okRequestBuilder = new Request.Builder(); if (urlStr.startsWith("http://")) { int httpPort = com.groupon.odo.proxylib.Utils.getSystemPort(Constants.SYS_HTTP_PORT); urlStr = urlStr.replace(getHostNameFromURL(urlStr), "127.0.0.1:" + httpPort); } okRequestBuilder = okRequestBuilder.url(urlStr); // copy request headers Enumeration<?> enm = request.getFieldNames(); boolean isGet = "GET".equals(request.getMethod()); boolean hasContent = false; boolean usedContentLength = false; long contentLength = 0; while (enm.hasMoreElements()) { String hdr = (String) enm.nextElement(); if (!isGet && HttpFields.__ContentType.equals(hdr)) { hasContent = true; } if (!isGet && HttpFields.__ContentLength.equals(hdr)) { contentLength = Long.parseLong(request.getField(hdr)); usedContentLength = true; } Enumeration<?> vals = request.getFieldValues(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { if (!isGet && HttpFields.__ContentLength.equals(hdr) && Integer.parseInt(val) > 0) { hasContent = true; } if (!_DontProxyHeaders.containsKey(hdr)) { okRequestBuilder = okRequestBuilder.addHeader(hdr, val); //httpReq.addRequestHeader(hdr, val); } } } } if ("GET".equals(request.getMethod())) { // don't need to do anything else } else if ("POST".equals(request.getMethod()) || "PUT".equals(request.getMethod()) || "DELETE".equals(request.getMethod())) { RequestBody okRequestBody = null; if (hasContent) { final String contentType = request.getContentType(); final byte[] bytes = IOUtils.toByteArray(request.getInputStream()); okRequestBody = new RequestBody() { @Override public MediaType contentType() { MediaType.parse(contentType); return null; } @Override public void writeTo(BufferedSink bufferedSink) throws IOException { bufferedSink.write(bytes); } }; // we need to add some ODO specific headers to give ODO a hint for content-length vs transfer-encoding // since okHTTP will automatically chunk even if the request was not chunked // this allows Odo to set the appropriate headers when the server request is made if (usedContentLength) { okRequestBuilder = okRequestBuilder.addHeader("ODO-POST-TYPE", "content-length:" + contentLength); } } else { okRequestBody = RequestBody.create(null, new byte[0]); } if ("POST".equals(request.getMethod())) { okRequestBuilder = okRequestBuilder.post(okRequestBody); } else if ("PUT".equals(request.getMethod())) { okRequestBuilder = okRequestBuilder.put(okRequestBody); } else if ("DELETE".equals(request.getMethod())) { okRequestBuilder = okRequestBuilder.delete(okRequestBody); } } else if ("OPTIONS".equals(request.getMethod())) { // NOT SUPPORTED } else if ("HEAD".equals(request.getMethod())) { okRequestBuilder = okRequestBuilder.head(); } else { LOG.warn("Unexpected request method %s, giving up", request.getMethod()); request.setHandled(true); return -1; } Request okRequest = okRequestBuilder.build(); Response okResponse = okHttpClient.newCall(okRequest).execute(); // Set status and response message response.setStatus(okResponse.code()); response.setReason(okResponse.message()); // copy response headers for (int headerNum = 0; headerNum < okResponse.headers().size(); headerNum++) { String headerName = okResponse.headers().name(headerNum); if (!_DontProxyHeaders.containsKey(headerName) && !_ProxyAuthHeaders.containsKey(headerName)) { response.addField(headerName, okResponse.headers().value(headerNum)); } } // write output to response output stream try { IOUtils.copy(okResponse.body().byteStream(), response.getOutputStream()); } catch (Exception e) { // ignoring this until we refactor the proxy // The copy occasionally fails due to an issue where okResponse has more data in the body than it's supposed to // The client still gets all of the data it was expecting } request.setHandled(true); return okResponse.body().contentLength(); } catch (Exception e) { LOG.warn("Caught exception proxying: ", e); reportError(e, url, response); request.setHandled(true); return -1; } } private static void reportError(Exception e, URL url, HttpResponse response) { FirefoxErrorContent error = FirefoxErrorContent.GENERIC; if (e instanceof UnknownHostException) { error = FirefoxErrorContent.DNS_NOT_FOUND; } else if (e instanceof ConnectException) { error = FirefoxErrorContent.CONN_FAILURE; } else if (e instanceof ConnectTimeoutException) { error = FirefoxErrorContent.NET_TIMEOUT; } else if (e instanceof NoHttpResponseException) { error = FirefoxErrorContent.NET_RESET; } else if (e instanceof EOFException) { error = FirefoxErrorContent.NET_INTERRUPT; } else if (e instanceof IllegalArgumentException && e.getMessage().startsWith("Host name may not be null")) { error = FirefoxErrorContent.DNS_NOT_FOUND; } else if (e instanceof BadURIException) { error = FirefoxErrorContent.MALFORMED_URI; } else if (e instanceof SSLProtocolException) { return; } String shortDesc = String.format(error.getShortDesc(), url.getHost()); String text = String.format(FirefoxErrorConstants.ERROR_PAGE, error.getTitle(), shortDesc, error.getLongDesc()); try { response.setStatus(HttpResponse.__502_Bad_Gateway); response.setContentLength(text.length()); response.getOutputStream().write(text.getBytes()); } catch (IOException e1) { LOG.warn("IOException while trying to report an HTTP error"); } } public void setJettyServer(Server jettyServer) { this.jettyServer = jettyServer; } public void adjustListenerBuffers() { // configure the listeners to have larger buffers. We do this because we've seen cases where the header is // too large. Normally this would happen on "meaningless" JS includes for ad networks, but we eventually saw // it in a way that caused a Selenium script not to work due to too many headers (see [email protected]) HttpListener[] listeners = jettyServer.getListeners(); for (HttpListener listener : listeners) { if (listener instanceof SocketListener) { SocketListener sl = (SocketListener) listener; if (sl.getBufferReserve() != 512 * headerBufferMultiplier) { sl.setBufferReserve(512 * headerBufferMultiplier); } if (sl.getBufferSize() != 8192 * headerBufferMultiplier) { sl.setBufferSize(8192 * headerBufferMultiplier); } } } } // BEGIN ODO CHANGES /** * Cleanup function to remove all allocated listeners */ public void cleanup() { synchronized (_sslMap) { for (SslRelayOdo relay : _sslMap.values()) { if (relay.getHttpServer() != null && relay.isStarted()) { relay.getHttpServer().removeListener(relay); } } sslRelays.clear(); } } // END ODO CHANGES // BEGIN ODO CHANGES // Copied from SeleniumProxyHandler(renamed to SslRelayOdo from SslRelay; no other changes) public static class SslRelayOdo extends SslListener { InetAddrPort _addr; File nukeDirOrFile; private static final long serialVersionUID = 1L; SslRelayOdo(InetAddrPort addr) { _addr = addr; } public void setNukeDirOrFile(File nukeDirOrFile) { this.nukeDirOrFile = nukeDirOrFile; } protected void customizeRequest(Socket socket, HttpRequest request) { super.customizeRequest(socket, request); URI uri = request.getURI(); // Convert the URI to a proxy URL // // NOTE: Don't just add a host + port to the request URI, since this causes the URI to // get "dirty" and be rewritten, potentially breaking the proxy slightly. Instead, // create a brand new URI that includes the protocol, the host, and the port, but leaves // intact the path + query string "as is" so that it does not get rewritten. request.setURI(new URI("https://" + _addr.getHost() + ":" + _addr.getPort() + uri.toString())); } public void stop() throws InterruptedException { super.stop(); if (nukeDirOrFile != null) { if (nukeDirOrFile.isDirectory()) { LauncherUtils.recursivelyDeleteDir(nukeDirOrFile); } else { nukeDirOrFile.delete(); } } } } /** * @param url full url containing hostname * @return hostname */ public static String getHostNameFromURL(String url) { int urlLeftPos = url.indexOf("//"); String hostName = url.substring(urlLeftPos + 2); int urlRightPos = hostName.indexOf("/"); if (urlRightPos != -1) { hostName = hostName.substring(0, urlRightPos); } // now look for a port int portPos = hostName.indexOf(":"); if (portPos != -1) { hostName = hostName.substring(0, portPos); } return hostName; } // END ODO CHANGES }
Switching to use string for ip
browsermob-proxy/src/main/java/com/groupon/odo/bmp/BrowserMobProxyHandler.java
Switching to use string for ip
<ide><path>rowsermob-proxy/src/main/java/com/groupon/odo/bmp/BrowserMobProxyHandler.java <ide> <ide> private static final int HEADER_BUFFER_DEFAULT = 2; <ide> private static final long serialVersionUID = 1L; <add> private final String localIP = "127.0.0.1"; <ide> <ide> private Server jettyServer; <ide> private int headerBufferMultiplier = HEADER_BUFFER_DEFAULT; <ide> <ide> if (urlStr.startsWith("http://")) { <ide> int httpPort = com.groupon.odo.proxylib.Utils.getSystemPort(Constants.SYS_HTTP_PORT); <del> urlStr = urlStr.replace(getHostNameFromURL(urlStr), "127.0.0.1:" + httpPort); <add> urlStr = urlStr.replace(getHostNameFromURL(urlStr), localIP + ":" + httpPort); <ide> } <ide> <ide> okRequestBuilder = okRequestBuilder.url(urlStr);
Java
apache-2.0
942e280418d0991776b403b0a9af9295abe9517b
0
xtern/ignite,voipp/ignite,a1vanov/ignite,NSAmelchev/ignite,ptupitsyn/ignite,kidaa/incubator-ignite,xtern/ignite,VladimirErshov/ignite,apacheignite/ignite,ptupitsyn/ignite,nizhikov/ignite,agoncharuk/ignite,shroman/ignite,f7753/ignite,amirakhmedov/ignite,andrey-kuznetsov/ignite,andrey-kuznetsov/ignite,akuznetsov-gridgain/ignite,BiryukovVA/ignite,afinka77/ignite,SomeFire/ignite,avinogradovgg/ignite,nivanov/ignite,DoudTechData/ignite,arijitt/incubator-ignite,chandresh-pancholi/ignite,vsisko/incubator-ignite,samaitra/ignite,wmz7year/ignite,vadopolski/ignite,vsisko/incubator-ignite,BiryukovVA/ignite,nizhikov/ignite,ashutakGG/incubator-ignite,VladimirErshov/ignite,tkpanther/ignite,chandresh-pancholi/ignite,abhishek-ch/incubator-ignite,avinogradovgg/ignite,ryanzz/ignite,vadopolski/ignite,amirakhmedov/ignite,agoncharuk/ignite,a1vanov/ignite,StalkXT/ignite,dmagda/incubator-ignite,vadopolski/ignite,voipp/ignite,apache/ignite,dream-x/ignite,DoudTechData/ignite,shurun19851206/ignite,SomeFire/ignite,nizhikov/ignite,dlnufox/ignite,StalkXT/ignite,wmz7year/ignite,gridgain/apache-ignite,arijitt/incubator-ignite,mcherkasov/ignite,sk0x50/ignite,louishust/incubator-ignite,alexzaitzev/ignite,sk0x50/ignite,gargvish/ignite,svladykin/ignite,shurun19851206/ignite,ilantukh/ignite,abhishek-ch/incubator-ignite,amirakhmedov/ignite,rfqu/ignite,BiryukovVA/ignite,irudyak/ignite,thuTom/ignite,akuznetsov-gridgain/ignite,thuTom/ignite,nizhikov/ignite,afinka77/ignite,ntikhonov/ignite,sylentprayer/ignite,NSAmelchev/ignite,avinogradovgg/ignite,WilliamDo/ignite,gargvish/ignite,abhishek-ch/incubator-ignite,apache/ignite,endian675/ignite,iveselovskiy/ignite,shroman/ignite,amirakhmedov/ignite,ilantukh/ignite,vadopolski/ignite,gridgain/apache-ignite,samaitra/ignite,psadusumilli/ignite,kidaa/incubator-ignite,samaitra/ignite,voipp/ignite,irudyak/ignite,nivanov/ignite,zzcclp/ignite,rfqu/ignite,kromulan/ignite,chandresh-pancholi/ignite,arijitt/incubator-ignite,SomeFire/ignite,ashutakGG/incubator-ignite,vladisav/ignite,apache/ignite,shurun19851206/ignite,apache/ignite,gargvish/ignite,adeelmahmood/ignite,mcherkasov/ignite,afinka77/ignite,kidaa/incubator-ignite,dmagda/incubator-ignite,a1vanov/ignite,murador/ignite,wmz7year/ignite,rfqu/ignite,dlnufox/ignite,vladisav/ignite,louishust/incubator-ignite,daradurvs/ignite,vadopolski/ignite,avinogradovgg/ignite,sylentprayer/ignite,ascherbakoff/ignite,alexzaitzev/ignite,shroman/ignite,daradurvs/ignite,ascherbakoff/ignite,murador/ignite,leveyj/ignite,BiryukovVA/ignite,kromulan/ignite,endian675/ignite,DoudTechData/ignite,vsuslov/incubator-ignite,SharplEr/ignite,ascherbakoff/ignite,gargvish/ignite,vladisav/ignite,shroman/ignite,gridgain/apache-ignite,gridgain/apache-ignite,SharplEr/ignite,alexzaitzev/ignite,svladykin/ignite,dmagda/incubator-ignite,agura/incubator-ignite,ptupitsyn/ignite,ilantukh/ignite,akuznetsov-gridgain/ignite,daradurvs/ignite,ntikhonov/ignite,voipp/ignite,ryanzz/ignite,andrey-kuznetsov/ignite,amirakhmedov/ignite,BiryukovVA/ignite,thuTom/ignite,samaitra/ignite,pperalta/ignite,mcherkasov/ignite,andrey-kuznetsov/ignite,daradurvs/ignite,dream-x/ignite,avinogradovgg/ignite,ilantukh/ignite,avinogradovgg/ignite,VladimirErshov/ignite,vsisko/incubator-ignite,samaitra/ignite,dream-x/ignite,ptupitsyn/ignite,chandresh-pancholi/ignite,vldpyatkov/ignite,xtern/ignite,zzcclp/ignite,VladimirErshov/ignite,amirakhmedov/ignite,dream-x/ignite,vldpyatkov/ignite,agoncharuk/ignite,kromulan/ignite,dlnufox/ignite,voipp/ignite,SomeFire/ignite,agura/incubator-ignite,iveselovskiy/ignite,chandresh-pancholi/ignite,agura/incubator-ignite,vladisav/ignite,ashutakGG/incubator-ignite,nivanov/ignite,tkpanther/ignite,vladisav/ignite,dmagda/incubator-ignite,WilliamDo/ignite,sylentprayer/ignite,ilantukh/ignite,tkpanther/ignite,shroman/ignite,leveyj/ignite,psadusumilli/ignite,svladykin/ignite,vsuslov/incubator-ignite,kidaa/incubator-ignite,adeelmahmood/ignite,gargvish/ignite,vsisko/incubator-ignite,dream-x/ignite,agoncharuk/ignite,thuTom/ignite,murador/ignite,ascherbakoff/ignite,rfqu/ignite,tkpanther/ignite,daradurvs/ignite,SharplEr/ignite,ilantukh/ignite,afinka77/ignite,sk0x50/ignite,DoudTechData/ignite,ntikhonov/ignite,apacheignite/ignite,alexzaitzev/ignite,apacheignite/ignite,pperalta/ignite,rfqu/ignite,ascherbakoff/ignite,SharplEr/ignite,samaitra/ignite,nizhikov/ignite,NSAmelchev/ignite,vsuslov/incubator-ignite,apacheignite/ignite,f7753/ignite,StalkXT/ignite,psadusumilli/ignite,nizhikov/ignite,zzcclp/ignite,irudyak/ignite,vadopolski/ignite,shurun19851206/ignite,endian675/ignite,sylentprayer/ignite,dlnufox/ignite,iveselovskiy/ignite,voipp/ignite,pperalta/ignite,vladisav/ignite,iveselovskiy/ignite,sk0x50/ignite,vsuslov/incubator-ignite,sk0x50/ignite,svladykin/ignite,gargvish/ignite,ilantukh/ignite,nivanov/ignite,agura/incubator-ignite,mcherkasov/ignite,akuznetsov-gridgain/ignite,xtern/ignite,leveyj/ignite,shroman/ignite,gridgain/apache-ignite,chandresh-pancholi/ignite,wmz7year/ignite,sk0x50/ignite,zzcclp/ignite,NSAmelchev/ignite,DoudTechData/ignite,shroman/ignite,ilantukh/ignite,abhishek-ch/incubator-ignite,gargvish/ignite,f7753/ignite,endian675/ignite,NSAmelchev/ignite,voipp/ignite,alexzaitzev/ignite,wmz7year/ignite,alexzaitzev/ignite,gargvish/ignite,pperalta/ignite,ryanzz/ignite,ptupitsyn/ignite,leveyj/ignite,dmagda/incubator-ignite,irudyak/ignite,nivanov/ignite,amirakhmedov/ignite,ascherbakoff/ignite,agoncharuk/ignite,agura/incubator-ignite,voipp/ignite,SharplEr/ignite,endian675/ignite,akuznetsov-gridgain/ignite,rfqu/ignite,afinka77/ignite,agoncharuk/ignite,akuznetsov-gridgain/ignite,ilantukh/ignite,wmz7year/ignite,apacheignite/ignite,WilliamDo/ignite,wmz7year/ignite,nizhikov/ignite,andrey-kuznetsov/ignite,ptupitsyn/ignite,daradurvs/ignite,dmagda/incubator-ignite,SomeFire/ignite,vadopolski/ignite,f7753/ignite,alexzaitzev/ignite,thuTom/ignite,shroman/ignite,StalkXT/ignite,apache/ignite,apache/ignite,StalkXT/ignite,shroman/ignite,agura/incubator-ignite,ascherbakoff/ignite,arijitt/incubator-ignite,BiryukovVA/ignite,shurun19851206/ignite,afinka77/ignite,adeelmahmood/ignite,SomeFire/ignite,pperalta/ignite,irudyak/ignite,adeelmahmood/ignite,alexzaitzev/ignite,samaitra/ignite,svladykin/ignite,leveyj/ignite,ryanzz/ignite,louishust/incubator-ignite,ilantukh/ignite,vsisko/incubator-ignite,DoudTechData/ignite,f7753/ignite,murador/ignite,murador/ignite,shroman/ignite,dlnufox/ignite,murador/ignite,BiryukovVA/ignite,SharplEr/ignite,VladimirErshov/ignite,endian675/ignite,ntikhonov/ignite,dlnufox/ignite,DoudTechData/ignite,mcherkasov/ignite,mcherkasov/ignite,andrey-kuznetsov/ignite,dmagda/incubator-ignite,ascherbakoff/ignite,nizhikov/ignite,adeelmahmood/ignite,thuTom/ignite,sylentprayer/ignite,dream-x/ignite,samaitra/ignite,pperalta/ignite,ptupitsyn/ignite,SomeFire/ignite,SomeFire/ignite,vsisko/incubator-ignite,irudyak/ignite,murador/ignite,gridgain/apache-ignite,zzcclp/ignite,dmagda/incubator-ignite,daradurvs/ignite,tkpanther/ignite,zzcclp/ignite,WilliamDo/ignite,irudyak/ignite,leveyj/ignite,vsisko/incubator-ignite,ryanzz/ignite,thuTom/ignite,daradurvs/ignite,thuTom/ignite,NSAmelchev/ignite,abhishek-ch/incubator-ignite,dream-x/ignite,StalkXT/ignite,kromulan/ignite,zzcclp/ignite,wmz7year/ignite,agura/incubator-ignite,NSAmelchev/ignite,iveselovskiy/ignite,psadusumilli/ignite,StalkXT/ignite,ryanzz/ignite,vadopolski/ignite,VladimirErshov/ignite,NSAmelchev/ignite,shurun19851206/ignite,apache/ignite,louishust/incubator-ignite,vladisav/ignite,amirakhmedov/ignite,psadusumilli/ignite,tkpanther/ignite,adeelmahmood/ignite,apacheignite/ignite,sk0x50/ignite,arijitt/incubator-ignite,endian675/ignite,daradurvs/ignite,leveyj/ignite,vldpyatkov/ignite,samaitra/ignite,chandresh-pancholi/ignite,ptupitsyn/ignite,abhishek-ch/incubator-ignite,apache/ignite,BiryukovVA/ignite,svladykin/ignite,f7753/ignite,vsisko/incubator-ignite,agoncharuk/ignite,BiryukovVA/ignite,nizhikov/ignite,xtern/ignite,leveyj/ignite,ntikhonov/ignite,psadusumilli/ignite,vldpyatkov/ignite,WilliamDo/ignite,StalkXT/ignite,nivanov/ignite,amirakhmedov/ignite,f7753/ignite,WilliamDo/ignite,daradurvs/ignite,dlnufox/ignite,ryanzz/ignite,xtern/ignite,BiryukovVA/ignite,apacheignite/ignite,dream-x/ignite,VladimirErshov/ignite,andrey-kuznetsov/ignite,ntikhonov/ignite,a1vanov/ignite,sk0x50/ignite,ascherbakoff/ignite,voipp/ignite,shurun19851206/ignite,SharplEr/ignite,avinogradovgg/ignite,SomeFire/ignite,DoudTechData/ignite,rfqu/ignite,kidaa/incubator-ignite,NSAmelchev/ignite,andrey-kuznetsov/ignite,endian675/ignite,kromulan/ignite,ptupitsyn/ignite,ntikhonov/ignite,xtern/ignite,WilliamDo/ignite,andrey-kuznetsov/ignite,mcherkasov/ignite,nivanov/ignite,irudyak/ignite,SomeFire/ignite,kromulan/ignite,ptupitsyn/ignite,andrey-kuznetsov/ignite,afinka77/ignite,a1vanov/ignite,chandresh-pancholi/ignite,StalkXT/ignite,ashutakGG/incubator-ignite,SharplEr/ignite,agura/incubator-ignite,agoncharuk/ignite,VladimirErshov/ignite,SharplEr/ignite,nivanov/ignite,pperalta/ignite,sylentprayer/ignite,psadusumilli/ignite,arijitt/incubator-ignite,sylentprayer/ignite,chandresh-pancholi/ignite,ryanzz/ignite,shurun19851206/ignite,iveselovskiy/ignite,vsuslov/incubator-ignite,psadusumilli/ignite,dlnufox/ignite,xtern/ignite,kidaa/incubator-ignite,tkpanther/ignite,tkpanther/ignite,zzcclp/ignite,vldpyatkov/ignite,a1vanov/ignite,apache/ignite,afinka77/ignite,vldpyatkov/ignite,mcherkasov/ignite,vldpyatkov/ignite,a1vanov/ignite,vsuslov/incubator-ignite,ntikhonov/ignite,adeelmahmood/ignite,sk0x50/ignite,rfqu/ignite,adeelmahmood/ignite,a1vanov/ignite,kromulan/ignite,louishust/incubator-ignite,pperalta/ignite,ashutakGG/incubator-ignite,xtern/ignite,kromulan/ignite,gridgain/apache-ignite,samaitra/ignite,irudyak/ignite,sylentprayer/ignite,vladisav/ignite,ashutakGG/incubator-ignite,svladykin/ignite,f7753/ignite,louishust/incubator-ignite,WilliamDo/ignite,apacheignite/ignite,alexzaitzev/ignite,vldpyatkov/ignite,murador/ignite
/* @java.file.header */ /* _________ _____ __________________ _____ * __ ____/___________(_)______ /__ ____/______ ____(_)_______ * _ / __ __ ___/__ / _ __ / _ / __ _ __ `/__ / __ __ \ * / /_/ / _ / _ / / /_/ / / /_/ / / /_/ / _ / _ / / / * \____/ /_/ /_/ \_,__/ \____/ \__,_/ /_/ /_/ /_/ */ package org.gridgain.grid.cache.query; import org.gridgain.grid.*; import org.gridgain.grid.cache.*; import org.gridgain.grid.lang.*; import org.jetbrains.annotations.*; import java.util.*; /** * API for configuring and executing continuous cache queries. * <p> * Continuous queries are executed as follows: * <ol> * <li> * Query is sent to requested grid nodes. Note that for {@link GridCacheMode#LOCAL LOCAL} * and {@link GridCacheMode#REPLICATED REPLICATED} caches query will be always executed * locally. * </li> * <li> * Each node iterates through existing cache data and resisters listeners that will * notify about further updates. * <li> * Each key-value pair is passed through optional filter and if this filter returns * true, key-value pair is sent to the master node (the one that executed query). * If filter is not provided, all pairs are sent. * </li> * <li> * When master node receives key-value pairs, it notifies the local callback. * </li> * </ol> * <h2 class="header">NOTE</h2> * Under some concurrent circumstances callback may get several notifications * for one cache update. This should be taken into account when implementing callback. * <h1 class="header">Query usage</h1> * As an example, suppose we have cache with {@code 'Person'} objects and we need * to query all persons with salary above 1000. * <p> * Here is the {@code Person} class: * <pre name="code" class="java"> * public class Person { * // Name. * private String name; * * // Salary. * private double salary; * * ... * } * </pre> * <p> * You can create and execute continuous query like so: * <pre name="code" class="java"> * // Create new continuous query. * qry = cache.createContinuousQuery(); * * // Callback that is called locally when update notifications are received. * // It simply prints out information about all created persons. * qry.callback(new GridPredicate2&lt;UUID, Collection&lt;Map.Entry&lt;UUID, Person&gt;&gt;&gt;() { * &#64;Override public boolean apply(UUID uuid, Collection&lt;Map.Entry&lt;UUID, Person&gt;&gt; entries) { * for (Map.Entry&lt;UUID, Person&gt; e : entries) { * Person p = e.getValue(); * * X.println("&gt;&gt;&gt;"); * X.println("&gt;&gt;&gt; " + p.getFirstName() + " " + p.getLastName() + * "'s salary is " + p.getSalary()); * X.println("&gt;&gt;&gt;"); * } * * return true; * } * }); * * // This query will return persons with salary above 1000. * qry.filter(new GridPredicate2&lt;UUID, Person&gt;() { * &#64;Override public boolean apply(UUID uuid, Person person) { * return person.getSalary() &gt; 1000; * } * }); * * // Execute query. * qry.execute(); * </pre> * This will execute query on all nodes that have cache you are working with and notify callback * with both data that already exists in cache and further updates. * <p> * To stop receiving updates call {@link #close()} method: * <pre name="code" class="java"> * qry.cancel(); * </pre> * Note that one query instance can be executed only once. After it's cancelled, it's non-operational. * If you need to repeat execution, use {@link GridCacheQueries#createContinuousQuery()} method to create * new query. */ public interface GridCacheContinuousQuery<K, V> extends AutoCloseable { /** * Default buffer size. Size of {@code 1} means that all entries * will be sent to master node immediately (buffering is disabled). */ public static final int DFLT_BUF_SIZE = 1; /** Maximum default time interval after which buffer will be flushed (if buffering is enabled). */ public static final long DFLT_TIME_INTERVAL = 0; /** * Default value for automatic unsubscription flag. Remote filters * will be unregistered by default if master node leaves topology. */ public static final boolean DFLT_AUTO_UNSUBSCRIBE = true; /** * Sets mandatory local callback. This callback is called only * in local node when new updates are received. * <p> * The callback predicate accepts ID of the node from where updates * are received and collection of received entries. Note that * for removed entries value will be {@code null}. * <p> * If the predicate returns {@code false}, query execution will * be cancelled. * <p> * <b>WARNING:</b> all operations that involve any kind of JVM-local * or distributed locking (e.g., synchronization or transactional * cache operations), should be executed asynchronously without * blocking the thread that called the callback. Otherwise, you * can get deadlocks. * * @param cb Local callback. */ public void callback(GridBiPredicate<UUID, Collection<Map.Entry<K, V>>> cb); /** * Gets local callback. See {@link #callback(GridBiPredicate)} for more information. * * @return Local callback. */ public GridBiPredicate<UUID, Collection<Map.Entry<K, V>>> callback(); /** * Sets optional key-value filter. This filter is called before * entry is sent to the master node. * <p> * <b>WARNING:</b> all operations that involve any kind of JVM-local * or distributed locking (e.g., synchronization or transactional * cache operations), should be executed asynchronously without * blocking the thread that called the filter. Otherwise, you * can get deadlocks. * * @param filter Key-value filter. */ public void filter(@Nullable GridBiPredicate<K, V> filter); /** * Gets key-value filter. See {@link #filter(GridBiPredicate)} for more information. * * @return Key-value filter. */ @Nullable public GridBiPredicate<K, V> filter(); /** * Sets buffer size. * <p> * When a cache update happens, entry is first put into a buffer. * Entries from buffer will be sent to the master node only if * the buffer is full or time provided via {@link #timeInterval(long)} * method is exceeded. * <p> * Default buffer size is {@code 1} which means that entries will * be sent immediately (buffering is disabled). * * @param bufSize Buffer size. */ public void bufferSize(int bufSize); /** * Gets buffer size. See {@link #bufferSize(int)} for more information. * * @return Buffer size. */ public int bufferSize(); /** * Sets time interval. * <p> * When a cache update happens, entry is first put into a buffer. * Entries from buffer will be sent to the master node only if * the buffer is full (its size can be provided via {@link #bufferSize(int)} * method) or time provided via this method is exceeded. * <p> * Default time interval is {@code 0} which means that time check is * disabled and entries will be sent only when buffer is full. * * @param timeInterval Time interval. */ public void timeInterval(long timeInterval); /** * Gets time interval. See {@link #timeInterval(long)} for more information. * * @return Gets time interval. */ public long timeInterval(); /** * Sets automatic unsubscribe flag. * <p> * This flag indicates that query filters on remote nodes should be automatically * unregistered if master node (node that initiated the query) leaves topology. * If this flag is {@code false}, filters will be unregistered only when * the query is cancelled from master node, and won't ever be unregistered if * master node leaves grid. * <p> * Default value for this flag is {@code true}. * * @param autoUnsubscribe Automatic unsubscription flag. */ public void autoUnsubscribe(boolean autoUnsubscribe); /** * Gets automatic unsubscribe flag. See {@link #autoUnsubscribe(boolean)} * for more information. * * @return Automatic unsubscribe flag. */ public boolean isAutoUnsubscribe(); /** * Starts continuous query execution on the whole grid. * <p> * Note that if grid contains nodes without appropriate cache, * these nodes will be filtered out. * <p> * Also note that for {@link GridCacheMode#LOCAL LOCAL} * and {@link GridCacheMode#REPLICATED REPLICATED} caches * query will be always executed locally. * * @throws GridException In case of error. */ public void execute() throws GridException; /** * Starts continuous query execution on provided set of nodes. * <p> * Note that if provided projection contains nodes without * appropriate cache, these nodes will be filtered out. * <p> * Also note that for {@link GridCacheMode#LOCAL LOCAL} * and {@link GridCacheMode#REPLICATED REPLICATED} caches * query will be always executed locally. * * @param prj Grid projection. * @throws GridException In case of error. */ public void execute(@Nullable GridProjection prj) throws GridException; /** * Stops continuous query execution. * <p> * Note that one query instance can be executed only once. * After it's cancelled, it's non-operational. * If you need to repeat execution, use {@link GridCacheQueries#createContinuousQuery()} * method to create new query. * * @throws GridException In case of error. */ @Override public void close() throws GridException; }
modules/core/java/org/gridgain/grid/cache/query/GridCacheContinuousQuery.java
/* @java.file.header */ /* _________ _____ __________________ _____ * __ ____/___________(_)______ /__ ____/______ ____(_)_______ * _ / __ __ ___/__ / _ __ / _ / __ _ __ `/__ / __ __ \ * / /_/ / _ / _ / / /_/ / / /_/ / / /_/ / _ / _ / / / * \____/ /_/ /_/ \_,__/ \____/ \__,_/ /_/ /_/ /_/ */ package org.gridgain.grid.cache.query; import org.gridgain.grid.*; import org.gridgain.grid.cache.*; import org.gridgain.grid.lang.*; import org.jetbrains.annotations.*; import java.util.*; /** * API for configuring and executing continuous cache queries. * <p> * Continuous queries are executed as follows: * <ol> * <li> * Query is sent to requested grid nodes. Note that for {@link GridCacheMode#LOCAL LOCAL} * and {@link GridCacheMode#REPLICATED REPLICATED} caches query will be always executed * locally. * </li> * <li> * Each node iterates through existing cache data and resisters listeners that will * notify about further updates. * <li> * Each key-value pair is passed through optional filter and if this filter returns * true, key-value pair is sent to the master node (the one that executed query). * If filter is not provided, all pairs are sent. * </li> * <li> * When master node receives key-value pairs, it notifies the local callback. * </li> * </ol> * <h2 class="header">NOTE</h2> * Under some concurrent circumstances callback may get several notifications * for one cache update. This should be taken into account when implementing callback. * <h1 class="header">Query usage</h1> * As an example, suppose we have cache with {@code 'Person'} objects and we need * to query all persons with salary above 1000. * <p> * Here is the {@code Person} class: * <pre name="code" class="java"> * public class Person { * // Name. * private String name; * * // Salary. * private double salary; * * ... * } * </pre> * <p> * You can create and execute continuous query like so: * <pre name="code" class="java"> * // Create new continuous query. * qry = cache.createContinuousQuery(); * * // Callback that is called locally when update notifications are received. * // It simply prints out information about all created persons. * qry.callback(new GridPredicate2&lt;UUID, Collection&lt;Map.Entry&lt;UUID, Person&gt;&gt;&gt;() { * &#64;Override public boolean apply(UUID uuid, Collection&lt;Map.Entry&lt;UUID, Person&gt;&gt; entries) { * for (Map.Entry&lt;UUID, Person&gt; e : entries) { * Person p = e.getValue(); * * X.println("&gt;&gt;&gt;"); * X.println("&gt;&gt;&gt; " + p.getFirstName() + " " + p.getLastName() + * "'s salary is " + p.getSalary()); * X.println("&gt;&gt;&gt;"); * } * * return true; * } * }); * * // This query will return persons with salary above 1000. * qry.filter(new GridPredicate2&lt;UUID, Person&gt;() { * &#64;Override public boolean apply(UUID uuid, Person person) { * return person.getSalary() &gt; 1000; * } * }); * * // Execute query. * qry.execute(); * </pre> * This will execute query on all nodes that have cache you are working with and notify callback * with both data that already exists in cache and further updates. * <p> * To stop receiving updates call {@link #close()} method: * <pre name="code" class="java"> * qry.cancel(); * </pre> * Note that one query instance can be executed only once. After it's cancelled, it's non-operational. * If you need to repeat execution, use {@link GridCacheQueries#createContinuousQuery()} method to create * new query. */ public interface GridCacheContinuousQuery<K, V> extends AutoCloseable { /** * Default buffer size. Size of {@code 1} means that all entries * will be sent to master node immediately (buffering is disabled). */ public static final int DFLT_BUF_SIZE = 1; /** Maximum default time interval after which buffer will be flushed (if buffering is enabled). */ public static final long DFLT_TIME_INTERVAL = 0; /** * Default value for automatic unsubscription flag. Remote filters * will be unregistered by default if master node leaves topology. */ public static final boolean DFLT_AUTO_UNSUBSCRIBE = true; /** * Sets mandatory local callback. This callback is called only * in local node when new updates are received. * <p> * The callback predicate accepts ID of the node from where updates * are received and collection of received entries. Note that * for removed entries value will be {@code null}. * <p> * If the predicate returns {@code false}, query execution will * be cancelled. * * @param cb Local callback. */ public void callback(GridBiPredicate<UUID, Collection<Map.Entry<K, V>>> cb); /** * Gets local callback. See {@link #callback(GridBiPredicate)} for more information. * * @return Local callback. */ public GridBiPredicate<UUID, Collection<Map.Entry<K, V>>> callback(); /** * Sets optional key-value filter. This filter is called before * entry is sent to the master node. * * @param filter Key-value filter. */ public void filter(@Nullable GridBiPredicate<K, V> filter); /** * Gets key-value filter. See {@link #filter(GridBiPredicate)} for more information. * * @return Key-value filter. */ @Nullable public GridBiPredicate<K, V> filter(); /** * Sets buffer size. * <p> * When a cache update happens, entry is first put into a buffer. * Entries from buffer will be sent to the master node only if * the buffer is full or time provided via {@link #timeInterval(long)} * method is exceeded. * <p> * Default buffer size is {@code 1} which means that entries will * be sent immediately (buffering is disabled). * * @param bufSize Buffer size. */ public void bufferSize(int bufSize); /** * Gets buffer size. See {@link #bufferSize(int)} for more information. * * @return Buffer size. */ public int bufferSize(); /** * Sets time interval. * <p> * When a cache update happens, entry is first put into a buffer. * Entries from buffer will be sent to the master node only if * the buffer is full (its size can be provided via {@link #bufferSize(int)} * method) or time provided via this method is exceeded. * <p> * Default time interval is {@code 0} which means that time check is * disabled and entries will be sent only when buffer is full. * * @param timeInterval Time interval. */ public void timeInterval(long timeInterval); /** * Gets time interval. See {@link #timeInterval(long)} for more information. * * @return Gets time interval. */ public long timeInterval(); /** * Sets automatic unsubscribe flag. * <p> * This flag indicates that query filters on remote nodes should be automatically * unregistered if master node (node that initiated the query) leaves topology. * If this flag is {@code false}, filters will be unregistered only when * the query is cancelled from master node, and won't ever be unregistered if * master node leaves grid. * <p> * Default value for this flag is {@code true}. * * @param autoUnsubscribe Automatic unsubscription flag. */ public void autoUnsubscribe(boolean autoUnsubscribe); /** * Gets automatic unsubscribe flag. See {@link #autoUnsubscribe(boolean)} * for more information. * * @return Automatic unsubscribe flag. */ public boolean isAutoUnsubscribe(); /** * Starts continuous query execution on the whole grid. * <p> * Note that if grid contains nodes without appropriate cache, * these nodes will be filtered out. * <p> * Also note that for {@link GridCacheMode#LOCAL LOCAL} * and {@link GridCacheMode#REPLICATED REPLICATED} caches * query will be always executed locally. * * @throws GridException In case of error. */ public void execute() throws GridException; /** * Starts continuous query execution on provided set of nodes. * <p> * Note that if provided projection contains nodes without * appropriate cache, these nodes will be filtered out. * <p> * Also note that for {@link GridCacheMode#LOCAL LOCAL} * and {@link GridCacheMode#REPLICATED REPLICATED} caches * query will be always executed locally. * * @param prj Grid projection. * @throws GridException In case of error. */ public void execute(@Nullable GridProjection prj) throws GridException; /** * Stops continuous query execution. * <p> * Note that one query instance can be executed only once. * After it's cancelled, it's non-operational. * If you need to repeat execution, use {@link GridCacheQueries#createContinuousQuery()} * method to create new query. * * @throws GridException In case of error. */ @Override public void close() throws GridException; }
# GG-7171 - JavaDoc
modules/core/java/org/gridgain/grid/cache/query/GridCacheContinuousQuery.java
# GG-7171 - JavaDoc
<ide><path>odules/core/java/org/gridgain/grid/cache/query/GridCacheContinuousQuery.java <ide> * <p> <ide> * If the predicate returns {@code false}, query execution will <ide> * be cancelled. <add> * <p> <add> * <b>WARNING:</b> all operations that involve any kind of JVM-local <add> * or distributed locking (e.g., synchronization or transactional <add> * cache operations), should be executed asynchronously without <add> * blocking the thread that called the callback. Otherwise, you <add> * can get deadlocks. <ide> * <ide> * @param cb Local callback. <ide> */ <ide> /** <ide> * Sets optional key-value filter. This filter is called before <ide> * entry is sent to the master node. <add> * <p> <add> * <b>WARNING:</b> all operations that involve any kind of JVM-local <add> * or distributed locking (e.g., synchronization or transactional <add> * cache operations), should be executed asynchronously without <add> * blocking the thread that called the filter. Otherwise, you <add> * can get deadlocks. <ide> * <ide> * @param filter Key-value filter. <ide> */
JavaScript
mit
a8e4981bcabd28227fab3e5d7c91b93422c5be8a
0
elvinyung/rowt.js
// rowt.js - a simple URL router. var _routeObject; var _routeIgnore = ['_']; var typeConversionFns = { 'int': parseInt, 'float': parseFloat, 'bool': function(str) { return (str == 'true'); }, 'any': function(str) { return str; } } var routeHandler = function() { urlHash = location.hash.substring(1).trim(); for (routeRegex in _routeObject) { var routeParamNames = _routeObject[routeRegex][0]; var routeParamTypes = _routeObject[routeRegex][1]; var routeAction = _routeObject[routeRegex][2]; var routeRegex = new RegExp(routeRegex); var routeMatch = routeRegex.exec(urlHash); if (!!routeMatch) { routeMatch = routeMatch.slice(1); var routeParams = {}; for (index in routeParamNames) { typeConvert = typeConversionFns[routeParamTypes[index]]; routeParamVal = typeConvert(routeMatch[index]) routeParams[routeParamNames[index]] = routeParamVal; } routeAction(routeParams); return; } } }; var registerRoute = function(route, routeAction) { var routeRegex = '^'; var routeParamNames = []; var routeParamTypes = []; var routeTokens = route.split('/'); for (token in routeTokens) { token = routeTokens[token]; if (token.indexOf(':') != -1) { token = token.split(':'); var paramType = token[0]; var paramName = token[1]; routeParamNames.push(paramName); routeParamTypes.push(paramType || 'any'); routeRegex += '\/'; if (paramType == 'int') { routeRegex += '(\\d+)'; } else if (paramType == 'float') { routeRegex += '(\\d+\.\\d+)'; } else { routeRegex += '([^\/]+)'; } } else if (token[0] == '{' && token[token.length-1] == '}') { //handle `{param}` cases var regexStr = token(1, token.length-1); if (!!(new Regexp(regexStr))) { routeRegex += regexStr; } else { throw 'invalid regex literal'; } } else if (!token) { } else { routeRegex += '\/' + token; } } routeRegex += '$'; _routeObject[routeRegex] = [routeParamNames, routeParamTypes, routeAction]; } var initRowt = function() { if (!("onhashchange" in window)) { throw "onhashchange not supported in this browser"; } _routeObject = _routeObject || {}; window.onhashchange = routeHandler; return { addRoute: function(route, routeAction) { registerRoute(route, routeAction); }, addRoutes: function(routeDict) { for (route in routeDict) { registerRoute(route, routeDict[route]); } }, removeRoute: function(route) { if (!_routeObject[route]) { return; }; delete _routeObject[route]; }, getRoute: function(route) { return _routeObject[route]; }, otherwiseRoute: function(routeAction) { _routeObject.otherwise = routeAction; } }; };
rowt.js
// rowt.js - a simple URL router. var _routeObject; var _routeIgnore = ['_']; var typeConversionFns = { 'int': parseInt, 'float': parseFloat, 'bool': function(str) { return (str == 'true'); }, 'any': function(str) { return str; } } var routeHandler = function() { urlHash = location.hash.substring(1).trim(); for (routeRegex in _routeObject) { var routeParamNames = _routeObject[routeRegex][0]; var routeParamTypes = _routeObject[routeRegex][1]; var routeAction = _routeObject[routeRegex][2]; var routeRegex = new RegExp(routeRegex); var routeMatch = routeRegex.exec(urlHash); if (!!routeMatch) { routeMatch = routeMatch.slice(1); var routeParams = {}; for (index in routeParamNames) { typeConvert = typeConversionFns[routeParamTypes[index]]; routeParamVal = typeConvert(routeMatch[index]) routeParams[routeParamNames[index]] = routeParamVal; } routeAction(routeParams); return; } } }; var registerRoute = function(route, routeAction) { var routeRegex = '^'; var routeParamNames = []; var routeParamTypes = []; var routeTokens = route.split('/'); for (token in routeTokens) { token = routeTokens[token]; if (token.indexOf(':') != -1) { token = token.split(':'); var paramType = token[0]; var paramName = token[1]; routeParamNames.push(paramName); routeParamTypes.push(paramType || 'any'); routeRegex += '\/'; if (paramType == 'int') { routeRegex += '(\\d+)'; } else if (paramType == 'float') { routeRegex += '(\\d+\.\\d+)'; } else { routeRegex += '([^\/]+)'; } } else if (token[0] == '{' && token[token.length-1] == '}') { //handle `{param}` cases var regexStr = token(1, token.length-1); if (!!(new Regexp(regexStr))) { routeRegex += regexStr; } } else if (!token) { } else { routeRegex += '\/' + token; } } routeRegex += '$'; _routeObject[routeRegex] = [routeParamNames, routeParamTypes, routeAction]; } var initRowt = function() { if (!("onhashchange" in window)) { throw "onhashchange not supported in this browser"; } _routeObject = _routeObject || {}; window.onhashchange = routeHandler; return { addRoute: function(route, routeAction) { registerRoute(route, routeAction); }, addRoutes: function(routeDict) { for (route in routeDict) { registerRoute(route, routeDict[route]); } }, removeRoute: function(route) { if (!_routeObject[route]) { return; }; delete _routeObject[route]; }, getRoute: function(route) { return _routeObject[route]; }, otherwiseRoute: function(routeAction) { _routeObject.otherwise = routeAction; } }; };
handle invalid regex literals
rowt.js
handle invalid regex literals
<ide><path>owt.js <ide> { <ide> routeRegex += regexStr; <ide> } <add> else <add> { <add> throw 'invalid regex literal'; <add> } <ide> } <ide> else if (!token) <ide> {
JavaScript
isc
7e81d341443b90d527b00621cf2593c96e0ed8db
0
giancarlobonansea/clusterednode-client,giancarlobonansea/clusterednode-client,giancarlobonansea/clusterednode-client
(function(app) { app.AppSimulator = (function() { function AppSimulator(HTTPService) { this.histogram = [[50, 0, 0, 0, 0], [75, 0, 0, 0, 0], [87.5, 0, 0, 0, 0], [93.75, 0, 0, 0, 0], [96.875, 0, 0, 0, 0], [98.4375, 0, 0, 0, 0], [99.21875, 0, 0, 0, 0], [100, 0, 0, 0, 0]]; this.requests = [[], []]; this.isDuration = false; this.reqConn = 4; this.reqCount = 100; this.reqDuration = 5; this.reqInterval = 50; this.running = false; this.reqErrors = 0; this.reqOK = 0; this.loopCon = 0; this.duration = 0; this.totAngular = 0; this.totNginx = 0; this.totNode = 0; this.totRedis = 0; this.tpAngular = 0; this.tpNginx = 0; this.tpNode = 0; this.tpRedis = 0; this.showReference = false; this.calculating = false; this.liveEvents = false; this.httpService = HTTPService; this.urlOptions = [['https://giancarlobonansea.homeip.net:33333/api', 'DNS Public'], ['https://raspberrypi4:8010/api', 'DNS Private'], ['https://192.168.69.242:8010/api', 'IP Private']]; this.nodes = ["raspberrypi2", "raspberrypi3", "raspberrypi5", "raspberrypi6"]; this.urlHDR = 'https://giancarlobonansea.homeip.net:33333/hdr'; this.selectedUrl = this.urlOptions[0][0]; this.initEVMatrix(); this.socket = io('https://giancarlobonansea.homeip.net:33331'); this.liveTTL = 500; var selfMtx = this; // Receive redis.io realtime info this.socket.on('redis', function(data) { var x = data.x, y = data.y; if (selfMtx.evMatrix[x][y] !== 3) { selfMtx.evMatrix[x][y] = 3; setTimeout(function() { selfMtx.evMatrix[x][y] = selfMtx.mapDBmatrix(x, y); }, selfMtx.liveTTL); } }); this.barChartOptions = { chart: { type: 'multiBarChart', showControls: false, height: 400, margin: { top: 20, right: 20, bottom: 20, left: 45 }, x: function(d) {return d.label;}, y: function(d) {return d.value;}, clipEdge: true, stacked: true, showXAxis: false, duration: 500, xAxis: { showMaxMin: false }, yAxis: { tickFormat: function(d) { return d3.format('d')(d); } } } }; this.lineChartOptions = { chart: { type: 'lineWithFocusChart', showControls: false, height: 400, showLegend: true, clipEdge: true, duration: 500, margin: { top: 20, right: 20, bottom: 40, left: 55 }, x: function(d) { return d.x; }, y: function(d) { return d.y; }, useInteractiveGuideline: true, xAxis: { axisLabel: 'Percentile (%)' // ,tickFormat: function(d) { // return d3.format('.5f')(d); // } }, yAxis: { axisLabel: 'AngularJS Latency (ms)', axisLabelDistance: -10, rotateYLabel: true }, x2Axis: { // tickFormat: function(d) { // return d3.format('.5f')(d); // } }, y2Axis: {}, brushExtent: [75, 100] } }; this.polarChartOptions = { chart: { type: 'pieChart', height: 299, showLegend: false, donut: true, padAngle: 0.08, cornerRadius: 5, title: 'nginX', x: function(d) {return d.key;}, y: function(d) {return d.y;}, showLabels: true, labelType: function(d) {return d.data.key + ': ' + (d.data.y | 0);}, labelsOutside: true, duration: 500 } }; this.polarChartOptions2 = { chart: { type: 'pieChart', height: 299, showLegend: false, donut: true, padAngle: 0.08, cornerRadius: 5, title: 'AngularJS', x: function(d) {return d.key;}, y: function(d) {return d.y;}, showLabels: true, labelsOutside: true, labelType: function(d) {return d.data.key + ': ' + (d.data.y | 0);}, duration: 500 } }; this.barChartData = [{key: 'raspberrypi2-redis', values: [{label: '', value: 0}]}, {key: 'raspberrypi3-redis', values: [{label: '', value: 0}]}, {key: 'raspberrypi5-redis', values: [{label: '', value: 0}]}, {key: 'raspberrypi6-redis', values: [{label: '', value: 0}]}, {key: 'raspberrypi2-node', values: [{label: '', value: 0}]}, {key: 'raspberrypi3-node', values: [{label: '', value: 0}]}, {key: 'raspberrypi5-node', values: [{label: '', value: 0}]}, {key: 'raspberrypi6-node', values: [{label: '', value: 0}]}, {key: 'raspberrypi2-nginx', values: [{label: '', value: 0}]}, {key: 'raspberrypi3-nginx', values: [{label: '', value: 0}]}, {key: 'raspberrypi5-nginx', values: [{label: '', value: 0}]}, {key: 'raspberrypi6-nginx', values: [{label: '', value: 0}]}, {key: 'raspberrypi2-angular', values: [{label: '', value: 0}]}, {key: 'raspberrypi3-angular', values: [{label: '', value: 0}]}, {key: 'raspberrypi5-angular', values: [{label: '', value: 0}]}, {key: 'raspberrypi6-angular', values: [{label: '', value: 0}]} ]; this.polarChartData = [{key: 'raspberrypi2', y: 25}, {key: 'raspberrypi3', y: 25}, {key: 'raspberrypi5', y: 25}, {key: 'raspberrypi6', y: 25}]; this.polarChartData2 = [{key: 'raspberrypi2', y: 25}, {key: 'raspberrypi3', y: 25}, {key: 'raspberrypi5', y: 25}, {key: 'raspberrypi6', y: 25}]; this.lineChartData = [ {key: 'w/o Coord. Omission', values: [], area: false}, {key: 'Latency/Percentile', values: [], area: true} ]; this.observableRequests = undefined; this.links = { HTTP2: { title: "HTTP/2", anchor: [ { href: 'https://http2.akamai.com/demo', desc: 'HTTP/2: the Future of the Internet | Akamai' }, { href: 'https://http2.github.io', desc: "HTTP/2 Github repository" }, { href: 'https://http2.github.io/http2-spec/', desc: 'Hypertext Transfer Protocol Version 2 (HTTP/2) draft-ietf-httpbis-http2-latest' }, { href: 'https://docs.google.com/presentation/d/1r7QXGYOLCh4fcUq0jDdDwKJWNqWK1o4xMtYpKZCJYjM/present?slide=id.g4ec7b01d4_5_150', desc: "HTTP/2 is here, let's optimize! - Velocity 2015 - Google Slides" }, { href: 'http://caniuse.com/#search=HTTP%2F2', desc: 'Can I use... HTTP/2' }, { href: 'https://hpbn.co/http2/', desc: "HTTP: HTTP/2 - High Performance Browser Networking (O'Reilly)" }, { href: 'https://www.smashingmagazine.com/2016/02/getting-ready-for-http2/', desc: 'Getting Ready For HTTP/2: A Guide For Web Designers And Developers' }, { href: 'http://qnimate.com/post-series/http2-complete-tutorial/', desc: 'HTTP/2 Complete Tutorial' }, { href: 'http://javascriptplayground.com/blog/2016/03/http2-and-you/', desc: 'HTTP/2 and You' }, { href: 'https://chrome.google.com/webstore/detail/http2-and-spdy-indicator/mpbpobfflnpcgagjijhmgnchggcjblin', desc: 'HTTP/2 and SPDY indicator' }, { href: "http://www.aosabook.org/en/posa/secrets-of-mobile-network-performance.html", desc: "Secrets of Mobile Network Performance" } ] }, pm2: { title: "Keymetrics pm2 (v1.1.3)", anchor: [ { href: "http://pm2.keymetrics.io/", desc: "PM2 - Advanced Node.js process manager" }, { href: "http://pm2.keymetrics.io/docs/usage/cluster-mode/", desc: "PM2 - Cluster Mode" }, { href: "https://keymetrics.io/", desc: "Keymetrics I/O - Monitor and Augment Node.js" }, { href: "http://pm2.keymetrics.io/docs/usage/application-declaration/", desc: "PM2 - Application Declaration" }, { href: "http://pm2.keymetrics.io/docs/usage/deployment/", desc: "PM2 - Deployment" } ] }, angular2: { title: "AngularJS 2 (v2.0.0-rc3)", anchor: [ {href: "https://angular.io", desc: "One framework - Angular 2"}, {href: "https://angular.io/docs/js/latest/guide/cheatsheet.html", desc: "Angular Cheat Sheet - js"}, {href: "https://medium.com/google-developer-experts/angular-2-introduction-to-new-http-module-1278499db2a0#.ttmhbubnd", desc: "Angular 2 — Introduction to new HTTP module" }, {href: "http://blog.caelum.com.br/angularjs-seo-google-analytics-e-virtual-pages/", desc: "AngularJS: SEO, Google Analytics e Virtual Pages" }, {href: "https://coryrylan.com/blog/angular-2-observable-data-services", desc: "Angular 2 Observable Data Services" }, {href: "http://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html", desc: "Taking advantage of Observables in Angular 2" } ] }, ng2nvd3: { title: "ng2-nvd3 Charting Library (v1.1.1)", anchor: [ {href: "https://github.com/krispo/ng2-nvd3", desc: "Angular2 component for nvd3"} ] }, stunnel: { title: "stunnel (v5.33)", anchor: [ {href: "https://www.stunnel.org/index.html", desc: "Stunnel - a proxy designed to add TLS encryption functionality to existing clients and servers" }, {href: "http://bencane.com/2014/02/18/sending-redis-traffic-through-an-ssl-tunnel-with-stunnel/", desc: "Sending redis traffic through an SSL tunnel with stunnel" } ] }, github: { title: "GitHub", anchor: [ {href: "https://github.com/giancarlobonansea/clusterednode-client", desc: "NLB HA Clustered Node PoC - Client app" }, {href: "https://github.com/giancarlobonansea/clusterednode-worker", desc: "NLB HA Clustered Node PoC - Worker process" }, {href: "https://github.com/giancarlobonansea/clusterednode-hdrhist", desc: "NLB HA Clustered Node PoC - HDR Histogram service" }, {href: "https://github.com/giancarlobonansea/clusterednode-config", desc: "NLB HA Clustered Node PoC - Configuration files" } ] }, nginx: { title: "nginX (v1.11.1)", anchor: [ { href: "https://www.nginx.com/blog/7-tips-for-faster-http2-performance/", desc: "7 Tips for Faster HTTP/2 Performance" }, { href: "https://www.quora.com/How-can-nginx-handle-concurrent-requests-with-a-single-worker-process", desc: "How can nginx handle concurrent requests with a single worker process?" }, { href: "https://www.nginx.com/resources/admin-guide/load-balancer/", desc: "NGINX Load Balancing - HTTP and TCP Load Balancer" }, { href: "https://serversforhackers.com/so-you-got-yourself-a-loadbalancer", desc: "So You Got Yourself a Loadbalancer" }, { href: "http://www.aosabook.org/en/nginx.html", desc: "The Architecture of Open Source Applications (Volume 2): nginx" }, { href: "https://www.nginx.com/blog/inside-nginx-how-we-designed-for-performance-scale/", desc: "Inside NGINX: How We Designed for Performance & Scale" }, { href: "https://www.nginx.com/blog/introducing-the-nginx-microservices-reference-architecture/", desc: "Introducing the Microservices Reference Architecture from NGINX" }, { href: "https://www.nginx.com/blog/building-microservices-using-an-api-gateway/", desc: "Building Microservices: Using an API Gateway" }, { href: "http://www.slideshare.net/joshzhu/nginx-internals", desc: "nginX Internals - slide presentation" }, { href: "http://www.thegeekstuff.com/2013/11/nginx-vs-apache/?utm_source=tuicool", desc: "Nginx Vs Apache: Nginx Basic Architecture and Scalability" }, { href: "https://www.digitalocean.com/community/tutorials/apache-vs-nginx-practical-considerations", desc: "Apache vs Nginx: Practical Considerations" }, { href: "http://www.linuxbrigade.com/reduce-time_wait-socket-connections/", desc: "Reduce TIME_WAIT socket connections" }, { href: "https://vincent.bernat.im/en/blog/2014-tcp-time-wait-state-linux.html", desc: "Coping with the TCP TIME-WAIT state on busy Linux servers" }, { href: "https://easyengine.io/tutorials/linux/sysctl-conf/", desc: "Performance - Sysctl Tweaks" }, { href: "https://tweaked.io/guide/kernel/", desc: "Tweaked.io making your servers fly" }, { href: "https://www.nginx.com/blog/nginx-load-balance-deployment-models/", desc: "NGINX Load Balancing Deployment Scenarios" } ] }, hdr: { title: "HDR Histograms w/o Coordinated Omission (v2.1.9)", anchor: [ { href: "http://bravenewgeek.com/everything-you-know-about-latency-is-wrong/", desc: "Everything You Know About Latency Is Wrong" }, { href: "http://hdrhistogram.org/", desc: "HdrHistogram: A High Dynamic Range Histogram" }, { href: "https://github.com/giltene/wrk2", desc: "wrk2 - a HTTP benchmarking tool based mostly on wrk" }, { href: "https://www.npmjs.com/package/native-hdr-histogram", desc: "node.js bindings for hdr histogram C implementation" }, { href: "http://psy-lob-saw.blogspot.com.br/2015/02/hdrhistogram-better-latency-capture.html", desc: "HdrHistogram: A better latency capture method" }, { href: "https://www.youtube.com/watch?v=6Rs0p3mPNr0", desc: "How NOT to measure latency - Gil Tene" }, { href: "https://nirajrules.wordpress.com/2009/09/17/measuring-performance-response-vs-latency-vs-throughput-vs-load-vs-scalability-vs-stress-vs-robustness/", desc: "Performance Testing – Response vs. Latency vs. Throughput vs. Load vs. Scalability vs. Stress vs. Robustness" } ] }, redis: { title: "redis.io (v3.2.1)", anchor: [ { href: "http://redis.io/", desc: "redis.io - open source in-memory data structure store (database, cache and message broker)" }, { href: "http://redis.js.org/", desc: "REDIS - A Node.js redis client" }, { href: "http://redis.io/topics/rediscli", desc: "redis-cli, the Redis command line interface" }, { href: "http://bluebirdjs.com/docs/getting-started.html", desc: "Bluebird - full featured promise library with unmatched performance" }, { href: "http://redis.io/topics/latency", desc: "Redis latency problems troubleshooting" }, { href: "http://redis.io/topics/latency-monitor", desc: "Redis latency monitoring framework" }, { href: "https://www.datadoghq.com/blog/how-to-collect-redis-metrics/", desc: "How to collect Redis metrics" }, { href: "https://www.datadoghq.com/wp-content/uploads/2013/09/Understanding-the-Top-5-Redis-Performance-Metrics.pdf", desc: "Understanding the Top 5 Redis Performance Metrics" }, { href: "http://www.iamtherealbill.com/2014/12/redis-performance-thoughts-2/", desc: "More Thoughts on Redis Performance" }, { href: "http://redis.io/topics/cluster-tutorial", desc: "Redis cluster tutorial" }, { href: "http://redis.io/topics/cluster-spec", desc: "Redis Cluster Specification" }, { href: "http://redis.io/commands", desc: "Redis Command Sheet" }, { href: "http://redis.io/presentation/Redis_Cluster.pdf", desc: "Redis Cluster - a pragmatic approach to distribution" }, { href: "https://github.com/luin/ioredis", desc: "A robust, performance-focused and full-featured Redis client for Node" }, { href: "https://github.com/luin/ioredis/wiki/Improve-Performance", desc: "ioredis - Improve Performance" }, { href: "https://github.com/thunks/thunk-redis", desc: "The fastest thunk/promise-based redis client, support all redis features" }, { href: "https://github.com/twitter/twemproxy", desc: "A fast, light-weight proxy for memcached and redis" }, { href: "http://engineering.bloomreach.com/the-evolution-of-fault-tolerant-redis-cluster/", desc: "The Evolution of Fault Tolerant Redis Cluster" }, { href: "http://www.iamtherealbill.com/2015/04/clusterizing-redis-intro/", desc: "A Primer on Clusterizing Redis" }, { href: "http://redis.io/topics/distlock", desc: "Distributed locks with Redis" }, { href: "http://redis.io/topics/notifications", desc: "Redis Keyspace Notifications" }, { href: "https://www.infoq.com/presentations/Real-Time-Delivery-Twitter", desc: "redis use-cases: Real-Time Delivery Architecture at Twitter" }, { href: "http://code.flickr.net/2011/10/11/talk-real-time-updates-on-the-cheap-for-fun-and-profit/", desc: "redis use-cases: Flickr - Real-time Updates on the Cheap for Fun and Profit" }, { href: "http://shokunin.co/blog/2014/11/11/operational_redis.html", desc: "Running Redis in production - network and CPU balancing" }, { href: "https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/Performance_Tuning_Guide/network-rps.html", desc: "RPS - Receive Packet Steering for network performance" } ] }, node: { title: "Node.js (v6.2.2)", anchor: [ { href: "https://nodejs.org/en/", desc: "Node.js - a JavaScript runtime built on Chrome's V8 JavaScript engine" }, { href: "http://thisdavej.com/beginners-guide-to-installing-node-js-on-a-raspberry-pi/", desc: "Beginner’s Guide to Installing Node.js on a Raspberry Pi" }, { href: "http://blog.keithcirkel.co.uk/load-balancing-node-js/", desc: "Load balancing Node.js" }, { href: "https://www.npmjs.com/package/http2", desc: "An HTTP/2 client and server implementation" }, { href: "http://nodeschool.io/", desc: "NodeSchool.io - Node.js concepts via interactive command-line games" }, { href: "https://nodejs.org/static/documents/casestudies/Nodejs-at-Uber.pdf", desc: "How Uber Uses Node.js to Scale Their Business" }, { href: "https://www.youtube.com/watch?v=p74282nDMX8", desc: "Node.js at Netflix" }, { href: "https://www.youtube.com/watch?v=ElI5QtUISWM", desc: "Node.js at Uber" }, { href: "https://www.youtube.com/watch?v=-00ImeLt9ec", desc: "Node.js at PayPal" }, { href: "https://www.youtube.com/watch?v=BJPeLJhv1Ic", desc: "Node.js at CapitalOne" } ] }, ga: { title: "Google Analytics", anchor: [ { href: "https://analytics.google.com/", desc: "Google Analytics" } ] }, quic: { title: "Google QUIC", anchor: [ { href: "https://en.wikipedia.org/wiki/QUIC", desc: "QUIC (Quick UDP Internet Connections)" }, { href: "https://docs.google.com/document/d/1RNHkx_VvKWyWg6Lr8SZ-saqsQx7rFV-ev2jRFUoVD34/edit", desc: "QUIC: Design Document and Specification Rationale" }, { href: "https://docs.google.com/document/d/1lmL9EF6qKrk7gbazY8bIdvq3Pno2Xj_l_YShP40GLQE/edit", desc: "QUIC FAQ for Geeks" }, { href: "https://www.youtube.com/watch?v=hQZ-0mXFmk8", desc: "QUIC: next generation multiplexed transport over UDP" }, { href: "http://c3lab.poliba.it/images/3/3b/QUIC_SAC15.pdf", desc: "HTTP over UDP: an Experimental Investigation of QUIC" }, { href: "https://www.chromium.org/quic", desc: "QUIC, a multiplexed stream transport over UDP" }, { href: "http://blog.chromium.org/2015/04/a-quic-update-on-googles-experimental.html", desc: "A QUIC update on Google’s experimental transport" } ] }, open: { title: "Open Source architectures", anchor: [ { href: "http://www.aosabook.org/en/index.html", desc: "The Architecture of Open Source Applications" }, { href: "https://www.youtube.com/watch?v=jm75pxsb80c", desc: "Microservice Developer Experience" }, { href: "https://www.youtube.com/watch?v=SYNJFX0oIBU", desc: "Node.js for Enterprise APIs Panel Discussion" }, { href: "https://www.youtube.com/watch?v=D9TUU5bK0iE", desc: "Rebuilding the Ship as it Sails: Making Large Legacy Sites Responsive" }, { href: "https://strongloop.com/", desc: "Strongloop - Compose APIs, Build, Deploy and Monitor Node" } ] }, openssl: { title: "OpenSSL (v1.0.2h)", anchor: [ { href: "https://www.openssl.org/", desc: "OpenSSL - Cryptography and SSL/TLS Toolkit" } ] }, socket: { title: "Socket.IO (v1.4.8)", anchor: [ { href: "http://socket.io/blog/", desc: "Socket.IO - THE FASTEST AND MOST RELIABLE REAL-TIME ENGINE" }, { href: "http://stackoverflow.com/questions/19496790/drop-packets-if-falling-behind-with-socket-io-in-node-js", desc: "How to handle dropping packets on volatile messages" }, { href: "http://blog.mixu.net/2011/11/22/performance-benchmarking-socket-io-0-8-7-0-7-11-and-0-6-17-and-nodes-native-tcp/", desc: "Performance benchmarking Socket.io 0.8.7, 0.7.11 and 0.6.17 and Node's native TCP" } ] } }; } AppSimulator.parameters = [ app.HTTPService ]; AppSimulator.annotations = [ new ng.core.Component({ selector: 'node-cluster-simulator', templateUrl: 'simulator.html', providers: [ app.HTTPService, ng.http.HTTP_PROVIDERS ], directives: [nvD3] }) ]; AppSimulator.prototype.setSmall = function() { if (this.isDuration) { this.reqDuration = 5; this.reqInterval = 50; this.reqConn = 4; } else { this.reqCount = 100; this.reqConn = 2; } ga('send', 'event', 'Simulation', 'Configuration', 'Small Preset'); }; AppSimulator.prototype.setMedium = function() { if (this.isDuration) { this.reqDuration = 10; this.reqInterval = 30; this.reqConn = 4; } else { this.reqCount = 512; this.reqConn = 16; } ga('send', 'event', 'Simulation', 'Configuration', 'Medium Preset'); }; AppSimulator.prototype.setLarge = function() { if (this.isDuration) { this.reqDuration = 30; this.reqInterval = 25; this.reqConn = 4; } else { this.reqCount = 1024; this.reqConn = 64; } ga('send', 'event', 'Simulation', 'Configuration', 'Large Preset'); }; AppSimulator.prototype.setHuge = function() { if (this.isDuration) { this.reqDuration = 60; this.reqInterval = 25; this.reqConn = 8; } else { this.reqCount = 2048; this.reqConn = 128; } ga('send', 'event', 'Simulation', 'Configuration', 'Huge Preset'); }; AppSimulator.prototype.setDuration = function() { this.isDuration = true; }; AppSimulator.prototype.setRequests = function() { this.isDuration = false; }; AppSimulator.prototype.isDurationMethod = function() { return this.isDuration; }; AppSimulator.prototype.isRequestMethod = function() { return !this.isDuration; }; AppSimulator.prototype.usedDurationMethod = function() { return this.execMode === 'STABILITY'; }; AppSimulator.prototype.usedRequestMethod = function() { return this.execMode === 'STRESS'; }; AppSimulator.prototype.getSimulationMethod = function() { return this.isDuration ? 'STABILITY' : 'STRESS'; }; AppSimulator.prototype.isRunning = function() { return this.running; }; AppSimulator.prototype.calculateHistogram = function() { this.barChartData = [{key: 'raspberrypi2-redis', values: []}, {key: 'raspberrypi3-redis', values: []}, {key: 'raspberrypi5-redis', values: []}, {key: 'raspberrypi6-redis', values: []}, {key: 'raspberrypi2-node', values: []}, {key: 'raspberrypi3-node', values: []}, {key: 'raspberrypi5-node', values: []}, {key: 'raspberrypi6-node', values: []}, {key: 'raspberrypi2-nginx', values: []}, {key: 'raspberrypi3-nginx', values: []}, {key: 'raspberrypi5-nginx', values: []}, {key: 'raspberrypi6-nginx', values: []}, {key: 'raspberrypi2-angular', values: []}, {key: 'raspberrypi3-angular', values: []}, {key: 'raspberrypi5-angular', values: []}, {key: 'raspberrypi6-angular', values: []}]; this.polarChartData = [{key: 'raspberrypi2', y: 0}, {key: 'raspberrypi3', y: 0}, {key: 'raspberrypi5', y: 0}, {key: 'raspberrypi6', y: 0}]; this.polarChartData2 = [{key: 'raspberrypi2', y: 0}, {key: 'raspberrypi3', y: 0}, {key: 'raspberrypi5', y: 0}, {key: 'raspberrypi6', y: 0}]; this.lineChartData = [ {key: 'w/o Coord. Omission', values: [], area: false}, {key: 'Latency/Percentile', values: [], area: true} ]; this.disregard = Math.ceil(this.reqExecuted * 4.55 / 100.0); this.discardLower = Math.floor(this.disregard/2); this.discardUpper = this.reqExecuted - Math.ceil(this.disregard / 2) - 1; // // Populate barchart as processed (no sorting) // for (var i = 0; i < this.requests[0].length; i++) { var rtt2 = this.requests[0][i].hst === 0 ? this.requests[0][i].rtt : 0; var rtt3 = this.requests[0][i].hst === 1 ? this.requests[0][i].rtt : 0; var rtt5 = this.requests[0][i].hst === 2 ? this.requests[0][i].rtt : 0; var rtt6 = this.requests[0][i].hst === 3 ? this.requests[0][i].rtt : 0; var tsn2 = this.requests[0][i].hst === 0 ? this.requests[0][i].tsn : 0; var tsn3 = this.requests[0][i].hst === 1 ? this.requests[0][i].tsn : 0; var tsn5 = this.requests[0][i].hst === 2 ? this.requests[0][i].tsn : 0; var tsn6 = this.requests[0][i].hst === 3 ? this.requests[0][i].tsn : 0; var exts2 = this.requests[0][i].hst === 0 ? this.requests[0][i].exts : 0; var exts3 = this.requests[0][i].hst === 1 ? this.requests[0][i].exts : 0; var exts5 = this.requests[0][i].hst === 2 ? this.requests[0][i].exts : 0; var exts6 = this.requests[0][i].hst === 3 ? this.requests[0][i].exts : 0; var red2 = this.requests[0][i].hst === 0 ? this.requests[0][i].red : 0; var red3 = this.requests[0][i].hst === 1 ? this.requests[0][i].red : 0; var red5 = this.requests[0][i].hst === 2 ? this.requests[0][i].red : 0; var red6 = this.requests[0][i].hst === 3 ? this.requests[0][i].red : 0; this.barChartData[0].values.push({label: this.requests[0][i].rid, value: Math.ceil(red2)}); this.barChartData[1].values.push({label: this.requests[0][i].rid, value: Math.ceil(red3)}); this.barChartData[2].values.push({label: this.requests[0][i].rid, value: Math.ceil(red5)}); this.barChartData[3].values.push({label: this.requests[0][i].rid, value: Math.ceil(red6)}); this.barChartData[4].values.push({label: this.requests[0][i].rid, value: Math.ceil(exts2 - red2)}); this.barChartData[5].values.push({label: this.requests[0][i].rid, value: Math.ceil(exts3 - red3)}); this.barChartData[6].values.push({label: this.requests[0][i].rid, value: Math.ceil(exts5 - red5)}); this.barChartData[7].values.push({label: this.requests[0][i].rid, value: Math.ceil(exts6 - red6)}); this.barChartData[8].values.push({label: this.requests[0][i].rid, value: Math.floor(tsn2 - exts2)}); this.barChartData[9].values.push({label: this.requests[0][i].rid, value: Math.floor(tsn3 - exts3)}); this.barChartData[10].values.push({label: this.requests[0][i].rid, value: Math.floor(tsn5 - exts5)}); this.barChartData[11].values.push({label: this.requests[0][i].rid, value: Math.floor(tsn6 - exts6)}); this.barChartData[12].values.push({label: this.requests[0][i].rid, value: rtt2 - tsn2}); this.barChartData[13].values.push({label: this.requests[0][i].rid, value: rtt3 - tsn3}); this.barChartData[14].values.push({label: this.requests[0][i].rid, value: rtt5 - tsn5}); this.barChartData[15].values.push({label: this.requests[0][i].rid, value: rtt6 - tsn6}); } // // HDR by RTT (AngularJS time) // var hdrRTTpost = {"arr": []}; for (var n = 0; n < this.requests[0].length; n++) { hdrRTTpost.arr.push(this.requests[0][n].rtt); } // // Sorting by RTT (AngularJS time) // this.totReqAng = [0,0,0,0]; this.requests[0].sort(function(a, b) {return a.rtt - b.rtt}); for (i = 0; i < this.requests[0].length; i++) { rtt2 = this.requests[0][i].hst === 0 ? this.requests[0][i].rtt : 0; rtt3 = this.requests[0][i].hst === 1 ? this.requests[0][i].rtt : 0; rtt5 = this.requests[0][i].hst === 2 ? this.requests[0][i].rtt : 0; rtt6 = this.requests[0][i].hst === 3 ? this.requests[0][i].rtt : 0; this.polarChartData2[0].y += ((i>=this.discardLower)&&(i<=this.discardUpper))?rtt2:0; this.polarChartData2[1].y += ((i>=this.discardLower)&&(i<=this.discardUpper))?rtt3:0; this.polarChartData2[2].y += ((i>=this.discardLower)&&(i<=this.discardUpper))?rtt5:0; this.polarChartData2[3].y += ((i>=this.discardLower)&&(i<=this.discardUpper))?rtt6:0; this.totReqAng[0] += ((this.requests[0][i].hst===0)&&(i>=this.discardLower)&&(i<=this.discardUpper))?1:0; this.totReqAng[1] += ((this.requests[0][i].hst===1)&&(i>=this.discardLower)&&(i<=this.discardUpper))?1:0; this.totReqAng[2] += ((this.requests[0][i].hst===2)&&(i>=this.discardLower)&&(i<=this.discardUpper))?1:0; this.totReqAng[3] += ((this.requests[0][i].hst===3)&&(i>=this.discardLower)&&(i<=this.discardUpper))?1:0; this.totAngular += ((i>=this.discardLower)&&(i<=this.discardUpper))?this.requests[0][i].rtt:0; } this.polarChartData2[0].y = this.polarChartData2[0].y / this.totReqAng[0]; this.polarChartData2[1].y = this.polarChartData2[1].y / this.totReqAng[1]; this.polarChartData2[2].y = this.polarChartData2[2].y / this.totReqAng[2]; this.polarChartData2[3].y = this.polarChartData2[3].y / this.totReqAng[3]; this.tpAngular = Math.ceil(this.reqExecuted / (this.duration / 1000)); for (i = 0; i < this.histogram.length; i++) { this.histogram[i][1] = this.requests[0][Math.ceil(this.reqExecuted * this.histogram[i][0] / 100) - 1].rtt; } // // Sorting by TSN (nginX time) // this.totReqNgi = [0,0,0,0]; this.requests[0].sort(function(a, b) {return a.tsn - b.tsn}); for (i = 0; i < this.histogram.length; i++) { this.histogram[i][2] = this.requests[0][Math.ceil(this.reqExecuted * this.histogram[i][0] / 100) - 1].tsn; } for (i = 0; i < this.requests[0].length; i++) { tsn2 = this.requests[0][i].hst === 0 ? this.requests[0][i].tsn : 0; tsn3 = this.requests[0][i].hst === 1 ? this.requests[0][i].tsn : 0; tsn5 = this.requests[0][i].hst === 2 ? this.requests[0][i].tsn : 0; tsn6 = this.requests[0][i].hst === 3 ? this.requests[0][i].tsn : 0; this.polarChartData[0].y += ((i>=this.discardLower)&&(i<=this.discardUpper))?tsn2:0; this.polarChartData[1].y += ((i>=this.discardLower)&&(i<=this.discardUpper))?tsn3:0; this.polarChartData[2].y += ((i>=this.discardLower)&&(i<=this.discardUpper))?tsn5:0; this.polarChartData[3].y += ((i>=this.discardLower)&&(i<=this.discardUpper))?tsn6:0; this.totReqNgi[0] += ((this.requests[0][i].hst===0)&&(i>=this.discardLower)&&(i<=this.discardUpper))?1:0; this.totReqNgi[1] += ((this.requests[0][i].hst===1)&&(i>=this.discardLower)&&(i<=this.discardUpper))?1:0; this.totReqNgi[2] += ((this.requests[0][i].hst===2)&&(i>=this.discardLower)&&(i<=this.discardUpper))?1:0; this.totReqNgi[3] += ((this.requests[0][i].hst===3)&&(i>=this.discardLower)&&(i<=this.discardUpper))?1:0; this.totNginx += ((i>=this.discardLower)&&(i<=this.discardUpper))?this.requests[0][i].tsn:0; } this.polarChartData[0].y = this.polarChartData[0].y / this.totReqNgi[0]; this.polarChartData[1].y = this.polarChartData[1].y / this.totReqNgi[1]; this.polarChartData[2].y = this.polarChartData[2].y / this.totReqNgi[2]; this.polarChartData[3].y = this.polarChartData[3].y / this.totReqNgi[3]; this.tpNginx = Math.ceil(this.tpAngular * this.totAngular / this.totNginx); // // Sort by EXTS (nodeJS time) // this.requests[0].sort(function(a, b) {return a.exts - b.exts}); for (i = 0; i < this.histogram.length; i++) { this.histogram[i][3] = this.requests[0][Math.ceil(this.reqExecuted * this.histogram[i][0] / 100) - 1].exts; } for (i = 0; i < this.requests[0].length; i++) { this.totNode += ((i>=this.discardLower)&&(i<=this.discardUpper))?this.requests[0][i].exts:0; } this.tpNode = Math.ceil(this.tpNginx * this.totNginx / this.totNode); // // Sort by RED (redis.io time) // this.requests[0].sort(function(a, b) {return a.red - b.red}); for (i = 0; i < this.histogram.length; i++) { this.histogram[i][4] = this.requests[0][Math.ceil(this.reqExecuted * this.histogram[i][0] / 100) - 1].red; } for (i = 0; i < this.requests[0].length; i++) { this.totRedis += ((i >= this.discardLower) && (i <= this.discardUpper)) ? this.requests[0][i].red : 0; } this.tpRedis = Math.ceil(this.tpNode * this.totNode / this.totRedis); // // Calculating HDR Histogram // this.hdrRTTresults = {table: [], chart: []}; this.lineChartData[0].values = []; this.lineChartData[1].values = []; var selfRTT = this; this.observableRTT = this.httpService.post(this.urlHDR, JSON.stringify(hdrRTTpost)).subscribe( function(response) { selfRTT.hdrRTTresults = response; selfRTT.requests[0].sort(function(a, b) {return a.rtt - b.rtt}); for (var n = 0; n < selfRTT.hdrRTTresults.chart.length; n++) { var idx = ((selfRTT.hdrRTTresults.chart[n].percentile * selfRTT.reqOK / 100) | 0) - 1; selfRTT.lineChartData[0].values.push({ x: selfRTT.hdrRTTresults.chart[n].percentile, y: selfRTT.hdrRTTresults.chart[n].value }); selfRTT.lineChartData[1].values.push({ x: selfRTT.hdrRTTresults.chart[n].percentile, y: selfRTT.requests[0][(idx < 0) ? 0 : idx].rtt }); } }, function(error) { console.log("HDR Service error"); }, function() { selfRTT.observableRTT.unsubscribe(); selfRTT.observableRTT = undefined; selfRTT.calculating = false; selfRTT.running = false; selfRTT.liveEvents = false; } ); ga('send', 'event', 'Simulation', 'Execution', 'Throughput', this.tpAngular); }; AppSimulator.prototype.onRefLink = function(title, desc) { ga('send', 'event', 'Reference', title, desc); }; AppSimulator.prototype.percValue = function() { return Math.ceil(this.reqOK * 100 / this.reqCount); }; AppSimulator.prototype.calcPosition = function(hist) { return Math.ceil(this.reqOK * hist / 100); }; AppSimulator.prototype.getDurationRequests = function() { var tot = (this.reqDuration * 1000 * this.reqConn / this.reqInterval) | 0; return tot - (tot % this.reqConn); }; AppSimulator.prototype.getDurationThroughput = function() { return (this.getDurationRequests() / this.reqDuration) | 0; }; AppSimulator.prototype.checkStop = function() { this.duration = Date.now() - this.iniTime; if (this.reqOK + this.reqErrors >= this.reqCount) { this.calculating = true; this.reqExecuted = this.reqCount; var selfStop = this; setTimeout(function(){ selfStop.calculateHistogram(); }, 500); return true; } return false; }; AppSimulator.prototype.throwHTTPrequests = function(i) { var self = this; var arrReq = []; for (var j = 0; ((j < this.reqConn) && (i + j < this.reqCount)); j++) { arrReq.push(this.requests[1][i + j]); } self.observableRequests = Rx.Observable.forkJoin(arrReq).subscribe( function(response) { for (var k = 0; k < response.length; k++) { self.requests[0][response[k].reqId] = { rid: 'Request ' + ((response[k].reqId | 0) + 1), hst: self.nodeIdx[response[k].json.hostname][0], rtt: response[k].rtt, tsn: response[k].tsn, exts: response[k].exts, red: response[k].red }; if (!(response[k].json.pid in self.pidIdx[response[k].json.hostname])) { self.results[self.nodeIdx[response[k].json.hostname][0]][1].push([response[k].json.pid, []]); self.pidIdx[response[k].json.hostname][response[k].json.pid] = self.results[self.nodeIdx[response[k].json.hostname][0]][1].length - 1; } self.results[self.nodeIdx[response[k].json.hostname][0]][1][self.pidIdx[response[k].json.hostname][response[k].json.pid]][1].push(++self.reqOK); self.nodeIdx[response[k].json.hostname][1]++; } }, function(error) { self.reqErrors++; }, function() { self.observableRequests.unsubscribe(); self.observableRequests = undefined; if (!self.checkStop()) { self.loopCon += self.reqConn; self.throwHTTPrequests(self.loopCon); } } ); }; AppSimulator.prototype.throwHTTPduration = function() { var self = this, reqId = 0; self.countRequests = 0; self.countResponses = 0; self.timerRunning = true; var intervalFunction = function() { if (self.timerRunning && self.countRequests < self.reqCount) { self.countRequests += self.reqConn; var arrReq = []; for (var j = 0; j < self.reqConn; j++) { self.requests[0].push({rtt: 0, hst: '', rid: 0, tsn: 0, exts: 0, red: 0}); self.requests[1].push(self.httpService.get(reqId, self.selectedUrl)); arrReq.push(self.requests[1][reqId]); reqId++; } var observableRequestsA = Rx.Observable.forkJoin(arrReq).subscribe( function(response) { self.duration = Date.now() - self.iniTime; if (self.countResponses < self.reqCount) { for (var k = 0; k < response.length; k++) { self.requests[0][response[k].reqId] = { rid: 'Request ' + ((response[k].reqId | 0) + 1), hst: self.nodeIdx[response[k].json.hostname][0], rtt: response[k].rtt, tsn: response[k].tsn, exts: response[k].exts, red: response[k].red }; if (!(response[k].json.pid in self.pidIdx[response[k].json.hostname])) { self.results[self.nodeIdx[response[k].json.hostname][0]][1].push([response[k].json.pid, []]); self.pidIdx[response[k].json.hostname][response[k].json.pid] = self.results[self.nodeIdx[response[k].json.hostname][0]][1].length - 1; } self.results[self.nodeIdx[response[k].json.hostname][0]][1][self.pidIdx[response[k].json.hostname][response[k].json.pid]][1].push(++self.reqOK); self.nodeIdx[response[k].json.hostname][1]++; self.countResponses++; } } else { if (self.countResponses > self.reqCount) { for (var z = 0; z < self.reqConn; z++) { self.requests[0].pop(); self.requests[1].pop(); self.countResponses--; } } } }, function(error) { self.duration = Date.now() - self.iniTime; if (self.countResponses < self.reqCount) { self.reqErrors++; self.countResponses++; } else { if (self.countResponses > self.reqCount) { for (var z = 0; z < self.reqConn; z++) { self.requests[0].pop(); self.requests[1].pop(); self.countResponses--; } } } }, function() { if (!self.timerRunning && !self.calculating && self.countRequests === self.countResponses) { if (self.intervalHandler) { clearInterval(self.intervalHandler); } self.calculating = true; var selfStop = self; self.reqExecuted = self.countResponses; setTimeout(function() { selfStop.calculateHistogram(); }, 500); } observableRequestsA.unsubscribe(); observableRequestsA = undefined; } ); } else { if (!self.calculating && self.countRequests === self.countResponses) { if (self.intervalHandler) { clearInterval(self.intervalHandler); } self.calculating = true; var selfStop = self; self.reqExecuted = self.countResponses; setTimeout(function() { selfStop.calculateHistogram(); }, 500); } } }; self.iniTime = Date.now(); setTimeout(function() { self.timerRunning = false; }, self.reqDuration * 1000 + 10); intervalFunction(); self.intervalHandler = setInterval(intervalFunction, self.reqInterval); }; AppSimulator.prototype.getDatabaseStatus = function(cond) { switch (cond) { case 0: return 'text-info'; case 2: return 'text-primary'; case 1: return 'text-muted'; case 3: return 'text-danger bg-danger'; } }; AppSimulator.prototype.showRef = function() { this.showReference = !this.showReference; if (this.showReference) { this.liveEvents = false; } }; AppSimulator.prototype.showLive = function() { this.liveEvents = !this.liveEvents; if (this.liveEvents) { this.showReference = false; } }; AppSimulator.prototype.mapDBmatrix = function(x, y) { return ((((x * 32) + y) * 16 / 2731) | 0); }; AppSimulator.prototype.initEVMatrix = function() { this.evMatrix = []; for (var i = 0; i < 16; i++) { this.evMatrix.push([]); for (var j = 0; j < 32; j++) { this.evMatrix[i].push(this.mapDBmatrix(i, j)); } } }; AppSimulator.prototype.initSimulator = function() { this.liveEvents = true; this.showReference = false; this.reqOK = 0; this.reqErrors = 0; this.duration = 0; this.loopCon = 0; this.histogram = [[50, 0, 0, 0, 0], [75, 0, 0, 0, 0], [87.5, 0, 0, 0, 0], [93.75, 0, 0, 0, 0], [96.875, 0, 0, 0, 0], [98.4375, 0, 0, 0, 0], [99.21875, 0, 0, 0, 0], [100, 0, 0, 0, 0]]; this.requests = [[], []]; this.results = [["raspberrypi2", []], ["raspberrypi3", []], ["raspberrypi5", []], ["raspberrypi6", []]]; this.nodeIdx = { "raspberrypi2": [0, 0], "raspberrypi3": [1, 0], "raspberrypi5": [2, 0], "raspberrypi6": [3, 0] }; this.pidIdx = { "raspberrypi2": {}, "raspberrypi3": {}, "raspberrypi5": {}, "raspberrypi6": {} }; this.totAngular = 0; this.totNginx = 0; this.totNode = 0; this.totRedis = 0; this.tpAngular = 0; this.tpNginx = 0; this.tpNode = 0; this.tpRedis = 0; this.observableRequests = undefined; this.execMode = this.getSimulationMethod(); this.execReq = this.reqCount; this.execDuration = this.reqDuration; this.execInterval = this.reqInterval; this.execConn = this.reqConn; this.execMaxReq = this.getDurationRequests(); this.initEVMatrix(); this.running = true; if (this.isDuration) { this.reqCount = this.getDurationRequests(); this.throwHTTPduration(); } else { for (var reqId = 0; reqId < this.reqCount; reqId++) { this.requests[0].push({rtt: 0, hst: '', rid: 0, tsn: 0, exts: 0, red: 0}); this.requests[1].push(this.httpService.get(reqId, this.selectedUrl)); } this.iniTime = Date.now(); this.throwHTTPrequests(this.loopCon); } }; return AppSimulator; })(); })(window.app || (window.app = {}));
app.simulator.js
(function(app) { app.AppSimulator = (function() { function AppSimulator(HTTPService) { this.histogram = [[50, 0, 0, 0, 0], [75, 0, 0, 0, 0], [87.5, 0, 0, 0, 0], [93.75, 0, 0, 0, 0], [96.875, 0, 0, 0, 0], [98.4375, 0, 0, 0, 0], [99.21875, 0, 0, 0, 0], [100, 0, 0, 0, 0]]; this.requests = [[], []]; this.isDuration = false; this.reqConn = 4; this.reqCount = 100; this.reqDuration = 5; this.reqInterval = 50; this.running = false; this.reqErrors = 0; this.reqOK = 0; this.loopCon = 0; this.duration = 0; this.totAngular = 0; this.totNginx = 0; this.totNode = 0; this.totRedis = 0; this.tpAngular = 0; this.tpNginx = 0; this.tpNode = 0; this.tpRedis = 0; this.showReference = false; this.calculating = false; this.liveEvents = false; this.httpService = HTTPService; this.urlOptions = [['https://giancarlobonansea.homeip.net:33333/api', 'DNS Public'], ['https://raspberrypi4:8010/api', 'DNS Private'], ['https://192.168.69.242:8010/api', 'IP Private']]; this.nodes = ["raspberrypi2", "raspberrypi3", "raspberrypi5", "raspberrypi6"]; this.urlHDR = 'https://giancarlobonansea.homeip.net:33333/hdr'; this.selectedUrl = this.urlOptions[0][0]; this.initEVMatrix(); this.socket = io('https://giancarlobonansea.homeip.net:32402'); this.liveTTL = 500; var selfMtx = this; // Receive redis.io realtime info this.socket.on('redis', function(data) { var x = data.x, y = data.y; if (selfMtx.evMatrix[x][y] !== 3) { selfMtx.evMatrix[x][y] = 3; setTimeout(function() { selfMtx.evMatrix[x][y] = selfMtx.mapDBmatrix(x, y); }, selfMtx.liveTTL); } }); this.barChartOptions = { chart: { type: 'multiBarChart', showControls: false, height: 400, margin: { top: 20, right: 20, bottom: 20, left: 45 }, x: function(d) {return d.label;}, y: function(d) {return d.value;}, clipEdge: true, stacked: true, showXAxis: false, duration: 500, xAxis: { showMaxMin: false }, yAxis: { tickFormat: function(d) { return d3.format('d')(d); } } } }; this.lineChartOptions = { chart: { type: 'lineWithFocusChart', showControls: false, height: 400, showLegend: true, clipEdge: true, duration: 500, margin: { top: 20, right: 20, bottom: 40, left: 55 }, x: function(d) { return d.x; }, y: function(d) { return d.y; }, useInteractiveGuideline: true, xAxis: { axisLabel: 'Percentile (%)' // ,tickFormat: function(d) { // return d3.format('.5f')(d); // } }, yAxis: { axisLabel: 'AngularJS Latency (ms)', axisLabelDistance: -10, rotateYLabel: true }, x2Axis: { // tickFormat: function(d) { // return d3.format('.5f')(d); // } }, y2Axis: {}, brushExtent: [75, 100] } }; this.polarChartOptions = { chart: { type: 'pieChart', height: 299, showLegend: false, donut: true, padAngle: 0.08, cornerRadius: 5, title: 'nginX', x: function(d) {return d.key;}, y: function(d) {return d.y;}, showLabels: true, labelType: function(d) {return d.data.key + ': ' + (d.data.y | 0);}, labelsOutside: true, duration: 500 } }; this.polarChartOptions2 = { chart: { type: 'pieChart', height: 299, showLegend: false, donut: true, padAngle: 0.08, cornerRadius: 5, title: 'AngularJS', x: function(d) {return d.key;}, y: function(d) {return d.y;}, showLabels: true, labelsOutside: true, labelType: function(d) {return d.data.key + ': ' + (d.data.y | 0);}, duration: 500 } }; this.barChartData = [{key: 'raspberrypi2-redis', values: [{label: '', value: 0}]}, {key: 'raspberrypi3-redis', values: [{label: '', value: 0}]}, {key: 'raspberrypi5-redis', values: [{label: '', value: 0}]}, {key: 'raspberrypi6-redis', values: [{label: '', value: 0}]}, {key: 'raspberrypi2-node', values: [{label: '', value: 0}]}, {key: 'raspberrypi3-node', values: [{label: '', value: 0}]}, {key: 'raspberrypi5-node', values: [{label: '', value: 0}]}, {key: 'raspberrypi6-node', values: [{label: '', value: 0}]}, {key: 'raspberrypi2-nginx', values: [{label: '', value: 0}]}, {key: 'raspberrypi3-nginx', values: [{label: '', value: 0}]}, {key: 'raspberrypi5-nginx', values: [{label: '', value: 0}]}, {key: 'raspberrypi6-nginx', values: [{label: '', value: 0}]}, {key: 'raspberrypi2-angular', values: [{label: '', value: 0}]}, {key: 'raspberrypi3-angular', values: [{label: '', value: 0}]}, {key: 'raspberrypi5-angular', values: [{label: '', value: 0}]}, {key: 'raspberrypi6-angular', values: [{label: '', value: 0}]} ]; this.polarChartData = [{key: 'raspberrypi2', y: 25}, {key: 'raspberrypi3', y: 25}, {key: 'raspberrypi5', y: 25}, {key: 'raspberrypi6', y: 25}]; this.polarChartData2 = [{key: 'raspberrypi2', y: 25}, {key: 'raspberrypi3', y: 25}, {key: 'raspberrypi5', y: 25}, {key: 'raspberrypi6', y: 25}]; this.lineChartData = [ {key: 'w/o Coord. Omission', values: [], area: false}, {key: 'Latency/Percentile', values: [], area: true} ]; this.observableRequests = undefined; this.links = { HTTP2: { title: "HTTP/2", anchor: [ { href: 'https://http2.akamai.com/demo', desc: 'HTTP/2: the Future of the Internet | Akamai' }, { href: 'https://http2.github.io', desc: "HTTP/2 Github repository" }, { href: 'https://http2.github.io/http2-spec/', desc: 'Hypertext Transfer Protocol Version 2 (HTTP/2) draft-ietf-httpbis-http2-latest' }, { href: 'https://docs.google.com/presentation/d/1r7QXGYOLCh4fcUq0jDdDwKJWNqWK1o4xMtYpKZCJYjM/present?slide=id.g4ec7b01d4_5_150', desc: "HTTP/2 is here, let's optimize! - Velocity 2015 - Google Slides" }, { href: 'http://caniuse.com/#search=HTTP%2F2', desc: 'Can I use... HTTP/2' }, { href: 'https://hpbn.co/http2/', desc: "HTTP: HTTP/2 - High Performance Browser Networking (O'Reilly)" }, { href: 'https://www.smashingmagazine.com/2016/02/getting-ready-for-http2/', desc: 'Getting Ready For HTTP/2: A Guide For Web Designers And Developers' }, { href: 'http://qnimate.com/post-series/http2-complete-tutorial/', desc: 'HTTP/2 Complete Tutorial' }, { href: 'http://javascriptplayground.com/blog/2016/03/http2-and-you/', desc: 'HTTP/2 and You' }, { href: 'https://chrome.google.com/webstore/detail/http2-and-spdy-indicator/mpbpobfflnpcgagjijhmgnchggcjblin', desc: 'HTTP/2 and SPDY indicator' }, { href: "http://www.aosabook.org/en/posa/secrets-of-mobile-network-performance.html", desc: "Secrets of Mobile Network Performance" } ] }, pm2: { title: "Keymetrics pm2 (v1.1.3)", anchor: [ { href: "http://pm2.keymetrics.io/", desc: "PM2 - Advanced Node.js process manager" }, { href: "http://pm2.keymetrics.io/docs/usage/cluster-mode/", desc: "PM2 - Cluster Mode" }, { href: "https://keymetrics.io/", desc: "Keymetrics I/O - Monitor and Augment Node.js" }, { href: "http://pm2.keymetrics.io/docs/usage/application-declaration/", desc: "PM2 - Application Declaration" }, { href: "http://pm2.keymetrics.io/docs/usage/deployment/", desc: "PM2 - Deployment" } ] }, angular2: { title: "AngularJS 2 (v2.0.0-rc3)", anchor: [ {href: "https://angular.io", desc: "One framework - Angular 2"}, {href: "https://angular.io/docs/js/latest/guide/cheatsheet.html", desc: "Angular Cheat Sheet - js"}, {href: "https://medium.com/google-developer-experts/angular-2-introduction-to-new-http-module-1278499db2a0#.ttmhbubnd", desc: "Angular 2 — Introduction to new HTTP module" }, {href: "http://blog.caelum.com.br/angularjs-seo-google-analytics-e-virtual-pages/", desc: "AngularJS: SEO, Google Analytics e Virtual Pages" }, {href: "https://coryrylan.com/blog/angular-2-observable-data-services", desc: "Angular 2 Observable Data Services" }, {href: "http://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html", desc: "Taking advantage of Observables in Angular 2" } ] }, ng2nvd3: { title: "ng2-nvd3 Charting Library (v1.1.1)", anchor: [ {href: "https://github.com/krispo/ng2-nvd3", desc: "Angular2 component for nvd3"} ] }, stunnel: { title: "stunnel (v5.32)", anchor: [ {href: "https://www.stunnel.org/index.html", desc: "Stunnel - a proxy designed to add TLS encryption functionality to existing clients and servers" }, {href: "http://bencane.com/2014/02/18/sending-redis-traffic-through-an-ssl-tunnel-with-stunnel/", desc: "Sending redis traffic through an SSL tunnel with stunnel" } ] }, github: { title: "GitHub", anchor: [ {href: "https://github.com/giancarlobonansea/clusterednode-client", desc: "NLB HA Clustered Node PoC - Client app" }, {href: "https://github.com/giancarlobonansea/clusterednode-worker", desc: "NLB HA Clustered Node PoC - Worker process" }, {href: "https://github.com/giancarlobonansea/clusterednode-hdrhist", desc: "NLB HA Clustered Node PoC - HDR Histogram service" }, {href: "https://github.com/giancarlobonansea/clusterednode-config", desc: "NLB HA Clustered Node PoC - Configuration files" } ] }, nginx: { title: "nginX (v1.11.1)", anchor: [ { href: "https://www.nginx.com/blog/7-tips-for-faster-http2-performance/", desc: "7 Tips for Faster HTTP/2 Performance" }, { href: "https://www.quora.com/How-can-nginx-handle-concurrent-requests-with-a-single-worker-process", desc: "How can nginx handle concurrent requests with a single worker process?" }, { href: "https://www.nginx.com/resources/admin-guide/load-balancer/", desc: "NGINX Load Balancing - HTTP and TCP Load Balancer" }, { href: "https://serversforhackers.com/so-you-got-yourself-a-loadbalancer", desc: "So You Got Yourself a Loadbalancer" }, { href: "http://www.aosabook.org/en/nginx.html", desc: "The Architecture of Open Source Applications (Volume 2): nginx" }, { href: "https://www.nginx.com/blog/inside-nginx-how-we-designed-for-performance-scale/", desc: "Inside NGINX: How We Designed for Performance & Scale" }, { href: "https://www.nginx.com/blog/introducing-the-nginx-microservices-reference-architecture/", desc: "Introducing the Microservices Reference Architecture from NGINX" }, { href: "https://www.nginx.com/blog/building-microservices-using-an-api-gateway/", desc: "Building Microservices: Using an API Gateway" }, { href: "http://www.slideshare.net/joshzhu/nginx-internals", desc: "nginX Internals - slide presentation" }, { href: "http://www.thegeekstuff.com/2013/11/nginx-vs-apache/?utm_source=tuicool", desc: "Nginx Vs Apache: Nginx Basic Architecture and Scalability" }, { href: "https://www.digitalocean.com/community/tutorials/apache-vs-nginx-practical-considerations", desc: "Apache vs Nginx: Practical Considerations" }, { href: "http://www.linuxbrigade.com/reduce-time_wait-socket-connections/", desc: "Reduce TIME_WAIT socket connections" }, { href: "https://vincent.bernat.im/en/blog/2014-tcp-time-wait-state-linux.html", desc: "Coping with the TCP TIME-WAIT state on busy Linux servers" }, { href: "https://easyengine.io/tutorials/linux/sysctl-conf/", desc: "Performance - Sysctl Tweaks" }, { href: "https://tweaked.io/guide/kernel/", desc: "Tweaked.io making your servers fly" }, { href: "https://www.nginx.com/blog/nginx-load-balance-deployment-models/", desc: "NGINX Load Balancing Deployment Scenarios" } ] }, hdr: { title: "HDR Histograms w/o Coordinated Omission (v2.1.9)", anchor: [ { href: "http://bravenewgeek.com/everything-you-know-about-latency-is-wrong/", desc: "Everything You Know About Latency Is Wrong" }, { href: "http://hdrhistogram.org/", desc: "HdrHistogram: A High Dynamic Range Histogram" }, { href: "https://github.com/giltene/wrk2", desc: "wrk2 - a HTTP benchmarking tool based mostly on wrk" }, { href: "https://www.npmjs.com/package/native-hdr-histogram", desc: "node.js bindings for hdr histogram C implementation" }, { href: "http://psy-lob-saw.blogspot.com.br/2015/02/hdrhistogram-better-latency-capture.html", desc: "HdrHistogram: A better latency capture method" }, { href: "https://www.youtube.com/watch?v=6Rs0p3mPNr0", desc: "How NOT to measure latency - Gil Tene" }, { href: "https://nirajrules.wordpress.com/2009/09/17/measuring-performance-response-vs-latency-vs-throughput-vs-load-vs-scalability-vs-stress-vs-robustness/", desc: "Performance Testing – Response vs. Latency vs. Throughput vs. Load vs. Scalability vs. Stress vs. Robustness" } ] }, redis: { title: "redis.io (v3.2.1)", anchor: [ { href: "http://redis.io/", desc: "redis.io - open source in-memory data structure store (database, cache and message broker)" }, { href: "http://redis.js.org/", desc: "REDIS - A Node.js redis client" }, { href: "http://redis.io/topics/rediscli", desc: "redis-cli, the Redis command line interface" }, { href: "http://bluebirdjs.com/docs/getting-started.html", desc: "Bluebird - full featured promise library with unmatched performance" }, { href: "http://redis.io/topics/latency", desc: "Redis latency problems troubleshooting" }, { href: "http://redis.io/topics/latency-monitor", desc: "Redis latency monitoring framework" }, { href: "https://www.datadoghq.com/blog/how-to-collect-redis-metrics/", desc: "How to collect Redis metrics" }, { href: "https://www.datadoghq.com/wp-content/uploads/2013/09/Understanding-the-Top-5-Redis-Performance-Metrics.pdf", desc: "Understanding the Top 5 Redis Performance Metrics" }, { href: "http://www.iamtherealbill.com/2014/12/redis-performance-thoughts-2/", desc: "More Thoughts on Redis Performance" }, { href: "http://redis.io/topics/cluster-tutorial", desc: "Redis cluster tutorial" }, { href: "http://redis.io/topics/cluster-spec", desc: "Redis Cluster Specification" }, { href: "http://redis.io/commands", desc: "Redis Command Sheet" }, { href: "http://redis.io/presentation/Redis_Cluster.pdf", desc: "Redis Cluster - a pragmatic approach to distribution" }, { href: "https://github.com/luin/ioredis", desc: "A robust, performance-focused and full-featured Redis client for Node" }, { href: "https://github.com/luin/ioredis/wiki/Improve-Performance", desc: "ioredis - Improve Performance" }, { href: "https://github.com/thunks/thunk-redis", desc: "The fastest thunk/promise-based redis client, support all redis features" }, { href: "https://github.com/twitter/twemproxy", desc: "A fast, light-weight proxy for memcached and redis" }, { href: "http://engineering.bloomreach.com/the-evolution-of-fault-tolerant-redis-cluster/", desc: "The Evolution of Fault Tolerant Redis Cluster" }, { href: "http://www.iamtherealbill.com/2015/04/clusterizing-redis-intro/", desc: "A Primer on Clusterizing Redis" }, { href: "http://redis.io/topics/distlock", desc: "Distributed locks with Redis" }, { href: "http://redis.io/topics/notifications", desc: "Redis Keyspace Notifications" }, { href: "https://www.infoq.com/presentations/Real-Time-Delivery-Twitter", desc: "redis use-cases: Real-Time Delivery Architecture at Twitter" }, { href: "http://code.flickr.net/2011/10/11/talk-real-time-updates-on-the-cheap-for-fun-and-profit/", desc: "redis use-cases: Flickr - Real-time Updates on the Cheap for Fun and Profit" } ] }, node: { title: "Node.js (v6.2.2)", anchor: [ { href: "https://nodejs.org/en/", desc: "Node.js - a JavaScript runtime built on Chrome's V8 JavaScript engine" }, { href: "http://thisdavej.com/beginners-guide-to-installing-node-js-on-a-raspberry-pi/", desc: "Beginner’s Guide to Installing Node.js on a Raspberry Pi" }, { href: "http://blog.keithcirkel.co.uk/load-balancing-node-js/", desc: "Load balancing Node.js" }, { href: "https://www.npmjs.com/package/http2", desc: "An HTTP/2 client and server implementation" }, { href: "http://nodeschool.io/", desc: "NodeSchool.io - Node.js concepts via interactive command-line games" }, { href: "https://nodejs.org/static/documents/casestudies/Nodejs-at-Uber.pdf", desc: "How Uber Uses Node.js to Scale Their Business" }, { href: "https://www.youtube.com/watch?v=p74282nDMX8", desc: "Node.js at Netflix" }, { href: "https://www.youtube.com/watch?v=ElI5QtUISWM", desc: "Node.js at Uber" }, { href: "https://www.youtube.com/watch?v=-00ImeLt9ec", desc: "Node.js at PayPal" }, { href: "https://www.youtube.com/watch?v=BJPeLJhv1Ic", desc: "Node.js at CapitalOne" } ] }, ga: { title: "Google Analytics", anchor: [ { href: "https://analytics.google.com/", desc: "Google Analytics" } ] }, quic: { title: "Google QUIC", anchor: [ { href: "https://en.wikipedia.org/wiki/QUIC", desc: "QUIC (Quick UDP Internet Connections)" }, { href: "https://docs.google.com/document/d/1RNHkx_VvKWyWg6Lr8SZ-saqsQx7rFV-ev2jRFUoVD34/edit", desc: "QUIC: Design Document and Specification Rationale" }, { href: "https://docs.google.com/document/d/1lmL9EF6qKrk7gbazY8bIdvq3Pno2Xj_l_YShP40GLQE/edit", desc: "QUIC FAQ for Geeks" }, { href: "https://www.youtube.com/watch?v=hQZ-0mXFmk8", desc: "QUIC: next generation multiplexed transport over UDP" }, { href: "http://c3lab.poliba.it/images/3/3b/QUIC_SAC15.pdf", desc: "HTTP over UDP: an Experimental Investigation of QUIC" }, { href: "https://www.chromium.org/quic", desc: "QUIC, a multiplexed stream transport over UDP" }, { href: "http://blog.chromium.org/2015/04/a-quic-update-on-googles-experimental.html", desc: "A QUIC update on Google’s experimental transport" } ] }, open: { title: "Open Source architectures", anchor: [ { href: "http://www.aosabook.org/en/index.html", desc: "The Architecture of Open Source Applications" }, { href: "https://www.youtube.com/watch?v=jm75pxsb80c", desc: "Microservice Developer Experience" }, { href: "https://www.youtube.com/watch?v=SYNJFX0oIBU", desc: "Node.js for Enterprise APIs Panel Discussion" }, { href: "https://www.youtube.com/watch?v=D9TUU5bK0iE", desc: "Rebuilding the Ship as it Sails: Making Large Legacy Sites Responsive" }, { href: "https://strongloop.com/", desc: "Strongloop - Compose APIs, Build, Deploy and Monitor Node" } ] }, openssl: { title: "OpenSSL (v1.0.2h)", anchor: [ { href: "https://www.openssl.org/", desc: "OpenSSL - Cryptography and SSL/TLS Toolkit" } ] }, socket: { title: "Socket.io (v1.4.8)", anchor: [ { href: "http://socket.io/blog/", desc: "Socket.IO - THE FASTEST AND MOST RELIABLE REAL-TIME ENGINE" }, { href: "http://stackoverflow.com/questions/19496790/drop-packets-if-falling-behind-with-socket-io-in-node-js", desc: "How to handle dropping packets on volatile messages" }, { href: "http://blog.mixu.net/2011/11/22/performance-benchmarking-socket-io-0-8-7-0-7-11-and-0-6-17-and-nodes-native-tcp/", desc: "Performance benchmarking Socket.io 0.8.7, 0.7.11 and 0.6.17 and Node's native TCP" } ] } }; } AppSimulator.parameters = [ app.HTTPService ]; AppSimulator.annotations = [ new ng.core.Component({ selector: 'node-cluster-simulator', templateUrl: 'simulator.html', providers: [ app.HTTPService, ng.http.HTTP_PROVIDERS ], directives: [nvD3] }) ]; AppSimulator.prototype.setSmall = function() { if (this.isDuration) { this.reqDuration = 5; this.reqInterval = 50; this.reqConn = 4; } else { this.reqCount = 100; this.reqConn = 2; } ga('send', 'event', 'Simulation', 'Configuration', 'Small Preset'); }; AppSimulator.prototype.setMedium = function() { if (this.isDuration) { this.reqDuration = 10; this.reqInterval = 30; this.reqConn = 4; } else { this.reqCount = 512; this.reqConn = 16; } ga('send', 'event', 'Simulation', 'Configuration', 'Medium Preset'); }; AppSimulator.prototype.setLarge = function() { if (this.isDuration) { this.reqDuration = 30; this.reqInterval = 25; this.reqConn = 4; } else { this.reqCount = 1024; this.reqConn = 64; } ga('send', 'event', 'Simulation', 'Configuration', 'Large Preset'); }; AppSimulator.prototype.setHuge = function() { if (this.isDuration) { this.reqDuration = 60; this.reqInterval = 25; this.reqConn = 8; } else { this.reqCount = 2048; this.reqConn = 128; } ga('send', 'event', 'Simulation', 'Configuration', 'Huge Preset'); }; AppSimulator.prototype.setDuration = function() { this.isDuration = true; }; AppSimulator.prototype.setRequests = function() { this.isDuration = false; }; AppSimulator.prototype.isDurationMethod = function() { return this.isDuration; }; AppSimulator.prototype.isRequestMethod = function() { return !this.isDuration; }; AppSimulator.prototype.usedDurationMethod = function() { return this.execMode === 'STABILITY'; }; AppSimulator.prototype.usedRequestMethod = function() { return this.execMode === 'STRESS'; }; AppSimulator.prototype.getSimulationMethod = function() { return this.isDuration ? 'STABILITY' : 'STRESS'; }; AppSimulator.prototype.isRunning = function() { return this.running; }; AppSimulator.prototype.calculateHistogram = function() { this.barChartData = [{key: 'raspberrypi2-redis', values: []}, {key: 'raspberrypi3-redis', values: []}, {key: 'raspberrypi5-redis', values: []}, {key: 'raspberrypi6-redis', values: []}, {key: 'raspberrypi2-node', values: []}, {key: 'raspberrypi3-node', values: []}, {key: 'raspberrypi5-node', values: []}, {key: 'raspberrypi6-node', values: []}, {key: 'raspberrypi2-nginx', values: []}, {key: 'raspberrypi3-nginx', values: []}, {key: 'raspberrypi5-nginx', values: []}, {key: 'raspberrypi6-nginx', values: []}, {key: 'raspberrypi2-angular', values: []}, {key: 'raspberrypi3-angular', values: []}, {key: 'raspberrypi5-angular', values: []}, {key: 'raspberrypi6-angular', values: []}]; this.polarChartData = [{key: 'raspberrypi2', y: 0}, {key: 'raspberrypi3', y: 0}, {key: 'raspberrypi5', y: 0}, {key: 'raspberrypi6', y: 0}]; this.polarChartData2 = [{key: 'raspberrypi2', y: 0}, {key: 'raspberrypi3', y: 0}, {key: 'raspberrypi5', y: 0}, {key: 'raspberrypi6', y: 0}]; this.lineChartData = [ {key: 'w/o Coord. Omission', values: [], area: false}, {key: 'Latency/Percentile', values: [], area: true} ]; this.disregard = Math.ceil(this.reqExecuted * 4.55 / 100.0); this.discardLower = Math.floor(this.disregard/2); this.discardUpper = this.reqExecuted - Math.ceil(this.disregard / 2) - 1; // // Populate barchart as processed (no sorting) // for (var i = 0; i < this.requests[0].length; i++) { var rtt2 = this.requests[0][i].hst === 0 ? this.requests[0][i].rtt : 0; var rtt3 = this.requests[0][i].hst === 1 ? this.requests[0][i].rtt : 0; var rtt5 = this.requests[0][i].hst === 2 ? this.requests[0][i].rtt : 0; var rtt6 = this.requests[0][i].hst === 3 ? this.requests[0][i].rtt : 0; var tsn2 = this.requests[0][i].hst === 0 ? this.requests[0][i].tsn : 0; var tsn3 = this.requests[0][i].hst === 1 ? this.requests[0][i].tsn : 0; var tsn5 = this.requests[0][i].hst === 2 ? this.requests[0][i].tsn : 0; var tsn6 = this.requests[0][i].hst === 3 ? this.requests[0][i].tsn : 0; var exts2 = this.requests[0][i].hst === 0 ? this.requests[0][i].exts : 0; var exts3 = this.requests[0][i].hst === 1 ? this.requests[0][i].exts : 0; var exts5 = this.requests[0][i].hst === 2 ? this.requests[0][i].exts : 0; var exts6 = this.requests[0][i].hst === 3 ? this.requests[0][i].exts : 0; var red2 = this.requests[0][i].hst === 0 ? this.requests[0][i].red : 0; var red3 = this.requests[0][i].hst === 1 ? this.requests[0][i].red : 0; var red5 = this.requests[0][i].hst === 2 ? this.requests[0][i].red : 0; var red6 = this.requests[0][i].hst === 3 ? this.requests[0][i].red : 0; this.barChartData[0].values.push({label: this.requests[0][i].rid, value: Math.ceil(red2)}); this.barChartData[1].values.push({label: this.requests[0][i].rid, value: Math.ceil(red3)}); this.barChartData[2].values.push({label: this.requests[0][i].rid, value: Math.ceil(red5)}); this.barChartData[3].values.push({label: this.requests[0][i].rid, value: Math.ceil(red6)}); this.barChartData[4].values.push({label: this.requests[0][i].rid, value: Math.ceil(exts2 - red2)}); this.barChartData[5].values.push({label: this.requests[0][i].rid, value: Math.ceil(exts3 - red3)}); this.barChartData[6].values.push({label: this.requests[0][i].rid, value: Math.ceil(exts5 - red5)}); this.barChartData[7].values.push({label: this.requests[0][i].rid, value: Math.ceil(exts6 - red6)}); this.barChartData[8].values.push({label: this.requests[0][i].rid, value: Math.floor(tsn2 - exts2)}); this.barChartData[9].values.push({label: this.requests[0][i].rid, value: Math.floor(tsn3 - exts3)}); this.barChartData[10].values.push({label: this.requests[0][i].rid, value: Math.floor(tsn5 - exts5)}); this.barChartData[11].values.push({label: this.requests[0][i].rid, value: Math.floor(tsn6 - exts6)}); this.barChartData[12].values.push({label: this.requests[0][i].rid, value: rtt2 - tsn2}); this.barChartData[13].values.push({label: this.requests[0][i].rid, value: rtt3 - tsn3}); this.barChartData[14].values.push({label: this.requests[0][i].rid, value: rtt5 - tsn5}); this.barChartData[15].values.push({label: this.requests[0][i].rid, value: rtt6 - tsn6}); } // // HDR by RTT (AngularJS time) // var hdrRTTpost = {"arr": []}; for (var n = 0; n < this.requests[0].length; n++) { hdrRTTpost.arr.push(this.requests[0][n].rtt); } // // Sorting by RTT (AngularJS time) // this.totReqAng = [0,0,0,0]; this.requests[0].sort(function(a, b) {return a.rtt - b.rtt}); for (i = 0; i < this.requests[0].length; i++) { rtt2 = this.requests[0][i].hst === 0 ? this.requests[0][i].rtt : 0; rtt3 = this.requests[0][i].hst === 1 ? this.requests[0][i].rtt : 0; rtt5 = this.requests[0][i].hst === 2 ? this.requests[0][i].rtt : 0; rtt6 = this.requests[0][i].hst === 3 ? this.requests[0][i].rtt : 0; this.polarChartData2[0].y += ((i>=this.discardLower)&&(i<=this.discardUpper))?rtt2:0; this.polarChartData2[1].y += ((i>=this.discardLower)&&(i<=this.discardUpper))?rtt3:0; this.polarChartData2[2].y += ((i>=this.discardLower)&&(i<=this.discardUpper))?rtt5:0; this.polarChartData2[3].y += ((i>=this.discardLower)&&(i<=this.discardUpper))?rtt6:0; this.totReqAng[0] += ((this.requests[0][i].hst===0)&&(i>=this.discardLower)&&(i<=this.discardUpper))?1:0; this.totReqAng[1] += ((this.requests[0][i].hst===1)&&(i>=this.discardLower)&&(i<=this.discardUpper))?1:0; this.totReqAng[2] += ((this.requests[0][i].hst===2)&&(i>=this.discardLower)&&(i<=this.discardUpper))?1:0; this.totReqAng[3] += ((this.requests[0][i].hst===3)&&(i>=this.discardLower)&&(i<=this.discardUpper))?1:0; this.totAngular += ((i>=this.discardLower)&&(i<=this.discardUpper))?this.requests[0][i].rtt:0; } this.polarChartData2[0].y = this.polarChartData2[0].y / this.totReqAng[0]; this.polarChartData2[1].y = this.polarChartData2[1].y / this.totReqAng[1]; this.polarChartData2[2].y = this.polarChartData2[2].y / this.totReqAng[2]; this.polarChartData2[3].y = this.polarChartData2[3].y / this.totReqAng[3]; this.tpAngular = Math.ceil(this.reqExecuted / (this.duration / 1000)); for (i = 0; i < this.histogram.length; i++) { this.histogram[i][1] = this.requests[0][Math.ceil(this.reqExecuted * this.histogram[i][0] / 100) - 1].rtt; } // // Sorting by TSN (nginX time) // this.totReqNgi = [0,0,0,0]; this.requests[0].sort(function(a, b) {return a.tsn - b.tsn}); for (i = 0; i < this.histogram.length; i++) { this.histogram[i][2] = this.requests[0][Math.ceil(this.reqExecuted * this.histogram[i][0] / 100) - 1].tsn; } for (i = 0; i < this.requests[0].length; i++) { tsn2 = this.requests[0][i].hst === 0 ? this.requests[0][i].tsn : 0; tsn3 = this.requests[0][i].hst === 1 ? this.requests[0][i].tsn : 0; tsn5 = this.requests[0][i].hst === 2 ? this.requests[0][i].tsn : 0; tsn6 = this.requests[0][i].hst === 3 ? this.requests[0][i].tsn : 0; this.polarChartData[0].y += ((i>=this.discardLower)&&(i<=this.discardUpper))?tsn2:0; this.polarChartData[1].y += ((i>=this.discardLower)&&(i<=this.discardUpper))?tsn3:0; this.polarChartData[2].y += ((i>=this.discardLower)&&(i<=this.discardUpper))?tsn5:0; this.polarChartData[3].y += ((i>=this.discardLower)&&(i<=this.discardUpper))?tsn6:0; this.totReqNgi[0] += ((this.requests[0][i].hst===0)&&(i>=this.discardLower)&&(i<=this.discardUpper))?1:0; this.totReqNgi[1] += ((this.requests[0][i].hst===1)&&(i>=this.discardLower)&&(i<=this.discardUpper))?1:0; this.totReqNgi[2] += ((this.requests[0][i].hst===2)&&(i>=this.discardLower)&&(i<=this.discardUpper))?1:0; this.totReqNgi[3] += ((this.requests[0][i].hst===3)&&(i>=this.discardLower)&&(i<=this.discardUpper))?1:0; this.totNginx += ((i>=this.discardLower)&&(i<=this.discardUpper))?this.requests[0][i].tsn:0; } this.polarChartData[0].y = this.polarChartData[0].y / this.totReqNgi[0]; this.polarChartData[1].y = this.polarChartData[1].y / this.totReqNgi[1]; this.polarChartData[2].y = this.polarChartData[2].y / this.totReqNgi[2]; this.polarChartData[3].y = this.polarChartData[3].y / this.totReqNgi[3]; this.tpNginx = Math.ceil(this.tpAngular * this.totAngular / this.totNginx); // // Sort by EXTS (nodeJS time) // this.requests[0].sort(function(a, b) {return a.exts - b.exts}); for (i = 0; i < this.histogram.length; i++) { this.histogram[i][3] = this.requests[0][Math.ceil(this.reqExecuted * this.histogram[i][0] / 100) - 1].exts; } for (i = 0; i < this.requests[0].length; i++) { this.totNode += ((i>=this.discardLower)&&(i<=this.discardUpper))?this.requests[0][i].exts:0; } this.tpNode = Math.ceil(this.tpNginx * this.totNginx / this.totNode); // // Sort by RED (redis.io time) // this.requests[0].sort(function(a, b) {return a.red - b.red}); for (i = 0; i < this.histogram.length; i++) { this.histogram[i][4] = this.requests[0][Math.ceil(this.reqExecuted * this.histogram[i][0] / 100) - 1].red; } for (i = 0; i < this.requests[0].length; i++) { this.totRedis += ((i >= this.discardLower) && (i <= this.discardUpper)) ? this.requests[0][i].red : 0; } this.tpRedis = Math.ceil(this.tpNode * this.totNode / this.totRedis); // // Calculating HDR Histogram // this.hdrRTTresults = {table: [], chart: []}; this.lineChartData[0].values = []; this.lineChartData[1].values = []; var selfRTT = this; this.observableRTT = this.httpService.post(this.urlHDR, JSON.stringify(hdrRTTpost)).subscribe( function(response) { selfRTT.hdrRTTresults = response; selfRTT.requests[0].sort(function(a, b) {return a.rtt - b.rtt}); for (var n = 0; n < selfRTT.hdrRTTresults.chart.length; n++) { var idx = ((selfRTT.hdrRTTresults.chart[n].percentile * selfRTT.reqOK / 100) | 0) - 1; selfRTT.lineChartData[0].values.push({ x: selfRTT.hdrRTTresults.chart[n].percentile, y: selfRTT.hdrRTTresults.chart[n].value }); selfRTT.lineChartData[1].values.push({ x: selfRTT.hdrRTTresults.chart[n].percentile, y: selfRTT.requests[0][(idx < 0) ? 0 : idx].rtt }); } }, function(error) { console.log("HDR Service error"); }, function() { selfRTT.observableRTT.unsubscribe(); selfRTT.observableRTT = undefined; selfRTT.calculating = false; selfRTT.running = false; selfRTT.liveEvents = false; } ); ga('send', 'event', 'Simulation', 'Execution', 'Throughput', this.tpAngular); }; AppSimulator.prototype.onRefLink = function(title, desc) { ga('send', 'event', 'Reference', title, desc); }; AppSimulator.prototype.percValue = function() { return Math.ceil(this.reqOK * 100 / this.reqCount); }; AppSimulator.prototype.calcPosition = function(hist) { return Math.ceil(this.reqOK * hist / 100); }; AppSimulator.prototype.getDurationRequests = function() { var tot = (this.reqDuration * 1000 * this.reqConn / this.reqInterval) | 0; return tot - (tot % this.reqConn); }; AppSimulator.prototype.getDurationThroughput = function() { return (this.getDurationRequests() / this.reqDuration) | 0; }; AppSimulator.prototype.checkStop = function() { this.duration = Date.now() - this.iniTime; if (this.reqOK + this.reqErrors >= this.reqCount) { this.calculating = true; this.reqExecuted = this.reqCount; var selfStop = this; setTimeout(function(){ selfStop.calculateHistogram(); }, 500); return true; } return false; }; AppSimulator.prototype.throwHTTPrequests = function(i) { var self = this; var arrReq = []; for (var j = 0; ((j < this.reqConn) && (i + j < this.reqCount)); j++) { arrReq.push(this.requests[1][i + j]); } self.observableRequests = Rx.Observable.forkJoin(arrReq).subscribe( function(response) { for (var k = 0; k < response.length; k++) { self.requests[0][response[k].reqId] = { rid: 'Request ' + ((response[k].reqId | 0) + 1), hst: self.nodeIdx[response[k].json.hostname][0], rtt: response[k].rtt, tsn: response[k].tsn, exts: response[k].exts, red: response[k].red }; if (!(response[k].json.pid in self.pidIdx[response[k].json.hostname])) { self.results[self.nodeIdx[response[k].json.hostname][0]][1].push([response[k].json.pid, []]); self.pidIdx[response[k].json.hostname][response[k].json.pid] = self.results[self.nodeIdx[response[k].json.hostname][0]][1].length - 1; } self.results[self.nodeIdx[response[k].json.hostname][0]][1][self.pidIdx[response[k].json.hostname][response[k].json.pid]][1].push(++self.reqOK); self.nodeIdx[response[k].json.hostname][1]++; } }, function(error) { self.reqErrors++; }, function() { self.observableRequests.unsubscribe(); self.observableRequests = undefined; if (!self.checkStop()) { self.loopCon += self.reqConn; self.throwHTTPrequests(self.loopCon); } } ); }; AppSimulator.prototype.throwHTTPduration = function() { var self = this, reqId = 0; self.countRequests = 0; self.countResponses = 0; self.timerRunning = true; var intervalFunction = function() { if (self.timerRunning && self.countRequests < self.reqCount) { self.countRequests += self.reqConn; var arrReq = []; for (var j = 0; j < self.reqConn; j++) { self.requests[0].push({rtt: 0, hst: '', rid: 0, tsn: 0, exts: 0, red: 0}); self.requests[1].push(self.httpService.get(reqId, self.selectedUrl)); arrReq.push(self.requests[1][reqId]); reqId++; } var observableRequestsA = Rx.Observable.forkJoin(arrReq).subscribe( function(response) { self.duration = Date.now() - self.iniTime; if (self.countResponses < self.reqCount) { for (var k = 0; k < response.length; k++) { self.requests[0][response[k].reqId] = { rid: 'Request ' + ((response[k].reqId | 0) + 1), hst: self.nodeIdx[response[k].json.hostname][0], rtt: response[k].rtt, tsn: response[k].tsn, exts: response[k].exts, red: response[k].red }; if (!(response[k].json.pid in self.pidIdx[response[k].json.hostname])) { self.results[self.nodeIdx[response[k].json.hostname][0]][1].push([response[k].json.pid, []]); self.pidIdx[response[k].json.hostname][response[k].json.pid] = self.results[self.nodeIdx[response[k].json.hostname][0]][1].length - 1; } self.results[self.nodeIdx[response[k].json.hostname][0]][1][self.pidIdx[response[k].json.hostname][response[k].json.pid]][1].push(++self.reqOK); self.nodeIdx[response[k].json.hostname][1]++; self.countResponses++; } } else { if (self.countResponses > self.reqCount) { for (var z = 0; z < self.reqConn; z++) { self.requests[0].pop(); self.requests[1].pop(); self.countResponses--; } } } }, function(error) { self.duration = Date.now() - self.iniTime; if (self.countResponses < self.reqCount) { self.reqErrors++; self.countResponses++; } else { if (self.countResponses > self.reqCount) { for (var z = 0; z < self.reqConn; z++) { self.requests[0].pop(); self.requests[1].pop(); self.countResponses--; } } } }, function() { if (!self.timerRunning && !self.calculating && self.countRequests === self.countResponses) { if (self.intervalHandler) { clearInterval(self.intervalHandler); } self.calculating = true; var selfStop = self; self.reqExecuted = self.countResponses; setTimeout(function() { selfStop.calculateHistogram(); }, 500); } observableRequestsA.unsubscribe(); observableRequestsA = undefined; } ); } else { if (!self.calculating && self.countRequests === self.countResponses) { if (self.intervalHandler) { clearInterval(self.intervalHandler); } self.calculating = true; var selfStop = self; self.reqExecuted = self.countResponses; setTimeout(function() { selfStop.calculateHistogram(); }, 500); } } }; self.iniTime = Date.now(); setTimeout(function() { self.timerRunning = false; }, self.reqDuration * 1000 + 10); intervalFunction(); self.intervalHandler = setInterval(intervalFunction, self.reqInterval); }; AppSimulator.prototype.getDatabaseStatus = function(cond) { switch (cond) { case 0: return 'text-info'; case 2: return 'text-primary'; case 1: return 'text-muted'; case 3: return 'text-danger bg-danger'; } }; AppSimulator.prototype.showRef = function() { this.showReference = !this.showReference; if (this.showReference) { this.liveEvents = false; } }; AppSimulator.prototype.showLive = function() { this.liveEvents = !this.liveEvents; if (this.liveEvents) { this.showReference = false; } }; AppSimulator.prototype.mapDBmatrix = function(x, y) { return ((((x * 32) + y) * 16 / 2731) | 0); }; AppSimulator.prototype.initEVMatrix = function() { this.evMatrix = []; for (var i = 0; i < 16; i++) { this.evMatrix.push([]); for (var j = 0; j < 32; j++) { this.evMatrix[i].push(this.mapDBmatrix(i, j)); } } }; AppSimulator.prototype.initSimulator = function() { this.liveEvents = true; this.showReference = false; this.reqOK = 0; this.reqErrors = 0; this.duration = 0; this.loopCon = 0; this.histogram = [[50, 0, 0, 0, 0], [75, 0, 0, 0, 0], [87.5, 0, 0, 0, 0], [93.75, 0, 0, 0, 0], [96.875, 0, 0, 0, 0], [98.4375, 0, 0, 0, 0], [99.21875, 0, 0, 0, 0], [100, 0, 0, 0, 0]]; this.requests = [[], []]; this.results = [["raspberrypi2", []], ["raspberrypi3", []], ["raspberrypi5", []], ["raspberrypi6", []]]; this.nodeIdx = { "raspberrypi2": [0, 0], "raspberrypi3": [1, 0], "raspberrypi5": [2, 0], "raspberrypi6": [3, 0] }; this.pidIdx = { "raspberrypi2": {}, "raspberrypi3": {}, "raspberrypi5": {}, "raspberrypi6": {} }; this.totAngular = 0; this.totNginx = 0; this.totNode = 0; this.totRedis = 0; this.tpAngular = 0; this.tpNginx = 0; this.tpNode = 0; this.tpRedis = 0; this.observableRequests = undefined; this.execMode = this.getSimulationMethod(); this.execReq = this.reqCount; this.execDuration = this.reqDuration; this.execInterval = this.reqInterval; this.execConn = this.reqConn; this.execMaxReq = this.getDurationRequests(); this.initEVMatrix(); this.running = true; if (this.isDuration) { this.reqCount = this.getDurationRequests(); this.throwHTTPduration(); } else { for (var reqId = 0; reqId < this.reqCount; reqId++) { this.requests[0].push({rtt: 0, hst: '', rid: 0, tsn: 0, exts: 0, red: 0}); this.requests[1].push(this.httpService.get(reqId, this.selectedUrl)); } this.iniTime = Date.now(); this.throwHTTPrequests(this.loopCon); } }; return AppSimulator; })(); })(window.app || (window.app = {}));
Introduced RPi7 and RPi8 - decomissioned Redis on RPi0 and RPI1 - changed ports and deployment for Redis PUBUB
app.simulator.js
Introduced RPi7 and RPi8 - decomissioned Redis on RPi0 and RPI1 - changed ports and deployment for Redis PUBUB
<ide><path>pp.simulator.js <ide> this.urlHDR = 'https://giancarlobonansea.homeip.net:33333/hdr'; <ide> this.selectedUrl = this.urlOptions[0][0]; <ide> this.initEVMatrix(); <del> this.socket = io('https://giancarlobonansea.homeip.net:32402'); <add> this.socket = io('https://giancarlobonansea.homeip.net:33331'); <ide> this.liveTTL = 500; <ide> var selfMtx = this; <ide> // Receive redis.io realtime info <ide> ] <ide> }, <ide> stunnel: { <del> title: "stunnel (v5.32)", anchor: [ <add> title: "stunnel (v5.33)", anchor: [ <ide> {href: "https://www.stunnel.org/index.html", <ide> desc: "Stunnel - a proxy designed to add TLS encryption functionality to existing clients and servers" <ide> }, <ide> { <ide> href: "http://code.flickr.net/2011/10/11/talk-real-time-updates-on-the-cheap-for-fun-and-profit/", <ide> desc: "redis use-cases: Flickr - Real-time Updates on the Cheap for Fun and Profit" <add> }, <add> { <add> href: "http://shokunin.co/blog/2014/11/11/operational_redis.html", <add> desc: "Running Redis in production - network and CPU balancing" <add> }, <add> { <add> href: "https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/Performance_Tuning_Guide/network-rps.html", <add> desc: "RPS - Receive Packet Steering for network performance" <ide> } <ide> ] <ide> }, <ide> ] <ide> }, <ide> socket: { <del> title: "Socket.io (v1.4.8)", <add> title: "Socket.IO (v1.4.8)", <ide> anchor: [ <ide> { <ide> href: "http://socket.io/blog/",
JavaScript
mit
3dba7a297fd441c155e214b0327ba96288e8a556
0
JacobFischer/Cerveau,siggame/Cerveau,siggame/Cerveau,JacobFischer/Cerveau
// Unit: A unit group in the game. This may consist of a ship and any number of crew. const Class = require("classe"); const log = require(`${__basedir}/gameplay/log`); const GameObject = require("./gameObject"); //<<-- Creer-Merge: requires -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // any additional requires you want can be required here safely between Creer re-runs //<<-- /Creer-Merge: requires -->> // @class Unit: A unit group in the game. This may consist of a ship and any number of crew. let Unit = Class(GameObject, { /** * Initializes Units. * * @param {Object} data - a simple mapping passed in to the constructor with whatever you sent with it. GameSettings are in here by key/value as well. */ init: function(data) { GameObject.init.apply(this, arguments); /** * Whether this Unit has performed its action this turn. * * @type {boolean} */ this.acted = this.acted || false; /** * How many crew are on this Tile. This number will always be <= crewHealth. * * @type {number} */ this.crew = this.crew || 0; /** * How much total health the crew on this Tile have. * * @type {number} */ this.crewHealth = this.crewHealth || 0; /** * How much gold this Unit is carrying. * * @type {number} */ this.gold = this.gold || 0; /** * How many more times this Unit may move this turn. * * @type {number} */ this.moves = this.moves || 0; /** * The Player that owns and can control this Unit, or null if the Unit is neutral. * * @type {Player} */ this.owner = this.owner || null; /** * (Merchants only) The path this Unit will follow. The first element is the Tile this Unit will move to next. * * @type {Array.<Tile>} */ this.path = this.path || []; /** * If a ship is on this Tile, how much health it has remaining. 0 for no ship. * * @type {number} */ this.shipHealth = this.shipHealth || 0; /** * (Merchants only) The number of turns this merchant ship won't be able to move. They will still attack. Merchant ships are stunned when they're attacked. * * @type {number} */ this.stunTurns = this.stunTurns || 0; /** * (Merchants only) The Port this Unit is moving to. * * @type {Port} */ this.targetPort = this.targetPort || null; /** * The Tile this Unit is on. * * @type {Tile} */ this.tile = this.tile || null; //<<-- Creer-Merge: init -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. this.acted = data.acted || true; this.crew = data.crew || 0; this.crewHealth = data.crewHealth || this.crew * this.game.crewHealth; this.gold = data.gold || 0; this.moves = data.moves || 0; this.owner = data.owner || null; this.path = data.path || []; this.shipHealth = data.shipHealth || 0; this.targetPort = data.targetPort || null; this.tile = data.tile || null; this.stunTurns = data.stunTurns || 0; //<<-- /Creer-Merge: init -->> }, gameObjectName: "Unit", /** * Invalidation function for attack * Try to find a reason why the passed in parameters are invalid, and return a human readable string telling them why it is invalid * * @param {Player} player - the player that called this. * @param {Tile} tile - The Tile to attack. * @param {string} target - Whether to attack 'crew' or 'ship'. Crew deal damage to crew and ships deal damage to ships. Consumes any remaining moves. * @param {Object} args - a key value table of keys to the arg (passed into this function) * @returns {string|undefined} a string that is the invalid reason, if the arguments are invalid. Otherwise undefined (nothing) if the inputs are valid. */ invalidateAttack: function(player, tile, target, args) { // <<-- Creer-Merge: invalidateAttack -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. const reason = this._invalidate(player, true); if(reason) { return reason; } if(!tile) { return `${this} needs to know which tile to attack!`; } let t = target.charAt(0).toUpperCase(); if(t === "C") { if(!tile.unit) { return `There be nothin' for ${this} to attack on ${tile}!`; } if(tile.unit.player === player) { return `${this} doesn't have time for a mutany! Don't be attackin' yer own men!`; } if(tile.unit.crew <= 0) { return `${tile} has got no crew for you to attack!`; } let dx = this.tile.x - tile.x; let dy = this.tile.y - tile.y; let distSq = dx * dx + dy * dy; if(distSq > this.game.crewRange * this.game.crewRange) { return `${this} isn't in range for that attack. Yer swords don't reach off yonder!`; } } else if(t === "S") { if(!tile.unit) { return `There be nothin' for ${this} to attack on ${tile}!`; } if(tile.unit.shipHealth <= 0) { return `There be no ship for ${this} to attack.`; } if(this.shipHealth <= 0) { return `${this} has no ship to perform the attack.`; } if(tile.unit.player === player) { return `${this} doesn't have time for a mutany! Don't be attackin' yer own ship!`; } let dx = this.tile.x - tile.x; let dy = this.tile.y - tile.y; let distSq = dx * dx + dy * dy; if(distSq > this.game.shipRange * this.game.shipRange) { return `${this} isn't in range for that attack. Ye don't wanna fire blindly into the wind!`; } } else { return `${this} needs to attack somethin' valid ('ship' or 'crew'), not '${target}'.`; } // Developer: try to invalidate the game logic for Unit's attack function here return undefined; // meaning valid // <<-- /Creer-Merge: invalidateAttack -->> }, /** * Attacks either the 'crew' or 'ship' on a Tile in range. * * @param {Player} player - the player that called this. * @param {Tile} tile - The Tile to attack. * @param {string} target - Whether to attack 'crew' or 'ship'. Crew deal damage to crew and ships deal damage to ships. Consumes any remaining moves. * @returns {boolean} True if successfully attacked, false otherwise. */ attack: function(player, tile, target) { // <<-- Creer-Merge: attack -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. target = target.charAt(0).toUpperCase(); let deadCrew = 0; let deadShips = 0; let gold = 0; let merchant = tile.unit.targetPort !== null; let neutral = !merchant && !tile.owner; if(target === "C") { // Crew attacking crew tile.unit.crewHealth -= this.game.crewDamage * this.crew; tile.unit.crewHealth = Math.max(0, tile.unit.crewHealth); // For counting the dead accurately if(tile.unit.crew > tile.unit.crewHealth) { deadCrew = tile.unit.crew - tile.unit.crewHealth; tile.unit.crew = tile.unit.crewHealth; } // Check if the crew was completely destroyed if(tile.unit.crewHealth <= 0) { if(tile.unit.shipHealth <= 0) { gold += tile.unit.gold; // Mark it as dead tile.unit.tile = null; tile.unit = null; } else { tile.unit.owner = null; tile.unit.shipHealth = 1; // Make sure it's not a merchant ship anymore either tile.unit.targetPort = null; tile.unit.path = []; } } } else { // Ship attacking ship tile.unit.shipHealth -= this.game.shipDamage; tile.unit.shipHealth = Math.max(0, tile.unit.shipHealth); // Check if ship was destroyed if(tile.unit.shipHealth <= 0) { deadShips += 1; gold += tile.unit.gold; // Mark it as dead tile.unit.tile = null; tile.unit = null; } } // Infamy this.acted = true; this.gold += gold; // Calculate the infamy factor let factor = 1; if(!merchant) { // Calculate each player's net worth let allyWorth = player.netWorth() + player.gold - gold; let opponentWorth = player.opponent.netWorth() + player.opponent.gold + gold; opponentWorth += deadCrew * this.game.crewCost + deadShips * this.game.shipCost; if(allyWorth > opponentWorth) { factor = 0.5; } else if(allyWorth < opponentWorth) { factor = 2; } } // Calculate infamy let infamy = deadCrew * this.game.crewCost + deadShips * this.game.shipCost; infamy *= factor; if(!neutral) { if(!merchant) { infamy = Math.min(infamy, player.opponent.infamy); player.opponent.infamy -= infamy; } player.infamy += infamy; } if(merchant && tile.unit) { tile.unit.stunTurns = 2; } return true; // <<-- /Creer-Merge: attack -->> }, /** * Invalidation function for bury * Try to find a reason why the passed in parameters are invalid, and return a human readable string telling them why it is invalid * * @param {Player} player - the player that called this. * @param {number} amount - How much gold this Unit should bury. Amounts <= 0 will bury as much as possible. * @param {Object} args - a key value table of keys to the arg (passed into this function) * @returns {string|undefined} a string that is the invalid reason, if the arguments are invalid. Otherwise undefined (nothing) if the inputs are valid. */ invalidateBury: function(player, amount, args) { // <<-- Creer-Merge: invalidateBury -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. const reason = this._invalidate(player, false); if(reason) { return reason; } if(this.tile.type !== "land") { return `${this} can't bury gold on the sea.`; } if(this.tile.port) { return `${this} can't bury gold in ports.`; } let dx = this.tile.x - player.port.tile.x; let dy = this.tile.y - player.port.tile.y; let distSq = dx * dx + dy * dy; if(distSq < this.game.minInterestDistance * this.game.minInterestDistance) { return `${this} is too close to home! Ye gotta bury yer loot far away from yer port.`; } return undefined; // meaning valid // <<-- /Creer-Merge: invalidateBury -->> }, /** * Buries gold on this Unit's Tile. Gold must be a certain distance away for it to get interest (Game.minInterestDistance). * * @param {Player} player - the player that called this. * @param {number} amount - How much gold this Unit should bury. Amounts <= 0 will bury as much as possible. * @returns {boolean} True if successfully buried, false otherwise. */ bury: function(player, amount) { // <<-- Creer-Merge: bury -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. if(amount <= 0) { amount = this.gold; } else { amount = Math.min(this.gold, amount); } this.tile.gold += amount; this.gold -= amount; return true; // <<-- /Creer-Merge: bury -->> }, /** * Invalidation function for deposit * Try to find a reason why the passed in parameters are invalid, and return a human readable string telling them why it is invalid * * @param {Player} player - the player that called this. * @param {number} amount - The amount of gold to deposit. Amounts <= 0 will deposit all the gold on this Unit. * @param {Object} args - a key value table of keys to the arg (passed into this function) * @returns {string|undefined} a string that is the invalid reason, if the arguments are invalid. Otherwise undefined (nothing) if the inputs are valid. */ invalidateDeposit: function(player, amount, args) { // <<-- Creer-Merge: invalidateDeposit -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. const reason = this._invalidate(player, false); if(reason) { return reason; } let neighbors = [this.tile, this.tile.tileNorth, this.tile.tileEast, this.tile.tileSouth, this.tile.tileWest]; let found = neighbors.find(t => t && t.port && t.port.owner !== player.opponent); if(!found) { return `Arr, ${this} has to deposit yer booty in yer home port or a merchant port, matey!`; } if(this.gold <= 0) { return `Shiver me timbers! ${this} doesn't have any booty to deposit!`; } return undefined; // meaning valid // <<-- /Creer-Merge: invalidateDeposit -->> }, /** * Puts gold into an adjacent Port. If that Port is the Player's port, the gold is added to that Player. If that Port is owned by merchants, it adds to that Port's investment. * * @param {Player} player - the player that called this. * @param {number} amount - The amount of gold to deposit. Amounts <= 0 will deposit all the gold on this Unit. * @returns {boolean} True if successfully deposited, false otherwise. */ deposit: function(player, amount) { // <<-- Creer-Merge: deposit -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // Adjust amount amount = Math.min(Math.max(amount, 0), this.gold); if(amount <= 0) { amount = this.gold; } this.gold -= amount; // Check for this player's port let neighbors = [this.tile, this.tile.tileNorth, this.tile.tileEast, this.tile.tileSouth, this.tile.tileWest]; let tile = neighbors.find(t => t && t.port && t.port.owner === player, this); if(tile) { player.gold += amount; } else { // Get the merchant's port tile = neighbors.find(t => t && t.port && !t.port.owner, this); tile.port.investment += amount; } return true; // <<-- /Creer-Merge: deposit -->> }, /** * Invalidation function for dig * Try to find a reason why the passed in parameters are invalid, and return a human readable string telling them why it is invalid * * @param {Player} player - the player that called this. * @param {number} amount - How much gold this Unit should take. Amounts <= 0 will dig up as much as possible. * @param {Object} args - a key value table of keys to the arg (passed into this function) * @returns {string|undefined} a string that is the invalid reason, if the arguments are invalid. Otherwise undefined (nothing) if the inputs are valid. */ invalidateDig: function(player, amount, args) { // <<-- Creer-Merge: invalidateDig -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. const reason = this._invalidate(player, false); if(reason) { return reason; } // Checking to see if the tile is anything other than a land type. if(this.tile.type !== "land") { return `${this} can't dig in the sea!`; } // Checking to see if the tile has gold to be dug up. if(this.tile.gold === 0) { return `There be no booty for ${this} to plunder.`; } return undefined; // meaning valid // <<-- /Creer-Merge: invalidateDig -->> }, /** * Digs up gold on this Unit's Tile. * * @param {Player} player - the player that called this. * @param {number} amount - How much gold this Unit should take. Amounts <= 0 will dig up as much as possible. * @returns {boolean} True if successfully dug up, false otherwise. */ dig: function(player, amount) { // <<-- Creer-Merge: dig -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // If the amount requested is <= 0 or greater than what is current give all. if(amount <= 0 || amount > this.tile.gold) { // Adds the amount of gold from the current tile to the Unit. this.gold += this.tile.gold; // Sets the gold on tile to 0. this.tile.gold = 0; return true; } // Else if amount is less than what is there take that amount. else { // Adds amount requested to Unit. this.gold += amount; // Subtracts amount from Tile's gold this.tile.gold -= amount; return true; } // <<-- /Creer-Merge: dig -->> }, /** * Invalidation function for move * Try to find a reason why the passed in parameters are invalid, and return a human readable string telling them why it is invalid * * @param {Player} player - the player that called this. * @param {Tile} tile - The Tile this Unit should move to. * @param {Object} args - a key value table of keys to the arg (passed into this function) * @returns {string|undefined} a string that is the invalid reason, if the arguments are invalid. Otherwise undefined (nothing) if the inputs are valid. */ invalidateMove: function(player, tile, args) { // <<-- Creer-Merge: invalidateMove -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. const reason = this._invalidate(player, false); if(reason) { return reason; } const ship = this.shipHealth > 0; if(this.moves <= 0) { return `${this}'s crew are too tired to travel any further.`; } if(this.acted) { return `${this} can't move after acting. The men are too tired!`; } if(!tile) { return `${this} must have a destination to move to.`; } if(this.tile.tileEast !== tile && this.tile.tileNorth !== tile && this.tile.tileWest !== tile && this.tile.tileSouth !== tile) { return `${tile} be too far for ${this} to move to.`; } if(tile.unit && tile.unit.owner !== player && tile.unit.owner !== null) { return `${this} refuses to share the same ground with a living foe.`; } if(!ship && tile.type === "water" && !tile.port) { return `${this} has no ship and can't walk on water!`; } if(ship && tile.type === "land") { return `Land ho! ${this} belongs in the sea! Use 'Unit.split' if ye want to move just yer crew ashore.`; } if(ship && tile.shipHealth > 0) { return `There be a ship there. If ye move ${this} to ${tile}, ye'll scuttle yer ship!`; } if(!ship && tile.ship && this.acted) { return `${this} already acted, and it be too tired to board that ship.`; } if(tile.port && tile.port.owner !== player) { return `${this} can't enter an enemy port!`; } return undefined; // meaning valid // <<-- /Creer-Merge: invalidateMove -->> }, /** * Moves this Unit from its current Tile to an adjacent Tile. If this Unit merges with another one, the other Unit will be destroyed and its tile will be set to null. Make sure to check that your Unit's tile is not null before doing things with it. * * @param {Player} player - the player that called this. * @param {Tile} tile - The Tile this Unit should move to. * @returns {boolean} True if it moved, false otherwise. */ move: function(player, tile) { // <<-- Creer-Merge: move -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. if(tile.unit) { this.moves--; this.mergeOnto(tile.unit); } else { // Move this unit to that tile this.tile.unit = null; this.tile = tile; tile.unit = this; this.moves -= 1; } return true; // <<-- /Creer-Merge: move -->> }, /** * Invalidation function for rest * Try to find a reason why the passed in parameters are invalid, and return a human readable string telling them why it is invalid * * @param {Player} player - the player that called this. * @param {Object} args - a key value table of keys to the arg (passed into this function) * @returns {string|undefined} a string that is the invalid reason, if the arguments are invalid. Otherwise undefined (nothing) if the inputs are valid. */ invalidateRest: function(player, args) { // <<-- Creer-Merge: invalidateRest -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. const reason = this._invalidate(player, true); if(reason) { return reason; } // Check if it's in range const radius = this.game.restRange; if(Math.pow(this.tile.x - player.port.tile.x, 2) + Math.pow(this.tile.y - player.port.tile.y, 2) > radius * radius) { return `${this} has no nearby port to rest at. No home tavern means no free rum!`; } return undefined; // meaning valid // <<-- /Creer-Merge: invalidateRest -->> }, /** * Regenerates this Unit's health. Must be used in range of a port. * * @param {Player} player - the player that called this. * @returns {boolean} True if successfully rested, false otherwise. */ rest: function(player) { // <<-- Creer-Merge: rest -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // Heal the units this.crewHealth += Math.ceil(this.game.crewHealth * this.game.healFactor) * this.crew; this.crewHealth = Math.min(this.crewHealth, this.crew * this.game.crewHealth); if(this.shipHealth > 0) { this.shipHealth += Math.ceil(this.game.shipHealth * this.game.healFactor); this.shipHealth = Math.min(this.shipHealth, this.game.shipHealth); } // Make sure the unit can't do anything else this turn this.acted = true; this.moves = 0; return true; // <<-- /Creer-Merge: rest -->> }, /** * Invalidation function for split * Try to find a reason why the passed in parameters are invalid, and return a human readable string telling them why it is invalid * * @param {Player} player - the player that called this. * @param {Tile} tile - The Tile to move the crew to. * @param {number} amount - The number of crew to move onto that Tile. Amount <= 0 will move all the crew to that Tile. * @param {number} gold - The amount of gold the crew should take with them. Gold < 0 will move all the gold to that Tile. * @param {Object} args - a key value table of keys to the arg (passed into this function) * @returns {string|undefined} a string that is the invalid reason, if the arguments are invalid. Otherwise undefined (nothing) if the inputs are valid. */ invalidateSplit: function(player, tile, amount, gold, args) { // <<-- Creer-Merge: invalidateSplit -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. const reason = this._invalidate(player, false); if(reason) { return reason; } if(!tile) { return `${this} can't split onto null!`; } // Check to see if the crew has a move to move if(this.moves <= 0) { return `${this} can't split cause they be out of moves.`; } // Check to see if they have already acted. if(this.acted) { return `${this} crew are too tired to split!`; } // Check to see if it is not one of the tiles around in the current direction if(this.tile.tileEast !== tile && this.tile.tileNorth !== tile && this.tile.tileWest !== tile && this.tile.tileSouth !== tile) { return `${tile} be too far for ${this} to split to.`; } // Check to make sure target tile is a valid tile if(tile.type !== "land" && tile.unit.shipHealth <= 0 && tile.port === null) { return `${this} can't split here!`; } return undefined; // meaning valid // <<-- /Creer-Merge: invalidateSplit -->> }, /** * Moves a number of crew from this Unit to the given Tile. This will consume a move from those crew. * * @param {Player} player - the player that called this. * @param {Tile} tile - The Tile to move the crew to. * @param {number} amount - The number of crew to move onto that Tile. Amount <= 0 will move all the crew to that Tile. * @param {number} gold - The amount of gold the crew should take with them. Gold < 0 will move all the gold to that Tile. * @returns {boolean} True if successfully split, false otherwise. */ split: function(player, tile, amount, gold) { // <<-- Creer-Merge: split -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // Create a new unit let newUnit = this.game.create("Unit", { owner: player, tile: tile, }); // Check if boarding a ship if(tile.type === "water" && tile.unit.shipHealth > 0) { newUnit.acted = true; } // Adjust the amount of crew to split if(amount <= 0) { amount = this.crew; } else { amount = Math.min(amount, this.crew); } // Some helpful constants const movePercent = amount / this.crew; const stayPercent = 1 - movePercent; // Adjust the amount of gold to move if(gold < 0 || (movePercent >= 1 && this.shipHealth <= 0)) { gold = this.gold; } else { gold = Math.min(gold, this.gold); } // Move crew to new tile newUnit.crew += amount; this.crew -= amount; // Give new Unit health from old one newUnit.crewHealth += Math.ceil(this.crewHealth * movePercent); this.crewHealth = Math.floor(this.crewHealth * stayPercent); if(this.crew === 0) { this.owner = null; } // Move gold to new Unit newUnit.gold += gold; this.gold -= gold; // Set moves for the units that moved newUnit.moves = this.moves - 1; if(movePercent >= 1) { // Disassociating from old Tile if all the crew moved this.owner = null; if(this.shipHealth <= 0) { // If no units are left over, remove the unit this.tile.unit = null; this.tile = null; } } // Check if merging with another unit if(tile.unit) { tile.unit.mergeOnto(newUnit); tile.unit.owner = player; } else { tile.unit = newUnit; this.game.newUnits.push(newUnit); } return true; // <<-- /Creer-Merge: split -->> }, /** * Invalidation function for withdraw * Try to find a reason why the passed in parameters are invalid, and return a human readable string telling them why it is invalid * * @param {Player} player - the player that called this. * @param {number} amount - The amount of gold to withdraw. Amounts <= 0 will withdraw everything. * @param {Object} args - a key value table of keys to the arg (passed into this function) * @returns {string|undefined} a string that is the invalid reason, if the arguments are invalid. Otherwise undefined (nothing) if the inputs are valid. */ invalidateWithdraw: function(player, amount, args) { // <<-- Creer-Merge: invalidateWithdraw -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. const reason = this._invalidate(player, false); if(reason) { return reason; } const tile = player.port.tile; if(this.tile !== tile && this.tile.tileEast !== tile && this.tile.tileNorth !== tile && this.tile.tileWest !== tile && this.tile.tileSouth !== tile) { return `${this} has to withdraw yer booty from yer home port, matey!`; } return undefined; // meaning valid // <<-- /Creer-Merge: invalidateWithdraw -->> }, /** * Takes gold from the Player. You can only withdraw from your own Port. * * @param {Player} player - the player that called this. * @param {number} amount - The amount of gold to withdraw. Amounts <= 0 will withdraw everything. * @returns {boolean} True if successfully withdrawn, false otherwise. */ withdraw: function(player, amount) { // <<-- Creer-Merge: withdraw -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. if(amount <= 0) { // Take all the gold this.gold += player.gold; player.gold = 0; } else if(player.gold >= amount) { // Take some of the gold this.gold += amount; player.gold -= amount; } else if(player.gold <= amount) { // amount > player.gold, so just take it all this.gold += player.gold; player.gold = 0; } // Developer: Put your game logic for the Unit's withdraw function here return true; // <<-- /Creer-Merge: withdraw -->> }, //<<-- Creer-Merge: added-functions -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. /** * Tries to invalidate args for an action function * * @param {Player} player - the player commanding this Unit * @param {boolean} [checkAction] - true to check if this Unit has an action * @returns {string|undefined} the reason this is invalid, undefined if looks valid so far */ _invalidate: function(player, checkAction) { if(!player || player !== this.game.currentPlayer) { return `Avast, it isn't yer turn, ${player}.`; } if(this.owner !== player) { return `${this} isn't among yer crew.`; } if(checkAction && this.acted) { return `${this} can't perform another action this turn.`; } if(!this.tile || this.crew === 0) { return `Ye can't control ${this}.`; } }, mergeOnto: function(other) { this.tile.unit = null; other.tile.unit = this; this.tile = other.tile; other.tile = null; this.owner = other.owner || this.owner; this.crew += other.crew; this.crewHealth += other.crewHealth; this.shipHealth += other.shipHealth; this.gold += other.gold; this.acted &= other.acted || this.shipHealth > 0; this.moves = Math.min(this.moves, other.moves); }, //<<-- /Creer-Merge: added-functions -->> }); module.exports = Unit;
games/pirates/unit.js
// Unit: A unit group in the game. This may consist of a ship and any number of crew. const Class = require("classe"); const log = require(`${__basedir}/gameplay/log`); const GameObject = require("./gameObject"); //<<-- Creer-Merge: requires -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // any additional requires you want can be required here safely between Creer re-runs //<<-- /Creer-Merge: requires -->> // @class Unit: A unit group in the game. This may consist of a ship and any number of crew. let Unit = Class(GameObject, { /** * Initializes Units. * * @param {Object} data - a simple mapping passed in to the constructor with whatever you sent with it. GameSettings are in here by key/value as well. */ init: function(data) { GameObject.init.apply(this, arguments); /** * Whether this Unit has performed its action this turn. * * @type {boolean} */ this.acted = this.acted || false; /** * How many crew are on this Tile. This number will always be <= crewHealth. * * @type {number} */ this.crew = this.crew || 0; /** * How much total health the crew on this Tile have. * * @type {number} */ this.crewHealth = this.crewHealth || 0; /** * How much gold this Unit is carrying. * * @type {number} */ this.gold = this.gold || 0; /** * How many more times this Unit may move this turn. * * @type {number} */ this.moves = this.moves || 0; /** * The Player that owns and can control this Unit, or null if the Unit is neutral. * * @type {Player} */ this.owner = this.owner || null; /** * (Merchants only) The path this Unit will follow. The first element is the Tile this Unit will move to next. * * @type {Array.<Tile>} */ this.path = this.path || []; /** * If a ship is on this Tile, how much health it has remaining. 0 for no ship. * * @type {number} */ this.shipHealth = this.shipHealth || 0; /** * (Merchants only) The number of turns this merchant ship won't be able to move. They will still attack. Merchant ships are stunned when they're attacked. * * @type {number} */ this.stunTurns = this.stunTurns || 0; /** * (Merchants only) The Port this Unit is moving to. * * @type {Port} */ this.targetPort = this.targetPort || null; /** * The Tile this Unit is on. * * @type {Tile} */ this.tile = this.tile || null; //<<-- Creer-Merge: init -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. this.acted = data.acted || true; this.crew = data.crew || 0; this.crewHealth = data.crewHealth || this.crew * this.game.crewHealth; this.gold = data.gold || 0; this.moves = data.moves || 0; this.owner = data.owner || null; this.path = data.path || []; this.shipHealth = data.shipHealth || 0; this.targetPort = data.targetPort || null; this.tile = data.tile || null; this.stunTurns = data.stunTurns || 0; //<<-- /Creer-Merge: init -->> }, gameObjectName: "Unit", /** * Invalidation function for attack * Try to find a reason why the passed in parameters are invalid, and return a human readable string telling them why it is invalid * * @param {Player} player - the player that called this. * @param {Tile} tile - The Tile to attack. * @param {string} target - Whether to attack 'crew' or 'ship'. Crew deal damage to crew and ships deal damage to ships. Consumes any remaining moves. * @param {Object} args - a key value table of keys to the arg (passed into this function) * @returns {string|undefined} a string that is the invalid reason, if the arguments are invalid. Otherwise undefined (nothing) if the inputs are valid. */ invalidateAttack: function(player, tile, target, args) { // <<-- Creer-Merge: invalidateAttack -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. const reason = this._invalidate(player, true); if(reason) { return reason; } if(!tile) { return `${this} needs to know which tile to attack!`; } let t = target.charAt(0).toUpperCase(); if(t === "C") { if(!tile.unit) { return `There be nothin' for ${this} to attack on ${tile}!`; } if(tile.unit.player === player) { return `${this} doesn't have time for a mutany! Don't be attackin' yer own men!`; } if(tile.unit.crew <= 0) { return `${tile} has got no crew for you to attack!`; } let dx = this.tile.x - tile.x; let dy = this.tile.y - tile.y; let distSq = dx * dx + dy * dy; if(distSq > this.game.crewRange * this.game.crewRange) { return `${this} isn't in range for that attack. Yer swords don't reach off yonder!`; } } else if(t === "S") { if(!tile.unit) { return `There be nothin' for ${this} to attack on ${tile}!`; } if(tile.unit.shipHealth <= 0) { return `There be no ship for ${this} to attack.`; } if(this.shipHealth <= 0) { return `${this} has no ship to perform the attack.`; } if(tile.unit.player === player) { return `${this} doesn't have time for a mutany! Don't be attackin' yer own ship!`; } let dx = this.tile.x - tile.x; let dy = this.tile.y - tile.y; let distSq = dx * dx + dy * dy; if(distSq > this.game.shipRange * this.game.shipRange) { return `${this} isn't in range for that attack. Ye don't wanna fire blindly into the wind!`; } } else { return `${this} needs to attack somethin' valid ('ship' or 'crew'), not '${target}'.`; } // Developer: try to invalidate the game logic for Unit's attack function here return undefined; // meaning valid // <<-- /Creer-Merge: invalidateAttack -->> }, /** * Attacks either the 'crew' or 'ship' on a Tile in range. * * @param {Player} player - the player that called this. * @param {Tile} tile - The Tile to attack. * @param {string} target - Whether to attack 'crew' or 'ship'. Crew deal damage to crew and ships deal damage to ships. Consumes any remaining moves. * @returns {boolean} True if successfully attacked, false otherwise. */ attack: function(player, tile, target) { // <<-- Creer-Merge: attack -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. target = target.charAt(0).toUpperCase(); let deadCrew = 0; let deadShips = 0; let gold = 0; let merchant = tile.unit.targetPort !== null; let neutral = !merchant && !tile.owner; if(target === "C") { // Crew attacking crew tile.unit.crewHealth -= this.game.crewDamage * this.crew; tile.unit.crewHealth = Math.max(0, tile.unit.crewHealth); // For counting the dead accurately if(tile.unit.crew > tile.unit.crewHealth) { deadCrew = tile.unit.crew - tile.unit.crewHealth; tile.unit.crew = tile.unit.crewHealth; } // Check if the crew was completely destroyed if(tile.unit.crewHealth <= 0) { if(tile.unit.shipHealth <= 0) { gold += tile.unit.gold; // Mark it as dead tile.unit.tile = null; tile.unit = null; } else { tile.unit.owner = null; tile.unit.shipHealth = 1; // Make sure it's not a merchant ship anymore either tile.unit.targetPort = null; tile.unit.path = []; } } } else { // Ship attacking ship tile.unit.shipHealth -= this.game.shipDamage; tile.unit.shipHealth = Math.max(0, tile.unit.shipHealth); // Check if ship was destroyed if(tile.unit.shipHealth <= 0) { deadShips += 1; gold += tile.unit.gold; // Mark it as dead tile.unit.tile = null; tile.unit = null; } } // Infamy this.acted = true; this.gold += gold; // Calculate the infamy factor let factor = 1; if(!merchant) { // Calculate each player's net worth let allyWorth = player.netWorth() + player.gold - gold; let opponentWorth = player.opponent.netWorth() + player.opponent.gold + gold; opponentWorth += deadCrew * this.game.crewCost + deadShips * this.game.shipCost; if(allyWorth > opponentWorth) { factor = 0.5; } else if(allyWorth < opponentWorth) { factor = 2; } } // Calculate infamy let infamy = deadCrew * this.game.crewCost + deadShips * this.game.shipCost; infamy *= factor; if(!neutral) { if(!merchant) { infamy = Math.min(infamy, player.opponent.infamy); player.opponent.infamy -= infamy; } player.infamy += infamy; } if(merchant && tile.unit) { tile.unit.stunTurns = 2; } return true; // <<-- /Creer-Merge: attack -->> }, /** * Invalidation function for bury * Try to find a reason why the passed in parameters are invalid, and return a human readable string telling them why it is invalid * * @param {Player} player - the player that called this. * @param {number} amount - How much gold this Unit should bury. Amounts <= 0 will bury as much as possible. * @param {Object} args - a key value table of keys to the arg (passed into this function) * @returns {string|undefined} a string that is the invalid reason, if the arguments are invalid. Otherwise undefined (nothing) if the inputs are valid. */ invalidateBury: function(player, amount, args) { // <<-- Creer-Merge: invalidateBury -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. const reason = this._invalidate(player, false); if(reason) { return reason; } if(this.tile.type !== "land") { return `${this} can't bury gold on the sea.`; } if(this.tile.port) { return `${this} can't bury gold in ports.`; } let dx = this.tile.x - player.port.tile.x; let dy = this.tile.y - player.port.tile.y; let distSq = dx * dx + dy * dy; if(distSq < this.game.minInterestDistance * this.game.minInterestDistance) { return `${this} is too close to home! Ye gotta bury yer loot far away from yer port.`; } return undefined; // meaning valid // <<-- /Creer-Merge: invalidateBury -->> }, /** * Buries gold on this Unit's Tile. Gold must be a certain distance away for it to get interest (Game.minInterestDistance). * * @param {Player} player - the player that called this. * @param {number} amount - How much gold this Unit should bury. Amounts <= 0 will bury as much as possible. * @returns {boolean} True if successfully buried, false otherwise. */ bury: function(player, amount) { // <<-- Creer-Merge: bury -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. if(amount <= 0) { amount = this.gold; } else { amount = Math.min(this.gold, amount); } this.tile.gold += amount; this.gold -= amount; return true; // <<-- /Creer-Merge: bury -->> }, /** * Invalidation function for deposit * Try to find a reason why the passed in parameters are invalid, and return a human readable string telling them why it is invalid * * @param {Player} player - the player that called this. * @param {number} amount - The amount of gold to deposit. Amounts <= 0 will deposit all the gold on this Unit. * @param {Object} args - a key value table of keys to the arg (passed into this function) * @returns {string|undefined} a string that is the invalid reason, if the arguments are invalid. Otherwise undefined (nothing) if the inputs are valid. */ invalidateDeposit: function(player, amount, args) { // <<-- Creer-Merge: invalidateDeposit -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. const reason = this._invalidate(player, false); if(reason) { return reason; } let neighbors = [this.tile, this.tile.tileNorth, this.tile.tileEast, this.tile.tileSouth, this.tile.tileWest]; let found = neighbors.find(t => t && t.port && t.port.owner !== player.opponent); if(!found) { return `Arr, ${this} has to deposit yer booty in yer home port or a merchant port, matey!`; } if(this.gold <= 0) { return `Shiver me timbers! ${this} doesn't have any booty to deposit!`; } return undefined; // meaning valid // <<-- /Creer-Merge: invalidateDeposit -->> }, /** * Puts gold into an adjacent Port. If that Port is the Player's port, the gold is added to that Player. If that Port is owned by merchants, it adds to that Port's investment. * * @param {Player} player - the player that called this. * @param {number} amount - The amount of gold to deposit. Amounts <= 0 will deposit all the gold on this Unit. * @returns {boolean} True if successfully deposited, false otherwise. */ deposit: function(player, amount) { // <<-- Creer-Merge: deposit -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // Adjust amount amount = Math.min(Math.max(amount, 0), this.gold); if(amount <= 0) { amount = this.gold; } this.gold -= amount; // Check for this player's port let neighbors = [this.tile, this.tile.tileNorth, this.tile.tileEast, this.tile.tileSouth, this.tile.tileWest]; let tile = neighbors.find(t => t && t.port && t.port.owner === player, this); if(tile) { player.gold += amount; } else { // Get the merchant's port tile = neighbors.find(t => t && t.port && !t.port.owner, this); tile.port.investment += amount; } return true; // <<-- /Creer-Merge: deposit -->> }, /** * Invalidation function for dig * Try to find a reason why the passed in parameters are invalid, and return a human readable string telling them why it is invalid * * @param {Player} player - the player that called this. * @param {number} amount - How much gold this Unit should take. Amounts <= 0 will dig up as much as possible. * @param {Object} args - a key value table of keys to the arg (passed into this function) * @returns {string|undefined} a string that is the invalid reason, if the arguments are invalid. Otherwise undefined (nothing) if the inputs are valid. */ invalidateDig: function(player, amount, args) { // <<-- Creer-Merge: invalidateDig -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. const reason = this._invalidate(player, false); if(reason) { return reason; } // Checking to see if the tile is anything other than a land type. if(this.tile.type !== "land") { return `${this} can't dig in the sea!`; } // Checking to see if the tile has gold to be dug up. if(this.tile.gold === 0) { return `There be no booty for ${this} to plunder.`; } return undefined; // meaning valid // <<-- /Creer-Merge: invalidateDig -->> }, /** * Digs up gold on this Unit's Tile. * * @param {Player} player - the player that called this. * @param {number} amount - How much gold this Unit should take. Amounts <= 0 will dig up as much as possible. * @returns {boolean} True if successfully dug up, false otherwise. */ dig: function(player, amount) { // <<-- Creer-Merge: dig -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // If the amount requested is <= 0 or greater than what is current give all. if(amount <= 0 || amount > this.tile.gold) { // Adds the amount of gold from the current tile to the Unit. this.gold += this.tile.gold; // Sets the gold on tile to 0. this.tile.gold = 0; return true; } // Else if amount is less than what is there take that amount. else { // Adds amount requested to Unit. this.gold += amount; // Subtracts amount from Tile's gold this.tile.gold -= amount; return true; } // <<-- /Creer-Merge: dig -->> }, /** * Invalidation function for move * Try to find a reason why the passed in parameters are invalid, and return a human readable string telling them why it is invalid * * @param {Player} player - the player that called this. * @param {Tile} tile - The Tile this Unit should move to. * @param {Object} args - a key value table of keys to the arg (passed into this function) * @returns {string|undefined} a string that is the invalid reason, if the arguments are invalid. Otherwise undefined (nothing) if the inputs are valid. */ invalidateMove: function(player, tile, args) { // <<-- Creer-Merge: invalidateMove -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. const reason = this._invalidate(player, false); if(reason) { return reason; } const ship = this.shipHealth > 0; if(this.moves <= 0) { return `${this}'s crew are too tired to travel any further.`; } if(this.acted) { return `${this} can't move after acting. The men are too tired!`; } if(!tile) { return `${this} must have a destination to move to.`; } if(this.tile.tileEast !== tile && this.tile.tileNorth !== tile && this.tile.tileWest !== tile && this.tile.tileSouth !== tile) { return `${tile} be too far for ${this} to move to.`; } if(tile.unit && tile.unit.owner !== player && tile.unit.owner !== null) { return `${this} refuses to share the same ground with a living foe.`; } if(!ship && tile.type === "water" && !tile.port) { return `${this} has no ship and can't walk on water!`; } if(ship && tile.type === "land") { return `Land ho! ${this} belongs in the sea! Use 'Unit.split' if ye want to move just yer crew ashore.`; } if(ship && tile.shipHealth > 0) { return `There be a ship there. If ye move ${this} to ${tile}, ye'll scuttle yer ship!`; } if(!ship && tile.ship && this.acted) { return `${this} already acted, and it be too tired to board that ship.`; } if(tile.port && tile.port.owner !== player) { return `${this} can't enter an enemy port!`; } return undefined; // meaning valid // <<-- /Creer-Merge: invalidateMove -->> }, /** * Moves this Unit from its current Tile to an adjacent Tile. If this Unit merges with another one, the other Unit will be destroyed and its tile will be set to null. Make sure to check that your Unit's tile is not null before doing things with it. * * @param {Player} player - the player that called this. * @param {Tile} tile - The Tile this Unit should move to. * @returns {boolean} True if it moved, false otherwise. */ move: function(player, tile) { // <<-- Creer-Merge: move -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. if(tile.unit) { this.moves--; this.mergeOnto(tile.unit); } else { // Move this unit to that tile this.tile.unit = null; this.tile = tile; tile.unit = this; this.moves -= 1; } return true; // <<-- /Creer-Merge: move -->> }, /** * Invalidation function for rest * Try to find a reason why the passed in parameters are invalid, and return a human readable string telling them why it is invalid * * @param {Player} player - the player that called this. * @param {Object} args - a key value table of keys to the arg (passed into this function) * @returns {string|undefined} a string that is the invalid reason, if the arguments are invalid. Otherwise undefined (nothing) if the inputs are valid. */ invalidateRest: function(player, args) { // <<-- Creer-Merge: invalidateRest -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. const reason = this._invalidate(player, true); if(reason) { return reason; } // Check if it's in range const radius = this.game.restRange; if(Math.pow(this.tile.x - player.port.tile.x, 2) + Math.pow(this.tile.y - player.port.tile.y, 2) > radius * radius) { return `${this} has no nearby port to rest at. No home tavern means no free rum!`; } return undefined; // meaning valid // <<-- /Creer-Merge: invalidateRest -->> }, /** * Regenerates this Unit's health. Must be used in range of a port. * * @param {Player} player - the player that called this. * @returns {boolean} True if successfully rested, false otherwise. */ rest: function(player) { // <<-- Creer-Merge: rest -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // Heal the units this.crewHealth += Math.ceil(this.game.crewHealth * this.game.healFactor) * this.crew; this.crewHealth = Math.min(this.crewHealth, this.crew * this.game.crewHealth); if(this.shipHealth > 0) { this.shipHealth += Math.ceil(this.game.shipHealth * this.game.healFactor); this.shipHealth = Math.min(this.shipHealth, this.game.shipHealth); } // Make sure the unit can't do anything else this turn this.acted = true; this.moves = 0; return true; // <<-- /Creer-Merge: rest -->> }, /** * Invalidation function for split * Try to find a reason why the passed in parameters are invalid, and return a human readable string telling them why it is invalid * * @param {Player} player - the player that called this. * @param {Tile} tile - The Tile to move the crew to. * @param {number} amount - The number of crew to move onto that Tile. Amount <= 0 will move all the crew to that Tile. * @param {number} gold - The amount of gold the crew should take with them. Gold < 0 will move all the gold to that Tile. * @param {Object} args - a key value table of keys to the arg (passed into this function) * @returns {string|undefined} a string that is the invalid reason, if the arguments are invalid. Otherwise undefined (nothing) if the inputs are valid. */ invalidateSplit: function(player, tile, amount, gold, args) { // <<-- Creer-Merge: invalidateSplit -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. const reason = this._invalidate(player, false); if(reason) { return reason; } if(!tile) { return `${this} can't split onto null!`; } // Check to see if the crew has a move to move if(this.moves <= 0) { return `${this} can't split cause they be out of moves.`; } // Check to see if they have already acted. if(this.acted) { return `${this} crew are too tired to split!`; } // Check to see if it is not one of the tiles around in the current direction if(this.tile.tileEast !== tile && this.tile.tileNorth !== tile && this.tile.tileWest !== tile && this.tile.tileSouth !== tile) { return `${tile} be too far for ${this} to split to.`; } // Check to make sure target tile is a valid tile if(tile.type !== "land" && tile.unit.shipHealth <= 0 && tile.port === null) { return `${this} can't split here!`; } return undefined; // meaning valid // <<-- /Creer-Merge: invalidateSplit -->> }, /** * Moves a number of crew from this Unit to the given Tile. This will consume a move from those crew. * * @param {Player} player - the player that called this. * @param {Tile} tile - The Tile to move the crew to. * @param {number} amount - The number of crew to move onto that Tile. Amount <= 0 will move all the crew to that Tile. * @param {number} gold - The amount of gold the crew should take with them. Gold < 0 will move all the gold to that Tile. * @returns {boolean} True if successfully split, false otherwise. */ split: function(player, tile, amount, gold) { // <<-- Creer-Merge: split -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // Create a new unit let newUnit = this.game.create("Unit", { owner: player, tile: tile, }); // Check if boarding a ship if(tile.type === "water" && tile.unit.shipHealth > 0) { newUnit.acted = true; } // Adjust the amount of crew to split if(amount <= 0) { amount = this.crew; } else { amount = Math.min(amount, this.crew); } // Some helpful constants const movePercent = amount / this.crew; const stayPercent = 1 - movePercent; // Adjust the amount of gold to move if(gold < 0 || (movePercent >= 1 && this.shipHealth <= 0)) { gold = this.gold; } else { gold = Math.min(gold, this.gold); } // Move crew to new tile newUnit.crew += amount; this.crew -= amount; // Give new Unit health from old one newUnit.crewHealth += Math.ceil(this.crewHealth * movePercent); this.crewHealth = Math.floor(this.crewHealth * stayPercent); // Move gold to new Unit newUnit.gold += gold; this.gold -= gold; // Set moves for the units that moved newUnit.moves = this.moves - 1; if(movePercent >= 1) { // Disassociating from old Tile if all the crew moved this.owner = null; if(this.shipHealth <= 0) { // If no units are left over, remove the unit this.tile.unit = null; this.tile = null; } } // Check if merging with another unit if(tile.unit) { tile.unit.mergeOnto(newUnit); } else { tile.unit = newUnit; this.game.newUnits.push(newUnit); } return true; // <<-- /Creer-Merge: split -->> }, /** * Invalidation function for withdraw * Try to find a reason why the passed in parameters are invalid, and return a human readable string telling them why it is invalid * * @param {Player} player - the player that called this. * @param {number} amount - The amount of gold to withdraw. Amounts <= 0 will withdraw everything. * @param {Object} args - a key value table of keys to the arg (passed into this function) * @returns {string|undefined} a string that is the invalid reason, if the arguments are invalid. Otherwise undefined (nothing) if the inputs are valid. */ invalidateWithdraw: function(player, amount, args) { // <<-- Creer-Merge: invalidateWithdraw -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. const reason = this._invalidate(player, false); if(reason) { return reason; } const tile = player.port.tile; if(this.tile !== tile && this.tile.tileEast !== tile && this.tile.tileNorth !== tile && this.tile.tileWest !== tile && this.tile.tileSouth !== tile) { return `${this} has to withdraw yer booty from yer home port, matey!`; } return undefined; // meaning valid // <<-- /Creer-Merge: invalidateWithdraw -->> }, /** * Takes gold from the Player. You can only withdraw from your own Port. * * @param {Player} player - the player that called this. * @param {number} amount - The amount of gold to withdraw. Amounts <= 0 will withdraw everything. * @returns {boolean} True if successfully withdrawn, false otherwise. */ withdraw: function(player, amount) { // <<-- Creer-Merge: withdraw -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. if(amount <= 0) { // Take all the gold this.gold += player.gold; player.gold = 0; } else if(player.gold >= amount) { // Take some of the gold this.gold += amount; player.gold -= amount; } else if(player.gold <= amount) { // amount > player.gold, so just take it all this.gold += player.gold; player.gold = 0; } // Developer: Put your game logic for the Unit's withdraw function here return true; // <<-- /Creer-Merge: withdraw -->> }, //<<-- Creer-Merge: added-functions -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. /** * Tries to invalidate args for an action function * * @param {Player} player - the player commanding this Unit * @param {boolean} [checkAction] - true to check if this Unit has an action * @returns {string|undefined} the reason this is invalid, undefined if looks valid so far */ _invalidate: function(player, checkAction) { if(!player || player !== this.game.currentPlayer) { return `Avast, it isn't yer turn, ${player}.`; } if(this.owner !== player) { return `${this} isn't among yer crew.`; } if(checkAction && this.acted) { return `${this} can't perform another action this turn.`; } if(!this.tile || this.crew === 0) { return `Ye can't control ${this}.`; } }, mergeOnto: function(other) { this.tile.unit = null; other.tile.unit = this; this.tile = other.tile; other.tile = null; this.owner = other.owner || this.owner; this.crew += other.crew; this.crewHealth += other.crewHealth; this.shipHealth += other.shipHealth; this.gold += other.gold; this.acted &= other.acted || this.shipHealth > 0; this.moves = Math.min(this.moves, other.moves); }, //<<-- /Creer-Merge: added-functions -->> }); module.exports = Unit;
Maybe fixed split?
games/pirates/unit.js
Maybe fixed split?
<ide><path>ames/pirates/unit.js <ide> newUnit.crewHealth += Math.ceil(this.crewHealth * movePercent); <ide> this.crewHealth = Math.floor(this.crewHealth * stayPercent); <ide> <add> if(this.crew === 0) { <add> this.owner = null; <add> } <add> <ide> // Move gold to new Unit <ide> newUnit.gold += gold; <ide> this.gold -= gold; <ide> // Check if merging with another unit <ide> if(tile.unit) { <ide> tile.unit.mergeOnto(newUnit); <add> tile.unit.owner = player; <ide> } <ide> else { <ide> tile.unit = newUnit;
Java
apache-2.0
6f6172b9cecfd27d5a13b88ae8aa195aabcab964
0
ivanr/qlue
/* * Qlue Web Application Framework * Copyright 2009-2012 Ivan Ristic <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.webkreator.qlue; import com.webkreator.qlue.annotations.QlueCommandObject; import com.webkreator.qlue.annotations.QlueParameter; import com.webkreator.qlue.annotations.QluePersistentPage; import com.webkreator.qlue.exceptions.BadRequestException; import com.webkreator.qlue.exceptions.MethodNotAllowedException; import com.webkreator.qlue.exceptions.UnauthorizedException; import com.webkreator.qlue.util.BearerToken; import com.webkreator.qlue.util.HtmlEncoder; import com.webkreator.qlue.view.View; import com.webkreator.qlue.view.ViewResolver; import com.webkreator.qlue.view.velocity.QlueVelocityTool; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.PrintWriter; import java.io.Reader; import java.io.Serializable; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.*; /** * Represents a single unit of work application will perform. This class handles both non-persistent * and persistent pages. I used only one class for both because the intention is that applications * never really subclass this class directly. Rather, they should create their own base page class. And, * because Java doesn't support multiple inheritance, having two Qlue base classes would complicate things. */ public abstract class Page implements Serializable { /** * This is a meta-state that's used for parameter binding: matches * on all requests. Page state can't be set to this value. */ public static final String STATE_ANY = "ANY"; /** * This is a meta-state that's used for parameter binding: non-persistent * pages bind all STATE_DEFAULT parameters on every request; persistent * pages bind STATE_DEFAULT parameters only on POST requests. */ public static final String STATE_DEFAULT = "DEFAULT"; /** * This is a meta-state that's used for parameter binding: matches any * HTTP GET request. Page state can't be set to this value. */ public static final String STATE_GET = "GET"; /** * This is a meta-state that's used for parameter binding: matches any * HTTP POST request. Page state can't be set to this value. */ public static final String STATE_POST = "POST"; /** * This is the default state of every page, which is used until * it completes its first request. */ public static final String STATE_INIT = "INIT"; /** * This is the default working state, i.e., the state to * which pages transition after STATE_INIT. It's used for * convenience because most persistent pages have only * two states. */ public static final String STATE_IN_PROGRESS = "IN_PROGRESS"; /** * This is the final state for persistent pages; it indicates * that there is no more work to be done. */ public static final String STATE_FINISHED = "FINISHED"; protected static final Logger qlueLog = LoggerFactory.getLogger(Page.class); // -- Set by framework at the beginning of a transaction. protected transient QlueApplication app; protected transient TransactionContext context; protected transient Map<String, Object> model = new HashMap<String, Object>(); // -- Instance fields. private Integer id; private String state = STATE_INIT; private boolean cleanupInvoked; protected String viewName; protected String contentType = "text/html; charset=UTF-8"; protected Object commandObject; protected Errors errors = new Errors(); protected ShadowInput shadowInput = new ShadowInput(); protected Page() { } public Page(QlueApplication app) { setApp(app); determineDefaultViewName(app.getViewResolver()); determineCommandObject(); } /** * Has this page finished its work? */ public boolean isFinished() { return getState().equals(STATE_FINISHED); } /** * Retrieve unique page ID. */ public Integer getId() { return id; } /** * Set page ID. Pages are allocated IDs only prior to being persisted. * Transient pages do not need IDs. */ void setId(int id) { this.id = id; } public void clearShadowInput() { shadowInput = new ShadowInput(); } /** * Retrieve shadow input associated with page. */ public ShadowInput getShadowInput() { return shadowInput; } /** * Retrieve page state. */ public String getState() { return state; } /** * Change page state to given value. */ protected void setState(String state) { if ((state == Page.STATE_INIT) || (state == Page.STATE_ANY) || (state == Page.STATE_GET) || (state == Page.STATE_POST)) { throw new IllegalArgumentException("Invalid state transition: " + state); } this.state = state; } /** * Retrieve the application to which this page belongs. */ public QlueApplication getApp() { return app; } /** * Associate Qlue application with this page. */ void setApp(QlueApplication app) { this.app = app; } /** * Return a command object. By default, the page is the command object, but * a subclass has the option to use a different object. The page can use the * supplied context to choose which command object (out of several it might * be using) to return. */ public final synchronized Object getCommandObject() { if (commandObject == null) { determineCommandObject(); } return commandObject; } /** * This method will determine what the command object is supposed to be. The * page itself is the default command object, but subclass can override this * behavior. */ protected void determineCommandObject() { // Look for the command object among the page fields via the @QlueCommandObject annotation. try { Field[] fields = this.getClass().getFields(); for (Field f : fields) { if (f.isAnnotationPresent(QlueCommandObject.class)) { commandObject = f.get(this); // If the command object doesn't exist, we try to create a new instance. if (commandObject == null) { try { // Our first attempt is to use the default constructor. commandObject = f.getType().newInstance(); f.set(this, commandObject); } catch (InstantiationException ie) { // Inner classes have an implicit constructor that takes a reference to the parent object. // http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.8.1 try { commandObject = f.getType().getConstructor(this.getClass()).newInstance(this); f.set(this, commandObject); } catch (NoSuchMethodException | InstantiationException | InvocationTargetException ex) { throw new RuntimeException("Unable to create command object: " + f.getType()); } } } return; } } // Use the page itself as the command object. commandObject = this; } catch (IllegalAccessException e) { throw new RuntimeException(e); } } /** * Process one HTTP request. By default, pages accept only GET (and HEAD, * treated as GET) and POST. */ public View service() throws Exception { switch (context.request.getMethod()) { case "GET": case "HEAD": return onGet(); case "DELETE": return onDelete(); case "PATCH": return onPatch(); case "POST": return onPost(); case "PUT": return onPut(); default: throw new MethodNotAllowedException(); } } /** * Process a GET request. The default implementation does not actually do * anything -- it just throws an exception. */ public View onGet() throws Exception { throw new MethodNotAllowedException(); } /** * Process a DELETE request. The default implementation does not actually do * anything -- it just throws an exception. */ public View onDelete() throws Exception { throw new MethodNotAllowedException(); } public View onPatch() throws Exception { throw new MethodNotAllowedException(); } /** * Process a POST request. The default implementation does not actually do * anything -- it just throws an exception. */ public View onPost() throws Exception { throw new MethodNotAllowedException(); } /** * Process a PUT request. The default implementation does not actually do * anything -- it just throws an exception. */ public View onPut() throws Exception { throw new MethodNotAllowedException(); } /** * Retrieve the model associated with a page. */ public Map<String, Object> getModel() { return model; } /** * Add a key-value pair to the model. */ void addToModel(String key, Object value) { model.put(key, value); } /** * Retrieve value from the model, using the given key. */ public Object getFromModel(String key) { return model.get(key); } /** * Retrieve the default view name associated with page. */ public String getViewName() { return viewName; } /** * Retrieve the response content type associated with this page. */ public String getContentType() { return contentType; } /** * Set response content type. */ public void setContentType(String contentType) { this.contentType = contentType; } /** * Retrieve page transaction context. */ public TransactionContext getContext() { return context; } /** * Set page transaction context. */ void setContext(TransactionContext context) { this.context = context; } /** * Return page's format tool. By default, we respond with application's * format tool, but pages (subclasses) can create their own. */ public List<QlueVelocityTool> getVelocityTools() { return getApp().getVelocityTools(); } /** * Determine the default view name for this page. */ void determineDefaultViewName(ViewResolver resolver) { viewName = this.getClass().getSimpleName(); } public View initBackend() throws Exception { return null; } /** * This method is invoked right before the main service method. It allows * the page to prepare for request processing. The default implementation * will, on POST request, check that there is a nonce value supplied in the * request, and that the value matches the value stored in the session. It * will also expose the nonce to the model. */ public View checkAccess() throws Exception { if (context.isPost() && getClass().isAnnotationPresent(QluePersistentPage.class)) { verifySessionSecret(); } return null; } protected void verifySessionSecret() throws Exception { BearerToken sessionSecret = getQlueSession().getSessionSecret(); String suppliedSecret = context.getParameter("_secret"); if (suppliedSecret == null) { throw new UnauthorizedException("Secret session token hasn't been provided"); } try { if (sessionSecret.checkMaskedToken(suppliedSecret) == false) { throw new UnauthorizedException("Secret session token mismatch"); } } catch (IllegalArgumentException e) { throw new UnauthorizedException("Invalid secret session token"); } } public View validateParameters() { return null; } public View prepareForService() { return null; } public void startHttpSession() { getQlueSession(); } /** * Does this page has any parameter validation errors? */ protected boolean hasErrors() { return errors.hasErrors(); } /** * Retrieve validation errors. */ public Errors getErrors() { return errors; } /** * Adds a page-specific error message. */ protected void addError(String message) { errors.addError(message); } /** * Adds a field-specific error message. */ public void addError(String param, String message) { errors.addError(param, message); } /** * Retrieve session associated with this page. */ public QlueSession getQlueSession() { /* // This code used to determine who started the HTTP session. try { throw new RuntimeException(); } catch (Exception e) { e.printStackTrace(System.err); } */ return app.getQlueSession(context.getRequest()); } public boolean allowDirectOutput() { return app.allowDirectOutput(); } public boolean isQlueDevMode() { return app.isQlueDevMode(context); } public String getNoParamUri() { return context.getRequestUri(); } /** * Outputs page-specific debugging information. */ void writeDevelopmentInformation(PrintWriter out) { // Page fields out.println(" Id: " + getId()); out.println(" Class: " + this.getClass()); out.println(" State: " + HtmlEncoder.html(getState())); out.println(" Errors {"); // Errors int i = 1; for (Error e : errors.getAllErrors()) { out.print(" " + i++ + ". "); out.print(HtmlEncoder.html(e.getMessage())); if (e.getParam() != null) { out.print(" [field " + HtmlEncoder.html(e.getParam()) + "]"); } out.println(); } out.println(" }"); out.println(""); // Model out.println("<b>Model</b>\n"); Map<String, Object> model = getModel(); if (model != null) { TreeMap<String, Object> treeMap = new TreeMap<>(); for (Iterator<String> it = model.keySet().iterator(); it.hasNext(); ) { String name = it.next(); treeMap.put(name, model.get(name)); } Iterator<String> it = treeMap.keySet().iterator(); while (it.hasNext()) { String name = it.next(); Object o = treeMap.get(name); out.println(" " + HtmlEncoder.html(name) + ": " + ((o != null) ? HtmlEncoder.html(o.toString()) : "null")); } } } /** * Executes page rollback. The default implementation cleans up resources. */ public void rollback() { } /** * Executes page commit. The default implementation cleans up resources. */ public void commit() { } /** * In the default implementation, we delete any files that were created * during the processing of a multipart/form-data request. */ public void cleanup() { cleanupInvoked = true; deleteFiles(); } /** * Invoked after data validation and binding, but before request processing, * giving the page a chance to initialize itself. This method is invoked * only when the state is STATE_NEW (which means only once for a page). */ public View init() throws Exception { return null; } /** * Delete files created by processing multipart/form-data. */ void deleteFiles() { Object commandObject = getCommandObject(); if (commandObject == null) { return; } // Look for QlueFile instances Field[] fields = commandObject.getClass().getFields(); for (Field f : fields) { if (f.isAnnotationPresent(QlueParameter.class)) { if (QlueFile.class.isAssignableFrom(f.getType())) { // Delete temporary file QlueFile qf = null; try { qf = (QlueFile) f.get(commandObject); if (qf != null) { qf.delete(); } } catch (Exception e) { qlueLog.error("Qlue: Failed deleting file " + qf, e); } } } } } /** * Is page persistent? */ public boolean isPersistent() { return getClass().isAnnotationPresent(QluePersistentPage.class); } /** * This method is invoked after built-in parameter validation fails. The * default implementation will throw an exception for non-persistent pages, * and ignore the problem for persistent pages. */ public View handleParameterValidationFailure() throws Exception { if (isPersistent() == true) { // Persistent pages, by default, have to // explicitly handle their errors. return null; } // We're going to throw an exception here to interrupt normal // page processing. The errors should already be available in // the page, so there's no need for us to add anything else here. throw new BadRequestException(); } public View handleException(Exception e) { // Do nothing by default, let subclasses handle it. return null; } public boolean isCleanupInvoked() { return cleanupInvoked; } void setRoutedResponseHeaders() { for (Map.Entry<String, String> me : context.getResponseHeaders().entrySet()) { context.response.setHeader(me.getKey(), me.getValue()); } } protected boolean validateBean(Object object) { return validateBean(object, null); } protected boolean validateBean(Object object, String parentPath) { return app.doBeanValidation(object, parentPath, this); } protected Object convertJsonToObject(Reader reader, Class<?> type) { return app.convertJsonToObject(reader, type); } /** * Return the default state after INIT. Most persistent pages support * only two states, INIT and IN_PROGRESS, and Qlue will automatically * switch from one to the other unless the page explicitly makes * the transition. Pages can override this method if they wish to * use more meaningful state names. * * @return */ public String getDefaultStateAfterInit() { return Page.STATE_IN_PROGRESS; } }
src/main/java/com/webkreator/qlue/Page.java
/* * Qlue Web Application Framework * Copyright 2009-2012 Ivan Ristic <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.webkreator.qlue; import com.webkreator.qlue.annotations.QlueCommandObject; import com.webkreator.qlue.annotations.QlueParameter; import com.webkreator.qlue.annotations.QluePersistentPage; import com.webkreator.qlue.exceptions.BadRequestException; import com.webkreator.qlue.exceptions.MethodNotAllowedException; import com.webkreator.qlue.exceptions.UnauthorizedException; import com.webkreator.qlue.util.BearerToken; import com.webkreator.qlue.util.HtmlEncoder; import com.webkreator.qlue.view.View; import com.webkreator.qlue.view.ViewResolver; import com.webkreator.qlue.view.velocity.QlueVelocityTool; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.PrintWriter; import java.io.Reader; import java.io.Serializable; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.*; /** * Represents a single unit of work application will perform. This class handles both non-persistent * and persistent pages. I used only one class for both because the intention is that applications * never really subclass this class directly. Rather, they should create their own base page class. And, * because Java doesn't support multiple inheritance, having two Qlue base classes would complicate things. */ public abstract class Page implements Serializable { /** * This is a meta-state that's used for parameter binding: matches * on all requests. Page state can't be set to this value. */ public static final String STATE_ANY = "ANY"; /** * This is a meta-state that's used for parameter binding: non-persistent * pages bind all STATE_DEFAULT parameters on every request; persistent * pages bind STATE_DEFAULT parameters only on POST requests. */ public static final String STATE_DEFAULT = "DEFAULT"; /** * This is a meta-state that's used for parameter binding: matches any * HTTP GET request. Page state can't be set to this value. */ public static final String STATE_GET = "GET"; /** * This is a meta-state that's used for parameter binding: matches any * HTTP POST request. Page state can't be set to this value. */ public static final String STATE_POST = "POST"; /** * This is the default state of every page, which is used until * it completes its first request. */ public static final String STATE_INIT = "INIT"; /** * This is the default working state, i.e., the state to * which pages transition after STATE_INIT. It's used for * convenience because most persistent pages have only * two states. */ public static final String STATE_IN_PROGRESS = "IN_PROGRESS"; /** * This is the final state for persistent pages; it indicates * that there is no more work to be done. */ public static final String STATE_FINISHED = "FINISHED"; protected static final Logger qlueLog = LoggerFactory.getLogger(Page.class); // -- Set by framework at the beginning of a transaction. protected transient QlueApplication app; protected transient TransactionContext context; protected transient Map<String, Object> model = new HashMap<String, Object>(); // -- Instance fields. private Integer id; private String state = STATE_INIT; private boolean cleanupInvoked; protected String viewName; protected String contentType = "text/html; charset=UTF-8"; protected Object commandObject; protected Errors errors = new Errors(); protected ShadowInput shadowInput = new ShadowInput(); protected Page() { } public Page(QlueApplication app) { setApp(app); determineDefaultViewName(app.getViewResolver()); determineCommandObject(); } /** * Has this page finished its work? */ public boolean isFinished() { return getState().equals(STATE_FINISHED); } /** * Retrieve unique page ID. */ public Integer getId() { return id; } /** * Set page ID. Pages are allocated IDs only prior to being persisted. * Transient pages do not need IDs. */ void setId(int id) { this.id = id; } public void clearShadowInput() { shadowInput = new ShadowInput(); } /** * Retrieve shadow input associated with page. */ public ShadowInput getShadowInput() { return shadowInput; } /** * Retrieve page state. */ public String getState() { return state; } /** * Change page state to given value. */ protected void setState(String state) { if ((state == Page.STATE_INIT) || (state == Page.STATE_ANY) || (state == Page.STATE_GET) || (state == Page.STATE_POST)) { throw new IllegalArgumentException("Invalid state transition: " + state); } this.state = state; } /** * Retrieve the application to which this page belongs. */ public QlueApplication getApp() { return app; } /** * Associate Qlue application with this page. */ void setApp(QlueApplication app) { this.app = app; } /** * Return a command object. By default, the page is the command object, but * a subclass has the option to use a different object. The page can use the * supplied context to choose which command object (out of several it might * be using) to return. */ public final synchronized Object getCommandObject() { if (commandObject == null) { determineCommandObject(); } return commandObject; } /** * This method will determine what the command object is supposed to be. The * page itself is the default command object, but subclass can override this * behavior. */ protected void determineCommandObject() { // Look for the command object among the page fields via the @QlueCommandObject annotation. try { Field[] fields = this.getClass().getFields(); for (Field f : fields) { if (f.isAnnotationPresent(QlueCommandObject.class)) { commandObject = f.get(this); // If the command object doesn't exist, we try to create a new instance. if (commandObject == null) { try { // Our first attempt is to use the default constructor. commandObject = f.getType().newInstance(); f.set(this, commandObject); } catch (InstantiationException ie) { // Inner classes have an implicit constructor that takes a reference to the parent object. // http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.8.1 try { commandObject = f.getType().getConstructor(this.getClass()).newInstance(this); f.set(this, commandObject); } catch (NoSuchMethodException | InstantiationException | InvocationTargetException ex) { throw new RuntimeException("Unable to create command object: " + f.getType()); } } } return; } } // Use the page itself as the command object. commandObject = this; } catch (IllegalAccessException e) { throw new RuntimeException(e); } } /** * Process one HTTP request. By default, pages accept only GET (and HEAD, * treated as GET) and POST. */ public View service() throws Exception { switch (context.request.getMethod()) { case "GET": case "HEAD": return onGet(); case "DELETE": return onDelete(); case "PATCH": return onPatch(); case "POST": return onPost(); case "PUT": return onPut(); default: throw new MethodNotAllowedException(); } } /** * Process a GET request. The default implementation does not actually do * anything -- it just throws an exception. */ public View onGet() throws Exception { throw new MethodNotAllowedException(); } /** * Process a DELETE request. The default implementation does not actually do * anything -- it just throws an exception. */ public View onDelete() throws Exception { throw new MethodNotAllowedException(); } public View onPatch() throws Exception { throw new MethodNotAllowedException(); } /** * Process a POST request. The default implementation does not actually do * anything -- it just throws an exception. */ public View onPost() throws Exception { throw new MethodNotAllowedException(); } /** * Process a PUT request. The default implementation does not actually do * anything -- it just throws an exception. */ public View onPut() throws Exception { throw new MethodNotAllowedException(); } /** * Retrieve the model associated with a page. */ public Map<String, Object> getModel() { return model; } /** * Add a key-value pair to the model. */ void addToModel(String key, Object value) { model.put(key, value); } /** * Retrieve value from the model, using the given key. */ public Object getFromModel(String key) { return model.get(key); } /** * Retrieve the default view name associated with page. */ public String getViewName() { return viewName; } /** * Retrieve the response content type associated with this page. */ public String getContentType() { return contentType; } /** * Set response content type. */ public void setContentType(String contentType) { this.contentType = contentType; } /** * Retrieve page transaction context. */ public TransactionContext getContext() { return context; } /** * Set page transaction context. */ void setContext(TransactionContext context) { this.context = context; } /** * Return page's format tool. By default, we respond with application's * format tool, but pages (subclasses) can create their own. */ public List<QlueVelocityTool> getVelocityTools() { return getApp().getVelocityTools(); } /** * Determine the default view name for this page. */ void determineDefaultViewName(ViewResolver resolver) { viewName = this.getClass().getSimpleName(); } public View initBackend() throws Exception { return null; } /** * This method is invoked right before the main service method. It allows * the page to prepare for request processing. The default implementation * will, on POST request, check that there is a nonce value supplied in the * request, and that the value matches the value stored in the session. It * will also expose the nonce to the model. */ public View checkAccess() throws Exception { if (context.isPost() && getClass().isAnnotationPresent(QluePersistentPage.class)) { verifySessionSecret(); } return null; } protected void verifySessionSecret() throws Exception { BearerToken sessionSecret = getQlueSession().getSessionSecret(); String suppliedSecret = context.getParameter("_secret"); if (suppliedSecret == null) { throw new UnauthorizedException("Secret session token hasn't been provided"); } try { if (sessionSecret.checkMaskedToken(suppliedSecret) == false) { throw new UnauthorizedException("Secret session token mismatch"); } } catch (IllegalArgumentException e) { throw new UnauthorizedException("Invalid secret session token"); } } public View validateParameters() { return null; } public View prepareForService() { return null; } public void startHttpSession() { getQlueSession(); } /** * Does this page has any parameter validation errors? */ protected boolean hasErrors() { return errors.hasErrors(); } /** * Retrieve validation errors. */ public Errors getErrors() { return errors; } /** * Adds a page-specific error message. */ protected void addError(String message) { errors.addError(message); } /** * Adds a field-specific error message. */ public void addError(String param, String message) { errors.addError(param, message); } /** * Retrieve session associated with this page. */ public QlueSession getQlueSession() { /* // This code used to determine who started the HTTP session. try { throw new RuntimeException(); } catch (Exception e) { e.printStackTrace(System.err); } */ return app.getQlueSession(context.getRequest()); } public boolean allowDirectOutput() { return app.allowDirectOutput(); } public boolean isQlueDevMode() { return app.isQlueDevMode(context); } public String getNoParamUri() { return context.getRequestUri(); } /** * Outputs page-specific debugging information. */ void writeDevelopmentInformation(PrintWriter out) { // Page fields out.println(" Id: " + getId()); out.println(" Class: " + this.getClass()); out.println(" State: " + HtmlEncoder.html(getState())); out.println(" Errors {"); // Errors int i = 1; for (Error e : errors.getAllErrors()) { out.print(" " + i++ + ". "); out.print(HtmlEncoder.html(e.getMessage())); if (e.getParam() != null) { out.print(" [field " + HtmlEncoder.html(e.getParam()) + "]"); } out.println(); } out.println(" }"); out.println(""); // Model out.println("<b>Model</b>\n"); Map<String, Object> model = getModel(); TreeMap<String, Object> treeMap = new TreeMap<>(); for (Iterator<String> it = model.keySet().iterator(); it.hasNext(); ) { String name = it.next(); treeMap.put(name, model.get(name)); } Iterator<String> it = treeMap.keySet().iterator(); while (it.hasNext()) { String name = it.next(); Object o = treeMap.get(name); out.println(" " + HtmlEncoder.html(name) + ": " + ((o != null) ? HtmlEncoder.html(o.toString()) : "null")); } } /** * Executes page rollback. The default implementation cleans up resources. */ public void rollback() { } /** * Executes page commit. The default implementation cleans up resources. */ public void commit() { } /** * In the default implementation, we delete any files that were created * during the processing of a multipart/form-data request. */ public void cleanup() { cleanupInvoked = true; deleteFiles(); } /** * Invoked after data validation and binding, but before request processing, * giving the page a chance to initialize itself. This method is invoked * only when the state is STATE_NEW (which means only once for a page). */ public View init() throws Exception { return null; } /** * Delete files created by processing multipart/form-data. */ void deleteFiles() { Object commandObject = getCommandObject(); if (commandObject == null) { return; } // Look for QlueFile instances Field[] fields = commandObject.getClass().getFields(); for (Field f : fields) { if (f.isAnnotationPresent(QlueParameter.class)) { if (QlueFile.class.isAssignableFrom(f.getType())) { // Delete temporary file QlueFile qf = null; try { qf = (QlueFile) f.get(commandObject); if (qf != null) { qf.delete(); } } catch (Exception e) { qlueLog.error("Qlue: Failed deleting file " + qf, e); } } } } } /** * Is page persistent? */ public boolean isPersistent() { return getClass().isAnnotationPresent(QluePersistentPage.class); } /** * This method is invoked after built-in parameter validation fails. The * default implementation will throw an exception for non-persistent pages, * and ignore the problem for persistent pages. */ public View handleParameterValidationFailure() throws Exception { if (isPersistent() == true) { // Persistent pages, by default, have to // explicitly handle their errors. return null; } // We're going to throw an exception here to interrupt normal // page processing. The errors should already be available in // the page, so there's no need for us to add anything else here. throw new BadRequestException(); } public View handleException(Exception e) { // Do nothing by default, let subclasses handle it. return null; } public boolean isCleanupInvoked() { return cleanupInvoked; } void setRoutedResponseHeaders() { for (Map.Entry<String, String> me : context.getResponseHeaders().entrySet()) { context.response.setHeader(me.getKey(), me.getValue()); } } protected boolean validateBean(Object object) { return validateBean(object, null); } protected boolean validateBean(Object object, String parentPath) { return app.doBeanValidation(object, parentPath, this); } protected Object convertJsonToObject(Reader reader, Class<?> type) { return app.convertJsonToObject(reader, type); } /** * Return the default state after INIT. Most persistent pages support * only two states, INIT and IN_PROGRESS, and Qlue will automatically * switch from one to the other unless the page explicitly makes * the transition. Pages can override this method if they wish to * use more meaningful state names. * * @return */ public String getDefaultStateAfterInit() { return Page.STATE_IN_PROGRESS; } }
Qlue: Fixed NPE when writing development information to the page and the model object is null.
src/main/java/com/webkreator/qlue/Page.java
Qlue: Fixed NPE when writing development information to the page and the model object is null.
<ide><path>rc/main/java/com/webkreator/qlue/Page.java <ide> out.println("<b>Model</b>\n"); <ide> <ide> Map<String, Object> model = getModel(); <del> <del> TreeMap<String, Object> treeMap = new TreeMap<>(); <del> <del> for (Iterator<String> it = model.keySet().iterator(); it.hasNext(); ) { <del> String name = it.next(); <del> treeMap.put(name, model.get(name)); <del> } <del> <del> Iterator<String> it = treeMap.keySet().iterator(); <del> while (it.hasNext()) { <del> String name = it.next(); <del> Object o = treeMap.get(name); <del> out.println(" " <del> + HtmlEncoder.html(name) <del> + ": " <del> + ((o != null) ? HtmlEncoder.html(o.toString()) <del> : "null")); <add> if (model != null) { <add> TreeMap<String, Object> treeMap = new TreeMap<>(); <add> <add> for (Iterator<String> it = model.keySet().iterator(); it.hasNext(); ) { <add> String name = it.next(); <add> treeMap.put(name, model.get(name)); <add> } <add> <add> Iterator<String> it = treeMap.keySet().iterator(); <add> while (it.hasNext()) { <add> String name = it.next(); <add> Object o = treeMap.get(name); <add> out.println(" " <add> + HtmlEncoder.html(name) <add> + ": " <add> + ((o != null) ? HtmlEncoder.html(o.toString()) <add> : "null")); <add> } <ide> } <ide> } <ide>
Java
apache-2.0
5f1d4dccd5a34c8ee290cb27178d67b04b6c7d1b
0
google/ground-android,google/ground-android,google/ground-android
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gnd.persistence.remote.firestore.schema; import static com.google.android.gnd.persistence.remote.DataStoreException.checkNotEmpty; import static com.google.android.gnd.persistence.remote.DataStoreException.checkNotNull; import com.google.android.gnd.model.feature.Feature; import com.google.android.gnd.model.form.Form; import com.google.android.gnd.model.observation.MultipleChoiceResponse; import com.google.android.gnd.model.observation.Observation; import com.google.android.gnd.model.observation.ResponseMap; import com.google.android.gnd.model.observation.TextResponse; import com.google.android.gnd.persistence.remote.DataStoreException; import com.google.firebase.firestore.DocumentSnapshot; import java.util.List; import java.util.Map; import java8.util.Objects; import javax.annotation.Nullable; import timber.log.Timber; /** Converts between Firestore documents and {@link Observation} instances. */ class ObservationConverter { static Observation toObservation(Feature feature, DocumentSnapshot snapshot) throws DataStoreException { ObservationDocument doc = snapshot.toObject(ObservationDocument.class); String featureId = checkNotNull(doc.getFeatureId(), "featureId"); String formId = checkNotNull(doc.getFormId(), "formId"); if (!feature.getId().equals(featureId)) { Timber.e("Observation featureId doesn't match specified feature id"); } Form form = checkNotEmpty(feature.getLayer().getForm(formId), "form"); // Degrade gracefully when audit info missing in remote db. AuditInfoNestedObject created = Objects.requireNonNullElse(doc.getCreated(), AuditInfoNestedObject.FALLBACK_VALUE); AuditInfoNestedObject lastModified = Objects.requireNonNullElse(doc.getLastModified(), created); return Observation.newBuilder() .setId(snapshot.getId()) .setProject(feature.getProject()) .setFeature(feature) .setForm(form) .setResponses(toResponseMap(form, doc.getResponses())) .setCreated(AuditInfoConverter.toAuditInfo(created)) .setLastModified(AuditInfoConverter.toAuditInfo(lastModified)) .build(); } private static ResponseMap toResponseMap(Form form, @Nullable Map<String, Object> docResponses) { ResponseMap.Builder responses = ResponseMap.builder(); if (docResponses == null) { return responses.build(); } for (String fieldId : docResponses.keySet()) { Object obj = docResponses.get(fieldId); if (obj instanceof String) { TextResponse.fromString(((String) obj).trim()) .ifPresent(r -> responses.putResponse(fieldId, r)); // TODO(#23): Add support for number fields: // } else if (obj instanceof Float) { // responses.put(key, new NumericResponse((Float) obj)); } else if (obj instanceof List) { MultipleChoiceResponse.fromList((List<String>) obj) .ifPresent(r -> responses.putResponse(fieldId, r)); } else { Timber.e("Unsupported obj in db: %s", obj.getClass().getName()); } } return responses.build(); } }
gnd/src/main/java/com/google/android/gnd/persistence/remote/firestore/schema/ObservationConverter.java
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gnd.persistence.remote.firestore.schema; import static com.google.android.gnd.persistence.remote.DataStoreException.checkNotEmpty; import static com.google.android.gnd.persistence.remote.DataStoreException.checkNotNull; import com.google.android.gnd.model.feature.Feature; import com.google.android.gnd.model.form.Form; import com.google.android.gnd.model.observation.MultipleChoiceResponse; import com.google.android.gnd.model.observation.Observation; import com.google.android.gnd.model.observation.ResponseMap; import com.google.android.gnd.model.observation.TextResponse; import com.google.android.gnd.persistence.remote.DataStoreException; import com.google.firebase.firestore.DocumentSnapshot; import java.util.List; import java.util.Map; import java8.util.Objects; import javax.annotation.Nullable; import timber.log.Timber; /** Converts between Firestore documents and {@link Observation} instances. */ class ObservationConverter { static Observation toObservation(Feature feature, DocumentSnapshot snapshot) throws DataStoreException { ObservationDocument doc = snapshot.toObject(ObservationDocument.class); String featureId = checkNotNull(doc.getFeatureId(), "featureId"); String formId = checkNotNull(doc.getFormId(), "formId"); if (!feature.getId().equals(featureId)) { Timber.e("Observation featureId doesn't match specified feature id"); } Form form = checkNotEmpty(feature.getLayer().getForm(formId), "form"); // Degrade gracefully when audit info missing in remote db. AuditInfoNestedObject created = Objects.requireNonNullElse(doc.getCreated(), AuditInfoNestedObject.FALLBACK_VALUE); AuditInfoNestedObject lastModified = Objects.requireNonNullElse(doc.getLastModified(), created); return Observation.newBuilder() .setId(snapshot.getId()) .setProject(feature.getProject()) .setFeature(feature) .setForm(form) .setResponses(toResponseMap(doc.getResponses())) .setCreated(AuditInfoConverter.toAuditInfo(created)) .setLastModified(AuditInfoConverter.toAuditInfo(lastModified)) .build(); } private static ResponseMap toResponseMap(@Nullable Map<String, Object> docResponses) { ResponseMap.Builder responses = ResponseMap.builder(); if (docResponses == null) { return responses.build(); } for (String fieldId : docResponses.keySet()) { Object obj = docResponses.get(fieldId); if (obj instanceof String) { TextResponse.fromString(((String) obj).trim()) .ifPresent(r -> responses.putResponse(fieldId, r)); // TODO(#23): Add support for number fields: // } else if (obj instanceof Float) { // responses.put(key, new NumericResponse((Float) obj)); } else if (obj instanceof List) { MultipleChoiceResponse.fromList((List<String>) obj) .ifPresent(r -> responses.putResponse(fieldId, r)); } else { Timber.e("Unsupported obj in db: %s", obj.getClass().getName()); } } return responses.build(); } }
Pass Form into remote observation deserializer
gnd/src/main/java/com/google/android/gnd/persistence/remote/firestore/schema/ObservationConverter.java
Pass Form into remote observation deserializer
<ide><path>nd/src/main/java/com/google/android/gnd/persistence/remote/firestore/schema/ObservationConverter.java <ide> .setProject(feature.getProject()) <ide> .setFeature(feature) <ide> .setForm(form) <del> .setResponses(toResponseMap(doc.getResponses())) <add> .setResponses(toResponseMap(form, doc.getResponses())) <ide> .setCreated(AuditInfoConverter.toAuditInfo(created)) <ide> .setLastModified(AuditInfoConverter.toAuditInfo(lastModified)) <ide> .build(); <ide> } <ide> <del> private static ResponseMap toResponseMap(@Nullable Map<String, Object> docResponses) { <add> private static ResponseMap toResponseMap(Form form, @Nullable Map<String, Object> docResponses) { <ide> ResponseMap.Builder responses = ResponseMap.builder(); <ide> if (docResponses == null) { <ide> return responses.build();
JavaScript
mit
9f78caae775aa49cd830f8b0719b03b2388807c6
0
einsteinK/VaeBot,Vaeb/VaeBot
console.log('\n-STARTING-\n'); // ////////////////////////////////////////////////////////////////////////////////////////////// const Auth = require('./Auth.js'); exports.FileSys = require('fs'); exports.DateFormat = require('dateformat'); exports.Request = require('request'); exports.Urban = require('urban'); const TrelloObj = require('node-trello'); exports.Ytdl = require('ytdl-core'); exports.Path = require('path'); exports.NodeOpus = require('node-opus'); exports.Exec = require('child_process').exec; const YtInfoObj = require('youtube-node'); exports.YtInfo = new YtInfoObj(); exports.TrelloHandler = new TrelloObj(Auth.trelloKey, Auth.trelloToken); exports.linkGuilds = [ ['284746138995785729', '309785618932563968'], ]; // ////////////////////////////////////////////////////////////////////////////////////////////// global.index = module.exports; global.has = Object.prototype.hasOwnProperty; global.selfId = '224529399003742210'; global.vaebId = '107593015014486016'; global.Util = require('./Util.js'); global.Data = require('./data/ManageData.js'); global.Trello = require('./core/ManageTrello.js'); global.Mutes = require('./core/ManageMutes.js'); global.Music = require('./core/ManageMusic.js'); global.Cmds = require('./core/ManageCommands.js'); global.Events = require('./core/ManageEvents.js'); global.Discord = require('discord.js'); exports.YtInfo.setKey(Auth.youtube); Discord.GuildMember.prototype.getProp = function (p) { if (this[p] != null) return this[p]; return this.user[p]; }; Discord.User.prototype.getProp = function (p) { return this[p]; }; global.client = new Discord.Client({ disabledEvents: ['TYPING_START'], fetchAllMembers: true, disableEveryone: true, }); // ////////////////////////////////////////////////////////////////////////////////////////////// exports.dailyMutes = []; exports.dailyKicks = []; exports.dailyBans = []; exports.commandTypes = { locked: 'vaeb', staff: 'staff', public: 'null', }; const briefHour = 2; const msToHours = 1 / (1000 * 60 * 60); const dayMS = 24 / msToHours; let madeBriefing = false; global.colAction = 0xF44336; // Log of action, e.g. action from within command global.colUser = 0x4CAF50; // Log of member change global.colMessage = 0xFFEB3B; // Log of message change global.colCommand = 0x2196F3; // Log of command being executed exports.blockedUsers = {}; exports.blockedWords = []; exports.runFuncs = []; // ////////////////////////////////////////////////////////////////////////////////////////////// function setBriefing() { setTimeout(() => { const time1 = new Date(); const time2 = new Date(); time2.setHours(briefHour); time2.setMinutes(0); time2.setSeconds(0); time2.setMilliseconds(0); const t1 = +time1; const t2 = +time2; let t3 = t2 - t1; if (t3 < 0) t3 += dayMS; const channel = client.channels.get('168744024931434498'); // const guild = channel.guild; console.log(`\nSet daily briefing for ${t3 * msToHours} hours\n`); setTimeout(() => { // const upField = { name: '​', value: '​', inline: false }; const muteField = { name: 'Mutes', value: 'No mutes today', inline: false }; // var rightField = {name: "​", value: "​"} const kickField = { name: 'Kicks', value: 'No kicks today', inline: false }; const banField = { name: 'Bans', value: 'No bans today', inline: false }; const embFields = [muteField, kickField, banField]; const embObj = { title: 'Daily Briefing', description: '​', fields: embFields, footer: { text: '>> More info in #vaebot-log <<' }, thumbnail: { url: './resources/avatar.png' }, color: 0x00E676, }; if (exports.dailyMutes.length > 0) { const dataValues = []; for (let i = 0; i < exports.dailyMutes.length; i++) { const nowData = exports.dailyMutes[i]; const userId = nowData[0]; // const userName = nowData[1]; const userReason = nowData[2]; // const userTime = nowData[3]; const targMention = `<@${userId}>`; let reasonStr = ''; if (userReason != null && userReason.trim().length > 0) { reasonStr = ` : ${userReason}`; } dataValues.push(targMention + reasonStr); } muteField.value = dataValues.join('\n\n'); } muteField.value = `​\n${muteField.value}\n​`; if (exports.dailyKicks.length > 0) { const dataValues = []; for (let i = 0; i < exports.dailyKicks.length; i++) { const nowData = exports.dailyKicks[i]; const userId = nowData[0]; // const userName = nowData[1]; const userReason = nowData[2]; const targMention = `<@${userId}>`; let reasonStr = ''; if (userReason != null && userReason.trim().length > 0) { reasonStr = ` : ${userReason}`; } dataValues.push(targMention + reasonStr); } kickField.value = dataValues.join('\n\n'); } kickField.value = `​\n${kickField.value}\n​`; if (exports.dailyBans.length > 0) { const dataValues = []; for (let i = 0; i < exports.dailyBans.length; i++) { const nowData = exports.dailyBans[i]; const userId = nowData[0]; // const userName = nowData[1]; const userReason = nowData[2]; const targMention = `<@${userId}>`; let reasonStr = ''; if (userReason != null && userReason.trim().length > 0) { reasonStr = ` : ${userReason}`; } dataValues.push(targMention + reasonStr); } banField.value = dataValues.join('\n\n'); } banField.value = `​\n${banField.value}\n​`; if (exports.dailyMutes.length > 0 || exports.dailyKicks.length > 0 || exports.dailyBans.length > 0) { channel.send(undefined, { embed: embObj }) .catch(error => console.log(`\n[E_SendBriefing] ${error}`)); } exports.dailyMutes = []; // Reset exports.dailyKicks = []; exports.dailyBans = []; setBriefing(); }, t3); }, 2000); // Let's wait 2 seconds before starting countdown, just in case of floating point errors triggering multiple countdowns } exports.globalBan = { '201740276472086528': true, '75736018761818112': true, '123146298504380416': true, }; function securityFunc(guild, member, sendRoleParam) { const guildName = guild.name; // const guildId = guild.id; const memberId = member.id; const memberName = Util.getFullName(member); let sendRole = sendRoleParam; if (sendRole == null) sendRole = Util.getRole('SendMessages', guild); if (has.call(exports.globalBan, memberId)) { member.kick() .catch(console.error); console.log(`Globally banned user ${memberName} had already joined ${guildName}`); return; } if (sendRole != null) { const isMuted = Mutes.checkMuted(memberId, guild); if (isMuted) { if (Util.hasRole(member, sendRole)) { member.removeRole(sendRole) .catch(console.error); console.log(`Muted user ${memberName} had already joined ${guildName}`); } } else if (!Util.hasRole(member, sendRole)) { member.addRole(sendRole) .catch(console.error); console.log(`Assigned SendMessages to old member ${memberName}`); } } } function setupSecurity(guild) { const sendRole = Util.getRole('SendMessages', guild); console.log(`Setting up security for ${guild.name} (${guild.members.size} members)`); guild.members.forEach((member) => { securityFunc(guild, member, sendRole); }); } function setupSecurityVeil() { const veilGuild = client.guilds.get('284746138995785729'); if (!veilGuild) return console.log('[ERROR_VP] Veil guild not found!'); const guild = client.guilds.get('309785618932563968'); if (!guild) return console.log('[ERROR_VP] New Veil guild not found!'); const veilBuyer = veilGuild.roles.find('name', 'Buyer'); if (!veilBuyer) return console.log('[ERROR_VP] Veil Buyer role not found!'); const newBuyer = guild.roles.find('name', 'Buyer'); if (!newBuyer) return console.log('[ERROR_VP] New Buyer role not found!'); // const guildId = guild.id; // const guildName = guild.name; console.log(`Setting up auto-kick for ${guild.name} (${guild.members.size} members)`); guild.members.forEach((member) => { const memberId = member.id; if (memberId === vaebId) return; const memberName = Util.getFullName(member); const veilMember = Util.getMemberById(memberId, veilGuild); if (!veilMember) { console.log(`[Auto-Old-Kick 1] User not in Veil: ${memberName}`); member.kick() .catch(error => console.log(`\n[E_AutoOldKick1] ${memberName} | ${error}`)); return; } if (!veilMember.roles.has(veilBuyer.id)) { console.log(`[Auto-Old-Kick 2] User does not have Buyer role: ${memberName}`); member.kick() .catch(error => console.log(`\n[E_AutoOldKick2] ${memberName} | ${error}`)); return; } if (!member.roles.has(newBuyer.id)) { member.addRole(newBuyer) .catch(error => console.log(`\n[E_AutoOldAddRole1] ${memberName} | ${error}`)); console.log(`Updated old member with Buyer role: ${memberName}`); } }); return undefined; } // ////////////////////////////////////////////////////////////////////////////////////////////// Cmds.initCommands(); const veilGuilds = { '284746138995785729': true, '309785618932563968': true, }; client.on('ready', () => { console.log(`\nConnected as ${client.user.username}!\n`); if (madeBriefing === false) { madeBriefing = true; setBriefing(); } const nowGuilds = client.guilds; let securityNum = 0; let remaining = nowGuilds.size; const veilGuildsNum = Object.keys(veilGuilds).length; nowGuilds.forEach((guild) => { guild.fetchMembers() .then((newGuild) => { remaining--; if (has.call(veilGuilds, newGuild.id)) { securityNum++; if (securityNum === veilGuildsNum) setupSecurityVeil(); } setupSecurity(newGuild); Trello.setupCache(newGuild); if (remaining === 0) { console.log('\nFetched all Guild members!\n'); Mutes.restartTimeouts(); } }) .catch((error) => { remaining--; console.log(`E_READY_FETCH_MEMBERS: ${error}`); if (remaining === 0) { console.log('\nFetched all Guild members!\n'); Mutes.restartTimeouts(); } }); }); }); client.on('disconnect', (closeEvent) => { console.log('DISCONNECTED'); console.log(closeEvent); console.log(`Code: ${closeEvent.code}`); console.log(`Reason: ${closeEvent.reason}`); console.log(`Clean: ${closeEvent.wasClean}`); }); client.on('guildMemberRemove', (member) => { const guild = member.guild; Events.emit(guild, 'UserLeave', member); const sendLogData = [ 'User Left', guild, member, { name: 'Username', value: member.toString() }, { name: 'Highest Role', value: member.highestRole.name }, ]; Util.sendLog(sendLogData, colUser); }); client.on('guildMemberAdd', (member) => { const guild = member.guild; const guildId = guild.id; const guildName = guild.name; const memberId = member.id; const memberName = Util.getFullName(member); console.log(`User joined: ${memberName} (${memberId}) @ ${guildName}`); if (guildId === '309785618932563968') { const veilGuild = client.guilds.get('284746138995785729'); const veilBuyer = veilGuild.roles.find('name', 'Buyer'); const newBuyer = guild.roles.find('name', 'Buyer'); if (!veilGuild) { console.log('[ERROR_VP] Veil guild not found!'); } else if (!veilBuyer) { console.log('[ERROR_VP] Veil Buyer role not found!'); } else if (!newBuyer) { console.log('[ERROR_VP] New Buyer role not found!'); } else { const veilMember = Util.getMemberById(memberId, veilGuild); if (!veilMember) { console.log(`[Auto-Kick 1] User not in Veil: ${memberName}`); member.kick() .catch(error => console.log(`\n[E_AutoKick1] ${error}`)); return; } if (!veilMember.roles.has(veilBuyer.id)) { console.log(`[Auto-Kick 2] User does not have Buyer role: ${memberName}`); member.kick() .catch(error => console.log(`\n[E_AutoKick2] ${error}`)); return; } member.addRole(newBuyer) .catch(error => console.log(`\n[E_AutoAddRole1] ${error}`)); console.log('Awarded new member with Buyer role'); } } if (has.call(exports.globalBan, memberId)) { member.kick() .catch(console.error); console.log(`Globally banned user ${memberName} joined ${guildName}`); return; } const isMuted = Mutes.checkMuted(memberId, guild); if (isMuted) { console.log(`Muted user ${memberName} joined ${guildName}`); } else { const sendRole = Util.getRole('SendMessages', guild); if (sendRole) { member.addRole(sendRole) .catch(console.error); console.log(`Assigned SendMessages to new member ${memberName}`); } } if (memberId === '280579952263430145') member.setNickname('<- mentally challenged'); Events.emit(guild, 'UserJoin', member); const sendLogData = [ 'User Joined', guild, member, { name: 'Username', value: member.toString() }, ]; Util.sendLog(sendLogData, colUser); }); client.on('guildMemberUpdate', (oldMember, member) => { const guild = member.guild; const previousNick = oldMember.nickname; const nowNick = member.nickname; const oldRoles = oldMember.roles; const nowRoles = member.roles; const rolesAdded = nowRoles.filter(role => (!oldRoles.has(role.id))); const rolesRemoved = oldRoles.filter(role => (!nowRoles.has(role.id))); if (rolesAdded.size > 0) { rolesAdded.forEach((nowRole) => { if ((member.id === '214047714059616257' || member.id === '148931616452902912') && (nowRole.id === '293458258042159104' || nowRole.id === '284761589155102720')) { member.removeRole(nowRole); } if (nowRole.name === 'SendMessages' && Mutes.checkMuted(member.id, guild)) { member.removeRole(nowRole); console.log(`Force re-muted ${Util.getName(member)} (${member.id})`); } else { const sendLogData = [ 'Role Added', guild, member, { name: 'Username', value: member.toString() }, { name: 'Role Name', value: nowRole.name }, ]; Util.sendLog(sendLogData, colUser); } Events.emit(guild, 'UserRoleAdd', member, nowRole); }); } if (rolesRemoved.size > 0) { rolesRemoved.forEach((nowRole) => { if (nowRole.name === 'SendMessages' && !Mutes.checkMuted(member.id, guild)) { member.addRole(nowRole) .catch(console.error); console.log(`Force re-unmuted ${Util.getName(member)} (${member.id})`); } else { const sendLogData = [ 'Role Removed', guild, member, { name: 'Username', value: member.toString() }, { name: 'Role Name', value: nowRole.name }, ]; Util.sendLog(sendLogData, colUser); } Events.emit(guild, 'UserRoleRemove', member, nowRole); }); } if (previousNick !== nowNick) { if (member.id === '280579952263430145' && nowNick !== '<- mentally challenged') member.setNickname('<- mentally challenged'); Events.emit(guild, 'UserNicknameUpdate', member, previousNick, nowNick); const sendLogData = [ 'Nickname Updated', guild, member, { name: 'Username', value: member.toString() }, { name: 'Old Nickname', value: previousNick }, { name: 'New Nickname', value: nowNick }, ]; Util.sendLog(sendLogData, colUser); } }); client.on('messageUpdate', (oldMsgObj, newMsgObj) => { if (newMsgObj == null) return; const channel = newMsgObj.channel; if (channel.name === 'vaebot-log') return; const guild = newMsgObj.guild; const member = newMsgObj.member; const author = newMsgObj.author; const content = newMsgObj.content; const contentLower = content.toLowerCase(); // const isStaff = author.id == vaebId; // const msgId = newMsgObj.id; const oldContent = oldMsgObj.content; for (let i = 0; i < exports.blockedWords.length; i++) { if (contentLower.includes(exports.blockedWords[i].toLowerCase())) { newMsgObj.delete(); return; } } if (exports.runFuncs.length > 0) { for (let i = 0; i < exports.runFuncs.length; i++) { exports.runFuncs[i](newMsgObj, member, channel, guild); } } Events.emit(guild, 'MessageUpdate', member, channel, oldContent, content); if (oldContent !== content) { const sendLogData = [ 'Message Updated', guild, author, { name: 'Username', value: author.toString() }, { name: 'Channel Name', value: channel.toString() }, { name: 'Old Message', value: oldContent }, { name: 'New Message', value: content }, ]; Util.sendLog(sendLogData, colMessage); } }); exports.lockChannel = null; exports.calmSpeed = 7000; exports.slowChat = {}; exports.slowInterval = {}; exports.chatQueue = {}; exports.chatNext = {}; client.on('voiceStateUpdate', (oldMember, member) => { const oldChannel = oldMember.voiceChannel; // May be null const newChannel = member.voiceChannel; // May be null const oldChannelId = oldChannel ? oldChannel.id : null; const newChannelId = newChannel ? newChannel.id : null; // const guild = member.guild; if (member.id === selfId) { if (member.serverMute) { member.setMute(false); console.log('Force removed server-mute from bot'); } if (exports.lockChannel != null && oldChannelId === exports.lockChannel && newChannelId !== exports.lockChannel) { console.log('Force re-joined locked channel'); oldChannel.join(); } } }); /* Audit log types const Actions = { GUILD_UPDATE: 1, CHANNEL_CREATE: 10, CHANNEL_UPDATE: 11, CHANNEL_DELETE: 12, CHANNEL_OVERWRITE_CREATE: 13, CHANNEL_OVERWRITE_UPDATE: 14, CHANNEL_OVERWRITE_DELETE: 15, MEMBER_KICK: 20, MEMBER_PRUNE: 21, MEMBER_BAN_ADD: 22, MEMBER_BAN_REMOVE: 23, MEMBER_UPDATE: 24, MEMBER_ROLE_UPDATE: 25, ROLE_CREATE: 30, ROLE_UPDATE: 31, ROLE_DELETE: 32, INVITE_CREATE: 40, INVITE_UPDATE: 41, INVITE_DELETE: 42, WEBHOOK_CREATE: 50, WEBHOOK_UPDATE: 51, WEBHOOK_DELETE: 52, EMOJI_CREATE: 60, EMOJI_UPDATE: 61, EMOJI_DELETE: 62, MESSAGE_DELETE: 72, }; */ /* function chooseRelevantEntry(entries, options) { if (options.action == null || options.time == null) { console.log(options); console.log('Options did not contain necessary properties'); return undefined; } const strongest = [null, null]; entries.forEach((entry) => { if (entry.action !== options.action || (options.target != null && entry.target.id !== options.target.id)) return; const timeScore = -Math.abs(options.time - entry.createdTimestamp); if (strongest[0] == null || timeScore > strongest[0]) { strongest[0] = timeScore; strongest[1] = entry; } }); return strongest[1]; } */ client.on('messageDelete', (msgObj) => { if (msgObj == null) return; const channel = msgObj.channel; const guild = msgObj.guild; const member = msgObj.member; const author = msgObj.author; const content = msgObj.content; // const evTime = +new Date(); // const contentLower = content.toLowerCase(); // const isStaff = author.id == vaebId; // const msgId = msgObj.id; if (author.id === vaebId) return; Events.emit(guild, 'MessageDelete', member, channel, content); if (guild != null) { setTimeout(() => { guild.fetchAuditLogs({ // user: member, // limit: 1, type: 'MESSAGE_DELETE', }) .then((/* logs */) => { // console.log('[MD] Got audit log data'); // const entry = logs.entries.first(); // console.log(entry); // console.log(entry.executor.toString()); // console.log(entry.target.toString()); const sendLogData = [ 'Message Deleted', guild, author, { name: 'Username', value: author.toString() }, // { name: 'Moderator', value: entry.executor.toString() }, { name: 'Channel Name', value: channel.toString() }, { name: 'Message', value: content }, ]; Util.sendLog(sendLogData, colMessage); }) .catch((error) => { console.log(error); console.log('[MD] Failed to get audit log data'); }); }, 2000); /* setTimeout(() => { guild.fetchAuditLogs({ // user: member, type: 72, }) .then((logs) => { console.log('[MD] Got audit log data'); const entries = logs.entries; const entry = chooseRelevantEntry(entries, { time: evTime, target: author, action: 'MESSAGE_DELETE', }); console.log(entry); console.log(entry.executor.toString()); console.log(entry.target.toString()); const sendLogData = [ 'Message Deleted', guild, author, { name: 'Username', value: author.toString() }, { name: 'Moderator', value: entry.executor.toString() }, { name: 'Channel Name', value: channel.toString() }, { name: 'Message', value: content }, ]; Util.sendLog(sendLogData, colMessage); }) .catch((error) => { console.log(error); console.log('[MD] Failed to get audit log data'); }); }, 5000); */ } }); const messageStamps = {}; const userStatus = {}; const lastWarn = {}; const checkMessages = 5; // (n) const warnGrad = 13.5; // Higher = More Spam (Messages per Second) | 10 = 1 message per second const sameGrad = 4; const muteGrad = 9; const waitTime = 5.5; const endAlert = 15; /* const replaceAll = function (str, search, replacement) { return str.split(search).join(replacement); }; let contentLower = 'lol <qe23> tege <> <e321z> dz'; contentLower = contentLower.replace(/<[^ ]*?[:#@][^ ]*?>/gm, ''); // contentLower = replaceAll(contentLower, ' ', ''); console.log(contentLower); */ /* exports.runFuncs.push((msgObj, speaker, channel, guild) => { // More sensitive if (guild == null || msgObj == null || speaker == null || speaker.user.bot === true || speaker.id === vaebId) return; let contentLower = msgObj.content.toLowerCase(); contentLower = contentLower.replace(/<[^ ]*?[:#@][^ ]*?>/gm, ''); contentLower = Util.replaceAll(contentLower, ' ', ''); contentLower = Util.replaceAll(contentLower, 'one', '1'); contentLower = Util.replaceAll(contentLower, 'won', '1'); contentLower = Util.replaceAll(contentLower, 'uno', '1'); contentLower = Util.replaceAll(contentLower, 'una', '1'); contentLower = Util.replaceAll(contentLower, 'two', '2'); contentLower = Util.replaceAll(contentLower, 'dose', '2'); contentLower = Util.replaceAll(contentLower, 'dos', '2'); contentLower = Util.replaceAll(contentLower, 'too', '2'); contentLower = Util.replaceAll(contentLower, 'to', '2'); contentLower = Util.replaceAll(contentLower, 'three', '3'); contentLower = Util.replaceAll(contentLower, 'tres', '3'); contentLower = Util.replaceAll(contentLower, 'free', '3'); let triggered = false; if (contentLower === '3') { triggered = true; } else { // const trigger = [/11./g, /12[^8]/g, /13./g, /21./g, /22./g, /23./g, /31./g, /32[^h]/g, /33./g, /muteme/g, /onet.?o/g, /threet.?o/g]; // const trigger = [/[123][123][123]/g, /muteme/g]; const trigger = [/[123][^\d]?[^\d]?[123][^\d]?[^\d]?[123]/g, /[123][123]\d/g, /muteme/g]; for (let i = 0; i < trigger.length; i++) { if (trigger[i].test(contentLower)) { triggered = true; break; } } } if (triggered) { Mutes.doMute(speaker, 'Muted Themself', guild, Infinity, channel, speaker.displayName); } }); */ client.on('message', (msgObj) => { const channel = msgObj.channel; if (channel.name === 'vaebot-log') return; const guild = msgObj.guild; let speaker = msgObj.member; let author = msgObj.author; let content = msgObj.content; const authorId = author.id; // if (guild.id !== '166601083584643072') return; if (content.substring(content.length - 5) === ' -del' && authorId === vaebId) { msgObj.delete(); content = content.substring(0, content.length - 5); } let contentLower = content.toLowerCase(); const isStaff = (guild && speaker) ? Util.checkStaff(guild, speaker) : authorId === vaebId; if (exports.blockedUsers[authorId]) { msgObj.delete(); return; } if (!isStaff) { for (let i = 0; i < exports.blockedWords.length; i++) { if (contentLower.includes(exports.blockedWords[i].toLowerCase())) { msgObj.delete(); return; } } } if (guild != null && contentLower.substr(0, 5) === 'sudo ' && authorId === vaebId) { author = Util.getUserById(selfId); speaker = Util.getMemberById(selfId, guild); content = content.substring(5); contentLower = content.toLowerCase(); } if (exports.runFuncs.length > 0) { for (let i = 0; i < exports.runFuncs.length; i++) { exports.runFuncs[i](msgObj, speaker, channel, guild); } } const isMuted = Mutes.checkMuted(author.id, guild); if (guild != null && author.bot === false && content.length > 0 && !isMuted && author.id !== vaebId && author.id !== guild.owner.id) { if (!has.call(userStatus, authorId)) userStatus[authorId] = 0; if (!has.call(messageStamps, authorId)) messageStamps[authorId] = []; const nowStamps = messageStamps[authorId]; const stamp = (+new Date()); nowStamps.unshift({ stamp, message: contentLower }); if (userStatus[authorId] !== 1) { if (nowStamps.length > checkMessages) { nowStamps.splice(checkMessages, nowStamps.length - checkMessages); } if (nowStamps.length >= checkMessages) { const oldStamp = nowStamps[checkMessages - 1].stamp; const elapsed = (stamp - oldStamp) / 1000; const grad1 = (checkMessages / elapsed) * 10; let checkGrad1 = sameGrad; const latestMsg = nowStamps[0].message; for (let i = 0; i < checkMessages; i++) { if (nowStamps[i].message !== latestMsg) { checkGrad1 = warnGrad; break; } } // console.log("User: " + Util.getName(speaker) + " | Elapsed Since " + checkMessages + " Messages: " + elapsed + " | Gradient1: " + grad1); if (grad1 >= checkGrad1) { if (userStatus[authorId] === 0) { console.log(`${Util.getName(speaker)} warned, gradient ${grad1} larger than ${checkGrad1}`); userStatus[authorId] = 1; Util.print(channel, speaker.toString(), 'Warning: If you continue to spam you will be auto-muted'); setTimeout(() => { const lastStamp = nowStamps[0].stamp; setTimeout(() => { let numNew = 0; let checkGrad2 = sameGrad; const newStamp = (+new Date()); const latestMsg2 = nowStamps[0].message; // var origStamp2; for (let i = 0; i < nowStamps.length; i++) { const curStamp = nowStamps[i]; const isFinal = curStamp.stamp === lastStamp; if (isFinal && stamp === lastStamp) break; numNew++; // origStamp2 = curStamp.stamp; if (curStamp.message !== latestMsg2) checkGrad2 = muteGrad; if (isFinal) break; } if (numNew <= 1) { console.log(`[2_] ${Util.getName(speaker)} was put on alert`); lastWarn[authorId] = newStamp; userStatus[authorId] = 2; return; } let numNew2 = 0; let elapsed2 = 0; let grad2 = 0; // var elapsed2 = (newStamp-origStamp2)/1000; // var grad2 = (numNew/elapsed2)*10; for (let i = 2; i < numNew; i++) { const curStamp = nowStamps[i].stamp; const nowElapsed = (newStamp - curStamp) / 1000; const nowGradient = ((i + 1) / nowElapsed) * 10; if (nowGradient > grad2) { grad2 = nowGradient; elapsed2 = nowElapsed; numNew2 = i + 1; } } console.log(`[2] User: ${Util.getName(speaker)} | Messages Since ${elapsed2} Seconds: ${numNew2} | Gradient2: ${grad2}`); if (grad2 >= checkGrad2) { console.log(`[2] ${Util.getName(speaker)} muted, gradient ${grad2} larger than ${checkGrad2}`); Mutes.doMute(speaker, '[Auto-Mute] Spamming', guild, Infinity, channel, 'System'); userStatus[authorId] = 0; } else { console.log(`[2] ${Util.getName(speaker)} was put on alert`); lastWarn[authorId] = newStamp; userStatus[authorId] = 2; } }, waitTime * 1000); }, 350); } else if (userStatus[authorId] === 2) { console.log(`[3] ${Util.getName(speaker)} muted, repeated warns`); Mutes.doMute(speaker, '[Auto-Mute] Spamming', guild, Infinity, channel, 'System'); userStatus[authorId] = 0; } } else if (userStatus[authorId] === 2 && (stamp - lastWarn[authorId]) > (endAlert * 1000)) { console.log(`${Util.getName(speaker)} ended their alert`); userStatus[authorId] = 0; } } } } if (guild != null) { if (Music.guildQueue[guild.id] == null) Music.guildQueue[guild.id] = []; if (Music.guildMusicInfo[guild.id] == null) { Music.guildMusicInfo[guild.id] = { activeSong: null, activeAuthor: null, voteSkips: [], isAuto: false, }; } } if (guild && exports.slowChat[guild.id] && author.bot === false && !isStaff) { const nowTime = +new Date(); if (nowTime > exports.chatNext[guild.id]) { exports.chatNext[guild.id] = nowTime + exports.calmSpeed; } else { msgObj.delete(); const intervalNum = exports.calmSpeed / 1000; // var timeUntilSend = (exports.chatNext[guild.id] - nowTime) / 1000; author.send(`Your message has been deleted. ${guild.name} is temporarily in slow mode, meaning everyone must wait ${intervalNum} seconds after the previous message before they can send one.`); } // exports.chatQueue[guild.id].push(msgObj); } Cmds.checkMessage(msgObj, speaker || author, channel, guild, content, contentLower, authorId, isStaff); if (author.bot === true) { // RETURN IF BOT return; } Events.emit(guild, 'MessageCreate', speaker, channel, msgObj, content); if (contentLower.includes(('��').toLowerCase())) Util.print(channel, '��'); }); // ////////////////////////////////////////////////////////////////////////////////////////////// console.log('-CONNECTING-\n'); client.login(Auth.discordToken); process.on('unhandledRejection', (err) => { console.error(`Uncaught Promise Error: \n${err.stack}`); });
index.js
console.log('\n-STARTING-\n'); // ////////////////////////////////////////////////////////////////////////////////////////////// const Auth = require('./Auth.js'); exports.FileSys = require('fs'); exports.DateFormat = require('dateformat'); exports.Request = require('request'); exports.Urban = require('urban'); const TrelloObj = require('node-trello'); exports.Ytdl = require('ytdl-core'); exports.Path = require('path'); exports.NodeOpus = require('node-opus'); exports.Exec = require('child_process').exec; const YtInfoObj = require('youtube-node'); exports.YtInfo = new YtInfoObj(); exports.TrelloHandler = new TrelloObj(Auth.trelloKey, Auth.trelloToken); exports.linkGuilds = [ ['284746138995785729', '309785618932563968'], ]; // ////////////////////////////////////////////////////////////////////////////////////////////// global.index = module.exports; global.has = Object.prototype.hasOwnProperty; global.selfId = '224529399003742210'; global.vaebId = '107593015014486016'; global.Util = require('./Util.js'); global.Data = require('./data/ManageData.js'); global.Trello = require('./core/ManageTrello.js'); global.Mutes = require('./core/ManageMutes.js'); global.Music = require('./core/ManageMusic.js'); global.Cmds = require('./core/ManageCommands.js'); global.Events = require('./core/ManageEvents.js'); global.Discord = require('discord.js'); exports.YtInfo.setKey(Auth.youtube); Discord.GuildMember.prototype.getProp = function (p) { if (this[p] != null) return this[p]; return this.user[p]; }; Discord.User.prototype.getProp = function (p) { return this[p]; }; global.client = new Discord.Client({ disabledEvents: ['TYPING_START'], fetchAllMembers: true, disableEveryone: true, }); // ////////////////////////////////////////////////////////////////////////////////////////////// exports.dailyMutes = []; exports.dailyKicks = []; exports.dailyBans = []; exports.commandTypes = { locked: 'vaeb', staff: 'staff', public: 'null', }; const briefHour = 2; const msToHours = 1 / (1000 * 60 * 60); const dayMS = 24 / msToHours; let madeBriefing = false; global.colAction = 0xF44336; // Log of action, e.g. action from within command global.colUser = 0x4CAF50; // Log of member change global.colMessage = 0xFFEB3B; // Log of message change global.colCommand = 0x2196F3; // Log of command being executed exports.blockedUsers = {}; exports.blockedWords = []; exports.runFuncs = []; // ////////////////////////////////////////////////////////////////////////////////////////////// function setBriefing() { setTimeout(() => { const time1 = new Date(); const time2 = new Date(); time2.setHours(briefHour); time2.setMinutes(0); time2.setSeconds(0); time2.setMilliseconds(0); const t1 = +time1; const t2 = +time2; let t3 = t2 - t1; if (t3 < 0) t3 += dayMS; const channel = client.channels.get('168744024931434498'); // const guild = channel.guild; console.log(`\nSet daily briefing for ${t3 * msToHours} hours\n`); setTimeout(() => { // const upField = { name: '​', value: '​', inline: false }; const muteField = { name: 'Mutes', value: 'No mutes today', inline: false }; // var rightField = {name: "​", value: "​"} const kickField = { name: 'Kicks', value: 'No kicks today', inline: false }; const banField = { name: 'Bans', value: 'No bans today', inline: false }; const embFields = [muteField, kickField, banField]; const embObj = { title: 'Daily Briefing', description: '​', fields: embFields, footer: { text: '>> More info in #vaebot-log <<' }, thumbnail: { url: './resources/avatar.png' }, color: 0x00E676, }; if (exports.dailyMutes.length > 0) { const dataValues = []; for (let i = 0; i < exports.dailyMutes.length; i++) { const nowData = exports.dailyMutes[i]; const userId = nowData[0]; // const userName = nowData[1]; const userReason = nowData[2]; // const userTime = nowData[3]; const targMention = `<@${userId}>`; let reasonStr = ''; if (userReason != null && userReason.trim().length > 0) { reasonStr = ` : ${userReason}`; } dataValues.push(targMention + reasonStr); } muteField.value = dataValues.join('\n\n'); } muteField.value = `​\n${muteField.value}\n​`; if (exports.dailyKicks.length > 0) { const dataValues = []; for (let i = 0; i < exports.dailyKicks.length; i++) { const nowData = exports.dailyKicks[i]; const userId = nowData[0]; // const userName = nowData[1]; const userReason = nowData[2]; const targMention = `<@${userId}>`; let reasonStr = ''; if (userReason != null && userReason.trim().length > 0) { reasonStr = ` : ${userReason}`; } dataValues.push(targMention + reasonStr); } kickField.value = dataValues.join('\n\n'); } kickField.value = `​\n${kickField.value}\n​`; if (exports.dailyBans.length > 0) { const dataValues = []; for (let i = 0; i < exports.dailyBans.length; i++) { const nowData = exports.dailyBans[i]; const userId = nowData[0]; // const userName = nowData[1]; const userReason = nowData[2]; const targMention = `<@${userId}>`; let reasonStr = ''; if (userReason != null && userReason.trim().length > 0) { reasonStr = ` : ${userReason}`; } dataValues.push(targMention + reasonStr); } banField.value = dataValues.join('\n\n'); } banField.value = `​\n${banField.value}\n​`; if (exports.dailyMutes.length > 0 || exports.dailyKicks.length > 0 || exports.dailyBans.length > 0) { channel.send(undefined, { embed: embObj }) .catch(error => console.log(`\n[E_SendBriefing] ${error}`)); } exports.dailyMutes = []; // Reset exports.dailyKicks = []; exports.dailyBans = []; setBriefing(); }, t3); }, 2000); // Let's wait 2 seconds before starting countdown, just in case of floating point errors triggering multiple countdowns } exports.globalBan = { '201740276472086528': true, '75736018761818112': true, '123146298504380416': true, }; function securityFunc(guild, member, sendRoleParam) { const guildName = guild.name; // const guildId = guild.id; const memberId = member.id; const memberName = Util.getFullName(member); let sendRole = sendRoleParam; if (sendRole == null) sendRole = Util.getRole('SendMessages', guild); if (has.call(exports.globalBan, memberId)) { member.kick() .catch(console.error); console.log(`Globally banned user ${memberName} had already joined ${guildName}`); return; } if (sendRole != null) { const isMuted = Mutes.checkMuted(memberId, guild); if (isMuted) { if (Util.hasRole(member, sendRole)) { member.removeRole(sendRole) .catch(console.error); console.log(`Muted user ${memberName} had already joined ${guildName}`); } } else if (!Util.hasRole(member, sendRole)) { member.addRole(sendRole) .catch(console.error); console.log(`Assigned SendMessages to old member ${memberName}`); } } } function setupSecurity(guild) { const sendRole = Util.getRole('SendMessages', guild); console.log(`Setting up security for ${guild.name} (${guild.members.size} members)`); guild.members.forEach((member) => { securityFunc(guild, member, sendRole); }); } function setupSecurityVeil() { const veilGuild = client.guilds.get('284746138995785729'); if (!veilGuild) return console.log('[ERROR_VP] Veil guild not found!'); const guild = client.guilds.get('309785618932563968'); if (!guild) return console.log('[ERROR_VP] New Veil guild not found!'); const veilBuyer = veilGuild.roles.find('name', 'Buyer'); if (!veilBuyer) return console.log('[ERROR_VP] Veil Buyer role not found!'); const newBuyer = guild.roles.find('name', 'Buyer'); if (!newBuyer) return console.log('[ERROR_VP] New Buyer role not found!'); // const guildId = guild.id; // const guildName = guild.name; console.log(`Setting up auto-kick for ${guild.name} (${guild.members.size} members)`); guild.members.forEach((member) => { const memberId = member.id; if (memberId === vaebId) return; const memberName = Util.getFullName(member); const veilMember = Util.getMemberById(memberId, veilGuild); if (!veilMember) { console.log(`[Auto-Old-Kick 1] User not in Veil: ${memberName}`); member.kick() .catch(error => console.log(`\n[E_AutoOldKick1] ${memberName} | ${error}`)); return; } if (!veilMember.roles.has(veilBuyer.id)) { console.log(`[Auto-Old-Kick 2] User does not have Buyer role: ${memberName}`); member.kick() .catch(error => console.log(`\n[E_AutoOldKick2] ${memberName} | ${error}`)); return; } if (!member.roles.has(newBuyer.id)) { member.addRole(newBuyer) .catch(error => console.log(`\n[E_AutoOldAddRole1] ${memberName} | ${error}`)); console.log(`Updated old member with Buyer role: ${memberName}`); } }); return undefined; } // ////////////////////////////////////////////////////////////////////////////////////////////// Cmds.initCommands(); const veilGuilds = { '284746138995785729': true, '309785618932563968': true, }; client.on('ready', () => { console.log(`\nConnected as ${client.user.username}!\n`); if (madeBriefing === false) { madeBriefing = true; setBriefing(); } const nowGuilds = client.guilds; let securityNum = 0; let remaining = nowGuilds.size; const veilGuildsNum = Object.keys(veilGuilds).length; nowGuilds.forEach((guild) => { guild.fetchMembers() .then((newGuild) => { remaining--; if (has.call(veilGuilds, newGuild.id)) { securityNum++; if (securityNum === veilGuildsNum) setupSecurityVeil(); } setupSecurity(newGuild); Trello.setupCache(newGuild); if (remaining === 0) { console.log('\nFetched all Guild members!\n'); Mutes.restartTimeouts(); } }) .catch((error) => { remaining--; console.log(`E_READY_FETCH_MEMBERS: ${error}`); if (remaining === 0) { console.log('\nFetched all Guild members!\n'); Mutes.restartTimeouts(); } }); }); }); client.on('disconnect', (closeEvent) => { console.log('DISCONNECTED'); console.log(closeEvent); console.log(`Code: ${closeEvent.code}`); console.log(`Reason: ${closeEvent.reason}`); console.log(`Clean: ${closeEvent.wasClean}`); }); client.on('guildMemberRemove', (member) => { const guild = member.guild; Events.emit(guild, 'UserLeave', member); const sendLogData = [ 'User Left', guild, member, { name: 'Username', value: member.toString() }, { name: 'Highest Role', value: member.highestRole.name }, ]; Util.sendLog(sendLogData, colUser); }); client.on('guildMemberAdd', (member) => { const guild = member.guild; const guildId = guild.id; const guildName = guild.name; const memberId = member.id; const memberName = Util.getFullName(member); console.log(`User joined: ${memberName} (${memberId}) @ ${guildName}`); if (guildId === '309785618932563968') { const veilGuild = client.guilds.get('284746138995785729'); const veilBuyer = veilGuild.roles.find('name', 'Buyer'); const newBuyer = guild.roles.find('name', 'Buyer'); if (!veilGuild) { console.log('[ERROR_VP] Veil guild not found!'); } else if (!veilBuyer) { console.log('[ERROR_VP] Veil Buyer role not found!'); } else if (!newBuyer) { console.log('[ERROR_VP] New Buyer role not found!'); } else { const veilMember = Util.getMemberById(memberId, veilGuild); if (!veilMember) { console.log(`[Auto-Kick 1] User not in Veil: ${memberName}`); member.kick() .catch(error => console.log(`\n[E_AutoKick1] ${error}`)); return; } if (!veilMember.roles.has(veilBuyer.id)) { console.log(`[Auto-Kick 2] User does not have Buyer role: ${memberName}`); member.kick() .catch(error => console.log(`\n[E_AutoKick2] ${error}`)); return; } member.addRole(newBuyer) .catch(error => console.log(`\n[E_AutoAddRole1] ${error}`)); console.log('Awarded new member with Buyer role'); } } if (has.call(exports.globalBan, memberId)) { member.kick() .catch(console.error); console.log(`Globally banned user ${memberName} joined ${guildName}`); return; } const isMuted = Mutes.checkMuted(memberId, guild); if (isMuted) { console.log(`Muted user ${memberName} joined ${guildName}`); } else { const sendRole = Util.getRole('SendMessages', guild); if (sendRole) { member.addRole(sendRole) .catch(console.error); console.log(`Assigned SendMessages to new member ${memberName}`); } } // if (memberId == "208661173153824769") member.setNickname("<- weird person"); // if (memberId == "264481367545479180") member.setNickname("devourer of penis"); Events.emit(guild, 'UserJoin', member); const sendLogData = [ 'User Joined', guild, member, { name: 'Username', value: member.toString() }, ]; Util.sendLog(sendLogData, colUser); }); client.on('guildMemberUpdate', (oldMember, member) => { const guild = member.guild; const previousNick = oldMember.nickname; const nowNick = member.nickname; const oldRoles = oldMember.roles; const nowRoles = member.roles; const rolesAdded = nowRoles.filter(role => (!oldRoles.has(role.id))); const rolesRemoved = oldRoles.filter(role => (!nowRoles.has(role.id))); if (rolesAdded.size > 0) { rolesAdded.forEach((nowRole) => { if ((member.id === '214047714059616257' || member.id === '148931616452902912') && (nowRole.id === '293458258042159104' || nowRole.id === '284761589155102720')) { member.removeRole(nowRole); } if (nowRole.name === 'SendMessages' && Mutes.checkMuted(member.id, guild)) { member.removeRole(nowRole); console.log(`Force re-muted ${Util.getName(member)} (${member.id})`); } else { const sendLogData = [ 'Role Added', guild, member, { name: 'Username', value: member.toString() }, { name: 'Role Name', value: nowRole.name }, ]; Util.sendLog(sendLogData, colUser); } Events.emit(guild, 'UserRoleAdd', member, nowRole); }); } if (rolesRemoved.size > 0) { rolesRemoved.forEach((nowRole) => { if (nowRole.name === 'SendMessages' && !Mutes.checkMuted(member.id, guild)) { member.addRole(nowRole) .catch(console.error); console.log(`Force re-unmuted ${Util.getName(member)} (${member.id})`); } else { const sendLogData = [ 'Role Removed', guild, member, { name: 'Username', value: member.toString() }, { name: 'Role Name', value: nowRole.name }, ]; Util.sendLog(sendLogData, colUser); } Events.emit(guild, 'UserRoleRemove', member, nowRole); }); } if (previousNick !== nowNick) { // if (member.id == "208661173153824769" && nowNick != "<- weird person") member.setNickname("<- weird person"); // if (member.id == "264481367545479180" && nowNick != "devourer of penis") member.setNickname("devourer of penis"); // if (member.id == selfId && nowNick != null && nowNick != "") member.setNickname(""); // if (member.id == vaebId && nowNick != null && nowNick != "") member.setNickname(""); Events.emit(guild, 'UserNicknameUpdate', member, previousNick, nowNick); const sendLogData = [ 'Nickname Updated', guild, member, { name: 'Username', value: member.toString() }, { name: 'Old Nickname', value: previousNick }, { name: 'New Nickname', value: nowNick }, ]; Util.sendLog(sendLogData, colUser); } }); client.on('messageUpdate', (oldMsgObj, newMsgObj) => { if (newMsgObj == null) return; const channel = newMsgObj.channel; if (channel.name === 'vaebot-log') return; const guild = newMsgObj.guild; const member = newMsgObj.member; const author = newMsgObj.author; const content = newMsgObj.content; const contentLower = content.toLowerCase(); // const isStaff = author.id == vaebId; // const msgId = newMsgObj.id; const oldContent = oldMsgObj.content; for (let i = 0; i < exports.blockedWords.length; i++) { if (contentLower.includes(exports.blockedWords[i].toLowerCase())) { newMsgObj.delete(); return; } } if (exports.runFuncs.length > 0) { for (let i = 0; i < exports.runFuncs.length; i++) { exports.runFuncs[i](newMsgObj, member, channel, guild); } } Events.emit(guild, 'MessageUpdate', member, channel, oldContent, content); if (oldContent !== content) { const sendLogData = [ 'Message Updated', guild, author, { name: 'Username', value: author.toString() }, { name: 'Channel Name', value: channel.toString() }, { name: 'Old Message', value: oldContent }, { name: 'New Message', value: content }, ]; Util.sendLog(sendLogData, colMessage); } }); exports.lockChannel = null; exports.calmSpeed = 7000; exports.slowChat = {}; exports.slowInterval = {}; exports.chatQueue = {}; exports.chatNext = {}; client.on('voiceStateUpdate', (oldMember, member) => { const oldChannel = oldMember.voiceChannel; // May be null const newChannel = member.voiceChannel; // May be null const oldChannelId = oldChannel ? oldChannel.id : null; const newChannelId = newChannel ? newChannel.id : null; // const guild = member.guild; if (member.id === selfId) { if (member.serverMute) { member.setMute(false); console.log('Force removed server-mute from bot'); } if (exports.lockChannel != null && oldChannelId === exports.lockChannel && newChannelId !== exports.lockChannel) { console.log('Force re-joined locked channel'); oldChannel.join(); } } }); /* Audit log types const Actions = { GUILD_UPDATE: 1, CHANNEL_CREATE: 10, CHANNEL_UPDATE: 11, CHANNEL_DELETE: 12, CHANNEL_OVERWRITE_CREATE: 13, CHANNEL_OVERWRITE_UPDATE: 14, CHANNEL_OVERWRITE_DELETE: 15, MEMBER_KICK: 20, MEMBER_PRUNE: 21, MEMBER_BAN_ADD: 22, MEMBER_BAN_REMOVE: 23, MEMBER_UPDATE: 24, MEMBER_ROLE_UPDATE: 25, ROLE_CREATE: 30, ROLE_UPDATE: 31, ROLE_DELETE: 32, INVITE_CREATE: 40, INVITE_UPDATE: 41, INVITE_DELETE: 42, WEBHOOK_CREATE: 50, WEBHOOK_UPDATE: 51, WEBHOOK_DELETE: 52, EMOJI_CREATE: 60, EMOJI_UPDATE: 61, EMOJI_DELETE: 62, MESSAGE_DELETE: 72, }; */ /* function chooseRelevantEntry(entries, options) { if (options.action == null || options.time == null) { console.log(options); console.log('Options did not contain necessary properties'); return undefined; } const strongest = [null, null]; entries.forEach((entry) => { if (entry.action !== options.action || (options.target != null && entry.target.id !== options.target.id)) return; const timeScore = -Math.abs(options.time - entry.createdTimestamp); if (strongest[0] == null || timeScore > strongest[0]) { strongest[0] = timeScore; strongest[1] = entry; } }); return strongest[1]; } */ client.on('messageDelete', (msgObj) => { if (msgObj == null) return; const channel = msgObj.channel; const guild = msgObj.guild; const member = msgObj.member; const author = msgObj.author; const content = msgObj.content; // const evTime = +new Date(); // const contentLower = content.toLowerCase(); // const isStaff = author.id == vaebId; // const msgId = msgObj.id; if (author.id === vaebId) return; Events.emit(guild, 'MessageDelete', member, channel, content); if (guild != null) { setTimeout(() => { guild.fetchAuditLogs({ // user: member, // limit: 1, type: 'MESSAGE_DELETE', }) .then((/* logs */) => { // console.log('[MD] Got audit log data'); // const entry = logs.entries.first(); // console.log(entry); // console.log(entry.executor.toString()); // console.log(entry.target.toString()); const sendLogData = [ 'Message Deleted', guild, author, { name: 'Username', value: author.toString() }, // { name: 'Moderator', value: entry.executor.toString() }, { name: 'Channel Name', value: channel.toString() }, { name: 'Message', value: content }, ]; Util.sendLog(sendLogData, colMessage); }) .catch((error) => { console.log(error); console.log('[MD] Failed to get audit log data'); }); }, 2000); /* setTimeout(() => { guild.fetchAuditLogs({ // user: member, type: 72, }) .then((logs) => { console.log('[MD] Got audit log data'); const entries = logs.entries; const entry = chooseRelevantEntry(entries, { time: evTime, target: author, action: 'MESSAGE_DELETE', }); console.log(entry); console.log(entry.executor.toString()); console.log(entry.target.toString()); const sendLogData = [ 'Message Deleted', guild, author, { name: 'Username', value: author.toString() }, { name: 'Moderator', value: entry.executor.toString() }, { name: 'Channel Name', value: channel.toString() }, { name: 'Message', value: content }, ]; Util.sendLog(sendLogData, colMessage); }) .catch((error) => { console.log(error); console.log('[MD] Failed to get audit log data'); }); }, 5000); */ } }); const messageStamps = {}; const userStatus = {}; const lastWarn = {}; const checkMessages = 5; // (n) const warnGrad = 13.5; // Higher = More Spam (Messages per Second) | 10 = 1 message per second const sameGrad = 4; const muteGrad = 9; const waitTime = 5.5; const endAlert = 15; /* const replaceAll = function (str, search, replacement) { return str.split(search).join(replacement); }; let contentLower = 'lol <qe23> tege <> <e321z> dz'; contentLower = contentLower.replace(/<[^ ]*?[:#@][^ ]*?>/gm, ''); // contentLower = replaceAll(contentLower, ' ', ''); console.log(contentLower); */ /* exports.runFuncs.push((msgObj, speaker, channel, guild) => { // More sensitive if (guild == null || msgObj == null || speaker == null || speaker.user.bot === true || speaker.id === vaebId) return; let contentLower = msgObj.content.toLowerCase(); contentLower = contentLower.replace(/<[^ ]*?[:#@][^ ]*?>/gm, ''); contentLower = Util.replaceAll(contentLower, ' ', ''); contentLower = Util.replaceAll(contentLower, 'one', '1'); contentLower = Util.replaceAll(contentLower, 'won', '1'); contentLower = Util.replaceAll(contentLower, 'uno', '1'); contentLower = Util.replaceAll(contentLower, 'una', '1'); contentLower = Util.replaceAll(contentLower, 'two', '2'); contentLower = Util.replaceAll(contentLower, 'dose', '2'); contentLower = Util.replaceAll(contentLower, 'dos', '2'); contentLower = Util.replaceAll(contentLower, 'too', '2'); contentLower = Util.replaceAll(contentLower, 'to', '2'); contentLower = Util.replaceAll(contentLower, 'three', '3'); contentLower = Util.replaceAll(contentLower, 'tres', '3'); contentLower = Util.replaceAll(contentLower, 'free', '3'); let triggered = false; if (contentLower === '3') { triggered = true; } else { // const trigger = [/11./g, /12[^8]/g, /13./g, /21./g, /22./g, /23./g, /31./g, /32[^h]/g, /33./g, /muteme/g, /onet.?o/g, /threet.?o/g]; // const trigger = [/[123][123][123]/g, /muteme/g]; const trigger = [/[123][^\d]?[^\d]?[123][^\d]?[^\d]?[123]/g, /[123][123]\d/g, /muteme/g]; for (let i = 0; i < trigger.length; i++) { if (trigger[i].test(contentLower)) { triggered = true; break; } } } if (triggered) { Mutes.doMute(speaker, 'Muted Themself', guild, Infinity, channel, speaker.displayName); } }); */ client.on('message', (msgObj) => { const channel = msgObj.channel; if (channel.name === 'vaebot-log') return; const guild = msgObj.guild; let speaker = msgObj.member; let author = msgObj.author; let content = msgObj.content; const authorId = author.id; // if (guild.id !== '166601083584643072') return; if (content.substring(content.length - 5) === ' -del' && authorId === vaebId) { msgObj.delete(); content = content.substring(0, content.length - 5); } let contentLower = content.toLowerCase(); const isStaff = (guild && speaker) ? Util.checkStaff(guild, speaker) : authorId === vaebId; if (exports.blockedUsers[authorId]) { msgObj.delete(); return; } if (!isStaff) { for (let i = 0; i < exports.blockedWords.length; i++) { if (contentLower.includes(exports.blockedWords[i].toLowerCase())) { msgObj.delete(); return; } } } if (guild != null && contentLower.substr(0, 5) === 'sudo ' && authorId === vaebId) { author = Util.getUserById(selfId); speaker = Util.getMemberById(selfId, guild); content = content.substring(5); contentLower = content.toLowerCase(); } if (exports.runFuncs.length > 0) { for (let i = 0; i < exports.runFuncs.length; i++) { exports.runFuncs[i](msgObj, speaker, channel, guild); } } const isMuted = Mutes.checkMuted(author.id, guild); if (guild != null && author.bot === false && content.length > 0 && !isMuted && author.id !== vaebId && author.id !== guild.owner.id) { if (!has.call(userStatus, authorId)) userStatus[authorId] = 0; if (!has.call(messageStamps, authorId)) messageStamps[authorId] = []; const nowStamps = messageStamps[authorId]; const stamp = (+new Date()); nowStamps.unshift({ stamp, message: contentLower }); if (userStatus[authorId] !== 1) { if (nowStamps.length > checkMessages) { nowStamps.splice(checkMessages, nowStamps.length - checkMessages); } if (nowStamps.length >= checkMessages) { const oldStamp = nowStamps[checkMessages - 1].stamp; const elapsed = (stamp - oldStamp) / 1000; const grad1 = (checkMessages / elapsed) * 10; let checkGrad1 = sameGrad; const latestMsg = nowStamps[0].message; for (let i = 0; i < checkMessages; i++) { if (nowStamps[i].message !== latestMsg) { checkGrad1 = warnGrad; break; } } // console.log("User: " + Util.getName(speaker) + " | Elapsed Since " + checkMessages + " Messages: " + elapsed + " | Gradient1: " + grad1); if (grad1 >= checkGrad1) { if (userStatus[authorId] === 0) { console.log(`${Util.getName(speaker)} warned, gradient ${grad1} larger than ${checkGrad1}`); userStatus[authorId] = 1; Util.print(channel, speaker.toString(), 'Warning: If you continue to spam you will be auto-muted'); setTimeout(() => { const lastStamp = nowStamps[0].stamp; setTimeout(() => { let numNew = 0; let checkGrad2 = sameGrad; const newStamp = (+new Date()); const latestMsg2 = nowStamps[0].message; // var origStamp2; for (let i = 0; i < nowStamps.length; i++) { const curStamp = nowStamps[i]; const isFinal = curStamp.stamp === lastStamp; if (isFinal && stamp === lastStamp) break; numNew++; // origStamp2 = curStamp.stamp; if (curStamp.message !== latestMsg2) checkGrad2 = muteGrad; if (isFinal) break; } if (numNew <= 1) { console.log(`[2_] ${Util.getName(speaker)} was put on alert`); lastWarn[authorId] = newStamp; userStatus[authorId] = 2; return; } let numNew2 = 0; let elapsed2 = 0; let grad2 = 0; // var elapsed2 = (newStamp-origStamp2)/1000; // var grad2 = (numNew/elapsed2)*10; for (let i = 2; i < numNew; i++) { const curStamp = nowStamps[i].stamp; const nowElapsed = (newStamp - curStamp) / 1000; const nowGradient = ((i + 1) / nowElapsed) * 10; if (nowGradient > grad2) { grad2 = nowGradient; elapsed2 = nowElapsed; numNew2 = i + 1; } } console.log(`[2] User: ${Util.getName(speaker)} | Messages Since ${elapsed2} Seconds: ${numNew2} | Gradient2: ${grad2}`); if (grad2 >= checkGrad2) { console.log(`[2] ${Util.getName(speaker)} muted, gradient ${grad2} larger than ${checkGrad2}`); Mutes.doMute(speaker, '[Auto-Mute] Spamming', guild, Infinity, channel, 'System'); userStatus[authorId] = 0; } else { console.log(`[2] ${Util.getName(speaker)} was put on alert`); lastWarn[authorId] = newStamp; userStatus[authorId] = 2; } }, waitTime * 1000); }, 350); } else if (userStatus[authorId] === 2) { console.log(`[3] ${Util.getName(speaker)} muted, repeated warns`); Mutes.doMute(speaker, '[Auto-Mute] Spamming', guild, Infinity, channel, 'System'); userStatus[authorId] = 0; } } else if (userStatus[authorId] === 2 && (stamp - lastWarn[authorId]) > (endAlert * 1000)) { console.log(`${Util.getName(speaker)} ended their alert`); userStatus[authorId] = 0; } } } } if (guild != null) { if (Music.guildQueue[guild.id] == null) Music.guildQueue[guild.id] = []; if (Music.guildMusicInfo[guild.id] == null) { Music.guildMusicInfo[guild.id] = { activeSong: null, activeAuthor: null, voteSkips: [], isAuto: false, }; } } if (guild && exports.slowChat[guild.id] && author.bot === false && !isStaff) { const nowTime = +new Date(); if (nowTime > exports.chatNext[guild.id]) { exports.chatNext[guild.id] = nowTime + exports.calmSpeed; } else { msgObj.delete(); const intervalNum = exports.calmSpeed / 1000; // var timeUntilSend = (exports.chatNext[guild.id] - nowTime) / 1000; author.send(`Your message has been deleted. ${guild.name} is temporarily in slow mode, meaning everyone must wait ${intervalNum} seconds after the previous message before they can send one.`); } // exports.chatQueue[guild.id].push(msgObj); } Cmds.checkMessage(msgObj, speaker || author, channel, guild, content, contentLower, authorId, isStaff); if (author.bot === true) { // RETURN IF BOT return; } Events.emit(guild, 'MessageCreate', speaker, channel, msgObj, content); if (contentLower.includes(('��').toLowerCase())) Util.print(channel, '��'); }); // ////////////////////////////////////////////////////////////////////////////////////////////// console.log('-CONNECTING-\n'); client.login(Auth.discordToken); process.on('unhandledRejection', (err) => { console.error(`Uncaught Promise Error: \n${err.stack}`); });
minor
index.js
minor
<ide><path>ndex.js <ide> } <ide> } <ide> <del> // if (memberId == "208661173153824769") member.setNickname("<- weird person"); <del> // if (memberId == "264481367545479180") member.setNickname("devourer of penis"); <add> if (memberId === '280579952263430145') member.setNickname('<- mentally challenged'); <ide> <ide> Events.emit(guild, 'UserJoin', member); <ide> <ide> } <ide> <ide> if (previousNick !== nowNick) { <del> // if (member.id == "208661173153824769" && nowNick != "<- weird person") member.setNickname("<- weird person"); <del> // if (member.id == "264481367545479180" && nowNick != "devourer of penis") member.setNickname("devourer of penis"); <del> // if (member.id == selfId && nowNick != null && nowNick != "") member.setNickname(""); <del> // if (member.id == vaebId && nowNick != null && nowNick != "") member.setNickname(""); <add> if (member.id === '280579952263430145' && nowNick !== '<- mentally challenged') member.setNickname('<- mentally challenged'); <ide> Events.emit(guild, 'UserNicknameUpdate', member, previousNick, nowNick); <ide> <ide> const sendLogData = [
Java
agpl-3.0
5d3c45d2c0063782e63b59ff8e28832e9f2b3663
0
roidelapluie/Gadgetbridge,roidelapluie/Gadgetbridge,ivanovlev/Gadgetbridge,rosenpin/Gadgetbridge,ivanovlev/Gadgetbridge,Freeyourgadget/Gadgetbridge,rosenpin/Gadgetbridge,Freeyourgadget/Gadgetbridge,rosenpin/Gadgetbridge,ivanovlev/Gadgetbridge,roidelapluie/Gadgetbridge,Freeyourgadget/Gadgetbridge,Freeyourgadget/Gadgetbridge
package nodomain.freeyourgadget.gadgetbridge.service.devices.miband2.operations; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCharacteristic; import android.content.SharedPreferences; import android.support.annotation.NonNull; import android.widget.Toast; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.text.DateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; import java.util.UUID; import java.util.concurrent.TimeUnit; import nodomain.freeyourgadget.gadgetbridge.GBApplication; import nodomain.freeyourgadget.gadgetbridge.Logging; import nodomain.freeyourgadget.gadgetbridge.R; import nodomain.freeyourgadget.gadgetbridge.database.DBHandler; import nodomain.freeyourgadget.gadgetbridge.database.DBHelper; import nodomain.freeyourgadget.gadgetbridge.devices.SampleProvider; import nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBand2Service; import nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandSampleProvider; import nodomain.freeyourgadget.gadgetbridge.entities.DaoSession; import nodomain.freeyourgadget.gadgetbridge.entities.Device; import nodomain.freeyourgadget.gadgetbridge.entities.MiBandActivitySample; import nodomain.freeyourgadget.gadgetbridge.entities.User; import nodomain.freeyourgadget.gadgetbridge.service.btle.BLETypeConversions; import nodomain.freeyourgadget.gadgetbridge.service.btle.TransactionBuilder; import nodomain.freeyourgadget.gadgetbridge.service.btle.actions.SetDeviceBusyAction; import nodomain.freeyourgadget.gadgetbridge.service.btle.actions.WaitAction; import nodomain.freeyourgadget.gadgetbridge.service.devices.miband2.MiBand2Support; import nodomain.freeyourgadget.gadgetbridge.service.devices.miband2.AbstractMiBand2Operation; import nodomain.freeyourgadget.gadgetbridge.util.ArrayUtils; import nodomain.freeyourgadget.gadgetbridge.util.DateTimeUtils; import nodomain.freeyourgadget.gadgetbridge.util.GB; /** * An operation that fetches activity data. For every fetch, a new operation must * be created, i.e. an operation may not be reused for multiple fetches. */ public class FetchActivityOperation extends AbstractMiBand2Operation { private static final Logger LOG = LoggerFactory.getLogger(FetchActivityOperation.class); private List<MiBandActivitySample> samples = new ArrayList<>(60*24); // 1day per default private byte lastPacketCounter = -1; private Calendar startTimestamp; public FetchActivityOperation(MiBand2Support support) { super(support); } @Override protected void enableNeededNotifications(TransactionBuilder builder, boolean enable) { if (!enable) { // dynamically enabled, but always disabled on finish builder.notify(getCharacteristic(MiBand2Service.UUID_CHARACTERISTIC_5_ACTIVITY_DATA), enable); } } @Override protected void doPerform() throws IOException { TransactionBuilder builder = performInitialized("fetching activity data"); getSupport().setLowLatency(builder); builder.add(new SetDeviceBusyAction(getDevice(), getContext().getString(R.string.busy_task_fetch_activity_data), getContext())); BluetoothGattCharacteristic characteristicFetch = getCharacteristic(MiBand2Service.UUID_UNKNOWN_CHARACTERISTIC4); builder.notify(characteristicFetch, true); BluetoothGattCharacteristic characteristicActivityData = getCharacteristic(MiBand2Service.UUID_CHARACTERISTIC_5_ACTIVITY_DATA); GregorianCalendar sinceWhen = getLastSuccessfulSyncTime(); builder.write(characteristicFetch, BLETypeConversions.join(new byte[] { MiBand2Service.COMMAND_ACTIVITY_DATA_START_DATE, 0x01 }, getSupport().getTimeBytes(sinceWhen, TimeUnit.MINUTES))); builder.add(new WaitAction(1000)); // TODO: actually wait for the success-reply builder.notify(characteristicActivityData, true); builder.write(characteristicFetch, new byte[] { MiBand2Service.COMMAND_FETCH_ACTIVITY_DATA }); builder.queue(getQueue()); } private GregorianCalendar getLastSuccessfulSyncTime() { long timeStampMillis = GBApplication.getPrefs().getLong(getLastSyncTimeKey(), 0); if (timeStampMillis != 0) { GregorianCalendar calendar = BLETypeConversions.createCalendar(); calendar.setTimeInMillis(timeStampMillis); return calendar; } GregorianCalendar calendar = BLETypeConversions.createCalendar(); calendar.add(Calendar.DAY_OF_MONTH, -10); return calendar; } private void saveLastSyncTimestamp(@NonNull GregorianCalendar timestamp) { SharedPreferences.Editor editor = GBApplication.getPrefs().getPreferences().edit(); editor.putLong(getLastSyncTimeKey(), timestamp.getTimeInMillis()); editor.apply(); } private String getLastSyncTimeKey() { return getDevice().getAddress() + "_" + "lastSyncTimeMillis"; } @Override public boolean onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { UUID characteristicUUID = characteristic.getUuid(); if (MiBand2Service.UUID_CHARACTERISTIC_5_ACTIVITY_DATA.equals(characteristicUUID)) { handleActivityNotif(characteristic.getValue()); return true; } else if (MiBand2Service.UUID_UNKNOWN_CHARACTERISTIC4.equals(characteristicUUID)) { handleActivityMetadata(characteristic.getValue()); return true; } else { return super.onCharacteristicChanged(gatt, characteristic); } } private void handleActivityFetchFinish() { LOG.info("Fetching activity data has finished."); saveSamples(); operationFinished(); unsetBusy(); } private void saveSamples() { if (samples.size() > 0) { // save all the samples that we got try (DBHandler handler = GBApplication.acquireDB()) { DaoSession session = handler.getDaoSession(); SampleProvider<MiBandActivitySample> sampleProvider = new MiBandSampleProvider(getDevice(), session); Device device = DBHelper.getDevice(getDevice(), session); User user = DBHelper.getUser(session); GregorianCalendar timestamp = (GregorianCalendar) startTimestamp.clone(); for (MiBandActivitySample sample : samples) { sample.setDevice(device); sample.setUser(user); sample.setTimestamp((int) (timestamp.getTimeInMillis() / 1000)); sample.setProvider(sampleProvider); if (LOG.isDebugEnabled()) { // LOG.debug("sample: " + sample); } timestamp.add(Calendar.MINUTE, 1); } sampleProvider.addGBActivitySamples(samples.toArray(new MiBandActivitySample[0])); saveLastSyncTimestamp(timestamp); LOG.info("Mi2 activity data: last sample timestamp: " + DateTimeUtils.formatDateTime(timestamp.getTime())); } catch (Exception ex) { GB.toast(getContext(), "Error saving activity samples", Toast.LENGTH_LONG, GB.ERROR); } finally { samples.clear(); } } } /** * Method to handle the incoming activity data. * There are two kind of messages we currently know: * - the first one is 11 bytes long and contains metadata (how many bytes to expect, when the data starts, etc.) * - the second one is 20 bytes long and contains the actual activity data * <p/> * The first message type is parsed by this method, for every other length of the value param, bufferActivityData is called. * * @param value */ private void handleActivityNotif(byte[] value) { if (!isOperationRunning()) { LOG.error("ignoring activity data notification because operation is not running. Data length: " + value.length); getSupport().logMessageContent(value); return; } if ((value.length % 4) == 1) { if ((byte) (lastPacketCounter + 1) == value[0] ) { lastPacketCounter++; bufferActivityData(value); } else { GB.toast("Error fetching activity data, invalid package counter: " + value[0], Toast.LENGTH_LONG, GB.ERROR); handleActivityFetchFinish(); return; } } else { GB.toast("Error fetching activity data, unexpected package length: " + value.length, Toast.LENGTH_LONG, GB.ERROR); } } /** * Creates samples from the given 17-length array * @param value */ private void bufferActivityData(byte[] value) { int len = value.length; if (len % 4 != 1) { throw new AssertionError("Unexpected activity array size: " + value); } for (int i = 1; i < len; i+=4) { MiBandActivitySample sample = createSample(value[i], value[i + 1], value[i + 2], value[i + 3]); samples.add(sample); } } private MiBandActivitySample createSample(byte category, byte intensity, byte steps, byte heartrate) { MiBandActivitySample sample = new MiBandActivitySample(); sample.setRawKind(category & 0xff); sample.setRawIntensity(intensity & 0xff); sample.setSteps(steps & 0xff); sample.setHeartRate(heartrate & 0xff); return sample; } private void handleActivityMetadata(byte[] value) { if (value.length == 15) { // first two bytes are whether our request was accepted if (ArrayUtils.equals(value, MiBand2Service.RESPONSE_ACTIVITY_DATA_START_DATE_SUCCESS, 0)) { // the third byte (0x01 on success) = ? // the 4th - 7th bytes probably somehow represent the number of bytes/packets to expect // last 8 bytes are the start date Calendar startTimestamp = getSupport().fromTimeBytes(org.apache.commons.lang3.ArrayUtils.subarray(value, 7, value.length)); setStartTimestamp(startTimestamp); GB.toast(getContext().getString(R.string.FetchActivityOperation_about_to_transfer_since, DateFormat.getDateTimeInstance().format(startTimestamp.getTime())), Toast.LENGTH_LONG, GB.INFO); } else { LOG.warn("Unexpected activity metadata: " + Logging.formatBytes(value)); handleActivityFetchFinish(); } } else if (value.length == 3) { if (Arrays.equals(MiBand2Service.RESPONSE_FINISH_SUCCESS, value)) { handleActivityFetchFinish(); } else { LOG.warn("Unexpected activity metadata: " + Logging.formatBytes(value)); handleActivityFetchFinish(); } } } private void setStartTimestamp(Calendar startTimestamp) { this.startTimestamp = startTimestamp; } }
app/src/main/java/nodomain/freeyourgadget/gadgetbridge/service/devices/miband2/operations/FetchActivityOperation.java
package nodomain.freeyourgadget.gadgetbridge.service.devices.miband2.operations; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCharacteristic; import android.widget.Toast; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.text.DateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; import java.util.UUID; import java.util.concurrent.TimeUnit; import nodomain.freeyourgadget.gadgetbridge.GBApplication; import nodomain.freeyourgadget.gadgetbridge.Logging; import nodomain.freeyourgadget.gadgetbridge.R; import nodomain.freeyourgadget.gadgetbridge.database.DBHandler; import nodomain.freeyourgadget.gadgetbridge.database.DBHelper; import nodomain.freeyourgadget.gadgetbridge.devices.SampleProvider; import nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBand2SampleProvider; import nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBand2Service; import nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandSampleProvider; import nodomain.freeyourgadget.gadgetbridge.entities.DaoSession; import nodomain.freeyourgadget.gadgetbridge.entities.Device; import nodomain.freeyourgadget.gadgetbridge.entities.MiBandActivitySample; import nodomain.freeyourgadget.gadgetbridge.entities.User; import nodomain.freeyourgadget.gadgetbridge.service.btle.BLETypeConversions; import nodomain.freeyourgadget.gadgetbridge.service.btle.TransactionBuilder; import nodomain.freeyourgadget.gadgetbridge.service.btle.actions.SetDeviceBusyAction; import nodomain.freeyourgadget.gadgetbridge.service.btle.actions.WaitAction; import nodomain.freeyourgadget.gadgetbridge.service.devices.miband2.MiBand2Support; import nodomain.freeyourgadget.gadgetbridge.service.devices.miband2.AbstractMiBand2Operation; import nodomain.freeyourgadget.gadgetbridge.util.ArrayUtils; import nodomain.freeyourgadget.gadgetbridge.util.DateTimeUtils; import nodomain.freeyourgadget.gadgetbridge.util.GB; /** * An operation that fetches activity data. For every fetch, a new operation must * be created, i.e. an operation may not be reused for multiple fetches. */ public class FetchActivityOperation extends AbstractMiBand2Operation { private static final Logger LOG = LoggerFactory.getLogger(FetchActivityOperation.class); private List<MiBandActivitySample> samples = new ArrayList<>(60*24); // 1day per default private byte lastPacketCounter = -1; private Calendar startTimestamp; public FetchActivityOperation(MiBand2Support support) { super(support); } @Override protected void enableNeededNotifications(TransactionBuilder builder, boolean enable) { if (!enable) { // dynamically enabled, but always disabled on finish builder.notify(getCharacteristic(MiBand2Service.UUID_CHARACTERISTIC_5_ACTIVITY_DATA), enable); } } @Override protected void doPerform() throws IOException { TransactionBuilder builder = performInitialized("fetching activity data"); getSupport().setLowLatency(builder); builder.add(new SetDeviceBusyAction(getDevice(), getContext().getString(R.string.busy_task_fetch_activity_data), getContext())); BluetoothGattCharacteristic characteristicFetch = getCharacteristic(MiBand2Service.UUID_UNKNOWN_CHARACTERISTIC4); builder.notify(characteristicFetch, true); BluetoothGattCharacteristic characteristicActivityData = getCharacteristic(MiBand2Service.UUID_CHARACTERISTIC_5_ACTIVITY_DATA); GregorianCalendar sinceWhen = getLastSuccessfulSynchronizedTime(); builder.write(characteristicFetch, BLETypeConversions.join(new byte[] { MiBand2Service.COMMAND_ACTIVITY_DATA_START_DATE, 0x01 }, getSupport().getTimeBytes(sinceWhen, TimeUnit.MINUTES))); builder.add(new WaitAction(1000)); // TODO: actually wait for the success-reply builder.notify(characteristicActivityData, true); builder.write(characteristicFetch, new byte[] { MiBand2Service.COMMAND_FETCH_ACTIVITY_DATA }); builder.queue(getQueue()); } private GregorianCalendar getLastSuccessfulSynchronizedTime() { try (DBHandler dbHandler = GBApplication.acquireDB()) { DaoSession session = dbHandler.getDaoSession(); SampleProvider<MiBandActivitySample> sampleProvider = new MiBand2SampleProvider(getDevice(), session); MiBandActivitySample sample = sampleProvider.getLatestActivitySample(); if (sample != null) { int timestamp = sample.getTimestamp(); GregorianCalendar calendar = BLETypeConversions.createCalendar(); calendar.setTimeInMillis((long) timestamp * 1000); return calendar; } } catch (Exception ex) { LOG.error("Error querying for latest activity sample, synchronizing the last 10 days", ex); } GregorianCalendar calendar = BLETypeConversions.createCalendar(); calendar.add(Calendar.DAY_OF_MONTH, -10); return calendar; } @Override public boolean onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { UUID characteristicUUID = characteristic.getUuid(); if (MiBand2Service.UUID_CHARACTERISTIC_5_ACTIVITY_DATA.equals(characteristicUUID)) { handleActivityNotif(characteristic.getValue()); return true; } else if (MiBand2Service.UUID_UNKNOWN_CHARACTERISTIC4.equals(characteristicUUID)) { handleActivityMetadata(characteristic.getValue()); return true; } else { return super.onCharacteristicChanged(gatt, characteristic); } } private void handleActivityFetchFinish() { LOG.info("Fetching activity data has finished."); saveSamples(); operationFinished(); unsetBusy(); } private void saveSamples() { if (samples.size() > 0) { // save all the samples that we got try (DBHandler handler = GBApplication.acquireDB()) { DaoSession session = handler.getDaoSession(); SampleProvider<MiBandActivitySample> sampleProvider = new MiBandSampleProvider(getDevice(), session); Device device = DBHelper.getDevice(getDevice(), session); User user = DBHelper.getUser(session); GregorianCalendar timestamp = (GregorianCalendar) startTimestamp.clone(); for (MiBandActivitySample sample : samples) { sample.setDevice(device); sample.setUser(user); sample.setTimestamp((int) (timestamp.getTimeInMillis() / 1000)); sample.setProvider(sampleProvider); if (LOG.isDebugEnabled()) { // LOG.debug("sample: " + sample); } timestamp.add(Calendar.MINUTE, 1); } sampleProvider.addGBActivitySamples(samples.toArray(new MiBandActivitySample[0])); LOG.info("Mi2 activity data: last sample timestamp: " + DateTimeUtils.formatDateTime(timestamp.getTime())); } catch (Exception ex) { GB.toast(getContext(), "Error saving activity samples", Toast.LENGTH_LONG, GB.ERROR); } finally { samples.clear(); } } } /** * Method to handle the incoming activity data. * There are two kind of messages we currently know: * - the first one is 11 bytes long and contains metadata (how many bytes to expect, when the data starts, etc.) * - the second one is 20 bytes long and contains the actual activity data * <p/> * The first message type is parsed by this method, for every other length of the value param, bufferActivityData is called. * * @param value */ private void handleActivityNotif(byte[] value) { if (!isOperationRunning()) { LOG.error("ignoring activity data notification because operation is not running. Data length: " + value.length); getSupport().logMessageContent(value); return; } if ((value.length % 4) == 1) { if ((byte) (lastPacketCounter + 1) == value[0] ) { lastPacketCounter++; bufferActivityData(value); } else { GB.toast("Error fetching activity data, invalid package counter: " + value[0], Toast.LENGTH_LONG, GB.ERROR); handleActivityFetchFinish(); return; } } else { GB.toast("Error fetching activity data, unexpected package length: " + value.length, Toast.LENGTH_LONG, GB.ERROR); } } /** * Creates samples from the given 17-length array * @param value */ private void bufferActivityData(byte[] value) { int len = value.length; if (len % 4 != 1) { throw new AssertionError("Unexpected activity array size: " + value); } for (int i = 1; i < len; i+=4) { MiBandActivitySample sample = createSample(value[i], value[i + 1], value[i + 2], value[i + 3]); samples.add(sample); } } private MiBandActivitySample createSample(byte category, byte intensity, byte steps, byte heartrate) { MiBandActivitySample sample = new MiBandActivitySample(); sample.setRawKind(category & 0xff); sample.setRawIntensity(intensity & 0xff); sample.setSteps(steps & 0xff); sample.setHeartRate(heartrate & 0xff); return sample; } private void handleActivityMetadata(byte[] value) { if (value.length == 15) { // first two bytes are whether our request was accepted if (ArrayUtils.equals(value, MiBand2Service.RESPONSE_ACTIVITY_DATA_START_DATE_SUCCESS, 0)) { // the third byte (0x01 on success) = ? // the 4th - 7th bytes probably somehow represent the number of bytes/packets to expect // last 8 bytes are the start date Calendar startTimestamp = getSupport().fromTimeBytes(org.apache.commons.lang3.ArrayUtils.subarray(value, 7, value.length)); setStartTimestamp(startTimestamp); GB.toast(getContext().getString(R.string.FetchActivityOperation_about_to_transfer_since, DateFormat.getDateTimeInstance().format(startTimestamp.getTime())), Toast.LENGTH_LONG, GB.INFO); } else { LOG.warn("Unexpected activity metadata: " + Logging.formatBytes(value)); handleActivityFetchFinish(); } } else if (value.length == 3) { if (Arrays.equals(MiBand2Service.RESPONSE_FINISH_SUCCESS, value)) { handleActivityFetchFinish(); } else { LOG.warn("Unexpected activity metadata: " + Logging.formatBytes(value)); handleActivityFetchFinish(); } } } private void setStartTimestamp(Calendar startTimestamp) { this.startTimestamp = startTimestamp; } }
Mi2: Remember and use last synced timestamp in preferences (instead of using the last sample's timestamp in the database. The database also contains manual hr measurements and live activity samples, so we would miss activity data before the last manual measurement. Closes #478
app/src/main/java/nodomain/freeyourgadget/gadgetbridge/service/devices/miband2/operations/FetchActivityOperation.java
Mi2: Remember and use last synced timestamp in preferences
<ide><path>pp/src/main/java/nodomain/freeyourgadget/gadgetbridge/service/devices/miband2/operations/FetchActivityOperation.java <ide> <ide> import android.bluetooth.BluetoothGatt; <ide> import android.bluetooth.BluetoothGattCharacteristic; <add>import android.content.SharedPreferences; <add>import android.support.annotation.NonNull; <ide> import android.widget.Toast; <ide> <ide> import org.slf4j.Logger; <ide> import nodomain.freeyourgadget.gadgetbridge.database.DBHandler; <ide> import nodomain.freeyourgadget.gadgetbridge.database.DBHelper; <ide> import nodomain.freeyourgadget.gadgetbridge.devices.SampleProvider; <del>import nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBand2SampleProvider; <ide> import nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBand2Service; <ide> import nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandSampleProvider; <ide> import nodomain.freeyourgadget.gadgetbridge.entities.DaoSession; <ide> builder.notify(characteristicFetch, true); <ide> BluetoothGattCharacteristic characteristicActivityData = getCharacteristic(MiBand2Service.UUID_CHARACTERISTIC_5_ACTIVITY_DATA); <ide> <del> GregorianCalendar sinceWhen = getLastSuccessfulSynchronizedTime(); <add> GregorianCalendar sinceWhen = getLastSuccessfulSyncTime(); <ide> builder.write(characteristicFetch, BLETypeConversions.join(new byte[] { MiBand2Service.COMMAND_ACTIVITY_DATA_START_DATE, 0x01 }, getSupport().getTimeBytes(sinceWhen, TimeUnit.MINUTES))); <ide> builder.add(new WaitAction(1000)); // TODO: actually wait for the success-reply <ide> builder.notify(characteristicActivityData, true); <ide> builder.queue(getQueue()); <ide> } <ide> <del> private GregorianCalendar getLastSuccessfulSynchronizedTime() { <del> try (DBHandler dbHandler = GBApplication.acquireDB()) { <del> DaoSession session = dbHandler.getDaoSession(); <del> SampleProvider<MiBandActivitySample> sampleProvider = new MiBand2SampleProvider(getDevice(), session); <del> MiBandActivitySample sample = sampleProvider.getLatestActivitySample(); <del> if (sample != null) { <del> int timestamp = sample.getTimestamp(); <del> GregorianCalendar calendar = BLETypeConversions.createCalendar(); <del> calendar.setTimeInMillis((long) timestamp * 1000); <del> return calendar; <del> } <del> } catch (Exception ex) { <del> LOG.error("Error querying for latest activity sample, synchronizing the last 10 days", ex); <del> } <del> <add> private GregorianCalendar getLastSuccessfulSyncTime() { <add> long timeStampMillis = GBApplication.getPrefs().getLong(getLastSyncTimeKey(), 0); <add> if (timeStampMillis != 0) { <add> GregorianCalendar calendar = BLETypeConversions.createCalendar(); <add> calendar.setTimeInMillis(timeStampMillis); <add> return calendar; <add> } <ide> GregorianCalendar calendar = BLETypeConversions.createCalendar(); <ide> calendar.add(Calendar.DAY_OF_MONTH, -10); <ide> return calendar; <add> } <add> <add> private void saveLastSyncTimestamp(@NonNull GregorianCalendar timestamp) { <add> SharedPreferences.Editor editor = GBApplication.getPrefs().getPreferences().edit(); <add> editor.putLong(getLastSyncTimeKey(), timestamp.getTimeInMillis()); <add> editor.apply(); <add> } <add> <add> private String getLastSyncTimeKey() { <add> return getDevice().getAddress() + "_" + "lastSyncTimeMillis"; <ide> } <ide> <ide> @Override <ide> } <ide> sampleProvider.addGBActivitySamples(samples.toArray(new MiBandActivitySample[0])); <ide> <add> saveLastSyncTimestamp(timestamp); <ide> LOG.info("Mi2 activity data: last sample timestamp: " + DateTimeUtils.formatDateTime(timestamp.getTime())); <ide> <ide> } catch (Exception ex) {
JavaScript
mit
0f4711f52ff0cb13556f9bc53bb2396a41fa7ae0
0
phodal/growth-ng,phodal/growth-ng,phodal/growth-ng,phodal/growth-ng,phodal/growth-ng,phodal/growth-ng
import React, { PropTypes } from 'react'; import { View } from 'react-native'; import htmlParse from '../../lib/htmlParse'; import H from './H'; import Bloackquote from './Blockquote'; import P from './P'; import Ul from './Ul'; import Ol from './Ol'; import Li from './Li'; import Img from './Img'; import A from './A'; import Pre from './Pre'; import Code from './Code'; import HtmlText from './HtmlText'; import Span from './Span'; function getKey(key) { return 'key'.concat(key); } function getParentName(node) { return ( node.parent && node.parent.parent ? node.parent.parent.name : ''); } function getTitleSize(node) { return 20 - (parseInt(node.name.substring(1, 2), 10) * 2); } function getmarginTop(node) { return node.parent.name === 'blockquote' ? 0 : 15; } const htmlToElement = (rawHtml, done) => { function domToElement(dom) { if (dom) { return dom.map((node, index) => { switch (node.name) { case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return ( <H fontSize={getTitleSize(node)} component={domToElement(node.children)} key={getKey(index)} />); case 'blockquote': return ( <Bloackquote component={domToElement(node.children)} key={getKey(index)} />); case 'p': return ( <P margintop={getmarginTop(node)} component={domToElement(node.children)} childrenName={node.children[0].name} key={getKey(index)} />); case 'ul': return ( <Ul component={domToElement(node.children)} key={getKey(index)} />); case 'ol': return ( <Ol component={domToElement(node.children)} key={getKey(index)} />); case 'li': return ( <Li component={domToElement(node.children)} parentName={node.parent.name} index={index} key={getKey(index)} />); case 'img': return (<Img uri={node.attribs.src} key={getKey(index)} />); case 'text': return ( <HtmlText text={node.text} component={domToElement(node.children)} parentName={getParentName(node)} key={getKey(index)} />); case 'span': return ( <Span component={domToElement(node.children)} key={getKey(index)} />); case 'a': return ( <A link={node.attribs.href} key={getKey(index)} component={domToElement(node.children)} />); case 'pre': return ( <Pre component={domToElement(node.children)} key={getKey(index)} />); case 'code': return ( <Code component={domToElement(node.children)} key={getKey(index)} />); default: return null; } }); } return null; } htmlParse(rawHtml, (dom) => { done(null, domToElement(dom, null, 'block')); }); }; class HtmlView extends React.Component { static componentName = 'HtmlView'; static propTypes = { value: PropTypes.string, }; static defaultProps = { value: '', }; constructor(props) { super(props); this.state = { element: null, }; } componentDidMount() { this.startHtmlRender(); } componentWillReceiveProps(props) { this.props = props; this.startHtmlRender(); } startHtmlRender() { if (!this.props.value) { return; } if (this.renderingHtml) { return; } this.renderingHtml = true; htmlToElement(this.props.value, (err, el) => { this.renderingHtml = false; this.setState({ element: el, }); }); } render() { if (this.state.element) { return ( <View style={{ flex: 1, paddingLeft: 15, paddingRight: 15, paddingBottom: 15, backgroundColor: 'white' }}> {this.state.element} </View>); } return <View />; } } export default HtmlView;
src/components/htmlview/HtmlView.js
import React, { PropTypes } from 'react'; import { Text, View } from 'react-native'; import htmlParse from '../../lib/htmlParse'; import H from './H'; import Bloackquote from './Blockquote'; import P from './P'; import Ul from './Ul'; import Ol from './Ol'; import Li from './Li'; import Img from './Img'; import A from './A'; import Pre from './Pre'; import Code from './Code'; import HtmlText from './HtmlText'; import Span from './Span'; function getKey(key) { return 'key'.concat(key); } function getParentName(node) { return ( node.parent && node.parent.parent ? node.parent.parent.name : ''); } function getTitleSize(node) { return 20 - (parseInt(node.name.substring(1, 2), 10) * 2); } function getmarginTop(node) { return node.parent.name === 'blockquote' ? 0 : 15; } const htmlToElement = (rawHtml, done) => { function domToElement(dom) { if (dom) { return dom.map((node, index) => { switch (node.name) { case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return ( <H fontSize={getTitleSize(node)} component={domToElement(node.children)} key={getKey(index)} />); case 'blockquote': return ( <Bloackquote component={domToElement(node.children)} key={getKey(index)} />); case 'p': return ( <P margintop={getmarginTop(node)} component={domToElement(node.children)} childrenName={node.children[0].name} key={getKey(index)} />); case 'ul': return ( <Ul component={domToElement(node.children)} key={getKey(index)} />); case 'ol': return ( <Ol component={domToElement(node.children)} key={getKey(index)} />); case 'li': return ( <Li component={domToElement(node.children)} parentName={node.parent.name} index={index} key={getKey(index)} />); case 'img': return (<Img uri={node.attribs.src} key={getKey(index)} />); case 'text': return ( <HtmlText text={node.text} component={domToElement(node.children)} parentName={getParentName(node)} key={getKey(index)} />); case 'span': { console.log(node) return ( <Span component={domToElement(node.children)} key={getKey(index)} />); } case 'a': return ( <A link={node.attribs.href} key={getKey(index)} component={domToElement(node.children)} />); case 'pre': return ( <Pre component={domToElement(node.children)} key={getKey(index)} />); case 'code': return ( <Code component={domToElement(node.children)} key={getKey(index)} />); default: return null; } }); } return null; } htmlParse(rawHtml, (dom) => { done(null, domToElement(dom, null, 'block')); }); }; class HtmlView extends React.Component { static componentName = 'HtmlView'; static propTypes = { value: PropTypes.string, }; static defaultProps = { value: '', }; constructor(props) { super(props); this.state = { element: null, }; } componentDidMount() { this.startHtmlRender(); } componentWillReceiveProps(props) { this.props = props; this.startHtmlRender(); } startHtmlRender() { if (!this.props.value) { return; } if (this.renderingHtml) { return; } this.renderingHtml = true; htmlToElement(this.props.value, (err, el) => { this.renderingHtml = false; this.setState({ element: el, }); }); } render() { if (this.state.element) { return ( <View style={{ flex: 1, paddingLeft: 15, paddingRight: 15, paddingBottom: 15, backgroundColor: 'white' }}> {this.state.element} </View>); } return <View />; } } export default HtmlView;
[T] htmlview: update html view
src/components/htmlview/HtmlView.js
[T] htmlview: update html view
<ide><path>rc/components/htmlview/HtmlView.js <ide> import React, { PropTypes } from 'react'; <del>import { Text, View } from 'react-native'; <add>import { View } from 'react-native'; <ide> import htmlParse from '../../lib/htmlParse'; <ide> import H from './H'; <ide> import Bloackquote from './Blockquote'; <ide> parentName={getParentName(node)} <ide> key={getKey(index)} <ide> />); <del> case 'span': { <del> console.log(node) <add> case 'span': <ide> return ( <ide> <Span <ide> component={domToElement(node.children)} <ide> key={getKey(index)} <ide> />); <del> } <ide> case 'a': <ide> return ( <ide> <A
Java
apache-2.0
595a82ec298ed3dfe2a8ae9b8cacc51077e62bf3
0
apache/lenya,apache/lenya,apache/lenya,apache/lenya
/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /* $Id: SCMFilenameFilter.java,v 1.3 2004/06/01 15:39:33 michi Exp $ */ package org.apache.lenya.cms.ant; import java.io.File; import java.io.FilenameFilter; import java.util.StringTokenizer; /** * Filter to exclude SCM files, such as CVS and .svn */ public class SCMFilenameFilter implements FilenameFilter { String[] excludes; /** * @param excludes e.g. CVS,.svn */ public SCMFilenameFilter(String excludes) { this.excludes = excludes.split(","); } /** * (non-Javadoc) * @see java.io.FilenameFilter#accept(java.io.File, java.lang.String) */ public boolean accept(File dir, String name) { for (int i = 0; i < excludes.length; i++) { if (name.equals(excludes[i])) { return false; } } return true; } }
src/java/org/apache/lenya/cms/ant/SCMFilenameFilter.java
/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /* $Id: SCMFilenameFilter.java,v 1.2 2004/06/01 15:37:05 andreas Exp $ */ package org.apache.lenya.cms.ant; import java.io.File; import java.io.FilenameFilter; import java.util.StringTokenizer; /** * */ public class SCMFilenameFilter implements FilenameFilter { String[] excludes; /** * */ public SCMFilenameFilter(String excludes) { this.excludes = excludes.split(","); } /** * (non-Javadoc) * @see java.io.FilenameFilter#accept(java.io.File, java.lang.String) */ public boolean accept(File dir, String name) { for (int i = 0; i < excludes.length; i++) { if (name.equals(excludes[i])) { return false; } } return true; } }
javadocs added git-svn-id: f6f45834fccde298d83fbef5743c9fd7982a26a3@43064 13f79535-47bb-0310-9956-ffa450edef68
src/java/org/apache/lenya/cms/ant/SCMFilenameFilter.java
javadocs added
<ide><path>rc/java/org/apache/lenya/cms/ant/SCMFilenameFilter.java <ide> * <ide> */ <ide> <del>/* $Id: SCMFilenameFilter.java,v 1.2 2004/06/01 15:37:05 andreas Exp $ */ <add>/* $Id: SCMFilenameFilter.java,v 1.3 2004/06/01 15:39:33 michi Exp $ */ <ide> <ide> package org.apache.lenya.cms.ant; <ide> <ide> import java.util.StringTokenizer; <ide> <ide> /** <del> * <add> * Filter to exclude SCM files, such as CVS and .svn <ide> */ <ide> public class SCMFilenameFilter implements FilenameFilter { <ide> String[] excludes; <ide> <ide> /** <del> * <add> * @param excludes e.g. CVS,.svn <ide> */ <ide> public SCMFilenameFilter(String excludes) { <ide> this.excludes = excludes.split(",");
Java
mit
1d8ccc813d94340c4d09df36bd9e630eec923c52
0
DDoS/Sponge,SRPlatin/Sponge,SpongePowered/SpongeForge,coaster3000/Sponge,caseif/Sponge,SpongeHistory/Sponge-History,coaster3000/Sponge,DDoS/SpongeForge,joseph00713/Sponge,Istar-Eldritch/Sponge,SpongePowered/SpongeForge,kenzierocks/SpongeForge,SpongeHistory/Sponge-History,kenzierocks/SpongeForge,lorenzoYolo123/lorenzoYolo123,kenzierocks/Sponge,caseif/Sponge,phase/Sponge,Istar-Eldritch/Sponge,phase/Sponge,kenzierocks/Sponge,lorenzoYolo123/lorenzoYolo123,DDoS/SpongeForge,joseph00713/Sponge,SRPlatin/Sponge,DDoS/Sponge
/** * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered.org <http://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.mod.asm.transformers; import static org.objectweb.asm.ClassWriter.COMPUTE_FRAMES; import static org.objectweb.asm.ClassWriter.COMPUTE_MAXS; import java.io.File; import java.util.HashMap; import java.util.Map; import net.minecraft.launchwrapper.IClassTransformer; import org.apache.logging.log4j.Logger; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; import org.spongepowered.api.event.Event; import org.spongepowered.api.event.state.InitializationEvent; import org.spongepowered.api.event.state.PreInitializationEvent; import org.spongepowered.api.event.state.ServerStartingEvent; import org.spongepowered.api.event.voxel.VoxelEvent; import cpw.mods.fml.relauncher.FMLRelaunchLog; import org.spongepowered.mod.asm.util.ASMHelper; public class EventTransformer implements IClassTransformer { private final static Map<String, Class<?>> events = new HashMap<String, Class<?>>(); static { events.put("cpw.mods.fml.common.event.FMLPreInitializationEvent", PreInitializationEvent.class); events.put("cpw.mods.fml.common.event.FMLInitializationEvent", InitializationEvent.class); events.put("cpw.mods.fml.common.event.FMLServerStartingEvent", ServerStartingEvent.class); events.put("net.minecraftforge.event.world.BlockEvent$BreakEvent", VoxelEvent.class); } @Override public byte[] transform(String name, String transformedName, byte[] bytes) { if (bytes == null || name.startsWith("net.minecraft.") || name.indexOf('.') == -1) { return bytes; } if (!events.containsKey(name)) { return bytes; } Class<?> interf = events.get(name); if (interf == null || !interf.isInterface()) { FMLRelaunchLog.warning(name + " cannot be processed"); return bytes; } String interfaceName = Type.getInternalName(interf); try { ClassReader cr = new ClassReader(bytes); ClassNode classNode = new ClassNode(); cr.accept(classNode, 0); classNode.interfaces.add(interfaceName); if (Event.class.isAssignableFrom(interf)) { classNode.methods.add(createGetGameMethod()); } // TODO: This is a temporary thing to make PreInit work. The different things needed to make different events work should be abstracted. if(PreInitializationEvent.class.isAssignableFrom(interf)) { ASMHelper.generateSelfForwardingMethod(classNode, "getConfigurationDirectory", "getModConfigurationDirectory", Type.getType(File.class)); ASMHelper.generateSelfForwardingMethod(classNode, "getPluginLog", "getModLog", Type.getType(Logger.class)); } ClassWriter cw = new ClassWriter(cr, COMPUTE_MAXS | COMPUTE_FRAMES); classNode.accept(cw); return cw.toByteArray(); } catch (Throwable t) { t.printStackTrace(); return bytes; } } private MethodNode createGetGameMethod() { MethodNode methodNode = new MethodNode(Opcodes.ASM4, Opcodes.ACC_PUBLIC, "getGame", "()Lorg/spongepowered/api/Game;", null, null); methodNode.instructions.add(new FieldInsnNode(Opcodes.GETSTATIC, "org/spongepowered/mod/SpongeMod", "instance", "Lorg/spongepowered/mod/SpongeMod;")); methodNode.instructions.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "org/spongepowered/mod/SpongeMod", "getGame", "()Lorg/spongepowered/mod/SpongeGame;", false)); methodNode.instructions.add(new InsnNode(Opcodes.ARETURN)); methodNode.maxLocals = 1; methodNode.maxStack = 1; return methodNode; } }
src/main/java/org/spongepowered/mod/asm/transformers/EventTransformer.java
/** * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered.org <http://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.mod.asm.transformers; import static org.objectweb.asm.ClassWriter.COMPUTE_FRAMES; import static org.objectweb.asm.ClassWriter.COMPUTE_MAXS; import java.util.HashMap; import java.util.Map; import net.minecraft.launchwrapper.IClassTransformer; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; import org.spongepowered.api.event.Event; import org.spongepowered.api.event.state.InitializationEvent; import org.spongepowered.api.event.state.PreInitializationEvent; import org.spongepowered.api.event.state.ServerStartingEvent; import org.spongepowered.api.event.voxel.VoxelEvent; import cpw.mods.fml.relauncher.FMLRelaunchLog; public class EventTransformer implements IClassTransformer { private final static Map<String, Class<?>> events = new HashMap<String, Class<?>>(); static { events.put("cpw.mods.fml.common.event.FMLPreInitializationEvent", PreInitializationEvent.class); events.put("cpw.mods.fml.common.event.FMLInitializationEvent", InitializationEvent.class); events.put("cpw.mods.fml.common.event.FMLServerStartingEvent", ServerStartingEvent.class); events.put("net.minecraftforge.event.world.BlockEvent$BreakEvent", VoxelEvent.class); } @Override public byte[] transform(String name, String transformedName, byte[] bytes) { if (bytes == null || name.startsWith("net.minecraft.") || name.indexOf('.') == -1) { return bytes; } if (!events.containsKey(name)) { return bytes; } Class<?> interf = events.get(name); if (interf == null || !interf.isInterface()) { FMLRelaunchLog.warning(name + " cannot be processed"); return bytes; } String interfaceName = Type.getInternalName(interf); try { ClassReader cr = new ClassReader(bytes); ClassNode classNode = new ClassNode(); cr.accept(classNode, 0); classNode.interfaces.add(interfaceName); if (Event.class.isAssignableFrom(interf)) { classNode.methods.add(createGetGameMethod()); } ClassWriter cw = new ClassWriter(cr, COMPUTE_MAXS | COMPUTE_FRAMES); classNode.accept(cw); return cw.toByteArray(); } catch (Throwable t) { t.printStackTrace(); return bytes; } } private MethodNode createGetGameMethod() { MethodNode methodNode = new MethodNode(Opcodes.ASM4, Opcodes.ACC_PUBLIC, "getGame", "()Lorg/spongepowered/api/Game;", null, null); methodNode.instructions.add(new FieldInsnNode(Opcodes.GETSTATIC, "org/spongepowered/mod/SpongeMod", "instance", "Lorg/spongepowered/mod/SpongeMod;")); methodNode.instructions.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "org/spongepowered/mod/SpongeMod", "getGame", "()Lorg/spongepowered/mod/SpongeGame;", false)); methodNode.instructions.add(new InsnNode(Opcodes.ARETURN)); methodNode.maxLocals = 1; methodNode.maxStack = 1; return methodNode; } }
Implement forwarding methods for PreInit event getSuggestedConfigurationDirectory() is still unimplemented
src/main/java/org/spongepowered/mod/asm/transformers/EventTransformer.java
Implement forwarding methods for PreInit event
<ide><path>rc/main/java/org/spongepowered/mod/asm/transformers/EventTransformer.java <ide> import static org.objectweb.asm.ClassWriter.COMPUTE_FRAMES; <ide> import static org.objectweb.asm.ClassWriter.COMPUTE_MAXS; <ide> <add>import java.io.File; <ide> import java.util.HashMap; <ide> import java.util.Map; <ide> <ide> import net.minecraft.launchwrapper.IClassTransformer; <ide> <add>import org.apache.logging.log4j.Logger; <ide> import org.objectweb.asm.ClassReader; <ide> import org.objectweb.asm.ClassWriter; <ide> import org.objectweb.asm.Opcodes; <ide> import org.spongepowered.api.event.voxel.VoxelEvent; <ide> <ide> import cpw.mods.fml.relauncher.FMLRelaunchLog; <add>import org.spongepowered.mod.asm.util.ASMHelper; <ide> <ide> public class EventTransformer implements IClassTransformer { <ide> <ide> if (Event.class.isAssignableFrom(interf)) { <ide> classNode.methods.add(createGetGameMethod()); <ide> } <add> <add> // TODO: This is a temporary thing to make PreInit work. The different things needed to make different events work should be abstracted. <add> if(PreInitializationEvent.class.isAssignableFrom(interf)) { <add> ASMHelper.generateSelfForwardingMethod(classNode, "getConfigurationDirectory", "getModConfigurationDirectory", <add> Type.getType(File.class)); <add> ASMHelper.generateSelfForwardingMethod(classNode, "getPluginLog", "getModLog", <add> Type.getType(Logger.class)); <add> } <ide> <ide> ClassWriter cw = new ClassWriter(cr, COMPUTE_MAXS | COMPUTE_FRAMES); <ide> classNode.accept(cw);
Java
apache-2.0
6a2f0ddc98863ba0269d5c2a2cca788341314e3d
0
cherryhill/collectionspace-application
/* Copyright 2010 University of Cambridge * Licensed under the Educational Community License (ECL), Version 2.0. You may not use this file except in * compliance with this License. * * You may obtain a copy of the ECL 2.0 License at https://source.collectionspace.org/collection-space/LICENSE.txt */ package org.collectionspace.chain.csp.webui.userdetails; import java.util.HashMap; import java.util.Map; import org.collectionspace.chain.csp.schema.Record; import org.collectionspace.chain.csp.schema.Spec; import org.collectionspace.chain.csp.webui.main.Request; import org.collectionspace.chain.csp.webui.main.WebMethod; import org.collectionspace.chain.csp.webui.main.WebUI; import org.collectionspace.csp.api.persistence.ExistException; import org.collectionspace.csp.api.persistence.Storage; import org.collectionspace.csp.api.persistence.UnderlyingStorageException; import org.collectionspace.csp.api.persistence.UnimplementedException; import org.collectionspace.csp.api.ui.UIException; import org.collectionspace.csp.api.ui.UIRequest; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class UserDetailsSearchList implements WebMethod { private static final Logger log=LoggerFactory.getLogger(UserDetailsSearchList.class); private boolean search; private String base; private Map<String,String> type_to_url=new HashMap<String,String>(); public UserDetailsSearchList(Record r,boolean search) { this.base=r.getID(); this.search=search; } private JSONObject generateMiniRecord(Storage storage,String type,String csid) throws ExistException, UnimplementedException, UnderlyingStorageException, JSONException { JSONObject out=storage.retrieveJSON(type+"/"+csid+"", new JSONObject()); out.put("csid",csid); out.put("recordtype",type_to_url.get(type)); return out; } private JSONObject generateEntry(Storage storage,String base,String member) throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException { return generateMiniRecord(storage,base,member); } private JSONObject pathsToJSON(Storage storage,String base,String[] paths,String key, JSONObject pagination) throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException { JSONObject out=new JSONObject(); JSONArray members=new JSONArray(); for(String p : paths){ JSONObject temp = generateEntry(storage,base,p); if(temp !=null){ members.put(temp); } } out.put(key,members); if(pagination!=null){ out.put("pagination",pagination); } return out; } private void search_or_list(Storage storage,UIRequest ui,String param, String pageSize, String pageNum) throws UIException { try { JSONObject restriction=new JSONObject(); String key="items"; if(param!=null) { restriction.put("screenName",param); key="results"; } if(pageSize!=null) { restriction.put("pageSize",pageSize); } if(pageNum!=null) { restriction.put("pageNum",pageNum); } JSONObject data = storage.getPathsJSON(base,restriction); String[] paths = (String[]) data.get("listItems"); JSONObject pagination = new JSONObject(); if(data.has("pagination")){ pagination = data.getJSONObject("pagination"); } JSONObject resultsObject=new JSONObject(); resultsObject = pathsToJSON(storage,base,paths,key,pagination); ui.sendJSONResponse(resultsObject); } catch (JSONException e) { throw new UIException("JSONException during autocompletion",e); } catch (ExistException e) { throw new UIException("ExistException during autocompletion",e); } catch (UnimplementedException e) { throw new UIException("UnimplementedException during autocompletion",e); } catch (UnderlyingStorageException x) { UIException uiexception = new UIException(x.getMessage(),x.getStatus(),x.getUrl(),x); ui.sendJSONResponse(uiexception.getJSON()); } } public void run(Object in,String[] tail) throws UIException { Request q=(Request)in; if(search) search_or_list(q.getStorage(),q.getUIRequest(),q.getUIRequest().getRequestArgument("query"),q.getUIRequest().getRequestArgument("pageSize"),q.getUIRequest().getRequestArgument("pageNum")); else search_or_list(q.getStorage(),q.getUIRequest(),null,q.getUIRequest().getRequestArgument("pageSize"),q.getUIRequest().getRequestArgument("pageNum")); } public void configure(WebUI ui,Spec spec) { for(Record r : spec.getAllRecords()) { type_to_url.put(r.getID(),r.getWebURL()); } } }
cspi-webui/src/main/java/org/collectionspace/chain/csp/webui/userdetails/UserDetailsSearchList.java
/* Copyright 2010 University of Cambridge * Licensed under the Educational Community License (ECL), Version 2.0. You may not use this file except in * compliance with this License. * * You may obtain a copy of the ECL 2.0 License at https://source.collectionspace.org/collection-space/LICENSE.txt */ package org.collectionspace.chain.csp.webui.userdetails; import java.util.HashMap; import java.util.Map; import org.collectionspace.chain.csp.schema.Record; import org.collectionspace.chain.csp.schema.Spec; import org.collectionspace.chain.csp.webui.main.Request; import org.collectionspace.chain.csp.webui.main.WebMethod; import org.collectionspace.chain.csp.webui.main.WebUI; import org.collectionspace.csp.api.persistence.ExistException; import org.collectionspace.csp.api.persistence.Storage; import org.collectionspace.csp.api.persistence.UnderlyingStorageException; import org.collectionspace.csp.api.persistence.UnimplementedException; import org.collectionspace.csp.api.ui.UIException; import org.collectionspace.csp.api.ui.UIRequest; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class UserDetailsSearchList implements WebMethod { private static final Logger log=LoggerFactory.getLogger(UserDetailsSearchList.class); private boolean search; private String base; private Map<String,String> type_to_url=new HashMap<String,String>(); public UserDetailsSearchList(Record r,boolean search) { this.base=r.getID(); this.search=search; } private JSONObject generateMiniRecord(Storage storage,String type,String csid) throws ExistException, UnimplementedException, UnderlyingStorageException, JSONException { JSONObject out=storage.retrieveJSON(type+"/"+csid+"", new JSONObject()); out.put("csid",csid); out.put("recordtype",type_to_url.get(type)); return out; } private JSONObject generateEntry(Storage storage,String base,String member) throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException { return generateMiniRecord(storage,base,member); } private JSONObject pathsToJSON(Storage storage,String base,String[] paths,String key) throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException { JSONObject out=new JSONObject(); JSONArray members=new JSONArray(); for(String p : paths) members.put(generateEntry(storage,base,p)); out.put(key,members); return out; } private void search_or_list(Storage storage,UIRequest ui,String param, String pageSize, String pageNum) throws UIException { try { JSONObject restriction=new JSONObject(); String key="items"; if(param!=null) { restriction.put("screenName",param); key="results"; } if(pageSize!=null) { restriction.put("pageSize",pageSize); } if(pageNum!=null) { restriction.put("pageNum",pageNum); } JSONObject data = storage.getPathsJSON(base,restriction); String[] paths = (String[]) data.get("listItems"); for(int i=0;i<paths.length;i++) { if(paths[i].startsWith(base+"/")) paths[i]=paths[i].substring((base+"/").length()); } JSONObject resultsObject=new JSONObject(); resultsObject = pathsToJSON(storage,base,paths,key); ui.sendJSONResponse(resultsObject); } catch (JSONException e) { throw new UIException("JSONException during autocompletion",e); } catch (ExistException e) { throw new UIException("ExistException during autocompletion",e); } catch (UnimplementedException e) { throw new UIException("UnimplementedException during autocompletion",e); } catch (UnderlyingStorageException x) { UIException uiexception = new UIException(x.getMessage(),x.getStatus(),x.getUrl(),x); ui.sendJSONResponse(uiexception.getJSON()); } } public void run(Object in,String[] tail) throws UIException { Request q=(Request)in; if(search) search_or_list(q.getStorage(),q.getUIRequest(),q.getUIRequest().getRequestArgument("query"),q.getUIRequest().getRequestArgument("pageSize"),q.getUIRequest().getRequestArgument("pageNum")); else search_or_list(q.getStorage(),q.getUIRequest(),null,q.getUIRequest().getRequestArgument("pageSize"),q.getUIRequest().getRequestArgument("pageNum")); } public void configure(WebUI ui,Spec spec) { for(Record r : spec.getAllRecords()) { type_to_url.put(r.getID(),r.getWebURL()); } } }
CSPACE-4785 - add pagination for users
cspi-webui/src/main/java/org/collectionspace/chain/csp/webui/userdetails/UserDetailsSearchList.java
CSPACE-4785 - add pagination for users
<ide><path>spi-webui/src/main/java/org/collectionspace/chain/csp/webui/userdetails/UserDetailsSearchList.java <ide> return generateMiniRecord(storage,base,member); <ide> } <ide> <del> private JSONObject pathsToJSON(Storage storage,String base,String[] paths,String key) throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException { <add> private JSONObject pathsToJSON(Storage storage,String base,String[] paths,String key, JSONObject pagination) throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException { <ide> JSONObject out=new JSONObject(); <ide> JSONArray members=new JSONArray(); <del> for(String p : paths) <del> members.put(generateEntry(storage,base,p)); <add> for(String p : paths){ <add> JSONObject temp = generateEntry(storage,base,p); <add> if(temp !=null){ <add> members.put(temp); <add> } <add> } <ide> out.put(key,members); <add> <add> <add> if(pagination!=null){ <add> out.put("pagination",pagination); <add> } <ide> return out; <ide> } <ide> <ide> } <ide> JSONObject data = storage.getPathsJSON(base,restriction); <ide> String[] paths = (String[]) data.get("listItems"); <del> for(int i=0;i<paths.length;i++) { <del> if(paths[i].startsWith(base+"/")) <del> paths[i]=paths[i].substring((base+"/").length()); <add> <add> <add> JSONObject pagination = new JSONObject(); <add> if(data.has("pagination")){ <add> pagination = data.getJSONObject("pagination"); <ide> } <add> <ide> JSONObject resultsObject=new JSONObject(); <del> resultsObject = pathsToJSON(storage,base,paths,key); <add> resultsObject = pathsToJSON(storage,base,paths,key,pagination); <ide> ui.sendJSONResponse(resultsObject); <ide> } catch (JSONException e) { <ide> throw new UIException("JSONException during autocompletion",e);
Java
apache-2.0
42e71de4c5a198f3e863dac31efb0e04f27c90ec
0
wso2/product-apim,tharikaGitHub/product-apim,thilinicooray/product-apim,pradeepmurugesan/product-apim,nu1silva/product-apim,dhanuka84/product-apim,chamilaadhi/product-apim,jaadds/product-apim,sambaheerathan/product-apim,hevayo/product-apim,dhanuka84/product-apim,wso2/product-apim,ChamNDeSilva/product-apim,dhanuka84/product-apim,pradeepmurugesan/product-apim,nu1silva/product-apim,tharikaGitHub/product-apim,pradeepmurugesan/product-apim,pradeepmurugesan/product-apim,tharikaGitHub/product-apim,dhanuka84/product-apim,chamilaadhi/product-apim,tharikaGitHub/product-apim,thilinicooray/product-apim,chamilaadhi/product-apim,jaadds/product-apim,irhamiqbal/product-apim,wso2/product-apim,irhamiqbal/product-apim,wso2/product-apim,nu1silva/product-apim,rswijesena/product-apim,sambaheerathan/product-apim,irhamiqbal/product-apim,ChamNDeSilva/product-apim,nu1silva/product-apim,dewmini/product-apim,lakmali/product-apim,abimarank/product-apim,irhamiqbal/product-apim,hevayo/product-apim,jaadds/product-apim,dewmini/product-apim,dewmini/product-apim,abimarank/product-apim,hevayo/product-apim,lakmali/product-apim,dewmini/product-apim,chamilaadhi/product-apim,jaadds/product-apim,wso2/product-apim,thilinicooray/product-apim,chamilaadhi/product-apim,tharikaGitHub/product-apim,hevayo/product-apim,nu1silva/product-apim,rswijesena/product-apim,dewmini/product-apim,tharindu1st/product-apim,thilinicooray/product-apim
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbon.apimgt.migration.client; import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.apimgt.impl.utils.APIMgtDBUtil; import org.wso2.carbon.apimgt.migration.APIMigrationException; import org.wso2.carbon.apimgt.migration.util.Constants; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.user.api.Tenant; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.core.tenant.TenantManager; import java.io.*; import java.sql.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.StringTokenizer; public abstract class MigrationClientBase { private static final Log log = LogFactory.getLog(MigrationClientBase.class); private List<Tenant> tenantsArray; public MigrationClientBase(String tenantArguments, String blackListTenantArguments, TenantManager tenantManager) throws UserStoreException { if (tenantArguments != null) { // Tenant arguments have been provided so need to load specific ones tenantArguments = tenantArguments.replaceAll("\\s", ""); // Remove spaces and tabs tenantsArray = new ArrayList(); buildTenantList(tenantManager, tenantsArray, tenantArguments); } else if (blackListTenantArguments != null) { blackListTenantArguments = blackListTenantArguments.replaceAll("\\s", ""); // Remove spaces and tabs List<Tenant> blackListTenants = new ArrayList(); buildTenantList(tenantManager, blackListTenants, blackListTenantArguments); List<Tenant> allTenants = new ArrayList(Arrays.asList(tenantManager.getAllTenants())); Tenant superTenant = new Tenant(); superTenant.setDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); superTenant.setId(MultitenantConstants.SUPER_TENANT_ID); allTenants.add(superTenant); tenantsArray = new ArrayList(); for (Tenant tenant : allTenants) { boolean isBlackListed = false; for (Tenant blackListTenant : blackListTenants) { if (blackListTenant.getId() == tenant.getId()) { isBlackListed = true; break; } } if (!isBlackListed) { tenantsArray.add(tenant); } } } else { // Load all tenants tenantsArray = new ArrayList(Arrays.asList(tenantManager.getAllTenants())); Tenant superTenant = new Tenant(); superTenant.setDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); superTenant.setId(MultitenantConstants.SUPER_TENANT_ID); tenantsArray.add(superTenant); } } private void buildTenantList(TenantManager tenantManager, List<Tenant> tenantList, String tenantArguments) throws UserStoreException { if (tenantArguments.contains(",")) { // Multiple arguments specified String[] parts = tenantArguments.split(","); for (int i = 0; i < parts.length; ++i) { if (parts[i].length() > 0) { populateTenants(tenantManager, tenantList, parts[i]); } } } else { // Only single argument provided populateTenants(tenantManager, tenantList, tenantArguments); } } private void populateTenants(TenantManager tenantManager, List<Tenant> tenantList, String argument) throws UserStoreException { log.debug("Argument provided : " + argument); if (argument.contains("@")) { // Username provided as argument int tenantID = tenantManager.getTenantId(argument); if (tenantID != -1) { tenantList.add(tenantManager.getTenant(tenantID)); } else { log.error("Tenant does not exist for username " + argument); } } else { // Domain name provided as argument if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(argument)) { Tenant superTenant = new Tenant(); superTenant.setDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); superTenant.setId(MultitenantConstants.SUPER_TENANT_ID); tenantList.add(superTenant); } else { Tenant[] tenants = tenantManager.getAllTenantsForTenantDomainStr(argument); if (tenants.length > 0) { tenantList.addAll(Arrays.asList(tenants)); } else { log.error("Tenant does not exist for domain " + argument); } } } } protected List<Tenant> getTenantsArray() { return tenantsArray; } protected void updateAPIManangerDatabase(String sqlScriptPath) throws SQLException { log.info("Database migration for API Manager started"); Connection connection = null; PreparedStatement preparedStatement = null; BufferedReader bufferedReader = null; try { connection = APIMgtDBUtil.getConnection(); connection.setAutoCommit(false); String dbType = MigrationDBCreator.getDatabaseType(connection); InputStream is = new FileInputStream(sqlScriptPath + dbType + ".sql"); bufferedReader = new BufferedReader(new InputStreamReader(is, "UTF8")); String sqlQuery = ""; boolean isFoundQueryEnd = false; String line; while ((line = bufferedReader.readLine()) != null) { line = line.trim(); if (line.startsWith("//") || line.startsWith("--")) { continue; } StringTokenizer stringTokenizer = new StringTokenizer(line); if (stringTokenizer.hasMoreTokens()) { String token = stringTokenizer.nextToken(); if ("REM".equalsIgnoreCase(token)) { continue; } } if (line.contains("\\n")) { line = line.replace("\\n", ""); } sqlQuery += ' ' + line; if (line.contains(";")) { isFoundQueryEnd = true; } if (org.wso2.carbon.apimgt.migration.util.Constants.DB_TYPE_ORACLE.equals(dbType)) { sqlQuery = sqlQuery.replace(";", ""); } if (org.wso2.carbon.apimgt.migration.util.Constants.DB_TYPE_DB2.equals(dbType)) { sqlQuery = sqlQuery.replace(";", ""); } if (isFoundQueryEnd) { if (sqlQuery.length() > 0) { log.debug("SQL to be executed : " + sqlQuery); preparedStatement = connection.prepareStatement(sqlQuery.trim()); preparedStatement.execute(); connection.commit(); } // Reset variables to read next SQL sqlQuery = ""; isFoundQueryEnd = false; } } bufferedReader.close(); } catch (IOException e) { //Errors logged to let user know the state of the db migration and continue other resource migrations log.error("Error occurred while migrating databases", e); } catch (Exception e) { /* MigrationDBCreator extends from org.wso2.carbon.utils.dbcreator.DatabaseCreator and in the super class method getDatabaseType throws generic Exception */ log.error("Error occurred while migrating databases", e); } finally { if (preparedStatement != null) { preparedStatement.close(); } if (connection != null) { connection.close(); } } log.info("DB resource migration done for all the tenants"); } /** * This method is used to remove the FK constraint which is unnamed * This finds the name of the constraint and build the query to delete the constraint and execute it * * @param sqlScriptPath path of sql script * @throws SQLException * @throws IOException */ protected void dropFKConstraint(String sqlScriptPath) throws SQLException { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; Statement statement = null; try { String queryToExecute = IOUtils.toString(new FileInputStream(new File(sqlScriptPath + "drop-fk.sql")), "UTF-8"); String queryArray[] = queryToExecute.split(Constants.LINE_BREAK); connection = APIMgtDBUtil.getConnection(); String dbType = MigrationDBCreator.getDatabaseType(connection); connection.setAutoCommit(false); statement = connection.createStatement(); if (Constants.DB_TYPE_ORACLE.equals(dbType)) { queryArray[0] = queryArray[0].replace(Constants.DELIMITER, ""); } resultSet = statement.executeQuery(queryArray[0]); String constraintName = null; while (resultSet.next()) { constraintName = resultSet.getString("constraint_name"); } if (constraintName != null) { queryToExecute = queryArray[1].replace("<temp_key_name>", constraintName); if (Constants.DB_TYPE_ORACLE.equals(dbType)) { queryToExecute = queryToExecute.replace(Constants.DELIMITER, ""); } if (queryToExecute.contains("\\n")) { queryToExecute = queryToExecute.replace("\\n", ""); } preparedStatement = connection.prepareStatement(queryToExecute); preparedStatement.execute(); connection.commit(); } } catch (APIMigrationException e) { //Foreign key might be already deleted, log the error and let it continue log.error("Error occurred while deleting foreign key", e); } catch (IOException e) { //If user does not add the file migration will continue and migrate the db without deleting // the foreign key reference log.error("Error occurred while finding the foreign key deletion query for execution", e); } catch (Exception e) { /* MigrationDBCreator extends from org.wso2.carbon.utils.dbcreator.DatabaseCreator and in the super class method getDatabaseType throws generic Exception */ log.error("Error occurred while deleting foreign key", e); } finally { if (statement != null) { statement.close(); } APIMgtDBUtil.closeAllConnections(preparedStatement, connection, resultSet); } } }
modules/distribution/resources/migration/wso2-api-migration-client/src/main/java/org/wso2/carbon/apimgt/migration/client/MigrationClientBase.java
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbon.apimgt.migration.client; import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.apimgt.impl.utils.APIMgtDBUtil; import org.wso2.carbon.apimgt.migration.APIMigrationException; import org.wso2.carbon.apimgt.migration.util.Constants; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.user.api.Tenant; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.core.tenant.TenantManager; import java.io.*; import java.sql.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.StringTokenizer; public abstract class MigrationClientBase { private static final Log log = LogFactory.getLog(MigrationClientBase.class); private List<Tenant> tenantsArray; public MigrationClientBase(String tenantArguments, String blackListTenantArguments, TenantManager tenantManager) throws UserStoreException { if (tenantArguments != null) { // Tenant arguments have been provided so need to load specific ones tenantArguments = tenantArguments.replaceAll("\\s", ""); // Remove spaces and tabs tenantsArray = new ArrayList(); buildTenantList(tenantManager, tenantsArray, tenantArguments); } else if (blackListTenantArguments != null) { blackListTenantArguments = blackListTenantArguments.replaceAll("\\s", ""); // Remove spaces and tabs List<Tenant> blackListTenants = new ArrayList(); buildTenantList(tenantManager, blackListTenants, blackListTenantArguments); List<Tenant> allTenants = new ArrayList(Arrays.asList(tenantManager.getAllTenants())); Tenant superTenant = new Tenant(); superTenant.setDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); superTenant.setId(MultitenantConstants.SUPER_TENANT_ID); allTenants.add(superTenant); tenantsArray = new ArrayList(); for (Tenant tenant : allTenants) { boolean isBlackListed = false; for (Tenant blackListTenant : blackListTenants) { if (blackListTenant.getId() == tenant.getId()) { isBlackListed = true; break; } } if (!isBlackListed) { tenantsArray.add(tenant); } } } else { // Load all tenants tenantsArray = new ArrayList(Arrays.asList(tenantManager.getAllTenants())); Tenant superTenant = new Tenant(); superTenant.setDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); superTenant.setId(MultitenantConstants.SUPER_TENANT_ID); tenantsArray.add(superTenant); } } private void buildTenantList(TenantManager tenantManager, List<Tenant> tenantList, String tenantArguments) throws UserStoreException { if (tenantArguments.contains(",")) { // Multiple arguments specified String[] parts = tenantArguments.split(","); for (int i = 0; i < parts.length; ++i) { if (parts[i].length() > 0) { populateTenants(tenantManager, tenantList, parts[i]); } } } else { // Only single argument provided populateTenants(tenantManager, tenantList, tenantArguments); } } private void populateTenants(TenantManager tenantManager, List<Tenant> tenantList, String argument) throws UserStoreException { log.debug("Argument provided : " + argument); if (argument.contains("@")) { // Username provided as argument int tenantID = tenantManager.getTenantId(argument); if (tenantID != -1) { tenantList.add(tenantManager.getTenant(tenantID)); } else { log.error("Tenant does not exist for username " + argument); } } else { // Domain name provided as argument if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(argument)) { Tenant superTenant = new Tenant(); superTenant.setDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); superTenant.setId(MultitenantConstants.SUPER_TENANT_ID); tenantList.add(superTenant); } else { Tenant[] tenants = tenantManager.getAllTenantsForTenantDomainStr(argument); if (tenants.length > 0) { tenantList.addAll(Arrays.asList(tenants)); } else { log.error("Tenant does not exist for domain " + argument); } } } } protected List<Tenant> getTenantsArray() { return tenantsArray; } protected void updateAPIManangerDatabase(String sqlScriptPath) throws SQLException { log.info("Database migration for API Manager started"); Connection connection = null; PreparedStatement preparedStatement = null; BufferedReader bufferedReader = null; try { connection = APIMgtDBUtil.getConnection(); connection.setAutoCommit(false); String dbType = MigrationDBCreator.getDatabaseType(connection); InputStream is = new FileInputStream(sqlScriptPath + dbType + ".sql"); bufferedReader = new BufferedReader(new InputStreamReader(is, "UTF8")); String sqlQuery = ""; boolean isFoundQueryEnd = false; String line; while ((line = bufferedReader.readLine()) != null) { line = line.trim(); if (line.startsWith("//") || line.startsWith("--")) { continue; } StringTokenizer stringTokenizer = new StringTokenizer(line); if (stringTokenizer.hasMoreTokens()) { String token = stringTokenizer.nextToken(); if ("REM".equalsIgnoreCase(token)) { continue; } } if (line.contains("\\n")) { line = line.replace("\\n", ""); } sqlQuery += ' ' + line; if (line.contains(";")) { isFoundQueryEnd = true; } if (org.wso2.carbon.apimgt.migration.util.Constants.DB_TYPE_ORACLE.equals(dbType)) { sqlQuery = sqlQuery.replace(";", ""); } if (isFoundQueryEnd) { if (sqlQuery.length() > 0) { log.debug("SQL to be executed : " + sqlQuery); preparedStatement = connection.prepareStatement(sqlQuery.trim()); preparedStatement.execute(); connection.commit(); } // Reset variables to read next SQL sqlQuery = ""; isFoundQueryEnd = false; } } bufferedReader.close(); } catch (IOException e) { //Errors logged to let user know the state of the db migration and continue other resource migrations log.error("Error occurred while migrating databases", e); } catch (Exception e) { /* MigrationDBCreator extends from org.wso2.carbon.utils.dbcreator.DatabaseCreator and in the super class method getDatabaseType throws generic Exception */ log.error("Error occurred while migrating databases", e); } finally { if (preparedStatement != null) { preparedStatement.close(); } if (connection != null) { connection.close(); } } log.info("DB resource migration done for all the tenants"); } /** * This method is used to remove the FK constraint which is unnamed * This finds the name of the constraint and build the query to delete the constraint and execute it * * @param sqlScriptPath path of sql script * @throws SQLException * @throws IOException */ protected void dropFKConstraint(String sqlScriptPath) throws SQLException { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; Statement statement = null; try { String queryToExecute = IOUtils.toString(new FileInputStream(new File(sqlScriptPath + "drop-fk.sql")), "UTF-8"); String queryArray[] = queryToExecute.split(Constants.LINE_BREAK); connection = APIMgtDBUtil.getConnection(); String dbType = MigrationDBCreator.getDatabaseType(connection); connection.setAutoCommit(false); statement = connection.createStatement(); if (Constants.DB_TYPE_ORACLE.equals(dbType)) { queryArray[0] = queryArray[0].replace(Constants.DELIMITER, ""); } resultSet = statement.executeQuery(queryArray[0]); String constraintName = null; while (resultSet.next()) { constraintName = resultSet.getString("constraint_name"); } if (constraintName != null) { queryToExecute = queryArray[1].replace("<temp_key_name>", constraintName); if (Constants.DB_TYPE_ORACLE.equals(dbType)) { queryToExecute = queryToExecute.replace(Constants.DELIMITER, ""); } if (queryToExecute.contains("\\n")) { queryToExecute = queryToExecute.replace("\\n", ""); } preparedStatement = connection.prepareStatement(queryToExecute); preparedStatement.execute(); connection.commit(); } } catch (APIMigrationException e) { //Foreign key might be already deleted, log the error and let it continue log.error("Error occurred while deleting foreign key", e); } catch (IOException e) { //If user does not add the file migration will continue and migrate the db without deleting // the foreign key reference log.error("Error occurred while finding the foreign key deletion query for execution", e); } catch (Exception e) { /* MigrationDBCreator extends from org.wso2.carbon.utils.dbcreator.DatabaseCreator and in the super class method getDatabaseType throws generic Exception */ log.error("Error occurred while deleting foreign key", e); } finally { if (statement != null) { statement.close(); } APIMgtDBUtil.closeAllConnections(preparedStatement, connection, resultSet); } } }
Adding DB2 support to migration client
modules/distribution/resources/migration/wso2-api-migration-client/src/main/java/org/wso2/carbon/apimgt/migration/client/MigrationClientBase.java
Adding DB2 support to migration client
<ide><path>odules/distribution/resources/migration/wso2-api-migration-client/src/main/java/org/wso2/carbon/apimgt/migration/client/MigrationClientBase.java <ide> } <ide> <ide> if (org.wso2.carbon.apimgt.migration.util.Constants.DB_TYPE_ORACLE.equals(dbType)) { <add> sqlQuery = sqlQuery.replace(";", ""); <add> } <add> if (org.wso2.carbon.apimgt.migration.util.Constants.DB_TYPE_DB2.equals(dbType)) { <ide> sqlQuery = sqlQuery.replace(";", ""); <ide> } <ide>
Java
apache-2.0
b0f46ed89ca0c2917a267ffe7cb3338ebc5bec6c
0
drakeet/MultiType
package me.drakeet.multitype.sample; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import me.drakeet.multitype.sample.bilibili.BilibiliActivity; import me.drakeet.multitype.sample.communicate_with_binder.SimpleActivity; import me.drakeet.multitype.sample.extra_apis.SeldomUsedApisPlayground; import me.drakeet.multitype.sample.multi_select.MultiSelectActivity; import me.drakeet.multitype.sample.normal.NormalActivity; import me.drakeet.multitype.sample.one2many.OneDataToManyActivity; import me.drakeet.multitype.sample.payload.TestPayloadActivity; import me.drakeet.multitype.sample.weibo.WeiboActivity; /** * @author drakeet */ public class MenuBaseActivity extends AppCompatActivity { @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent intent = new Intent(); switch (item.getItemId()) { case R.id.NormalActivity: intent.setClass(this, NormalActivity.class); break; case R.id.MultiSelectActivity: intent.setClass(this, MultiSelectActivity.class); break; case R.id.communicate_with_binder: intent.setClass(this, SimpleActivity.class); break; case R.id.BilibiliActivity: intent.setClass(this, BilibiliActivity.class); break; case R.id.WeiboActivity: intent.setClass(this, WeiboActivity.class); break; case R.id.OneDataToManyActivity: intent.setClass(this, OneDataToManyActivity.class); break; case R.id.TestPayloadActivity: intent.setClass(this, TestPayloadActivity.class); break; case R.id.SeldomUsedApisPlayground: intent.setClass(this, SeldomUsedApisPlayground.class); break; default: return false; } startActivity(intent); this.finish(); return true; } }
sample/src/main/java/me/drakeet/multitype/sample/MenuBaseActivity.java
package me.drakeet.multitype.sample; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import me.drakeet.multitype.sample.bilibili.BilibiliActivity; import me.drakeet.multitype.sample.communicate_with_binder.SimpleActivity; import me.drakeet.multitype.sample.extra_apis.SeldomUsedApisPlayground; import me.drakeet.multitype.sample.multi_select.MultiSelectActivity; import me.drakeet.multitype.sample.normal.NormalActivity; import me.drakeet.multitype.sample.one2many.OneDataToManyActivity; import me.drakeet.multitype.sample.payload.TestPayloadActivity; import me.drakeet.multitype.sample.weibo.WeiboActivity; /** * @author drakeet */ public class MenuBaseActivity extends AppCompatActivity { @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.menu_main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent intent = new Intent(); switch (item.getItemId()) { case R.id.NormalActivity: intent.setClass(this, NormalActivity.class); break; case R.id.MultiSelectActivity: intent.setClass(this, MultiSelectActivity.class); break; case R.id.communicate_with_binder: intent.setClass(this, SimpleActivity.class); break; case R.id.BilibiliActivity: intent.setClass(this, BilibiliActivity.class); break; case R.id.WeiboActivity: intent.setClass(this, WeiboActivity.class); break; case R.id.OneDataToManyActivity: intent.setClass(this, OneDataToManyActivity.class); break; case R.id.TestPayloadActivity: intent.setClass(this, TestPayloadActivity.class); break; case R.id.SeldomUsedApisPlayground: intent.setClass(this, SeldomUsedApisPlayground.class); break; default: return false; } startActivity(intent); this.finish(); return true; } }
[sample] Removed a duplicate code
sample/src/main/java/me/drakeet/multitype/sample/MenuBaseActivity.java
[sample] Removed a duplicate code
<ide><path>ample/src/main/java/me/drakeet/multitype/sample/MenuBaseActivity.java <ide> public boolean onCreateOptionsMenu(Menu menu) { <ide> super.onCreateOptionsMenu(menu); <ide> getMenuInflater().inflate(R.menu.menu_main, menu); <del> return super.onCreateOptionsMenu(menu); <add> return true; <ide> } <ide> <ide>