answer
stringlengths
17
10.2M
package org.jaudiotagger.audio.mp4.atom; import org.jaudiotagger.audio.exceptions.CannotReadException; import org.jaudiotagger.audio.mp4.Mp4NotMetaFieldKey; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.util.Map; import java.util.HashMap; /** * HdlrBox ( Handler box), * <p/> * Describes the type of metadata in the following ilst or minf atom */ public class Mp4HdlrBox extends AbstractMp4Box { public static final int VERSION_FLAG_LENGTH = 1; public static final int OTHER_FLAG_LENGTH = 3; public static final int RESERVED_FLAG_LENGTH = 4; public static final int HANDLER_LENGTH = 4; public static final int RESERVED1_LENGTH = 4; public static final int RESERVED2_LENGTH = 4; public static final int RESERVED3_LENGTH = 4; public static final int NAME_LENGTH = 2; public static final int HANDLER_POS = VERSION_FLAG_LENGTH + OTHER_FLAG_LENGTH + RESERVED_FLAG_LENGTH; public static final int RESERVED1_POS = HANDLER_POS + HANDLER_LENGTH; //Size used by iTunes, but other application could use different size because name field is variable public static final int ITUNES_META_HDLR_DAT_LENGTH = VERSION_FLAG_LENGTH + OTHER_FLAG_LENGTH + RESERVED_FLAG_LENGTH + HANDLER_LENGTH + RESERVED1_LENGTH + RESERVED2_LENGTH + RESERVED3_LENGTH + NAME_LENGTH; private int reserved; // 32 bit private String handlerType; // 4 bytes; private String name; // Variable length but 4 bytes in existing files private MediaDataType mediaDataType; private static Map<String, MediaDataType> mediaDataTypeMap; static { //Create maps to speed up lookup from raw value to enum mediaDataTypeMap = new HashMap<String, MediaDataType>(); for (MediaDataType next : MediaDataType.values()) { mediaDataTypeMap.put(next.getId(), next); } } /** * DataBuffer must start from from the start of the body * * @param header header info * @param dataBuffer data of box (doesnt include header data) */ public Mp4HdlrBox(Mp4BoxHeader header, ByteBuffer dataBuffer) { this.header = header; this.dataBuffer = dataBuffer; } public void processData() throws CannotReadException { //Skip other flags dataBuffer.position(dataBuffer.position() + VERSION_FLAG_LENGTH + OTHER_FLAG_LENGTH + RESERVED_FLAG_LENGTH); CharsetDecoder decoder = Charset.forName("ISO-8859-1").newDecoder(); try { handlerType = decoder.decode((ByteBuffer) dataBuffer.slice().limit(HANDLER_LENGTH)).toString(); } catch (CharacterCodingException cee) { //Ignore } //To get human readable name mediaDataType = mediaDataTypeMap.get( handlerType); } public String getHandlerType() { return handlerType; } public MediaDataType getMediaDataType() { return mediaDataType; } public String toString() { String s = "handlerType:" + handlerType + ":human readable:"+mediaDataType.getDescription(); return s; } public static enum MediaDataType { ODSM("odsm", "ObjectDescriptorStream - defined in ISO/IEC JTC1/SC29/WG11 - CODING OF MOVING PICTURES AND AUDIO"), CRSM("crsm", "ClockReferenceStream - defined in ISO/IEC JTC1/SC29/WG11 - CODING OF MOVING PICTURES AND AUDIO"), SDSM("sdsm", "SceneDescriptionStream - defined in ISO/IEC JTC1/SC29/WG11 - CODING OF MOVING PICTURES AND AUDIO"), M7SM("m7sm", "MPEG7Stream - defined in ISO/IEC JTC1/SC29/WG11 - CODING OF MOVING PICTURES AND AUDIO"), OCSM("ocsm", "ObjectContentInfoStream - defined in ISO/IEC JTC1/SC29/WG11 - CODING OF MOVING PICTURES AND AUDIO"), IPSM("ipsm", "IPMP Stream - defined in ISO/IEC JTC1/SC29/WG11 - CODING OF MOVING PICTURES AND AUDIO"), MJSM("mjsm", "MPEG-J Stream - defined in ISO/IEC JTC1/SC29/WG11 - CODING OF MOVING PICTURES AND AUDIO"), MDIR("mdir", "Apple Meta Data iTunes Reader"), MP7B("mp7b", "MPEG-7 binary XML"), MP7T("mp7t", "MPEG-7 XML"), VIDE("vide", "Video Track"), SOUN("soun", "Sound Track"), HINT("hint", "Hint Track"), APPL("appl", "Apple specific"), META("meta", "Timed Metadata track - defined in ISO/IEC JTC1/SC29/WG11 - CODING OF MOVING PICTURES AND AUDIO"),; private String id; private String description; MediaDataType(String id, String description) { this.id = id; this.description=description; } public String getId() { return id; } public String getDescription() { return description; } } /** * Create an iTunes style Hdlr box for use within Meta box * * <p>Useful when writing to mp4 that previously didn't contain an mp4 meta atom</p> * * <p>Doesnt write the child data but uses it to se the header length, only sets the atoms immediate * data</p * @return */ public static Mp4HdlrBox createiTunesStyleHdlrBox() { Mp4BoxHeader hdlrHeader = new Mp4BoxHeader(Mp4NotMetaFieldKey.HDLR.getFieldName()); hdlrHeader.setLength(Mp4BoxHeader.HEADER_LENGTH + Mp4HdlrBox.ITUNES_META_HDLR_DAT_LENGTH); ByteBuffer hdlrData = ByteBuffer.allocate(Mp4HdlrBox.ITUNES_META_HDLR_DAT_LENGTH); hdlrData.put(HANDLER_POS,(byte)0x6d); //mdir hdlrData.put(HANDLER_POS+1,(byte)0x64); hdlrData.put(HANDLER_POS+2,(byte)0x69); hdlrData.put(HANDLER_POS+3,(byte)0x72); hdlrData.put(RESERVED1_POS,(byte)0x61); //appl hdlrData.put(RESERVED1_POS+1,(byte)0x70); hdlrData.put(RESERVED1_POS+2,(byte)0x70); hdlrData.put(RESERVED1_POS+3,(byte)0x6c); hdlrData.rewind(); Mp4HdlrBox hdlrBox = new Mp4HdlrBox(hdlrHeader,hdlrData); return hdlrBox; } }
package org.opencms.main; import org.opencms.file.CmsObject; import org.opencms.file.CmsUser; import org.opencms.security.I_CmsAuthorizationHandler; import org.opencms.util.CmsUUID; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.commons.logging.Log; /** * Abstract class to grant the needed access to the session manager.<p> * * @since 6.5.4 */ public abstract class A_CmsAuthorizationHandler implements I_CmsAuthorizationHandler { /** The static log object for this class. */ protected static final Log LOG = CmsLog.getLog(A_CmsAuthorizationHandler.class); /** Additional parameters. */ protected Map<String, String> m_parameters; /** * @see org.opencms.security.I_CmsAuthorizationHandler#setParameters(java.util.Map) */ public void setParameters(Map<String, String> parameters) { m_parameters = parameters; } /** * Initializes a new cms object from the session data of the request.<p> * * If no session data is found, <code>null</code> is returned.<p> * * @param request the request * * @return the new initialized cms object * * @throws CmsException if something goes wrong */ protected CmsObject initCmsObjectFromSession(HttpServletRequest request) throws CmsException { // try to get an OpenCms user session info object for this request return OpenCmsCore.getInstance().initCmsObjectFromSession(request); } /** * Registers the current session with OpenCms.<p> * * @param request the current request * @param cms the cms object to register * * @return the updated cms context * * @throws CmsException if something goes wrong */ protected CmsObject registerSession(HttpServletRequest request, CmsObject cms) throws CmsException { // make sure we have a new session after login for security reasons HttpSession session = request.getSession(false); if (session != null) { session.invalidate(); } session = request.getSession(true); // update the request context cms = OpenCmsCore.getInstance().updateContext(request, cms); CmsUser user = cms.getRequestContext().getCurrentUser(); if (!user.isGuestUser() && !OpenCms.getDefaultUsers().isUserExport(user.getName())) { // create the session info object, only for 'real' users CmsSessionInfo sessionInfo = new CmsSessionInfo( cms.getRequestContext(), new CmsUUID(), request.getSession().getMaxInactiveInterval()); // register the updated cms object in the session manager OpenCmsCore.getInstance().getSessionManager().addSessionInfo(sessionInfo); } // return the updated cms object return cms; } }
package org.phenoscape.bridge; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.sql.SQLException; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.apache.log4j.Logger; import org.apache.xmlbeans.XmlException; import org.bbop.dataadapter.DataAdapterException; import org.obd.model.Graph; import org.obd.query.Shard; import org.obd.query.impl.AbstractSQLShard; import org.obd.query.impl.OBDSQLShard; import org.obo.dataadapter.OBOAdapter; import org.obo.dataadapter.OBOFileAdapter; import org.obo.datamodel.OBOSession; import org.oboedit.controller.SessionManager; import org.phenoscape.io.NeXMLReader; import org.phenoscape.model.DataSet; import org.phenoscape.model.OntologyController; public class PhenoscapeDataLoader { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub // String dataDir = args[0]; PhenoscapeDataLoader pdl = new PhenoscapeDataLoader(); try { pdl.loadData(args[0], args[1]); } catch (Exception e) { e.printStackTrace(); } } public void loadData(String dataDir, String dbConn) throws XmlException, IOException, SQLException, ClassNotFoundException { OBDModelBridge bridge = new OBDModelBridge(); NeXMLReader reader; DataSet ds; Graph g; // String basePath = "/home/cartik/data/"; File baseDataDir = new File(dataDir); int i = 0; // OBOSessionShard s = new OBOSessionShard(); File connParamFile = new File(dbConn); BufferedReader br = new BufferedReader(new FileReader(connParamFile)); String[] connParams = new String[3]; String param; int j = 0, t = 0; while ((param = br.readLine()) != null) { connParams[j++] = param; } Shard obdsql = new OBDSQLShard(); ((AbstractSQLShard) obdsql).connect(connParams[0], connParams[1], connParams[2]); final OBOSession oboSession = this.loadOBOSession(); List<File> baseDirs = Arrays.asList(baseDataDir.listFiles()); Collections.sort(baseDirs); for (File baseDir : baseDirs) { // check to avoid .. and . directories if (baseDir.isDirectory() && !baseDir.getName().contains(".")) { List<File> files = Arrays.asList(baseDir.listFiles()); Collections.sort(files); for (File dataFile : files) { // another check to avoid directories if (dataFile.isFile()) { System.out.println(++i + ". Started work with " + dataFile.getAbsolutePath()); reader = new NeXMLReader(dataFile, oboSession); ds = reader.getDataSet(); bridge.translate(ds, dataFile); g = bridge.getGraph(); obdsql.putGraph(g); // s.putGraph(g); t += g.getStatements().size(); System.out.println(g.getStatements().size() + " records added"); System.out.println(i + ". Finished loading " + dataFile.getAbsolutePath()); } } } } bridge.problemLog.flush(); bridge.problemLog.close(); System.out.println(t + " total statements from " + i + " files loaded. Done!"); } private OBOSession loadOBOSession() { final OBOFileAdapter fileAdapter = new OBOFileAdapter(); OBOFileAdapter.OBOAdapterConfiguration config = new OBOFileAdapter.OBOAdapterConfiguration(); config.setReadPaths(Arrays.asList(this.getPaths())); config.setBasicSave(false); config.setAllowDangling(true); config.setFollowImports(false); try { return fileAdapter.doOperation(OBOAdapter.READ_ONTOLOGY, config, null); } catch (DataAdapterException e) { log().fatal("Failed to load ontologies", e); return null; } } private String[] getPaths() { // TODO Auto-generated method stub // return an array of paths to OBO files, as strings return null; } private Logger log() { return Logger.getLogger(this.getClass()); } }
package org.treetank.sessionlayer; import org.treetank.api.IConstants; import org.treetank.api.IWriteTransaction; import org.treetank.nodelayer.Node; import org.treetank.pagelayer.UberPage; /** * <h1>WriteTransaction</h1> * * <p> * Single-threaded instance of only write transaction per session. * </p> */ public final class WriteTransaction extends ReadTransaction implements IWriteTransaction { /** * Constructor. * * @param sessionState State of the session. * @param transactionState State of this transaction. */ protected WriteTransaction( final SessionState sessionState, final WriteTransactionState transactionState) { super(sessionState, transactionState); } /** * {@inheritDoc} */ public final long insertElementAsFirstChild( final String localPart, final String uri, final String prefix) throws Exception { assertIsSelected(); setCurrentNode(((WriteTransactionState) getTransactionState()) .createElementNode( getCurrentNode().getNodeKey(), IConstants.NULL_KEY, IConstants.NULL_KEY, getCurrentNode().getFirstChildKey(), ((WriteTransactionState) getTransactionState()) .createNameKey(localPart), ((WriteTransactionState) getTransactionState()).createNameKey(uri), ((WriteTransactionState) getTransactionState()) .createNameKey(prefix))); updateParent(true); if (getCurrentNode().getChildCount() > 0) { updateRightSibling(); } return getCurrentNode().getNodeKey(); } /** * {@inheritDoc} */ public final long insertTextAsFirstChild(final byte[] value) throws Exception { assertIsSelected(); setCurrentNode(((WriteTransactionState) getTransactionState()) .createTextNode( getCurrentNode().getNodeKey(), IConstants.NULL_KEY, IConstants.NULL_KEY, value)); updateParent(true); if (getCurrentNode().getChildCount() > 0) { updateRightSibling(); } return getCurrentNode().getNodeKey(); } /** * {@inheritDoc} */ public final long insertElementAsRightSibling( final String localPart, final String uri, final String prefix) throws Exception { assertIsSelected(); if (getCurrentNode().getNodeKey() == IConstants.ROOT_KEY) { throw new IllegalStateException("Root node can not have siblings."); } // Create new right sibling node. setCurrentNode(((WriteTransactionState) getTransactionState()) .createElementNode( getCurrentNode().getParentKey(), IConstants.NULL_KEY, getCurrentNode().getNodeKey(), getCurrentNode().getRightSiblingKey(), ((WriteTransactionState) getTransactionState()) .createNameKey(localPart), ((WriteTransactionState) getTransactionState()).createNameKey(uri), ((WriteTransactionState) getTransactionState()) .createNameKey(prefix))); updateParent(false); updateLeftSibling(); updateRightSibling(); return getCurrentNode().getNodeKey(); } /** * {@inheritDoc} */ public final long insertTextAsRightSibling(final byte[] value) throws Exception { assertIsSelected(); if (getCurrentNode().getNodeKey() == IConstants.ROOT_KEY) { throw new IllegalStateException("Root node can not have siblings."); } // Create new right sibling node. setCurrentNode(((WriteTransactionState) getTransactionState()) .createTextNode(getCurrentNode().getParentKey(), getCurrentNode() .getNodeKey(), getCurrentNode().getRightSiblingKey(), value)); updateParent(false); updateLeftSibling(); updateRightSibling(); return getCurrentNode().getNodeKey(); } /** * {@inheritDoc} */ public final void insertAttribute( final String localPart, final String uri, final String prefix, final byte[] value) throws Exception { assertIsSelected(); prepareCurrentNode().insertAttribute( ((WriteTransactionState) getTransactionState()) .createNameKey(localPart), ((WriteTransactionState) getTransactionState()).createNameKey(uri), ((WriteTransactionState) getTransactionState()).createNameKey(prefix), value); } /** * {@inheritDoc} */ public final void insertNamespace(final String uri, final String prefix) throws Exception { assertIsSelected(); prepareCurrentNode().insertNamespace( ((WriteTransactionState) getTransactionState()).createNameKey(uri), ((WriteTransactionState) getTransactionState()).createNameKey(prefix)); } /** * {@inheritDoc} */ public final void remove() throws Exception { assertIsSelected(); if (getCurrentNode().getChildCount() > 0) { throw new IllegalStateException("INode " + getCurrentNode().getNodeKey() + " has " + getCurrentNode().getChildCount() + " child(ren) and can not be removed."); } if (getCurrentNode().getNodeKey() == IConstants.ROOT_KEY) { throw new IllegalStateException("Root node can not be removed."); } // Remember left and right sibling keys. final long parentKey = getCurrentNode().getParentKey(); final long nodeKey = getCurrentNode().getNodeKey(); final long leftSiblingNodeKey = getCurrentNode().getLeftSiblingKey(); final long rightSiblingNodeKey = getCurrentNode().getRightSiblingKey(); // Remove old node. ((WriteTransactionState) getTransactionState()).removeNode(nodeKey); // Get and adapt parent node. setCurrentNode(((WriteTransactionState) getTransactionState()) .prepareNode(parentKey)); ((Node) getCurrentNode()).decrementChildCount(); ((Node) getCurrentNode()).setFirstChildKey(rightSiblingNodeKey); // Adapt left sibling node if there is one. if (leftSiblingNodeKey != IConstants.NULL_KEY) { final Node leftSiblingNode = ((WriteTransactionState) getTransactionState()) .prepareNode(leftSiblingNodeKey); leftSiblingNode.setRightSiblingKey(rightSiblingNodeKey); } // Adapt right sibling node if there is one. if (rightSiblingNodeKey != IConstants.NULL_KEY) { final Node rightSiblingNode = ((WriteTransactionState) getTransactionState()) .prepareNode(rightSiblingNodeKey); rightSiblingNode.setLeftSiblingKey(leftSiblingNodeKey); } } /** * {@inheritDoc} */ public final void setAttribute( final int index, final String localPart, final String uri, final String prefix, final byte[] value) throws Exception { assertIsSelected(); prepareCurrentNode().setAttribute( index, ((WriteTransactionState) getTransactionState()) .createNameKey(localPart), ((WriteTransactionState) getTransactionState()).createNameKey(uri), ((WriteTransactionState) getTransactionState()).createNameKey(prefix), value); } /** * {@inheritDoc} */ public final void setNamespace( final int index, final String uri, final String prefix) throws Exception { assertIsSelected(); prepareCurrentNode().setNamespace( index, ((WriteTransactionState) getTransactionState()).createNameKey(uri), ((WriteTransactionState) getTransactionState()).createNameKey(prefix)); } /** * {@inheritDoc} */ public final void setLocalPart(final String localPart) throws Exception { assertIsSelected(); prepareCurrentNode().setLocalPartKey( ((WriteTransactionState) getTransactionState()) .createNameKey(localPart)); } /** * {@inheritDoc} */ public final void setURI(final String uri) throws Exception { assertIsSelected(); prepareCurrentNode().setURIKey( ((WriteTransactionState) getTransactionState()).createNameKey(uri)); } /** * {@inheritDoc} */ public void setPrefix(final String prefix) throws Exception { assertIsSelected(); prepareCurrentNode().setPrefixKey( ((WriteTransactionState) getTransactionState()).createNameKey(prefix)); } /** * {@inheritDoc} */ public final void setValue(final byte[] value) throws Exception { assertIsSelected(); prepareCurrentNode().setValue(value); } /** * {@inheritDoc} */ @Override public final void close() { throw new IllegalAccessError( "Write transactions must either be committed or aborted."); } /** * {@inheritDoc} */ public final void commit() throws Exception { final UberPage uberPage = ((WriteTransactionState) getTransactionState()) .commit(getSessionState().getSessionConfiguration()); // Close own state. getTransactionState().close(); // Callback on session to make sure everything is cleaned up. getSessionState().commitWriteTransaction(uberPage); getSessionState().closeWriteTransaction(); } /** * {@inheritDoc} */ public final void abort() { // Close own state. getTransactionState().close(); // Callback on session to make sure everything is cleaned up. getSessionState().abortWriteTransaction(); getSessionState().closeWriteTransaction(); } private final Node prepareCurrentNode() throws Exception { final Node modNode = ((WriteTransactionState) getTransactionState()) .prepareNode(getCurrentNode().getNodeKey()); setCurrentNode(modNode); return modNode; } private final void updateParent(final boolean updateFirstChild) throws Exception { final Node parentNode = ((WriteTransactionState) getTransactionState()) .prepareNode(getCurrentNode().getParentKey()); parentNode.incrementChildCount(); if (updateFirstChild) { parentNode.setFirstChildKey(getCurrentNode().getNodeKey()); } } private final void updateRightSibling() throws Exception { if (getCurrentNode().hasRightSibling()) { final Node rightSiblingNode = ((WriteTransactionState) getTransactionState()) .prepareNode(getCurrentNode().getRightSiblingKey()); rightSiblingNode.setLeftSiblingKey(getCurrentNode().getNodeKey()); } } private final void updateLeftSibling() throws Exception { final Node leftSiblingNode = ((WriteTransactionState) getTransactionState()) .prepareNode(getCurrentNode().getLeftSiblingKey()); leftSiblingNode.setRightSiblingKey(getCurrentNode().getNodeKey()); } }
package com.jetbrains.python.psi.impl; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.jetbrains.python.PyNames; import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.resolve.PyResolveContext; import org.jetbrains.annotations.Nullable; import java.io.File; /** * @author yole */ public class PyPathEvaluator { private PyPathEvaluator() { } @Nullable public static String evaluate(PyExpression expr) { if (expr == null) { return null; } VirtualFile vFile = expr.getContainingFile().getVirtualFile(); return evaluate(expr, vFile == null ? null : vFile.getPath()); } @Nullable public static String evaluate(PyExpression expr, String containingFilePath) { if (expr == null) { return null; } if (expr instanceof PyCallExpression) { final PyCallExpression call = (PyCallExpression)expr; final PyExpression[] args = call.getArguments(); if (call.isCalleeText(PyNames.DIRNAME) && args.length == 1) { String argValue = evaluate(args[0], containingFilePath); return argValue == null ? null : new File(argValue).getParent(); } else if (call.isCalleeText(PyNames.JOIN) && args.length >= 1) { return evaluatePathInJoin(containingFilePath, args, args.length); } else if (call.isCalleeText(PyNames.ABSPATH) && args.length == 1) { String argValue = evaluate(args[0], containingFilePath); // relative to directory of 'containingFilePath', not file if (argValue == null) { return null; } if (FileUtil.isAbsolute(argValue)) { return argValue; } else { return new File(new File(containingFilePath).getParent(), argValue).getPath(); } } else if (call.isCalleeText(PyNames.REPLACE) && args.length == 2) { final PyExpression callee = call.getCallee(); if (!(callee instanceof PyQualifiedExpression)) return null; final PyExpression qualifier = ((PyQualifiedExpression)callee).getQualifier(); String result = evaluate(qualifier, containingFilePath); if (result == null) return null; String arg1 = evaluate(args[0], containingFilePath); String arg2 = evaluate(args[1], containingFilePath); if (arg1 == null || arg2 == null) return null; return result.replace(arg1, arg2); } } else if (expr instanceof PyReferenceExpression) { if (((PyReferenceExpression)expr).getQualifier() == null) { final String refName = ((PyReferenceExpression)expr).getReferencedName(); if (PyNames.FILE.equals(refName)) { return containingFilePath; } PsiElement result = ((PyReferenceExpression)expr).getReference(PyResolveContext.noImplicits()).resolve(); if (result instanceof PyTargetExpression) { result = ((PyTargetExpression)result).findAssignedValue(); } if (result instanceof PyExpression) { return evaluate((PyExpression)result, containingFilePath); } } } else if (expr instanceof PyStringLiteralExpression) { return ((PyStringLiteralExpression)expr).getStringValue(); } return null; } public static String evaluatePathInJoin(String containingFilePath, PyExpression[] args, int endElement) { String result = null; for (int i = 0; i< endElement; i++) { String arg = evaluate(args[i], containingFilePath); if (arg == null) { return null; } if (result == null) { result = arg; } else { result = new File(result, arg).getPath(); } } return result; } }
package nl.hannahsten.texifyidea.util; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * @author Hannah Schellekens */ public class TexifyUtilTest { @Test public void appendExtension() throws Exception { String path = "SomePath"; String extension = "tex"; String actualResult = StringsKt.appendExtension(path, extension); String expectedResult = "SomePath.tex"; assertEquals("SomePath + tex", expectedResult, actualResult); } @Test public void appendExtensionEndsDot() throws Exception { String path = "SomePath."; String extension = "tex"; String actualResult = StringsKt.appendExtension(path, extension); String expectedResult = "SomePath.tex"; assertEquals("SomePath. + tex", expectedResult, actualResult); } @Test public void appendExtensionAlreadyThere() throws Exception { String path = "SomePath.tex"; String extension = "tex"; String actualResult = StringsKt.appendExtension(path, extension); String expectedResult = "SomePath.tex"; assertEquals("SomePath.tex + tex", expectedResult, actualResult); } @Test public void appendExtensionDoubleExtesion() throws Exception { String path = "SomePath.tex.tex"; String extension = "tex"; String actualResult = StringsKt.appendExtension(path, extension); String expectedResult = "SomePath.tex.tex"; assertEquals("SomePath.tex.tex + tex", expectedResult, actualResult); } @Test public void appendExtensionCrazyCapitals() throws Exception { String path = "SoMEPaTH.TEx"; String extension = "tEX"; String actualResult = StringsKt.appendExtension(path, extension); String expectedResult = "SomePath.tex"; assertTrue("SoMEPaTH.TEx + tEX", actualResult.equalsIgnoreCase(expectedResult)); } }
package musikerverwaltung.Swing; import musikerverwaltung.Graphics.*; import javax.swing.UIManager.*; import java.awt.*; import javax.swing.*; import javax.swing.plaf.InsetsUIResource; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; public class MusicLounge14 extends JFrame { // VersionsNr. festlegen private static final long serialVersionUID = 8L; // Felder: private Color bgheader; // Schriften: private Font fheader; // Instanzen erzeugen, die zur GUI hinzugefuegt werden private Uebersichtstabelle03 jtpmain = new Uebersichtstabelle03(); // Farben // Contentpane private Container copa; // JMenuBar private JMenuBar jmbmenu; // JMenu private JMenu jmdatei; // JMenuItem private JMenuItem jmiimport, jmiexport, jmiexit; // JPanel private JPanel jpall, jpheader, jpheaderleft, jpheaderright, jpmain, jpinfo, jpselect, jpfooter; // JLabels private JLabel jlheader, jlsearch, jlmenudate; // JButton private JButton jbmaintable, jbnewart, jbnewband, jbedit; // GradientJPanels private GradientJPanels03 gpright, gpleft, gpnew, gpmain, gpfooter; // JTextField private RoundJTextField03 jtfsearch; // Konstruktor private MusicLounge14() { // Titel (Aufruf mit super aus der Basisklasse) super("MusicLounge14"); try { for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (UnsupportedLookAndFeelException e) { // handle exception } catch (ClassNotFoundException e) { // handle exception } catch (InstantiationException e) { // handle exception } catch (IllegalAccessException e) { // handle exception } // Sauberes Schlieen ermoeglichen setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Schriften erzeugen fheader = new Font(Font.DIALOG, Font.BOLD + Font.ITALIC, 25); // Farben erzeugen bgheader = new Color(214, 214, 214); // Farbverlaeufe aus der Klasse >GradientPanel< gpright = new GradientJPanels03("gpheaderright"); gpleft = new GradientJPanels03("gpheaderleft"); // gpnew = new GradientJPanels03("gpnew"); gpmain = new GradientJPanels03("gpmain"); // GradientJPanels01 gpinfo = new GradientJPanels01("gpinfo"); gpfooter = new GradientJPanels03("gpfooter"); // Gibt ContentPane Objekt zurueck copa = getContentPane(); // JMenuBar erzeugen jmbmenu = new JMenuBar(); // JMenu erzeugen jmdatei = new JMenu("Datei"); // JMenuItems erzeugen jmiimport = new JMenuItem("Importieren"); jmiexport = new JMenuItem("Exportieren"); jmiexit = new JMenuItem("Beenden"); // Abstand setzen jmdatei.setMargin(new Insets(0, 10, 0, 100)); // Items dem Menupunkt hinzufuegen jmdatei.add(jmiimport); jmdatei.add(jmiexport); jmdatei.add(jmiexit); jlmenudate = new JLabel("Datum"); // Menupunkte der JMenubar hinzufuegen jmbmenu.add(jmdatei); jmbmenu.add(Box.createHorizontalStrut(1150)); jmbmenu.add(jlmenudate); // JMenubar dem Frame hinzufuegen add(jmbmenu, BorderLayout.NORTH); // JPanel erzeugen mit BorderLayout jpall = new JPanel(new BorderLayout()); jpall.setBackground(bgheader); jpheader = new JPanel(new BorderLayout()); jpheader.setBackground(bgheader); jpheaderleft = new JPanel(); jpheaderright = new JPanel(); jpmain = new JPanel(new BorderLayout()); jpinfo = new JPanel(); jpselect = new JPanel(new GridLayout(3, 1, 6, 6)); jpfooter = new JPanel(); // >jpselect< durchsichtig machen, damit zwischen den JButtons, der // Hintergrund durchgemalt wird jpselect.setOpaque(false); jpfooter.setOpaque(false); // JPanels der >jpall< hinzufuegen jpall.add(jpheader, BorderLayout.NORTH); jpall.add(jpmain, BorderLayout.CENTER); // jpall.add(gpinfo, BorderLayout.EAST); // jpall.add(gpnew, BorderLayout.WEST); jpall.add(gpfooter, BorderLayout.SOUTH); // JPanels der >jpheader< hinzufuegen jpheader.add(gpleft); jpheader.add(gpright, BorderLayout.EAST); // JLabel erzeugen jlheader = new JLabel("MusicLounge"); // Instanz der Klasse Incons erzeugen Icons01 searchicon = new Icons01(); // JLabel Icon zuweisen jlsearch = new JLabel(searchicon.icons[3]); // JButton erzeugen jbmaintable = new JButton("bersicht"); jbmaintable.setPreferredSize(new Dimension(150, 35)); jbnewart = new JButton("Neuer Artist"); jbnewart.setPreferredSize(new Dimension(150, 35)); jbnewband = new JButton("Neue Band"); jbnewband.setPreferredSize(new Dimension(150, 35)); jbedit = new JButton("Bearbeiten"); jbedit.setPreferredSize(new Dimension(100, 35)); // JTextField erzeugen jtfsearch = new RoundJTextField03(13); // JLabels der >jpheaderright< hinzufuegen gpleft.add(jpheaderleft.add(jlheader)); gpright.add(jpheaderright.add(jlsearch)); gpright.add(jpheaderright.add(jtfsearch)); // JTabbedPane einbinden // Pointer auf die Variable legen jtpmain.jtpmaindesc = jtpmain.jtpmaindesc(null); jpmain.add(jtpmain.jtpmaindesc, BorderLayout.CENTER); // Tabs hinzufuegen AddTabs02.insertArtist(jtpmain.jtpmaindesc, "Interpret eintragen"); AddTabs02.insertBand(jtpmain.jtpmaindesc, "Band eintragen"); // Schriftart hinzufuegen jlheader.setFont(fheader); // JButton der >jpselect< hinzufuegen jpselect.add(jbmaintable); jpselect.add(jbnewart); jpselect.add(jbnewband); // der Instanz von GradientPanel das JPanel >jpselect< hinzufuegen // gpnew.add(jpselect); // gpnew.setPreferredSize(new Dimension(200, 50)); // JButton der >jpedit< hinzufuegen // gpinfo.add(jpinfo.add(jbedit)); // gpinfo.setPreferredSize(new Dimension(200, 50)); // jpfooter gpfooter.add(jpfooter); // JPanel der ContentPane hinzufuegen copa.add(jpall); // ActionLister(); actionListenerJButton(); actionListenerJMenuItems(); searchKeyListener(); mouseListenerJTP(); // Anfangsposition und -groesse festlegen setBounds(50, 50, 1280, 720); // Groesse nicht veraenderbar setResizable(false); // Frame sichtbar machen setVisible(true); } private void actionListenerJButton() { // Button jbmaintable.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { jpmain.removeAll(); jpmain.revalidate(); jpmain.repaint(); // Pointer auf die Variable legen jtpmain.jtpmaindesc = jtpmain.jtpmaindesc(null); jpmain.add(jtpmain.jtpmaindesc); jpmain.setVisible(true); } }); } private void actionListenerJMenuItems() { // Button jmiexit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { System.exit(0); } }); } public void mouseListenerJTP() { jtpmain.jtpmaindesc.addMouseListener(new MouseListener() { @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub if (e.getButton() == 3) { int zahl = jtpmain.jtpmaindesc.getSelectedIndex(); int auswahl; if (zahl > 2) { auswahl = JOptionPane.showConfirmDialog(null, "Bist du sicher ? Alle Daten gehen verloren !", "Tab-Schlieen", JOptionPane.YES_NO_OPTION); if (auswahl == JOptionPane.YES_OPTION) { jtpmain.jtpmaindesc.remove(zahl); } } } } @Override public void mousePressed(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseClicked(MouseEvent e) { // TODO Auto-generated method stub } }); } // KeyListener fuer die Suchfunktion public void searchKeyListener() { jtfsearch.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyPressed(KeyEvent e) { // TODO Auto-generated method stub // Abfrage ob "Enter" gedrueckt wurde (KeyCode = 10) if (e.getKeyCode() == 10) { // zaehlen der Tabs int tabindex = jtpmain.jtpmaindesc.getTabCount(); // String-Array in dem die Title der Tabs gespeichert werden String[] title = new String[tabindex]; // Speicher der Tab-Titel im Array for (int j = 0; j < tabindex; j++) { title[j] = jtpmain.jtpmaindesc.getTitleAt(j); } // Neu zeichnen lassen jpmain.removeAll(); jpmain.revalidate(); jpmain.repaint(); // Pointer auf die Variable legen jtpmain.jtpmaindesc = jtpmain.jtpmaindesc(jtfsearch .getText()); // Hinzufuegen der TabbedPane zum Panel jpmain.add(jtpmain.jtpmaindesc); jpmain.setVisible(true); // Tabs hinzufuegen AddTabs02.insertArtist(jtpmain.jtpmaindesc, "Interpret eintragen"); AddTabs02.insertBand(jtpmain.jtpmaindesc, "Band eintragen"); // Vorher bestehende Tabs wieder hinzufuegen nach Suche for (int i = 0; i < tabindex; i++) { // Erst ab zweiten Tab ausfuehren if (i > 2) { // Uebergabe der Tab-Titel fuer Titel und // weiterleitung an die Suche AddTabs02.showArtist(jtpmain.jtpmaindesc, title[i], title[i]); } } // Text wieder leeren - muss am Ende stehen jtfsearch.setText(""); // MouseListener wieder hinzufuegen mouseListenerJTP(); } } }); } public static void main(String[] args) { // TODO Auto-generated method stub // Konfliktfreies spaeteres paralleles Betreiben des Dialoges // sicherstellen SwingUtilities.invokeLater(new Runnable() { public void run() { new MusicLounge14(); } }); } }
package com.intellij.refactoring; import com.intellij.codeInsight.CodeInsightTestCase; import com.intellij.idea.IdeaTestUtil; import com.intellij.openapi.application.ex.PathManagerEx; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.projectRoots.impl.JavaSdkImpl; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiPackage; import com.intellij.psi.impl.source.PostprocessReformattingAspect; import com.intellij.refactoring.move.moveClassesOrPackages.MoveClassesOrPackagesProcessor; import com.intellij.refactoring.move.moveClassesOrPackages.SingleSourceRootMoveDestination; import com.intellij.testFramework.PsiTestUtil; import java.io.File; public class MoveClassTest extends CodeInsightTestCase { public void testContextChange() throws Exception{ doTest("contextChange1", new String[]{"pack1.Class1"}, "pack2"); doTest("contextChange2", new String[]{"pack1.Class1"}, "pack2"); } public void testMoveMultiple() throws Exception{ doTest("moveMultiple1", new String[]{"pack1.Class1", "pack1.Class2"}, "pack2"); } public void testSecondaryClass() throws Exception{ doTest("secondaryClass", new String[]{"pack1.Class2"}, "pack1"); } public void testStringsAndComments() throws Exception{ doTest("stringsAndComments", new String[]{"pack1.Class1"}, "pack2"); } public void testStringsAndComments2() throws Exception{ doTest("stringsAndComments2", new String[]{"pack1.AClass"}, "pack2"); } public void testNonJava() throws Exception{ doTest("nonJava", new String[]{"pack1.Class1"}, "pack2"); } /* IMPLEMENT: getReferences() in JspAttributeValueImpl should be dealed with (soft refs?) public void testJsp() throws Exception{ doTest("jsp", new String[]{"pack1.TestClass"}, "pack2"); } */ public void testLocalClass() throws Exception{ doTest("localClass", new String[]{"pack1.A"}, "pack2"); } private void doTest(String testName, String[] classNames, String newPackageName) throws Exception{ String root = PathManagerEx.getTestDataPath()+ "/refactoring/moveClass/" + testName; String rootBefore = root + "/before"; PsiTestUtil.removeAllRoots(myModule, JavaSdkImpl.getMockJdk("java 1.4")); VirtualFile rootDir = PsiTestUtil.createTestProjectStructure(myProject, myModule, rootBefore, myFilesToDelete); performAction(classNames, newPackageName); String rootAfter = root + "/after"; VirtualFile rootDir2 = LocalFileSystem.getInstance().findFileByPath(rootAfter.replace(File.separatorChar, '/')); myProject.getComponent(PostprocessReformattingAspect.class).doPostponedFormatting(); IdeaTestUtil.assertDirectoriesEqual(rootDir2, rootDir, MultiFileTestCase.CVS_FILE_FILTER); } private void performAction(String[] classNames, String newPackageName) throws Exception{ final PsiClass[] classes = new PsiClass[classNames.length]; for(int i = 0; i < classes.length; i++){ String className = classNames[i]; classes[i] = myPsiManager.findClass(className); assertNotNull("Class " + className + " not found", classes[i]); } PsiPackage aPackage = myPsiManager.findPackage(newPackageName); assertNotNull(aPackage); final PsiDirectory[] dirs = aPackage.getDirectories(); assertEquals(dirs.length, 1); new MoveClassesOrPackagesProcessor(myProject, classes, new SingleSourceRootMoveDestination(PackageWrapper.create(dirs[0].getPackage()), dirs[0]), true, true, null).run(); PsiDocumentManager.getInstance(myProject).commitAllDocuments(); FileDocumentManager.getInstance().saveAllDocuments(); } }
package com.remote; import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import static android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; import com.facebook.react.LifecycleState; import com.facebook.react.ReactInstanceManager; import com.facebook.react.ReactRootView; import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler; import com.facebook.react.shell.MainReactPackage; import com.facebook.soloader.SoLoader; public class MainActivity extends Activity implements DefaultHardwareBackBtnHandler { private ReactInstanceManager mReactInstanceManager; private ReactRootView mReactRootView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mReactRootView = new ReactRootView(this); mReactInstanceManager = ReactInstanceManager.builder() .setApplication(getApplication()) .setBundleAssetName("index.android.bundle") .setJSMainModuleName("index.android") .addPackage(new MainReactPackage()) .setUseDeveloperSupport(BuildConfig.DEBUG) .setInitialLifecycleState(LifecycleState.RESUMED) .build(); mReactRootView.startReactApplication(mReactInstanceManager, "remote", null); setContentView(mReactRootView); getWindow().addFlags(FLAG_KEEP_SCREEN_ON); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) { mReactInstanceManager.showDevOptionsDialog(); return true; } return super.onKeyUp(keyCode, event); } @Override public void onBackPressed() { if (mReactInstanceManager != null) { mReactInstanceManager.onBackPressed(); } else { super.onBackPressed(); } } @Override public void invokeDefaultOnBackPressed() { super.onBackPressed(); } @Override protected void onPause() { super.onPause(); if (mReactInstanceManager != null) { mReactInstanceManager.onPause(); } } @Override protected void onResume() { super.onResume(); if (mReactInstanceManager != null) { mReactInstanceManager.onResume(this, this); } } }
package org.topq.jsystem.mobile; import java.util.List; import android.app.Instrumentation; import android.util.Log; import android.view.KeyEvent; import android.widget.TextView; import com.jayway.android.robotium.solo.Solo; public class SoloExecutor { private static final String TAG = "SoloExecutor"; private static final String SUCCESS_STRING = "SUCCESS:"; private static final String ERROR_STRING = "ERROR:"; private Instrumentation instrumentation; private Solo solo; private final ISoloProvider soloProvider; public SoloExecutor(final ISoloProvider soloProvider,Instrumentation instrumentation) { super(); this.soloProvider = soloProvider; this.instrumentation = instrumentation; } public String execute(final String data) { ScriptParser parser = new ScriptParser(data); String result = ""; for (CommandParser command : parser.getCommands()) { Log.d(TAG, "Process command: " + command.getCommand()); if (command.getCommand().equals("enterText")) { result += SUCCESS_STRING + "Mock tests"; } if (command.getCommand().equals("enterText")) { result += enterText(command.getArguments()); } else if (command.getCommand().equals("clickOnButton")) { result += clickOnButton(command.getArguments()); } else if (command.getCommand().equals("launch")) { result += launch(); } else if (command.getCommand().equals("clickInList")) { result += clickInList(command.getArguments()); } else if (command.getCommand().equals("clearEditText")) { result += clearEditText(command.getArguments()); } else if (command.getCommand().equals("clickOnButtonWithText")) { result += clickOnButtonWithText(command.getArguments()); } else if (command.getCommand().equals("clickOnView")) { result += clickOnView(command.getArguments()); } else if (command.getCommand().equals("clickOnText")) { result += clickOnText(command.getArguments()); } else if (command.getCommand().equals("goBack")) { result += goBack(); } else if (command.getCommand().equals("sendKey")) { result += sendKey(command.getArguments()); } else if (command.getCommand().equals("clickOnMenuItem")) { result += clickOnMenuItem(command.getArguments()); } else if (command.getCommand().equals("getText")) { result += getText(command.getArguments()); } else if (command.getCommand().equals("getTextViewIndex")) { result += getTextViewIndex(command.getArguments()); } else if (command.getCommand().equals("getTextView")) { result += getTextView(command.getArguments()); } else if (command.getCommand().equals("getCurrentTextViews")) { result += getCurrentTextViews(command.getArguments()); } else if (command.getCommand().equals("clickOnHardware")) { result+=clickOnHardware(command.getArguments()); } } return result; } private String getCurrentTextViews(String[] arguments) { String command = "the command getCurrentTextViews(" + arguments[0] + ")"; StringBuilder response = new StringBuilder(); try { List<TextView> textViews = solo.getCurrentTextViews(null); for (int i = 0; i < textViews.size(); i++) { response.append(i).append(",").append(textViews.get(i).getText().toString()).append(";"); } } catch (Error e) { String error = ERROR_STRING + command + "failed due to " + e.getMessage(); Log.d(TAG, error); return error; } return SUCCESS_STRING + command + ",Response: " + response.toString(); } private String getTextView(String[] arguments) { String command = "the command getTextView(" + arguments[0] + ")"; String response = ""; try { response = solo.getCurrentTextViews(null).get(Integer.parseInt(arguments[0])).getText().toString(); } catch (Error e) { String error = ERROR_STRING + command + "failed due to " + e.getMessage(); Log.d(TAG, error); return error; } return SUCCESS_STRING + command + ",Response: " + response; } private String getTextViewIndex(String[] arguments) { String command = "the command getTextViewIndex(" + arguments[0] + ")"; StringBuilder response = new StringBuilder(); try { List<TextView> textViews = solo.getCurrentTextViews(null); for (int i = 0; i < textViews.size(); i++) { if (arguments[0].trim().equals(textViews.get(i).getText().toString())) { response.append(i).append(";"); } } } catch (Error e) { String error = ERROR_STRING + command + "failed due to " + e.getMessage(); Log.d(TAG, error); return error; } return SUCCESS_STRING + command + ",Response: " + response.toString(); } private String getText(String[] arguments) { String command = "the command getText(" + arguments[0] + ")"; String response = ""; try { response = solo.getText(Integer.parseInt(arguments[0])).getText().toString(); } catch (Error e) { String error = ERROR_STRING + command + "failed due to " + e.getMessage(); Log.d(TAG, error); return error; } return SUCCESS_STRING + command + ",Response: " + response; } private String clickOnMenuItem(String[] arguments) { String command = "the command clickOnMenuItem(" + arguments[0] + ")"; try { solo.clickOnMenuItem(arguments[0]); } catch (Error e) { String error = ERROR_STRING + command + "failed due to " + e.getMessage(); Log.d(TAG, error); return error; } return SUCCESS_STRING + command; } private String sendKey(String[] arguments) { String command = "the command sendKey(" + arguments[0] + ")"; try { solo.sendKey(Integer.parseInt(arguments[0])); } catch (Error e) { String error = ERROR_STRING + command + "failed due to " + e.getMessage(); Log.d(TAG, error); return error; } return SUCCESS_STRING + command; } private String goBack() { String command = "the command goBack()"; try { solo.goBack(); } catch (Error e) { String error = ERROR_STRING + command + "failed due to " + e.getMessage(); Log.d(TAG, error); return error; } return SUCCESS_STRING + command; } private String clickOnView(String[] arguments) { String command = "the command clickOnView(" + arguments[0] + ")"; try { solo.clickOnView(solo.getCurrentViews().get(Integer.parseInt(arguments[0]))); } catch (Error e) { String error = ERROR_STRING + command + "failed due to " + e.getMessage(); Log.d(TAG, error); return error; } return SUCCESS_STRING + command; } private String clickOnButtonWithText(String[] arguments) { String command = "the command clickOnButton(" + arguments[0] + ")"; try { solo.clickOnButton(arguments[0]); } catch (Error e) { String error = ERROR_STRING + command + "failed due to " + e.getMessage(); Log.d(TAG, error); return error; } return SUCCESS_STRING + command; } private String clearEditText(String[] arguments) { String command = "the command clearEditText(" + arguments[0] + ")"; try { solo.clearEditText(Integer.parseInt(arguments[0])); } catch (Error e) { String error = ERROR_STRING + command + "failed due to " + e.getMessage(); Log.d(TAG, error); return error; } return SUCCESS_STRING + command; } private String clickInList(String[] arguments) { String command = "the command clickInList(" + arguments[0] + ")"; try { solo.clickInList(Integer.parseInt(arguments[0])); } catch (Error e) { String error = ERROR_STRING + command + "failed due to " + e.getMessage(); Log.d(TAG, error); return error; } return SUCCESS_STRING + command; } private String clickOnButton(String[] params) { String command = "the command clickOnButton(" + params[0] + ")"; try { solo.clickOnButton(Integer.parseInt(params[0])); } catch (Error e) { String error = ERROR_STRING + command + "failed due to " + e.getMessage(); Log.d(TAG, error); return error; } return SUCCESS_STRING + command; } private String enterText(String[] params) { String command = "the command clickOnButton(" + params[0] + ")"; try { solo.enterText(Integer.parseInt(params[0]), params[1]); } catch (Error e) { String error = ERROR_STRING + command + "failed due to " + e.getMessage(); Log.d(TAG, error); return error; } return SUCCESS_STRING + command; } private String clickOnText(String[] params) { String command = "the command clickOnText(" + params[0] + ")"; try { solo.clickOnText(params[0]); } catch (Error e) { String error = ERROR_STRING + command + "failed due to " + e.getMessage(); Log.d(TAG, error); return error; } return SUCCESS_STRING + command; } private String clickOnHardware(String[] keyString){ int key = (keyString[0] == "HOME" )? KeyEvent.KEYCODE_HOME : KeyEvent.KEYCODE_BACK; instrumentation.sendKeyDownUpSync(key); return SUCCESS_STRING + "click on hardware"; } private String launch() { Log.i(TAG, "Robotium: About to launch application"); String command = "the command launch"; try { solo = soloProvider.getSolo(); } catch (Error e) { String error = ERROR_STRING + command + "failed due to " + e.getMessage(); Log.d(TAG, error); return error; } return SUCCESS_STRING + command; } }
package to.rtc.cli.migrate; import java.io.File; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import to.rtc.cli.migrate.command.AcceptCommandDelegate; import to.rtc.cli.migrate.command.LoadCommandDelegate; import to.rtc.cli.migrate.util.Files; import com.ibm.team.filesystem.cli.core.Constants; import com.ibm.team.filesystem.cli.core.subcommands.IScmClientConfiguration; import com.ibm.team.filesystem.rcp.core.internal.changelog.IChangeLogOutput; import com.ibm.team.rtc.cli.infrastructure.internal.core.CLIClientException; public class RtcMigrator { private static final int ACCEPTS_BEFORE_LOCAL_HISTORY_CLEAN = 1000; protected final IChangeLogOutput output; private final IScmClientConfiguration config; private final String workspace; private final Migrator migrator; private static final Set<String> initiallyLoadedComponents = new HashSet<String>(); private File sandboxDirectory; public RtcMigrator(IChangeLogOutput output, IScmClientConfiguration config, String workspace, Migrator migrator, File sandboxDirectory) { this.output = output; this.config = config; this.workspace = workspace; this.migrator = migrator; this.sandboxDirectory = sandboxDirectory; } public void migrateTag(RtcTag tag) throws CLIClientException { List<RtcChangeSet> changeSets = tag.getOrderedChangeSets(); int changeSetCounter = 0; int numberOfChangesets = changeSets.size(); String tagName = tag.getName(); for (RtcChangeSet changeSet : changeSets) { long acceptDuration = accept(changeSet); long commitDuration = commit(changeSet); changeSetCounter++; output.writeLine("Migrated [" + tagName + "] [" + changeSetCounter + "]/[" + numberOfChangesets + "] changesets. Accept took " + acceptDuration + "ms commit took " + commitDuration + "ms"); if (migrator.needsIntermediateCleanup()) { intermediateCleanup(); } if (changeSetCounter % ACCEPTS_BEFORE_LOCAL_HISTORY_CLEAN == 0) { cleanLocalHistory(); } } cleanLocalHistory(); if (!"HEAD".equals(tagName)) { migrator.createTag(tag); } } void intermediateCleanup() { long startCleanup = System.currentTimeMillis(); migrator.intermediateCleanup(); output.writeLine("Intermediate cleanup had [" + (TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - startCleanup)) + "]sec"); } long commit(RtcChangeSet changeSet) { long startCommit = System.currentTimeMillis(); migrator.commitChanges(changeSet); long commitDuration = System.currentTimeMillis() - startCommit; return commitDuration; } long accept(RtcChangeSet changeSet) throws CLIClientException { long startAccept = System.currentTimeMillis(); acceptAndLoadChangeSet(changeSet); handleInitialLoad(changeSet); long acceptDuration = System.currentTimeMillis() - startAccept; return acceptDuration; } private void cleanLocalHistory() { File localHistoryDirectory = new File(sandboxDirectory, ".metadata/.plugins/org.eclipse.core.resources/.history"); if (localHistoryDirectory.exists() && localHistoryDirectory.isDirectory()) { long start = System.currentTimeMillis(); Files.delete(localHistoryDirectory); output.writeLine("Cleanup of local history had [" + (TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - start)) + "]sec"); } } private void acceptAndLoadChangeSet(RtcChangeSet changeSet) throws CLIClientException { output.setIndent(2); int result = new AcceptCommandDelegate(config, output, workspace, changeSet.getUuid(), false, true).run(); switch (result) { case Constants.STATUS_GAP: output.writeLine("Retry accepting with --accept-missing-changesets"); result = new AcceptCommandDelegate(config, output, workspace, changeSet.getUuid(), false, true).run(); if (Constants.STATUS_GAP == result) { throw new CLIClientException("There was a PROBLEM in accepting that we cannot solve."); } break; default: break; } } private void handleInitialLoad(RtcChangeSet changeSet) { if (!initiallyLoadedComponents.contains(changeSet.getComponent())) { try { new LoadCommandDelegate(config, output, workspace, changeSet.getComponent(), false).run(); initiallyLoadedComponents.add(changeSet.getComponent()); } catch (CLIClientException e) { // ignore throw new RuntimeException("Not a valid sandbox. Please run [scm load " + workspace + "] before [scm migrate-to-git] command"); } } } }
package uk.ac.ebi.atlas.dao; import com.google.common.collect.Lists; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import uk.ac.ebi.atlas.model.baseline.BaselineBioentitiesCount; import uk.ac.ebi.atlas.solr.query.conditions.IndexedAssayGroup; import javax.inject.Inject; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(locations = {"classpath:applicationContext.xml", "classpath:solrContextIT.xml", "classpath:oracleContext.xml"}) public class BaselineExpressionDaoIT { private static final String E_MTAB_599 = "E-MTAB-599"; @Inject private BaselineExpressionDao subject; @Test public void testGetExpressions() throws Exception { IndexedAssayGroup assayGroup = new IndexedAssayGroup(E_MTAB_599, "g2"); List<BaselineBioentitiesCount> bioentitiesCounts = subject.getBioentitiesCounts(Lists.newArrayList(assayGroup)); assertThat(bioentitiesCounts, hasSize(1)); assertThat(bioentitiesCounts.get(0).getExperimentAccession(), is(E_MTAB_599)); assertThat(bioentitiesCounts.get(0).getCount(), is(17719)); assertThat(bioentitiesCounts.get(0).getSpecies(), is("Mus musculus")); } }
package weed3test.features; import org.junit.Test; import org.noear.weed.DbContext; import weed3test.DbUtil; import weed3test.model.AppxModel; import java.util.HashMap; import java.util.Map; public class SqlTest { DbContext db = DbUtil.db; @Test public void test1() throws Exception { assert db.sql("select * from appx where app_id=?", 32) .getItem(AppxModel.class) .app_id == 32; } public void test2() throws Exception { Map<String, Object> map = new HashMap<>(); db.table("appx").setMap(map).upsert("akey"); } }
package consulo.cold; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLEncoder; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.io.ZipUtil; import consulo.cold.util.JavaCommandBuilder; /** * @author VISTALL * @since 12.04.2016 */ public class Main { private static final String ourDefaultPluginHost = "http://must-be.org/consulo/plugins/%s"; private static final String[] requiredPluginList = new String[]{ "org.consulo.devkit", "org.intellij.groovy", "org.intellij.intelliLang", "org.consulo.java", "JFlex Support", "com.intellij.junit", "com.intellij.properties", "com.intellij.regexp", "com.intellij.spellchecker", "com.intellij.uiDesigner", "com.intellij.xml" }; public static void main(String[] args) throws Exception { Logger.setFactory(ColdLoggerFactory.class); URL url = new URL("http://must-be.org/vulcan/site/_consulo-distribution/out/consulo-win-no-jre.zip"); File tempDirectory = new File(".", ".cold"); FileUtil.createDirectory(tempDirectory); File consuloBuildFile = FileUtilRt.createTempFile("consulo", "zip", true); FileOutputStream fileOutputStream = new FileOutputStream(consuloBuildFile); System.out.println("Downloading consulo build"); FileUtilRt.copy(url.openStream(), fileOutputStream); fileOutputStream.close(); System.out.println("Extracting consulo build"); ZipUtil.extract(consuloBuildFile, tempDirectory, null); String javaHome = System.getProperty("java.home"); if(javaHome == null) { System.out.println("No java home"); System.exit(-1); return; } if(javaHome.endsWith("jre")) { javaHome = new File(javaHome).getParent(); } if(javaHome == null) { System.out.println("No jdk home"); System.exit(-1); return; } File consuloPath = new File(tempDirectory, "Consulo"); downloadColdRunner(consuloPath); for(String pluginId : requiredPluginList) { downloadRequiredPlugin(consuloPath, pluginId); } start(javaHome, consuloPath.getPath(), tempDirectory.getParentFile().getAbsolutePath()); } private static void downloadColdRunner(File consuloPath) throws Exception { URL coldJar = new URL("https://github.com/consulo/cold/raw/master/build/cold-runner.jar"); File coldJarFile = new File(consuloPath, "lib/cold-runner.jar"); FileOutputStream fileOutputStream = new FileOutputStream(coldJarFile); System.out.println("Downloading cold-runner.jar"); FileUtilRt.copy(coldJar.openStream(), fileOutputStream); fileOutputStream.close(); System.out.println("Downloaded cold-runner.jar"); } private static void downloadRequiredPlugin(File consuloPath, String pluginId) throws Exception { String urlString = String.format(ourDefaultPluginHost, "download?id=") + URLEncoder.encode(pluginId, "UTF8") + "&build=SNAPSHOT&uuid=" + URLEncoder.encode("cold", "UTF8"); URL url = new URL(urlString); File tempFile = FileUtilRt.createTempFile(pluginId, "zip", true); FileOutputStream fileOutputStream = new FileOutputStream(tempFile); System.out.println("Downloading required plugin: " + pluginId); FileUtilRt.copy(url.openStream(), fileOutputStream); fileOutputStream.close(); System.out.println("Extracting required plugin: " + pluginId); ZipUtil.extract(tempFile, new File(consuloPath, "plugins"), null); } private static void start(String javaHome, String consuloPath, String workingDirectory) throws Exception { JavaCommandBuilder javaCommandBuilder = new JavaCommandBuilder(); javaCommandBuilder.setMainClassName("consulo.cold.runner.Main"); javaCommandBuilder.setJavaHome(javaHome); javaCommandBuilder.addClassPathEntry(javaHome + "/lib/tools.jar"); File libDir = new File(consuloPath, "lib"); for(File file : libDir.listFiles()) { javaCommandBuilder.addClassPathEntry(file.getAbsolutePath()); } javaCommandBuilder.addSystemProperty("jdk6.home", javaHome); javaCommandBuilder.addSystemProperty("consulo.home", consuloPath); execute(javaCommandBuilder.construct(), workingDirectory); } private static void execute(String[] args, String workDir) throws Exception { final Process process; System.out.println("Executing command: " + StringUtil.join(args, " ")); process = new ProcessBuilder(args).directory(new File(workDir)).redirectErrorStream(true).start(); try { Thread thread = new Thread() { @Override public void run() { InputStream inputStream = process.getInputStream(); try { int b; while((b = inputStream.read()) != -1) { String s = String.valueOf((char) b); System.out.print(s); } } catch(IOException e) { e.printStackTrace(); } } }; thread.setDaemon(true); thread.start(); System.exit(process.waitFor()); } catch(InterruptedException e) { process.destroy(); } } }
// $Id: GridVertCoord.java 63 2006-07-12 21:50:51Z edavis $ package ucar.nc2.iosp.grid; import ucar.ma2.*; import ucar.nc2.*; import ucar.nc2.constants.AxisType; import ucar.nc2.constants._Coordinate; import ucar.nc2.units.SimpleUnit; import ucar.grid.GridRecord; import ucar.grid.GridTableLookup; import ucar.grid.GridDefRecord; import ucar.grib.grib2.Grib2GridTableLookup; import ucar.grib.grib1.Grib1GridTableLookup; import ucar.grib.grib1.Grib1GDSVariables; import java.util.*; public class GridVertCoord implements Comparable { /** * logger */ static private org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(GridVertCoord.class); /** * typical record for this vertical coordinate */ private GridRecord typicalRecord; /** * level name */ private String levelName; /** * lookup table */ private GridTableLookup lookup; /** * sequence # */ private int seq = 0; /** * coord values */ private double[] coordValues; /** * uses bounds flag */ boolean usesBounds = false; /** * don't use vertical flag */ boolean dontUseVertical = false; /** * positive direction */ String positive = "up"; /** * units */ String units; /** * levels */ private List<LevelCoord> levels = new ArrayList<LevelCoord>(); // LevelCoord /** * Create a new GridVertCoord with the given name * * @param name name */ GridVertCoord(String name) { this.levelName = name; dontUseVertical = true; } /** * Create a new GridVertCoord with the appropriate params * * @param records list of GridRecords that make up this coord * @param levelName the name of the level * @param lookup the lookup table */ GridVertCoord(List<GridRecord> records, String levelName, GridTableLookup lookup, GridHorizCoordSys hcs) { this.typicalRecord = records.get(0); this.levelName = levelName; this.lookup = lookup; dontUseVertical = !lookup.isVerticalCoordinate(typicalRecord); positive = lookup.isPositiveUp(typicalRecord) ? "up" : "down"; units = lookup.getLevelUnit(typicalRecord); usesBounds = lookup.isLayer(this.typicalRecord); addLevels(records); if (typicalRecord.getLevelType1() == 109 && lookup instanceof Grib1GridTableLookup ) checkForPressureLevels( records, hcs ); if (GridServiceProvider.debugVert) { System.out.println("GribVertCoord: " + getVariableName() + "(" + typicalRecord.getLevelType1() + ") useVertical= " + (!dontUseVertical) + " positive=" + positive + " units=" + units); } } /** * Create a new GridVertCoord for a layer * * @param record layer record * @param levelName name of this level * @param lookup lookup table * @param level1 level 1 * @param level2 level 2 */ GridVertCoord(GridRecord record, String levelName, GridTableLookup lookup, double[] level1, double[] level2) { this.typicalRecord = record; this.levelName = levelName; this.lookup = lookup; //dontUseVertical = !lookup.isVerticalCoordinate(record); positive = lookup.isPositiveUp(record) ? "up" : "down"; units = lookup.getLevelUnit(record); usesBounds = lookup.isLayer(this.typicalRecord); levels = new ArrayList<LevelCoord>(level1.length); for (int i = 0; i < level1.length; i++) { levels.add(new LevelCoord(level1[i], (level2 == null) ? 0.0 : level2[i])); } Collections.sort(levels); if (positive.equals("down")) { Collections.reverse(levels); } dontUseVertical = (levels.size() == 1); } /** * Set the sequence number * * @param seq the sequence number */ void setSequence(int seq) { this.seq = seq; } /** * Set the level name * * @return the level name */ String getLevelName() { return levelName; } /** * Get the variable name * * @return the variable name */ String getVariableName() { return (seq == 0) ? levelName : levelName + seq; // more than one with same levelName } /** * Get the number of levels * * @return number of levels */ int getNLevels() { return dontUseVertical ? 1 : levels.size(); } /** * Add levels * * @param records GridRecords, one for each level */ void addLevels(List<GridRecord> records) { for (int i = 0; i < records.size(); i++) { GridRecord record = records.get(i); if (coordIndex(record) < 0) { levels.add(new LevelCoord(record.getLevel1(), record.getLevel2())); if (dontUseVertical && (levels.size() > 1)) { if (GridServiceProvider.debugVert) { logger.warn( "GribCoordSys: unused level coordinate has > 1 levels = " + levelName + " " + record.getLevelType1() + " " + levels.size()); } } } } Collections.sort(levels); if (positive.equals("down")) { Collections.reverse(levels); } } /** * Match levels * * @param records records to match * @return true if they have the same levels */ boolean matchLevels(List<GridRecord> records) { // first create a new list List<LevelCoord> levelList = new ArrayList<LevelCoord>(records.size()); for (GridRecord record : records) { LevelCoord lc = new LevelCoord(record.getLevel1(), record.getLevel2()); if (!levelList.contains(lc)) { levelList.add(lc); } } Collections.sort(levelList); if (positive.equals("down")) { Collections.reverse(levelList); } // gotta equal existing list return levelList.equals(levels); } /** * check for Sigma Pressure Levels */ void checkForPressureLevels( List<GridRecord> records, GridHorizCoordSys hcs ) { GridDefRecord gdr = hcs.getGds(); Grib1GDSVariables g1dr = (Grib1GDSVariables) gdr.getGdsv(); if( g1dr == null || ! g1dr.hasVerticalPressureLevels() ) return; int NV = g1dr.getNV(); if ( NV > 2 && NV < 255 ) { // Some data doesn't add Pressure Level values NV = NV / 2 -1; coordValues = new double[ levels.size() * NV ]; int idx = 0; for (LevelCoord lc : levels ) { double[] plevels = g1dr.getVerticalPressureLevels( lc.value1 ); System.arraycopy( plevels, 0, coordValues, idx, NV ); idx += NV; } } else { // add numeric values coordValues = new double[ levels.size()]; for (int i = 0; i < levels.size(); i++ ) { LevelCoord lc = levels.get( i ); coordValues[ i ] = lc.value1 ; } } } /** * Add this coord as a dimension to the netCDF file * * @param ncfile file to add to * @param g group in the file */ void addDimensionsToNetcdfFile(NetcdfFile ncfile, Group g) { if (dontUseVertical) { return; } int nlevs = levels.size(); ncfile.addDimension(g, new Dimension(getVariableName(), nlevs, true)); } /** * Add this coord as a variable in the netCDF file * * @param ncfile netCDF file to add to * @param g group in file */ void addToNetcdfFile(NetcdfFile ncfile, Group g) { if (dontUseVertical) { typicalRecord = null; return; } if (g == null) { g = ncfile.getRootGroup(); } // coordinate axis Variable v = new Variable(ncfile, g, null, getVariableName()); v.setDataType(DataType.DOUBLE); String desc = lookup.getLevelDescription(typicalRecord); if (lookup instanceof Grib2GridTableLookup && usesBounds) { desc = "Layer between " + desc; } v.addAttribute(new Attribute("long_name", desc)); v.addAttribute(new Attribute("units", lookup.getLevelUnit(typicalRecord))); // positive attribute needed for CF-1 Height and Pressure if (positive != null) { v.addAttribute(new Attribute("positive", positive)); } if (units != null) { AxisType axisType; if (SimpleUnit.isCompatible("millibar", units)) { axisType = AxisType.Pressure; } else if (SimpleUnit.isCompatible("m", units)) { axisType = AxisType.Height; } else { axisType = AxisType.GeoZ; } if (lookup instanceof Grib2GridTableLookup || lookup instanceof Grib1GridTableLookup) { v.addAttribute(new Attribute("GRIB_level_type", Integer.toString(typicalRecord.getLevelType1()))); } else { v.addAttribute(new Attribute("level_type", Integer.toString(typicalRecord.getLevelType1()))); } v.addAttribute(new Attribute(_Coordinate.AxisType, axisType.toString())); } if (coordValues == null) { coordValues = new double[levels.size()]; for (int i = 0; i < levels.size(); i++) { LevelCoord lc = (LevelCoord) levels.get(i); coordValues[i] = lc.mid; } } Array dataArray = Array.factory(DataType.DOUBLE, new int[]{coordValues.length}, coordValues); v.setDimensions(getVariableName()); v.setCachedData(dataArray, true); ncfile.addVariable(g, v); if (usesBounds) { String boundsDimName = "bounds_dim"; if (g.findDimension(boundsDimName) == null) { ncfile.addDimension(g, new Dimension(boundsDimName, 2, true)); } String bname = getVariableName() + "_bounds"; v.addAttribute(new Attribute("bounds", bname)); v.addAttribute(new Attribute(_Coordinate.ZisLayer, "true")); Variable b = new Variable(ncfile, g, null, bname); b.setDataType(DataType.DOUBLE); b.setDimensions(getVariableName() + " " + boundsDimName); b.addAttribute(new Attribute("long_name", "bounds for " + v.getName())); b.addAttribute(new Attribute("units", lookup.getLevelUnit(typicalRecord))); Array boundsArray = Array.factory(DataType.DOUBLE, new int[]{coordValues.length, 2}); ucar.ma2.Index ima = boundsArray.getIndex(); for (int i = 0; i < coordValues.length; i++) { LevelCoord lc = (LevelCoord) levels.get(i); boundsArray.setDouble(ima.set(i, 0), lc.value1); boundsArray.setDouble(ima.set(i, 1), lc.value2); } b.setCachedData(boundsArray, true); ncfile.addVariable(g, b); } } void empty() { // let all references to Index go, to reduce retained size typicalRecord = null; } /** * Get the index of the particular record * * @param record record in question * @return the index or -1 if not found */ int getIndex(GridRecord record) { if (dontUseVertical) { return 0; } return coordIndex(record); } /** * Compare this to another * * @param o the other GridVertCoord * @return the comparison */ public int compareTo(Object o) { GridVertCoord gv = (GridVertCoord) o; return getLevelName().compareToIgnoreCase(gv.getLevelName()); } /** * A level coordinate * * @author IDV Development Team * @version $Revision: 1.3 $ */ private class LevelCoord implements Comparable { /** * midpoint */ double mid; /** * top/bottom values */ double value1, value2; /** * Create a new LevelCoord * * @param value1 top * @param value2 bottom */ LevelCoord(double value1, double value2) { this.value1 = value1; this.value2 = value2; if (usesBounds && (value1 > value2)) { this.value1 = value2; this.value2 = value1; } mid = usesBounds ? (value1 + value2) / 2 : value1; } /** * Compare to another LevelCoord * * @param o another LevelCoord * @return the comparison */ public int compareTo(Object o) { LevelCoord other = (LevelCoord) o; // if (closeEnough(value1, other.value1) && closeEnough(value2, other.value2)) return 0; if (mid < other.mid) { return -1; } if (mid > other.mid) { return 1; } return 0; } /** * Check for equality * * @param oo object in question * @return true if equal */ public boolean equals(Object oo) { if (this == oo) { return true; } if (!(oo instanceof LevelCoord)) { return false; } LevelCoord other = (LevelCoord) oo; return (ucar.nc2.util.Misc.closeEnough(value1, other.value1) && ucar.nc2.util.Misc.closeEnough(value2, other.value2)); } /** * Generate a hashcode * * @return the hashcode */ public int hashCode() { return (int) (value1 * 100000 + value2 * 100); } } /** * Get the coordinate index for the record * * @param record record in question * @return index or -1 if not found */ private int coordIndex(GridRecord record) { double val = record.getLevel1(); double val2 = record.getLevel2(); if (usesBounds && (val > val2)) { val = record.getLevel2(); val2 = record.getLevel1(); } for (int i = 0; i < levels.size(); i++) { LevelCoord lc = (LevelCoord) levels.get(i); if (usesBounds) { if (ucar.nc2.util.Misc.closeEnough(lc.value1, val) && ucar.nc2.util.Misc.closeEnough(lc.value2, val2)) { return i; } } else { if (ucar.nc2.util.Misc.closeEnough(lc.value1, val)) { return i; } } } return -1; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package hu.sch.ejb; import hu.sch.domain.EntrantRequest; import hu.sch.domain.Group; import hu.sch.domain.Membership; import hu.sch.domain.User; import hu.sch.domain.PointRequest; import hu.sch.domain.Post; import hu.sch.domain.PostType; import hu.sch.domain.SvieMembershipType; import hu.sch.domain.SvieStatus; import hu.sch.domain.logging.Event; import hu.sch.domain.logging.EventType; import hu.sch.services.LogManagerLocal; import hu.sch.services.MailManagerLocal; import hu.sch.services.PostManagerLocal; import hu.sch.services.UserManagerLocal; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.Query; import org.apache.log4j.Logger; /** * * @author hege */ @Stateless @SuppressWarnings("unchecked") public class UserManagerBean implements UserManagerLocal { @PersistenceContext EntityManager em; @EJB(name = "LogManagerBean") LogManagerLocal logManager; @EJB(name = "MailManagerBean") MailManagerLocal mailManager; @EJB(name = "PostManagerBean") PostManagerLocal postManager; private static Logger log = Logger.getLogger(UserManagerBean.class); private static Event DELETEMEMBERSHIP_EVENT; private static Event CREATEMEMBERSHIP_EVENT; @PostConstruct private void initialize() { if (DELETEMEMBERSHIP_EVENT == null) { Query q = em.createNamedQuery(Event.getEventForEventType); q.setParameter("evt", EventType.TAGSAGTORLES); DELETEMEMBERSHIP_EVENT = (Event) q.getSingleResult(); q.setParameter("evt", EventType.JELENTKEZES); CREATEMEMBERSHIP_EVENT = (Event) q.getSingleResult(); } } public List<User> getAllUsers() { Query q = em.createNamedQuery(User.findAll); return q.getResultList(); } public void updateUserAttributes(User user) { User f = em.find(User.class, user.getId()); boolean changed = false; if (user.getEmailAddress() != null && !user.getEmailAddress().equals(f.getEmailAddress())) { f.setEmailAddress(user.getEmailAddress()); changed = true; } if (user.getNickName() != null && !user.getNickName().equals(f.getNickName())) { f.setNickName(user.getNickName()); changed = true; } if (user.getNeptunCode() != null && !user.getNeptunCode().equals(f.getNeptunCode())) { f.setNeptunCode(user.getNeptunCode()); changed = true; } if (user.getLastName() != null && !user.getLastName().equals(f.getLastName())) { f.setLastName(user.getLastName()); changed = true; } if (user.getFirstName() != null && !user.getFirstName().equals(f.getFirstName())) { f.setFirstName(user.getFirstName()); changed = true; } if (changed) { em.merge(f); em.flush(); } } public User findUserById(Long userId) { try { return em.find(User.class, userId); } catch (NoResultException e) { return null; } } public void addUserToGroup(User user, Group group, Date start, Date veg) { Membership ms = new Membership(); User _user = em.find(User.class, user.getId()); Group _group = em.find(Group.class, group.getId()); ms.setUser(_user); ms.setGroup(_group); ms.setStart(start); ms.setEnd(null); Post post = new Post(); post.setMembership(ms); Query q = em.createNamedQuery(PostType.searchForPostType); q.setParameter("pn", "feldolgozás alatt"); PostType postType = (PostType) q.getSingleResult(); post.setPostType(postType); List<Post> posts = new ArrayList<Post>(); posts.add(post); ms.setPosts(posts); _user.getMemberships().add(ms); _group.getMemberships().add(ms); em.persist(post); em.persist(ms); em.merge(_user); em.merge(_group); em.flush(); logManager.createLogEntry(group, user, CREATEMEMBERSHIP_EVENT); } public List<Group> getAllGroups() { Query q = em.createNamedQuery(Group.findAll); return q.getResultList(); } public List<String> getEveryGroupName() { Query q = em.createQuery("SELECT g.name FROM Group g " + "ORDER BY g.name"); return q.getResultList(); } public List<Group> findGroupByName(String name) { Query q = em.createQuery("SELECT g FROM Group g " + "WHERE g.name LIKE :groupName " + "ORDER BY g.name"); q.setParameter("groupName", name); return q.getResultList(); } public Group getGroupByName(String name) { Query q = em.createQuery("SELECT g FROM Group g " + "WHERE g.name=:groupName"); q.setParameter("groupName", name); try { Group csoport = (Group) q.getSingleResult(); return csoport; } catch (Exception e) { return null; } } public Group findGroupById(Long id) { return em.find(Group.class, id); } public void deleteMembership(Membership ms) { Membership temp = em.find(Membership.class, ms.getId()); User user = ms.getUser(); boolean userChanged = false; em.remove(temp); em.flush(); if (user.getSvieMembershipType().equals(SvieMembershipType.RENDESTAG) && user.getSvieStatus().equals(SvieStatus.ELFOGADVA) && ms.getGroup().getIsSvie()) { try { Query q = em.createQuery("SELECT ms.user FROM Membership ms " + "WHERE ms.user = :user AND ms.group.isSvie = true"); q.setParameter("user", user); q.getSingleResult(); } catch (NoResultException nre) { user.setSvieMembershipType(SvieMembershipType.PARTOLOTAG); userChanged = true; } } if (user.getSviePrimaryMembership() != null && ms.getId().equals(user.getSviePrimaryMembership().getId())) { user.setSviePrimaryMembership(null); userChanged = true; } if (userChanged) { em.merge(user); } logManager.createLogEntry(ms.getGroup(), ms.getUser(), DELETEMEMBERSHIP_EVENT); } public List<User> getCsoporttagokWithoutOregtagok(Long csoportId) { Query q = em.createQuery("SELECT ms.user FROM Membership ms JOIN " + "ms.user " + "WHERE ms.group.id=:groupId AND ms.end=NULL " + "ORDER BY ms.user.lastName ASC, ms.user.firstName ASC"); q.setParameter("groupId", csoportId); return q.getResultList(); } public List<User> getUsersWithPrimaryMembership(Long groupId) { Query q = em.createQuery("SELECT ms.user FROM Membership ms " + "WHERE ms.group.id=:groupId AND ms.user.sviePrimaryMembership = ms " + "AND ms.user.svieStatus = :svieStatus"); q.setParameter("groupId", groupId); q.setParameter("svieStatus", SvieStatus.ELFOGADVA); return q.getResultList(); } public List<User> getMembersForGroup(Long csoportId) { //Group cs = em.find(Group.class, csoportId); Query q = em.createQuery("SELECT ms.user FROM Membership ms JOIN " + "ms.user " + "WHERE ms.group.id=:groupId " + "ORDER BY ms.user.lastName ASC, ms.user.firstName ASC"); q.setParameter("groupId", csoportId); return q.getResultList(); } public List<EntrantRequest> getBelepoIgenyekForUser(User felhasznalo) { Query q = em.createQuery("SELECT e FROM EntrantRequest e " + "WHERE e.user=:user " + "ORDER BY e.valuation.semester DESC, e.entrantType ASC"); q.setParameter("user", felhasznalo); return q.getResultList(); } public List<PointRequest> getPontIgenyekForUser(User felhasznalo) { Query q = em.createQuery("SELECT p FROM PointRequest p " + "WHERE p.user=:user " + "ORDER BY p.valuation.semester DESC, p.valuation.group.name ASC"); q.setParameter("user", felhasznalo); return q.getResultList(); } public Group getGroupHierarchy() { Query q = em.createNamedQuery("groupHierarchy"); List<Group> csoportok = q.getResultList(); Group rootCsoport = new Group(); List<Group> rootCsoportok = new ArrayList<Group>(); rootCsoport.setSubGroups(rootCsoportok); for (Group cs : csoportok) { if (cs.getParent() != null) { if (cs.getParent().getSubGroups() == null) { cs.getParent().setSubGroups(new ArrayList<Group>()); } cs.getParent().getSubGroups().add(cs); } else { rootCsoportok.add(cs); } } return rootCsoport; } public User findUserWithCsoporttagsagokById(Long userId) { Query q = em.createNamedQuery(User.findWithMemberships); q.setParameter("id", userId); try { User user = (User) q.getSingleResult(); return user; } catch (Exception ex) { log.warn("Can't find user with memberships for this id: " + userId); return null; } } public Group findGroupWithCsoporttagsagokById(Long id) { Query q = em.createNamedQuery(Group.findWithMemberships); q.setParameter("id", id); try { Group group = (Group) q.getSingleResult(); return group; } catch (Exception ex) { log.warn("Can't find group with memberships", ex); return null; } } public void groupInfoUpdate(Group cs) { Group csoport = em.find(Group.class, cs.getId()); csoport.setFounded(cs.getFounded()); csoport.setName(cs.getName()); csoport.setWebPage(cs.getWebPage()); csoport.setIntroduction(cs.getIntroduction()); csoport.setMailingList(cs.getMailingList()); } @Override public Membership getMembership(Long memberId) { Membership cst = em.find(Membership.class, memberId); return cst; } @Override public Membership getMembership(final Long groupId, final Long userId) { Query q = em.createQuery("SELECT ms FROM Membership ms WHERE ms.user.id = :userId " + "AND ms.group.id = :groupId"); q.setParameter("groupId", groupId); q.setParameter("userId", userId); return (Membership) q.getSingleResult(); } public void setMemberToOldBoy(Membership ms) { ms.setEnd(new Date()); em.merge(ms); } public void setUserDelegateStatus(User user, boolean isDelegated) { user.setDelegated(isDelegated); em.merge(user); } public void setOldBoyToActive(Membership ms) { ms.setEnd(null); em.merge(ms); } @Override public void updateUser(User user) { em.merge(user); } @Override public void updateGroup(Group group) { em.merge(group); } /** * {@inheritDoc} */ @Override public User getGroupLeaderForGroup(Long groupId) { Query q = em.createNamedQuery(Post.getGroupLeaderForGroup); q.setParameter("id", groupId); try { User ret = (User) q.getSingleResult(); return ret; } catch (NoResultException nre) { log.error("Nem találtam meg ennek a körnek a körvezetőjét: " + groupId); return null; } } public List<Group> getAllGroupsWithCount() { Query q = em.createQuery("SELECT new hu.sch.domain.Group(g, " + "(SELECT COUNT(*) FROM Membership ms WHERE ms.user.sviePrimaryMembership = ms " + "AND ms.group.id = g.id AND ms.user.svieStatus = 'ELFOGADVA' " + "AND ms.user.svieMembershipType = 'RENDESTAG')) " + "FROM Group g WHERE g.status='akt'"); return q.getResultList(); } }
package ru.job4j.tracker; import java.util.Random; public class Tracker { private Item[] items = new Item[100]; private int pos = 0; private static final Random RN = new Random(); /** * . * * @param item Item * @return item */ public Item add(Item item) { item.setId(this.generateId()); this.items[pos++] = item; return item; } /** * . * * @return id */ private String generateId() { return String.valueOf(System.currentTimeMillis() + this.RN.nextInt()); } /** * . * * @param item Item */ public void update(Item item) { for (int i = 0; i < this.pos; i++) { if (this.items[i] != null && this.items[i].getId().equals(item.getId())) { this.items[i] = item; break; } } } /** * . * * @param item Item */ public void delete(Item item) { for (int i = 0; i < this.pos; i++) { if (this.items[i] != null && this.items[i].getId().equals(item.getId())) { System.arraycopy(this.items, i + 1, this.items, i, pos - i - 1); this.items[pos - 1] = null; pos break; } } } /** * . * * @return Item[] */ public Item[] findAll() { Item[] result = new Item[this.pos]; System.arraycopy(this.items, 0, result, 0, this.pos); return result; } /** * . * * @param key id * @return Item[] */ public Item[] findByName(String key) { Item[] result = new Item[1]; int n = 0; for (int i = 0; i < pos; i++) { if (this.items[i] != null && this.items[i].getName().equals(key)) { if (n == result.length) { result = resize(result, result.length * 2); } result[n++] = this.items[i]; } } return result; } /**. * * @param source Item[] * @param n int * @return Item[] */ private Item[] resize(Item[] source, int n) { Item[] dest = new Item[n]; System.arraycopy(source, 0, dest, 0, source.length); return dest; } /** * . * * @param id String * @return Item[] */ public Item findById(String id) { Item result = null; for (int i = 0; i < pos; i++) { if (items[i] != null && items[i].getId().equals(id)) { result = items[i]; break; } } return result; } } class Item { private String id; private String name; private String description; private long create; /**. * * @param name String * @param description String * @param create String */ Item(String name, String description, long create) { this.name = name; this.description = description; this.create = create; } /**. * * @param id String */ public void setId(String id) { this.id = id; } /**. * * @return id */ public String getId() { return this.id; } /**. * * @return name */ public String getName() { return this.name; } /** * * @return description */ public String getDescription() { return this.description; } /**. * * @return long date */ public long getCreate() { return this.create; } } class Task extends Item { /**. * * @param name String * @param description String * @param create String */ Task(String name, String description, long create) { super(name, description, create); } /**. * * @return String */ public String calculatePrice() { return "100%"; } }
package com.podio.sdk.domain.field; import com.podio.sdk.internal.Utils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class NumberField extends Field<NumberField.Value> { private static class Settings { private final Integer decimals = null; } public static class Configuration extends Field.Configuration { private final Value default_value = null; private final Settings settings = null; public Value getDefaultValue() { return default_value; } public int getNumberOfDecimals() { return settings != null ? Utils.getNative(settings.decimals, 0) : 0; } } public static class Value extends Field.Value { private final String value; public Value(Double value) { if (value != null) { this.value = Double.toString(value); } else { this.value = null; } } @Override public boolean equals(Object o) { if (o instanceof Value) { Value other = (Value) o; if (other.value != null) { return other.value.equals(this.value); } } return false; } @Override public Map<String, Object> getCreateData() { HashMap<String, Object> data = null; if (value != null) { data = new HashMap<String, Object>(); data.put("value", value); } return data; } @Override public int hashCode() { return value != null ? value.hashCode() : 0; } public String getValue() { return value; } } // Private fields. private final Configuration config = null; private final ArrayList<Value> values; public NumberField(String externalId) { super(externalId); this.values = new ArrayList<Value>(); } @Override public void setValues(List<Value> values) { this.values.clear(); this.values.addAll(values); } @Override public void addValue(Value value) { if (values != null && !values.contains(value)) { values.add(value); } } @Override public Value getValue(int index) { return values != null ? values.get(index) : null; } @Override public List<Value> getValues() { return values; } @Override public void removeValue(Value value) { if (values != null && values.contains(value)) { values.remove(value); } } @Override public int valuesCount() { return values != null ? values.size() : 0; } public Configuration getConfiguration() { return config; } }
package com.azure.data.cosmos.rx; import com.azure.data.cosmos.CompositePath; import com.azure.data.cosmos.CompositePathSortOrder; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosBridgeInternal; import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.CosmosClientTest; import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosContainerRequestOptions; import com.azure.data.cosmos.CosmosContainerSettings; import com.azure.data.cosmos.CosmosDatabase; import com.azure.data.cosmos.CosmosDatabaseForTest; import com.azure.data.cosmos.CosmosDatabaseResponse; import com.azure.data.cosmos.CosmosDatabaseSettings; import com.azure.data.cosmos.CosmosItem; import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.CosmosRequestOptions; import com.azure.data.cosmos.CosmosResponse; import com.azure.data.cosmos.CosmosResponseValidator; import com.azure.data.cosmos.CosmosUser; import com.azure.data.cosmos.CosmosUserSettings; import com.azure.data.cosmos.DataType; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.IncludedPath; import com.azure.data.cosmos.Index; import com.azure.data.cosmos.IndexingPolicy; import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.RetryOptions; import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.directconnectivity.Protocol; import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.PathParser; import com.azure.data.cosmos.internal.Utils; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; import io.reactivex.subscribers.TestSubscriber; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.mockito.stubbing.Answer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; import org.testng.annotations.DataProvider; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import rx.Observable; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.spy; public class TestSuiteBase extends CosmosClientTest { private static final int DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL = 500; private static final ObjectMapper objectMapper = new ObjectMapper(); protected static Logger logger = LoggerFactory.getLogger(TestSuiteBase.class.getSimpleName()); protected static final int TIMEOUT = 40000; protected static final int FEED_TIMEOUT = 40000; protected static final int SETUP_TIMEOUT = 60000; protected static final int SHUTDOWN_TIMEOUT = 12000; protected static final int SUITE_SETUP_TIMEOUT = 120000; protected static final int SUITE_SHUTDOWN_TIMEOUT = 60000; protected static final int WAIT_REPLICA_CATCH_UP_IN_MILLIS = 4000; protected final static ConsistencyLevel accountConsistency; protected static final ImmutableList<String> preferredLocations; private static final ImmutableList<ConsistencyLevel> desiredConsistencies; private static final ImmutableList<Protocol> protocols; protected int subscriberValidationTimeout = TIMEOUT; private static CosmosDatabase SHARED_DATABASE; private static CosmosContainer SHARED_MULTI_PARTITION_COLLECTION; private static CosmosContainer SHARED_MULTI_PARTITION_COLLECTION_WITH_COMPOSITE_AND_SPATIAL_INDEXES; private static CosmosContainer SHARED_SINGLE_PARTITION_COLLECTION; public TestSuiteBase(CosmosClientBuilder clientBuilder) { super(clientBuilder); } protected static CosmosDatabase getSharedCosmosDatabase(CosmosClient client) { return CosmosBridgeInternal.getCosmosDatabaseWithNewClient(SHARED_DATABASE, client); } protected static CosmosContainer getSharedMultiPartitionCosmosContainer(CosmosClient client) { return CosmosBridgeInternal.getCosmosContainerWithNewClient(SHARED_MULTI_PARTITION_COLLECTION, SHARED_DATABASE, client); } protected static CosmosContainer getSharedMultiPartitionCosmosContainerWithCompositeAndSpatialIndexes(CosmosClient client) { return CosmosBridgeInternal.getCosmosContainerWithNewClient(SHARED_MULTI_PARTITION_COLLECTION_WITH_COMPOSITE_AND_SPATIAL_INDEXES, SHARED_DATABASE, client); } protected static CosmosContainer getSharedSinglePartitionCosmosContainer(CosmosClient client) { return CosmosBridgeInternal.getCosmosContainerWithNewClient(SHARED_SINGLE_PARTITION_COLLECTION, SHARED_DATABASE, client); } static { accountConsistency = parseConsistency(TestConfigurations.CONSISTENCY); desiredConsistencies = immutableListOrNull( ObjectUtils.defaultIfNull(parseDesiredConsistencies(TestConfigurations.DESIRED_CONSISTENCIES), allEqualOrLowerConsistencies(accountConsistency))); preferredLocations = immutableListOrNull(parsePreferredLocation(TestConfigurations.PREFERRED_LOCATIONS)); protocols = ObjectUtils.defaultIfNull(immutableListOrNull(parseProtocols(TestConfigurations.PROTOCOLS)), ImmutableList.of(Protocol.HTTPS, Protocol.TCP)); } protected TestSuiteBase() { objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); objectMapper.configure(JsonParser.Feature.ALLOW_TRAILING_COMMA, true); objectMapper.configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, true); logger.debug("Initializing {} ...", this.getClass().getSimpleName()); } private static <T> ImmutableList<T> immutableListOrNull(List<T> list) { return list != null ? ImmutableList.copyOf(list) : null; } private static class DatabaseManagerImpl implements CosmosDatabaseForTest.DatabaseManager { public static DatabaseManagerImpl getInstance(CosmosClient client) { return new DatabaseManagerImpl(client); } private final CosmosClient client; private DatabaseManagerImpl(CosmosClient client) { this.client = client; } @Override public Flux<FeedResponse<CosmosDatabaseSettings>> queryDatabases(SqlQuerySpec query) { return client.queryDatabases(query, null); } @Override public Mono<CosmosDatabaseResponse> createDatabase(CosmosDatabaseSettings databaseDefinition) { return client.createDatabase(databaseDefinition); } @Override public CosmosDatabase getDatabase(String id) { return client.getDatabase(id); } } @BeforeSuite(groups = {"simple", "long", "direct", "multi-master", "emulator", "non-emulator"}, timeOut = SUITE_SETUP_TIMEOUT) public static void beforeSuite() { logger.info("beforeSuite Started"); CosmosClient houseKeepingClient = createGatewayHouseKeepingDocumentClient().build(); CosmosDatabaseForTest dbForTest = CosmosDatabaseForTest.create(DatabaseManagerImpl.getInstance(houseKeepingClient)); SHARED_DATABASE = dbForTest.createdDatabase; CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); options.offerThroughput(10100); SHARED_MULTI_PARTITION_COLLECTION = createCollection(SHARED_DATABASE, getCollectionDefinitionWithRangeRangeIndex(), options); SHARED_MULTI_PARTITION_COLLECTION_WITH_COMPOSITE_AND_SPATIAL_INDEXES = createCollection(SHARED_DATABASE, getCollectionDefinitionMultiPartitionWithCompositeAndSpatialIndexes(), options); options.offerThroughput(6000); SHARED_SINGLE_PARTITION_COLLECTION = createCollection(SHARED_DATABASE, getCollectionDefinitionWithRangeRangeIndex(), options); } @AfterSuite(groups = {"simple", "long", "direct", "multi-master", "emulator", "non-emulator"}, timeOut = SUITE_SHUTDOWN_TIMEOUT) public static void afterSuite() { logger.info("afterSuite Started"); CosmosClient houseKeepingClient = createGatewayHouseKeepingDocumentClient().build(); try { safeDeleteDatabase(SHARED_DATABASE); CosmosDatabaseForTest.cleanupStaleTestDatabases(DatabaseManagerImpl.getInstance(houseKeepingClient)); } finally { safeClose(houseKeepingClient); } } protected static void truncateCollection(CosmosContainer cosmosContainer) { CosmosContainerSettings cosmosContainerSettings = cosmosContainer.read().block().settings(); String cosmosContainerId = cosmosContainerSettings.id(); logger.info("Truncating collection {} ...", cosmosContainerId); CosmosClient houseKeepingClient = createGatewayHouseKeepingDocumentClient().build(); try { List<String> paths = cosmosContainerSettings.partitionKey().paths(); FeedOptions options = new FeedOptions(); options.maxDegreeOfParallelism(-1); options.enableCrossPartitionQuery(true); options.maxItemCount(100); logger.info("Truncating collection {} documents ...", cosmosContainer.id()); cosmosContainer.queryItems("SELECT * FROM root", options) .flatMap(page -> Flux.fromIterable(page.results())) .flatMap(doc -> { Object propertyValue = null; if (paths != null && !paths.isEmpty()) { List<String> pkPath = PathParser.getPathParts(paths.get(0)); propertyValue = doc.getObjectByPath(pkPath); if (propertyValue == null) { propertyValue = PartitionKey.None; } } return cosmosContainer.getItem(doc.id(), propertyValue).delete(); }).collectList().block(); logger.info("Truncating collection {} triggers ...", cosmosContainerId); cosmosContainer.queryTriggers("SELECT * FROM root", options) .flatMap(page -> Flux.fromIterable(page.results())) .flatMap(trigger -> { CosmosRequestOptions requestOptions = new CosmosRequestOptions(); // if (paths != null && !paths.isEmpty()) { // Object propertyValue = trigger.getObjectByPath(PathParser.getPathParts(paths.get(0))); // requestOptions.partitionKey(new PartitionKey(propertyValue)); return cosmosContainer.getTrigger(trigger.id()).delete(requestOptions); }).collectList().block(); logger.info("Truncating collection {} storedProcedures ...", cosmosContainerId); cosmosContainer.queryStoredProcedures("SELECT * FROM root", options) .flatMap(page -> Flux.fromIterable(page.results())) .flatMap(storedProcedure -> { CosmosRequestOptions requestOptions = new CosmosRequestOptions(); // if (paths != null && !paths.isEmpty()) { // Object propertyValue = storedProcedure.getObjectByPath(PathParser.getPathParts(paths.get(0))); // requestOptions.partitionKey(new PartitionKey(propertyValue)); return cosmosContainer.getStoredProcedure(storedProcedure.id()).delete(requestOptions); }).collectList().block(); logger.info("Truncating collection {} udfs ...", cosmosContainerId); cosmosContainer.queryUserDefinedFunctions("SELECT * FROM root", options) .flatMap(page -> Flux.fromIterable(page.results())) .flatMap(udf -> { CosmosRequestOptions requestOptions = new CosmosRequestOptions(); // if (paths != null && !paths.isEmpty()) { // Object propertyValue = udf.getObjectByPath(PathParser.getPathParts(paths.get(0))); // requestOptions.partitionKey(new PartitionKey(propertyValue)); return cosmosContainer.getUserDefinedFunction(udf.id()).delete(requestOptions); }).collectList().block(); } finally { houseKeepingClient.close(); } logger.info("Finished truncating collection {}.", cosmosContainerId); } protected static void waitIfNeededForReplicasToCatchUp(CosmosClientBuilder clientBuilder) { switch (clientBuilder.getDesiredConsistencyLevel()) { case EVENTUAL: case CONSISTENT_PREFIX: logger.info(" additional wait in EVENTUAL mode so the replica catch up"); // give times to replicas to catch up after a write try { TimeUnit.MILLISECONDS.sleep(WAIT_REPLICA_CATCH_UP_IN_MILLIS); } catch (Exception e) { logger.error("unexpected failure", e); } case SESSION: case BOUNDED_STALENESS: case STRONG: default: break; } } public static CosmosContainer createCollection(CosmosDatabase database, CosmosContainerSettings cosmosContainerSettings, CosmosContainerRequestOptions options) { return database.createContainer(cosmosContainerSettings, options).block().container(); } private static CosmosContainerSettings getCollectionDefinitionMultiPartitionWithCompositeAndSpatialIndexes() { final String NUMBER_FIELD = "numberField"; final String STRING_FIELD = "stringField"; final String NUMBER_FIELD_2 = "numberField2"; final String STRING_FIELD_2 = "stringField2"; final String BOOL_FIELD = "boolField"; final String NULL_FIELD = "nullField"; final String OBJECT_FIELD = "objectField"; final String ARRAY_FIELD = "arrayField"; final String SHORT_STRING_FIELD = "shortStringField"; final String MEDIUM_STRING_FIELD = "mediumStringField"; final String LONG_STRING_FIELD = "longStringField"; final String PARTITION_KEY = "pk"; PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); ArrayList<String> partitionKeyPaths = new ArrayList<String>(); partitionKeyPaths.add("/" + PARTITION_KEY); partitionKeyDefinition.paths(partitionKeyPaths); CosmosContainerSettings cosmosContainerSettings = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDefinition); IndexingPolicy indexingPolicy = new IndexingPolicy(); Collection<ArrayList<CompositePath>> compositeIndexes = new ArrayList<ArrayList<CompositePath>>(); //Simple ArrayList<CompositePath> compositeIndexSimple = new ArrayList<CompositePath>(); CompositePath compositePath1 = new CompositePath(); compositePath1.path("/" + NUMBER_FIELD); compositePath1.order(CompositePathSortOrder.ASCENDING); CompositePath compositePath2 = new CompositePath(); compositePath2.path("/" + STRING_FIELD); compositePath2.order(CompositePathSortOrder.DESCENDING); compositeIndexSimple.add(compositePath1); compositeIndexSimple.add(compositePath2); //Max Columns ArrayList<CompositePath> compositeIndexMaxColumns = new ArrayList<CompositePath>(); CompositePath compositePath3 = new CompositePath(); compositePath3.path("/" + NUMBER_FIELD); compositePath3.order(CompositePathSortOrder.DESCENDING); CompositePath compositePath4 = new CompositePath(); compositePath4.path("/" + STRING_FIELD); compositePath4.order(CompositePathSortOrder.ASCENDING); CompositePath compositePath5 = new CompositePath(); compositePath5.path("/" + NUMBER_FIELD_2); compositePath5.order(CompositePathSortOrder.DESCENDING); CompositePath compositePath6 = new CompositePath(); compositePath6.path("/" + STRING_FIELD_2); compositePath6.order(CompositePathSortOrder.ASCENDING); compositeIndexMaxColumns.add(compositePath3); compositeIndexMaxColumns.add(compositePath4); compositeIndexMaxColumns.add(compositePath5); compositeIndexMaxColumns.add(compositePath6); //Primitive Values ArrayList<CompositePath> compositeIndexPrimitiveValues = new ArrayList<CompositePath>(); CompositePath compositePath7 = new CompositePath(); compositePath7.path("/" + NUMBER_FIELD); compositePath7.order(CompositePathSortOrder.DESCENDING); CompositePath compositePath8 = new CompositePath(); compositePath8.path("/" + STRING_FIELD); compositePath8.order(CompositePathSortOrder.ASCENDING); CompositePath compositePath9 = new CompositePath(); compositePath9.path("/" + BOOL_FIELD); compositePath9.order(CompositePathSortOrder.DESCENDING); CompositePath compositePath10 = new CompositePath(); compositePath10.path("/" + NULL_FIELD); compositePath10.order(CompositePathSortOrder.ASCENDING); compositeIndexPrimitiveValues.add(compositePath7); compositeIndexPrimitiveValues.add(compositePath8); compositeIndexPrimitiveValues.add(compositePath9); compositeIndexPrimitiveValues.add(compositePath10); //Long Strings ArrayList<CompositePath> compositeIndexLongStrings = new ArrayList<CompositePath>(); CompositePath compositePath11 = new CompositePath(); compositePath11.path("/" + STRING_FIELD); CompositePath compositePath12 = new CompositePath(); compositePath12.path("/" + SHORT_STRING_FIELD); CompositePath compositePath13 = new CompositePath(); compositePath13.path("/" + MEDIUM_STRING_FIELD); CompositePath compositePath14 = new CompositePath(); compositePath14.path("/" + LONG_STRING_FIELD); compositeIndexLongStrings.add(compositePath11); compositeIndexLongStrings.add(compositePath12); compositeIndexLongStrings.add(compositePath13); compositeIndexLongStrings.add(compositePath14); compositeIndexes.add(compositeIndexSimple); compositeIndexes.add(compositeIndexMaxColumns); compositeIndexes.add(compositeIndexPrimitiveValues); compositeIndexes.add(compositeIndexLongStrings); indexingPolicy.compositeIndexes(compositeIndexes); cosmosContainerSettings.indexingPolicy(indexingPolicy); return cosmosContainerSettings; } public static CosmosContainer createCollection(CosmosClient client, String dbId, CosmosContainerSettings collectionDefinition) { return client.getDatabase(dbId).createContainer(collectionDefinition).block().container(); } public static void deleteCollection(CosmosClient client, String dbId, String collectionId) { client.getDatabase(dbId).getContainer(collectionId).delete().block(); } public static CosmosItem createDocument(CosmosContainer cosmosContainer, CosmosItemProperties item) { return cosmosContainer.createItem(item).block().item(); } /* // TODO: respect concurrencyLevel; public Flux<CosmosItemResponse> bulkInsert(CosmosContainer cosmosContainer, List<CosmosItemProperties> documentDefinitionList, int concurrencyLevel) { CosmosItemProperties first = documentDefinitionList.remove(0); Flux<CosmosItemResponse> result = Flux.from(cosmosContainer.createItem(first)); for (CosmosItemProperties docDef : documentDefinitionList) { result.concatWith(cosmosContainer.createItem(docDef)); } return result; } */ public List<CosmosItemProperties> bulkInsertBlocking(CosmosContainer cosmosContainer, List<CosmosItemProperties> documentDefinitionList) { /* return bulkInsert(cosmosContainer, documentDefinitionList, DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL) .parallel() .runOn(Schedulers.parallel()) .map(CosmosItemResponse::properties) .sequential() .collectList() .block(); */ return Flux.merge(documentDefinitionList.stream() .map(d -> cosmosContainer.createItem(d).map(response -> response.properties())) .collect(Collectors.toList())).collectList().block(); } public static ConsistencyLevel getAccountDefaultConsistencyLevel(CosmosClient client) { return CosmosBridgeInternal.getDatabaseAccount(client).block().getConsistencyPolicy().getDefaultConsistencyLevel(); } public static CosmosUser createUser(CosmosClient client, String databaseId, CosmosUserSettings userSettings) { return client.getDatabase(databaseId).read().block().database().createUser(userSettings).block().user(); } public static CosmosUser safeCreateUser(CosmosClient client, String databaseId, CosmosUserSettings user) { deleteUserIfExists(client, databaseId, user.id()); return createUser(client, databaseId, user); } private static CosmosContainer safeCreateCollection(CosmosClient client, String databaseId, CosmosContainerSettings collection, CosmosContainerRequestOptions options) { deleteCollectionIfExists(client, databaseId, collection.id()); return createCollection(client.getDatabase(databaseId), collection, options); } static protected CosmosContainerSettings getCollectionDefinition() { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList<String> paths = new ArrayList<String>(); paths.add("/mypk"); partitionKeyDef.paths(paths); CosmosContainerSettings collectionDefinition = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); return collectionDefinition; } static protected CosmosContainerSettings getCollectionDefinitionWithRangeRangeIndex() { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList<String> paths = new ArrayList<>(); paths.add("/mypk"); partitionKeyDef.paths(paths); IndexingPolicy indexingPolicy = new IndexingPolicy(); Collection<IncludedPath> includedPaths = new ArrayList<>(); IncludedPath includedPath = new IncludedPath();
package org.trianacode.TrianaCloud.Broker; import org.apache.log4j.Logger; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.map.ObjectMapper; import org.trianacode.TrianaCloud.Utils.Task; import org.trianacode.TrianaCloud.Utils.TrianaCloudServlet; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** * @author Kieran David Evans * @version 1.0.0 Feb 26, 2012 */ public class Results extends TrianaCloudServlet { private Logger logger = Logger.getLogger(this.getClass()); public static ConcurrentHashMap<String, Task> resultMap; private class TaskReturn { public String name; public String origin; public String totalTime; public String dataType; public String data; public String key; public String returnCode; } public void init() throws ServletException { try { resultMap = (ConcurrentHashMap<String, Task>) getServletContext().getAttribute("resultMap"); if (resultMap == null) { ServletException se = new ServletException("Couldn't get resultMap"); logger.error("Couldn't get the ResultMap", se); throw se; } } catch (Exception e) { ServletException se = new ServletException("Couldn't get resultMap"); logger.error("Something Happened!", se); throw se; } } public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String name = "action"; String value = request.getParameter(name); if (value == null) { // The request parameter 'param' was not present in the query string logger.error("Parameter \"action\" not defined in the request."); this.write404Error(response, "Parameter \"action\" not defined in the request."); } else if ("".equals(value)) { // The request parameter 'param' was present in the query string but has no value logger.error("Parameter \"action\" is null"); this.write404Error(response, "Parameter \"action\" is null."); } String pathInfo = isolatePath(request); String content = ""; if (!pathInfo.equalsIgnoreCase("")) { write404Error(response, "Unknown endpoint"); return; } if (value.equalsIgnoreCase("json")) { getJson(request, response); } else if (value.equalsIgnoreCase("file")) { getFile(request, response); } else if (value.equalsIgnoreCase("results")) { getResults(request, response); } else if (value.equalsIgnoreCase("byid")) { getJsonByID(request, response); } } public void getJsonByID(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String pname = "uuid"; String kvalue = request.getParameter(pname); if (kvalue == null) { System.out.println("UUID is null"); writeError(response, 500, "No ID specified."); return; } if (kvalue.equalsIgnoreCase("")) { System.out.println("UUID is blank"); } try { response.setStatus(200); response.setContentType("text/html"); response.getWriter().println(makeJSONByID(kvalue)); } catch (Exception e) { e.printStackTrace(); log.error(e); StringBuffer stack = new StringBuffer("Error: " + e.getMessage() + "<br/>"); StackTraceElement[] trace = e.getStackTrace(); for (StackTraceElement element : trace) { stack.append(element.toString()).append("<br/>"); } writeError(response, 500, stack.toString()); } catch (Throwable t) { writeThrowable(response, t); } } public String makeJSONByID(String UUID) throws IOException { ObjectMapper mapper = new ObjectMapper(new JsonFactory()); StringBuffer b = new StringBuffer(); Task t = resultMap.get("UUID"); if(t==null){ return "0"; } //Iterator it = resultMap.entrySet().iterator(); Set<TaskReturn> trs = new LinkedHashSet<TaskReturn>(); TaskReturn r = new TaskReturn(); r.key = UUID; r.name = t.getName(); r.origin = t.getOrigin(); r.dataType = t.getReturnDataType(); r.totalTime = (t.getTotalTime().getTime() + "ms"); r.returnCode = t.getReturnCode(); if (r.dataType.equalsIgnoreCase("string")) { r.data = new String(t.getReturnData(), "UTF-8"); } else { r.data = new String("" + t.getReturnData().length); } trs.add(r); b.append(mapper.writeValueAsString(trs)); System.out.println("JSON: " + b.toString()); return b.toString(); } public void getJson(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { try { response.setStatus(200); response.setContentType("text/html"); response.getWriter().println(makeJSON()); } catch (Exception e) { e.printStackTrace(); log.error(e); StringBuffer stack = new StringBuffer("Error: " + e.getMessage() + "<br/>"); StackTraceElement[] trace = e.getStackTrace(); for (StackTraceElement element : trace) { stack.append(element.toString()).append("<br/>"); } writeError(response, 500, stack.toString()); } catch (Throwable t) { writeThrowable(response, t); } } public String makeJSON() throws IOException { ObjectMapper mapper = new ObjectMapper(new JsonFactory()); StringBuffer b = new StringBuffer(); Iterator it = resultMap.entrySet().iterator(); Set<TaskReturn> trs = new LinkedHashSet<TaskReturn>(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry) it.next(); String key = (String) pairs.getKey(); Task t = (Task) pairs.getValue(); if (t != null) { TaskReturn r = new TaskReturn(); r.key = key; r.name = t.getName(); r.origin = t.getOrigin(); r.dataType = t.getReturnDataType(); r.totalTime = (t.getTotalTime().getTime() + "ms"); r.returnCode = t.getReturnCode(); if (r.dataType.equalsIgnoreCase("string")) { r.data = new String(t.getReturnData(), "UTF-8"); } trs.add(r); } } b.append(mapper.writeValueAsString(trs)); System.out.println("JSON: " + b.toString()); return b.toString(); } public void getFile(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ServletOutputStream op = response.getOutputStream(); String pname = "key"; String kvalue = request.getParameter(pname); if (kvalue == null) { System.out.println("Key is null"); } if (kvalue.equalsIgnoreCase("")) { System.out.println("Key is blank"); } Task t = resultMap.get(kvalue); if (t == null) { response.setStatus(404); response.setContentType("text/html"); return; } byte[] data = t.getReturnData(); response.setContentType("application/octet-stream"); response.setContentLength((int) data.length); response.setHeader("Content-Disposition", "attachment; filename=" + t.getFileName()); op.write(data); op.flush(); op.close(); } public void getResults(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { try { response.setStatus(200); response.setContentType("text/html"); StringBuffer b = new StringBuffer(); Iterator it = resultMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry) it.next(); String key = (String) pairs.getKey(); Task t = (Task) pairs.getValue(); if (t != null) { b.append("<div class=\"Title\">"); b.append(t.getOrigin()); b.append(" "); b.append(t.getTotalTime().getTime() + " ms"); b.append("</div>"); if (t.getReturnDataType().equalsIgnoreCase("string")) { b.append("<div class=\"toggle\"><pre>"); b.append(new String(t.getReturnData(), "UTF-8").replace("\n", "<br>")); b.append("</pre></div><p/>"); } else { b.append("<a href=\"/Broker/results?action=file&key="); b.append(key); b.append("\" display=\"none\">"); b.append(t.getName()); b.append("</a><p/>"); } } } response.getWriter().println(b.toString()); } catch (Exception e) { e.printStackTrace(); log.error(e); StringBuffer stack = new StringBuffer("Error: " + e.getMessage() + "<br/>"); StackTraceElement[] trace = e.getStackTrace(); for (StackTraceElement element : trace) { stack.append(element.toString()).append("<br/>"); } writeError(response, 500, stack.toString()); } catch (Throwable t) { writeThrowable(response, t); } } }
package com.hello.docker; public class HelloDocker { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Hello, docker"); System.out.println("This is an example"); } }
package com.doubleleft.hook; import com.loopj.android.http.*; import android.content.Context; import android.util.Log; import org.apache.http.HttpEntity; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.URLEncoder; public class Client { // Globally-available Client instance private static Client instance; private static AsyncHttpClient httpClient = new AsyncHttpClient(); public static Context context; // Extras public KeyValues keys; public Auth auth; public System system; // Settings private String appId; private String appKey; private String endpoint; /** * Returns the instance of the Client * * @return */ public static Client getInstance() { if (instance == null) { throw new ExceptionInInitializerError("Context not found. You need to call Client.setup(context) at least once."); } return instance; } public Client(Context context, String appId, String appKey, String endpoint) { this.appId = appId; this.appKey = appKey; this.endpoint= endpoint; auth = new Auth(this); keys = new KeyValues(this); system = new System(this); // Singleton instance = this; instance.context = context; // Request headers httpClient.addHeader("Content-Type", "application/json"); httpClient.addHeader("X-App-Id", appId); httpClient.addHeader("X-App-Key", appKey); } public Collection collection(String collectionName) { return new Collection(this, collectionName); } public Channel channel(String name, JSONObject options) { // TODO: implement client Channel API throw new Error("Channel API not implemented"); } public RequestHandle get(String segments, JSONObject data, AsyncHttpResponseHandler responseHandler) { return this.request(segments, "GET", data, responseHandler); } public RequestHandle post(String segments, JSONObject data, AsyncHttpResponseHandler responseHandler) { return this.request(segments, "POST", data, responseHandler); } public RequestHandle put(String segments, JSONObject data, AsyncHttpResponseHandler responseHandler) { return this.request(segments, "PUT", data, responseHandler); } public RequestHandle remove(String segments, AsyncHttpResponseHandler responseHandler) { // Send empty request params JSONObject params = new JSONObject(); return this.request(segments, "DELETE", params, responseHandler); } public RequestHandle request(String segments, String method, JSONObject data, AsyncHttpResponseHandler responseHandler) { if (auth.hasAuthToken()) { httpClient.addHeader("X-Auth-Token", auth.getAuthToken()); } else { httpClient.removeHeader("X-Auth-Token"); } RequestParams params = new RequestParams(); for(int i = 0; i<data.names().length(); i++) { try { params.put(data.names().getString(i), data.get(data.names().getString(i))); } catch (JSONException e) { e.printStackTrace(); } } RequestHandle handle; if (method == "POST") { handle = httpClient.post(endpoint + "/" + segments, params, responseHandler); } else if (method == "PUT") { handle = httpClient.put(endpoint + "/" + segments, params, responseHandler); } else if (method == "DELETE" || method == "GET") { String queryString = ""; try { queryString = URLEncoder.encode(data.toString(), "utf-8"); } catch (IOException e) { e.printStackTrace(); } handle = httpClient.get(endpoint + "/" + segments + "?" + queryString, responseHandler); } Log.d("hook", "request " + data.toString()); Log.d("hook", "URL_request " + endpoint + "/" + segments); return handle; } public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } public String getAppKey() { return appKey; } public void setAppKey(String appKey) { this.appKey = appKey; } public String getEndpoint() { return endpoint; } public void setEndpoint(String endpointUrl) { this.endpoint = endpointUrl; } }
package com.touchgraph.graphlayout; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Frame; import java.awt.Graphics; import java.awt.Image; import java.awt.Point; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Vector; import javax.swing.BorderFactory; import javax.swing.JPanel; import com.touchgraph.graphlayout.graphelements.GraphEltSet; import com.touchgraph.graphlayout.graphelements.ImmutableGraphEltSet; import com.touchgraph.graphlayout.graphelements.VisibleLocality; import com.touchgraph.graphlayout.interaction.GLEditUI; import com.touchgraph.graphlayout.interaction.TGAbstractClickUI; public class TGPanel extends JPanel { // static variables for use within the package private static final long serialVersionUID = 1L; private GraphEltSet completeEltSet; private VisibleLocality visibleLocality; private LocalityUtils localityUtils; public TGLayout tgLayout; protected BasicMouseMotionListener basicMML; protected Edge mouseOverE; // mouseOverE is the edge the mouse is over protected Node mouseOverN; // mouseOverN is the node the mouse is over protected boolean maintainMouseOver = false; // If true, then don't // change mouseOverN or // mouseOverE protected Node select; Node dragNode; // Node currently being dragged protected Point mousePos; // Mouse location, updated in the // mouseMotionListener Image offscreen; Dimension offscreensize; Graphics offgraphics; private Vector<GraphListener> graphListeners; private Vector<TGPaintListener> paintListeners; TGLensSet tgLensSet; // Converts between a nodes visual position (drawx, // drawy), // and its absolute position (x,y). AdjustOriginLens adjustOriginLens; SwitchSelectUI switchSelectUI; private Color backgroundColor; /** * Default constructor. */ public TGPanel(Color backgroundColor) { this.backgroundColor = backgroundColor; setLayout(null); setBorder(BorderFactory.createLineBorder(Color.BLACK)); setGraphEltSet(new GraphEltSet()); addMouseListener(new BasicMouseListener()); basicMML = new BasicMouseMotionListener(); addMouseMotionListener(basicMML); graphListeners = new Vector<GraphListener>(); paintListeners = new Vector<TGPaintListener>(); adjustOriginLens = new AdjustOriginLens(); switchSelectUI = new SwitchSelectUI(); TGLayout tgLayout = new TGLayout(this); setTGLayout(tgLayout); tgLayout.start(); setGraphEltSet(new GraphEltSet()); } public void setLensSet(TGLensSet lensSet) { tgLensSet = lensSet; } public void setTGLayout(TGLayout tgl) { tgLayout = tgl; } public void setGraphEltSet(GraphEltSet ges) { completeEltSet = ges; visibleLocality = new VisibleLocality(completeEltSet); localityUtils = new LocalityUtils(visibleLocality, this); } public AdjustOriginLens getAdjustOriginLens() { return adjustOriginLens; } public SwitchSelectUI getSwitchSelectUI() { return switchSelectUI; } // color and font setters ...................... // Node manipulation ........................... /** Returns an Iterator over all nodes in the complete graph. */ /* * public Iterator getAllNodes() { return completeEltSet.getNodes(); } */ /** Return the current visible locality. */ public ImmutableGraphEltSet getGES() { return visibleLocality; } /** Returns the current node count. */ public int getNodeCount() { return completeEltSet.nodeCount(); } /** * Returns the current node count within the VisibleLocality. * * @deprecated this method has been replaced by the * <tt>visibleNodeCount()</tt> method. */ public int nodeNum() { return visibleLocality.nodeCount(); } /** Returns the current node count within the VisibleLocality. */ public int visibleNodeCount() { return visibleLocality.nodeCount(); } /** * Return the Node whose ID matches the String <tt>id</tt>, null if no * match is found. * * @param id * The ID identifier used as a query. * @return The Node whose ID matches the provided 'id', null if no match is * found. */ public Node findNode(String id) { if (id == null) return null; // ignore return completeEltSet.findNode(id); } /** * Return the Node whose URL matches the String <tt>strURL</tt>, null if * no match is found. * * @param strURL * The URL identifier used as a query. * @return The Node whose URL matches the provided 'URL', null if no match * is found. */ public Node findNodeByURL(String strURL) { if (strURL == null) return null; // ignore return completeEltSet.findNodeByURL(strURL); } /** * Return a Collection of all Nodes whose label matches the String * <tt>label</tt>, null if no match is found. */ /* * public Collection findNodesByLabel( String label ) { if ( label == null ) * return null; // ignore return completeEltSet.findNodesByLabel(label); } */ /** * Return the first Nodes whose label contains the String <tt>substring</tt>, * null if no match is found. * * @param substring * The Substring used as a query. */ public Node findNodeLabelContaining(String substring) { if (substring == null) return null; // ignore return completeEltSet.findNodeLabelContaining(substring); } /** * Adds a Node, with its ID and label being the current node count plus 1. * * @see com.touchgraph.graphlayout.Node */ public Node addNode() throws TGException { String id = String.valueOf(getNodeCount() + 1); return addNode(id, null); } /** * Adds a Node, provided its label. The node is assigned a unique ID. * * @see com.touchgraph.graphlayout.graphelements.GraphEltSet */ public Node addNode(String label) throws TGException { return addNode(null, label); } /** * Adds a Node, provided its ID and label. * * @see com.touchgraph.graphlayout.Node */ public Node addNode(String id, String label) throws TGException { Node node; if (label == null) node = new Node(id); else node = new Node(id, label); updateDrawPos(node); // The addNode() call should probably take a // position, this just sets it at 0,0 addNode(node); return node; } /** * Add the Node <tt>node</tt> to the visibleLocality, checking for ID * uniqueness. */ public void addNode(final Node node) throws TGException { synchronized (localityUtils) { visibleLocality.addNode(node); resetDamper(); } } /** * Remove the Node object matching the ID <code>id</code>, returning true * if the deletion occurred, false if a Node matching the ID does not exist * (or if the ID value was null). * * @param id * The ID identifier used as a query. * @return true if the deletion occurred. */ public boolean deleteNodeById(String id) { if (id == null) return false; // ignore Node node = findNode(id); if (node == null) return false; else return deleteNode(node); } public boolean deleteNode(Node node) { synchronized (localityUtils) { if (visibleLocality.deleteNode(node)) { // delete from // visibleLocality, *AND // completeEltSet if (node == select) clearSelect(); resetDamper(); return true; } return false; } } public void clearAll() { synchronized (localityUtils) { visibleLocality.clearAll(); } } public Node getSelect() { return select; } public Node getMouseOverN() { return mouseOverN; } public synchronized void setMouseOverN(Node node) { if (dragNode != null || maintainMouseOver) return; // So you don't accidentally switch nodes while dragging if (mouseOverN != node) { mouseOverN = node; } if (mouseOverN == null) setCursor(new Cursor(Cursor.MOVE_CURSOR)); else setCursor(new Cursor(Cursor.HAND_CURSOR)); } // Edge manipulation ........................... /** Returns an Iterator over all edges in the complete graph. */ /* * public Iterator getAllEdges() { return completeEltSet.getEdges(); } */ public void deleteEdge(Edge edge) { synchronized (localityUtils) { visibleLocality.deleteEdge(edge); resetDamper(); } } public void deleteEdge(Node from, Node to) { synchronized (localityUtils) { visibleLocality.deleteEdge(from, to); } } /** * Returns the current edge count in the complete graph. */ public int getEdgeCount() { return completeEltSet.edgeCount(); } /** * Return the number of Edges in the Locality. * * @deprecated this method has been replaced by the * <tt>visibleEdgeCount()</tt> method. */ public int edgeNum() { return visibleLocality.edgeCount(); } /** * Return the number of Edges in the Locality. */ public int visibleEdgeCount() { return visibleLocality.edgeCount(); } public Edge findEdge(Node f, Node t) { return visibleLocality.findEdge(f, t); } public void addEdge(Edge e) { synchronized (localityUtils) { visibleLocality.addEdge(e); resetDamper(); } } public Edge addEdge(Node f, Node t, int tens) { synchronized (localityUtils) { return visibleLocality.addEdge(f, t, tens); } } public Edge getMouseOverE() { return mouseOverE; } public synchronized void setMouseOverE(Edge edge) { if (dragNode != null || maintainMouseOver) return; // No funny business while dragging if (mouseOverE != edge) { mouseOverE = edge; } } // miscellany .................................. protected class AdjustOriginLens extends TGAbstractLens { protected void applyLens(TGPoint2D p) { p.x = p.x + TGPanel.this.getSize().width / 2; p.y = p.y + TGPanel.this.getSize().height / 2; } protected void undoLens(TGPoint2D p) { p.x = p.x - TGPanel.this.getSize().width / 2; p.y = p.y - TGPanel.this.getSize().height / 2; } } public class SwitchSelectUI extends TGAbstractClickUI { public void mouseClicked(MouseEvent e) { if (mouseOverN != null) { if (mouseOverN != select) setSelect(mouseOverN); else clearSelect(); } } } void fireMovedEvent() { Vector<GraphListener> listeners; synchronized (this) { listeners = new Vector<GraphListener>(graphListeners); } for (int i = 0; i < listeners.size(); i++) { GraphListener gl = listeners.elementAt(i); gl.graphMoved(); } } public void fireResetEvent() { Vector<GraphListener> listeners; synchronized (this) { listeners = new Vector<GraphListener>(graphListeners); } for (int i = 0; i < listeners.size(); i++) { GraphListener gl = listeners.elementAt(i); gl.graphReset(); } } public synchronized void addGraphListener(GraphListener gl) { graphListeners.addElement(gl); } public synchronized void removeGraphListener(GraphListener gl) { graphListeners.removeElement(gl); } public synchronized void addPaintListener(TGPaintListener pl) { paintListeners.addElement(pl); } public synchronized void removePaintListener(TGPaintListener pl) { paintListeners.removeElement(pl); } public void setMaintainMouseOver(boolean maintain) { maintainMouseOver = maintain; } public void clearSelect() { if (select != null) { select = null; repaint(); } } /** * A convenience method that selects the first node of a graph, so that * hiding works. */ public void selectFirstNode() { setSelect(getGES().getFirstNode()); } public void setSelect(Node node) { if (node != null) { select = node; repaint(); } else if (node == null) clearSelect(); } public void multiSelect(TGPoint2D from, TGPoint2D to) { final double minX, minY, maxX, maxY; if (from.x > to.x) { maxX = from.x; minX = to.x; } else { minX = from.x; maxX = to.x; } if (from.y > to.y) { maxY = from.y; minY = to.y; } else { minY = from.y; maxY = to.y; } final Vector<Node> selectedNodes = new Vector<Node>(); for (Node node : visibleLocality.getNodeIterable()) { double x = node.drawx; double y = node.drawy; if (x > minX && x < maxX && y > minY && y < maxY) { selectedNodes.addElement(node); } } if (selectedNodes.size() > 0) { int r = (int) (Math.random() * selectedNodes.size()); setSelect(selectedNodes.elementAt(r)); } else { clearSelect(); } } public void updateLocalityFromVisibility() throws TGException { visibleLocality.updateLocalityFromVisibility(); } public void setLocale(Node node, int radius, int maxAddEdgeCount, int maxExpandEdgeCount, boolean unidirectional) throws TGException { localityUtils.setLocale(node, radius, maxAddEdgeCount, maxExpandEdgeCount, unidirectional); } public void fastFinishAnimation() { // Quickly wraps up the add node // animation localityUtils.fastFinishAnimation(); } public void setLocale(Node node, int radius) throws TGException { localityUtils.setLocale(node, radius); } public void expandNode(Node node) { localityUtils.expandNode(node); } public void hideNode(Node hideNode) { localityUtils.hideNode(hideNode); } public void collapseNode(Node collapseNode) { localityUtils.collapseNode(collapseNode); } public void hideEdge(Edge hideEdge) { visibleLocality.removeEdge(hideEdge); if (mouseOverE == hideEdge) setMouseOverE(null); resetDamper(); } public void setDragNode(Node node) { dragNode = node; tgLayout.setDragNode(node); } public Node getDragNode() { return dragNode; } void setMousePos(Point p) { mousePos = p; } public Point getMousePos() { return mousePos; } /** Start and stop the damper. Should be placed in the TGPanel too. */ public void startDamper() { if (tgLayout != null) tgLayout.startDamper(); } public void stopDamper() { if (tgLayout != null) tgLayout.stopDamper(); } /** Makes the graph mobile, and slowly slows it down. */ public void resetDamper() { if (tgLayout != null) tgLayout.resetDamper(); } /** Gently stops the graph from moving */ public void stopMotion() { if (tgLayout != null) tgLayout.stopMotion(); } class BasicMouseListener extends MouseAdapter { public void mouseEntered(MouseEvent e) { addMouseMotionListener(basicMML); } public void mouseExited(MouseEvent e) { removeMouseMotionListener(basicMML); mousePos = null; setMouseOverN(null); setMouseOverE(null); repaint(); } } class BasicMouseMotionListener implements MouseMotionListener { public void mouseDragged(MouseEvent e) { mousePos = e.getPoint(); findMouseOver(); try { Thread.sleep(6); // An attempt to make the // cursor flicker less } catch (InterruptedException ex) { // break; } } public void mouseMoved(MouseEvent e) { mousePos = e.getPoint(); synchronized (this) { Edge oldMouseOverE = mouseOverE; Node oldMouseOverN = mouseOverN; findMouseOver(); if (oldMouseOverE != mouseOverE || oldMouseOverN != mouseOverN) { repaint(); } // Replace the above lines with the commented portion below to // prevent whole graph // from being repainted simply to highlight a node On mouseOver. // This causes some annoying flickering though. /* * if(oldMouseOverE!=mouseOverE) { if (oldMouseOverE!=null) { * synchronized(oldMouseOverE) { * oldMouseOverE.paint(TGPanel.this.getGraphics(),TGPanel.this); * oldMouseOverE.from.paint(TGPanel.this.getGraphics(),TGPanel.this); * oldMouseOverE.to.paint(TGPanel.this.getGraphics(),TGPanel.this); } } * * if (mouseOverE!=null) { synchronized(mouseOverE) { * mouseOverE.paint(TGPanel.this.getGraphics(),TGPanel.this); * mouseOverE.from.paint(TGPanel.this.getGraphics(),TGPanel.this); * mouseOverE.to.paint(TGPanel.this.getGraphics(),TGPanel.this); } } } * * if(oldMouseOverN!=mouseOverN) { if (oldMouseOverN!=null) * oldMouseOverN.paint(TGPanel.this.getGraphics(),TGPanel.this); * if (mouseOverN!=null) * mouseOverN.paint(TGPanel.this.getGraphics(),TGPanel.this); } */ } } } protected synchronized void findMouseOver() { if (mousePos == null) { setMouseOverN(null); setMouseOverE(null); return; } final int mpx = mousePos.x; final int mpy = mousePos.y; final Node[] monA = new Node[1]; final Edge[] moeA = new Edge[1]; double minoverdist = 100; // Kind of a hack (see second if statement) // Nodes can be as wide as 200 (=2*100) for (Node node : visibleLocality.getNodeIterable()) { double x = node.drawx; double y = node.drawy; double dist = Math.sqrt((mpx - x) * (mpx - x) + (mpy - y) * (mpy - y)); if ((dist < minoverdist) && node.containsPoint(mpx, mpy)) { minoverdist = dist; monA[0] = node; } } double minDist = 8; // Tangential distance to the edge double minFromDist = 1000; // Distance to the edge's "from" node for (Edge edge: visibleLocality.getEdgeIterable()) { double x = edge.from.drawx; double y = edge.from.drawy; double dist = edge.distFromPoint(mpx, mpy); if (dist < minDist) { // Set the over edge to the edge with // the minimun tangential distance minDist = dist; minFromDist = Math.sqrt((mpx - x) * (mpx - x) + (mpy - y) * (mpy - y)); moeA[0] = edge; } else if (dist == minDist) { // If tangential distances are // identical, chose // the edge whose "from" node is closest. double fromDist = Math.sqrt((mpx - x) * (mpx - x) + (mpy - y) * (mpy - y)); if (fromDist < minFromDist) { minFromDist = fromDist; moeA[0] = edge; } } } setMouseOverN(monA[0]); if (monA[0] == null) setMouseOverE(moeA[0]); else setMouseOverE(null); } TGPoint2D topLeftDraw = null; TGPoint2D bottomRightDraw = null; public TGPoint2D getTopLeftDraw() { return new TGPoint2D(topLeftDraw); } public TGPoint2D getBottomRightDraw() { return new TGPoint2D(bottomRightDraw); } public TGPoint2D getCenter() { return tgLensSet.convDrawToReal(getSize().width / 2, getSize().height / 2); } public TGPoint2D getDrawCenter() { return new TGPoint2D(getSize().width / 2, getSize().height / 2); } public void updateGraphSize() { if (topLeftDraw == null) topLeftDraw = new TGPoint2D(0, 0); if (bottomRightDraw == null) bottomRightDraw = new TGPoint2D(0, 0); boolean firstNode = true; for (Node node : visibleLocality.getNodeIterable()) { if (firstNode) { // initialize topRight + bottomLeft topLeftDraw.setLocation(node.drawx, node.drawy); bottomRightDraw.setLocation(node.drawx, node.drawy); firstNode = false; } else { // Standard max and min finding topLeftDraw.setLocation( Math.min(node.drawx, topLeftDraw.x), Math.min( node.drawy, topLeftDraw.y)); bottomRightDraw.setLocation(Math.max(node.drawx, bottomRightDraw.x), Math.max(node.drawy, bottomRightDraw.y)); } } } public synchronized void processGraphMove() { updateDrawPositions(); updateGraphSize(); } public synchronized void repaintAfterMove() { // Called by TGLayout + // others to indicate that // graph has moved processGraphMove(); findMouseOver(); fireMovedEvent(); repaint(); } public void updateDrawPos(Node node) { // sets the visual position from the // real position TGPoint2D p = tgLensSet.convRealToDraw(node.x, node.y); node.drawx = p.x; node.drawy = p.y; } public void updatePosFromDraw(Node node) { // sets the real position from // the visual position TGPoint2D p = tgLensSet.convDrawToReal(node.drawx, node.drawy); node.x = p.x; node.y = p.y; } public void updateDrawPositions() { for (Node node : visibleLocality.getNodeIterable()) { updateDrawPos(node); } } Color myBrighter(Color c) { int r = c.getRed(); int g = c.getGreen(); int b = c.getBlue(); r = Math.min(r + 96, 255); g = Math.min(g + 96, 255); b = Math.min(b + 96, 255); return new Color(r, g, b); } public synchronized void paint(Graphics g) { update(g); } @SuppressWarnings("unchecked") public synchronized void update(Graphics g) { Dimension d = getSize(); if ((offscreen == null) || (d.width != offscreensize.width) || (d.height != offscreensize.height)) { offscreen = createImage(d.width, d.height); offscreensize = d; offgraphics = offscreen.getGraphics(); processGraphMove(); findMouseOver(); fireMovedEvent(); } offgraphics.setColor(backgroundColor); offgraphics.fillRect(0, 0, d.width, d.height); paintListeners = (Vector) paintListeners.clone(); for (int i = 0; i < paintListeners.size(); i++) { TGPaintListener pl = paintListeners.elementAt(i); pl.paintFirst(offgraphics); } for (Edge e : visibleLocality.getEdgeIterable()) { e.paint(offgraphics, TGPanel.this); } for (int i = 0; i < paintListeners.size(); i++) { TGPaintListener pl = paintListeners.elementAt(i); pl.paintAfterEdges(offgraphics); } for (Node node : visibleLocality.getNodeIterable()) { node.paint(offgraphics, TGPanel.this); } if (mouseOverE != null) { // Make the edge the mouse is over appear on // top. mouseOverE.paint(offgraphics, this); mouseOverE.from.paint(offgraphics, this); mouseOverE.to.paint(offgraphics, this); } if (select != null) { // Make the selected node appear on top. select.paint(offgraphics, this); } if (mouseOverN != null) { // Make the node the mouse is over appear on // top. mouseOverN.paint(offgraphics, this, true); } for (int i = 0; i < paintListeners.size(); i++) { TGPaintListener pl = paintListeners.elementAt(i); pl.paintLast(offgraphics); } paintComponents(offgraphics); // Paint any components that have been // added to this panel g.drawImage(offscreen, 0, 0, null); } public static void main(String[] args) { Frame frame; frame = new Frame("TGPanel"); TGPanel tgPanel = new TGPanel(Color.BLACK); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); TGLensSet tgls = new TGLensSet(); tgls.addLens(tgPanel.getAdjustOriginLens()); tgPanel.setLensSet(tgls); try { tgPanel.addNode(); // Add a starting node. } catch (TGException tge) { System.err.println(tge.getMessage()); } tgPanel.setVisible(true); new GLEditUI(tgPanel).activate(); frame.add("Center", tgPanel); frame.setSize(500, 500); frame.setVisible(true); } } // end com.touchgraph.graphlayout.TGPanel
package example; //-*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: //@homepage@ import java.awt.*; import java.awt.geom.*; import javax.swing.*; import javax.swing.plaf.basic.BasicTabbedPaneUI; public final class MainPanel extends JPanel { private final JTabbedPane tabs = new JTabbedPane() { @Override public void updateUI() { super.updateUI(); UIManager.put("TabbedPane.highlight", Color.GRAY); setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); setUI(new IsoscelesTrapezoidTabbedPaneUI()); } }; public MainPanel() { super(new BorderLayout()); tabs.addTab("JTextArea", new JScrollPane(new JTextArea())); tabs.addTab("JTree", new JScrollPane(new JTree())); tabs.addTab("JButton", new JButton("button")); tabs.addTab("JSplitPane", new JSplitPane()); add(tabs); setPreferredSize(new Dimension(320, 240)); } public static void main(String... args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowGUI(); } }); } public static void createAndShowGUI() { // try { // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // } catch (ClassNotFoundException | InstantiationException // ex.printStackTrace(); JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } class IsoscelesTrapezoidTabbedPaneUI extends BasicTabbedPaneUI { private static final int ADJ2 = 3; private final Color selectedTabColor = UIManager.getColor("TabbedPane.selected"); private final Color tabBackgroundColor = Color.LIGHT_GRAY; private final Color tabBorderColor = Color.GRAY; @SuppressWarnings("PMD.CyclomaticComplexity") @Override protected void paintTabArea(Graphics g, int tabPlacement, int selectedIndex) { int tabCount = tabPane.getTabCount(); Rectangle iconRect = new Rectangle(); Rectangle textRect = new Rectangle(); Rectangle clipRect = g.getClipBounds(); // copied from BasicTabbedPaneUI#paintTabArea(...) for (int i = runCount - 1; i >= 0; i int start = tabRuns[i]; int next = tabRuns[(i == runCount - 1) ? 0 : i + 1]; @SuppressWarnings("PMD.ConfusingTernary") // Avoid if (x != y) ..; else ..; int end = next != 0 ? next - 1 : tabCount - 1; // for (int j = start; j <= end; j++) { for (int j = end; j >= start; j if (j != selectedIndex && rects[j].intersects(clipRect)) { paintTab(g, tabPlacement, rects, j, iconRect, textRect); } } } if (selectedIndex >= 0 && rects[selectedIndex].intersects(clipRect)) { paintTab(g, tabPlacement, rects, selectedIndex, iconRect, textRect); } } @Override protected void paintTabBorder(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) { // Do nothing } @Override protected void paintFocusIndicator(Graphics g, int tabPlacement, Rectangle[] rects, int tabIndex, Rectangle iconRect, Rectangle textRect, boolean isSelected) { // Do nothing } @Override protected void paintContentBorderTopEdge(Graphics g, int tabPlacement, int selectedIndex, int x, int y, int w, int h) { super.paintContentBorderTopEdge(g, tabPlacement, selectedIndex, x, y, w, h); Rectangle selRect = getTabBounds(selectedIndex, calcRect); Graphics2D g2 = (Graphics2D) g.create(); g2.setColor(selectedTabColor); g2.drawLine(selRect.x - ADJ2 + 1, y, selRect.x + selRect.width + ADJ2 - 1, y); g2.dispose(); } @Override protected void paintTabBackground(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) { Graphics2D g2 = (Graphics2D) g.create(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); int textShiftOffset = isSelected ? 0 : 1; Rectangle clipRect = g2.getClipBounds(); clipRect.grow(ADJ2 + 1, 0); g2.setClip(clipRect); GeneralPath trapezoid = new GeneralPath(); trapezoid.moveTo(x - ADJ2, y + h); trapezoid.lineTo(x + ADJ2, y + textShiftOffset); trapezoid.lineTo(x + w - ADJ2, y + textShiftOffset); trapezoid.lineTo(x + w + ADJ2, y + h); // trapezoid.closePath(); // TEST: g2.setColor(isSelected ? tabPane.getBackground() : tabBackgroundColor); g2.setColor(isSelected ? selectedTabColor : tabBackgroundColor); g2.fill(trapezoid); g2.setColor(tabBorderColor); g2.draw(trapezoid); // GeneralPath shape = new GeneralPath(); // shape.moveTo(x - ADJ2, y + h); // shape.lineTo(x + ADJ2, y + textShiftOffset); // shape.lineTo(x + w - ADJ2, y + textShiftOffset); // shape.lineTo(x + w + ADJ2, y + h); // shape.closePath(); // g2.setColor(isSelected ? selectedTabColor : tabBackgroundColor); // g2.fill(shape); // GeneralPath border = new GeneralPath(); // border.moveTo(x - ADJ2, y + h); // // if (isSelected || tabIndex == 0) { // // border.moveTo(x - ADJ2, y + h); // // } else { // // // pentagon // // border.moveTo(x + ADJ2, y + h); // // border.lineTo(x, (y + h - 1) / 2); // border.lineTo(x + ADJ2, y + textShiftOffset); // border.lineTo(x + w - ADJ2, y + textShiftOffset); // border.lineTo(x + w + ADJ2, y + h); // g2.setColor(tabBorderColor); // g2.draw(border); g2.dispose(); } }
package cycronix.ctlib; import java.io.File; // CTftp: push files to FTP server // Matt Miller, Cycronix // 06/22/2015 import java.io.IOException; import java.io.OutputStream; import org.apache.commons.net.ftp.FTPClient; /** * CloudTurbine utility class that extends CTwriter class to write via FTP versus local filesystem * <p> * @author Matt Miller (MJM), Cycronix * @version 2015/06/01 * */ public class CTftp extends CTwriter { private FTPClient client = new FTPClient(); private String loginDir = ""; private String currentDir = ""; // constructor public CTftp(String dstFolder) throws IOException { super(dstFolder); } public CTftp(String dstFolder, double itrimTime) throws IOException { super(dstFolder); throw new IOException("CTftp does not yet support file trim"); } public void login(String host, String user, String pw) throws Exception { client.connect(host); boolean success = client.login(user, pw); if(!success) { throw new IOException("FTP login failed, host: "+host+", user: "+user); } client.setFileType(FTPClient.BINARY_FILE_TYPE); loginDir = client.printWorkingDirectory(); CTinfo.debugPrint("FTP login, u: "+user+", pw: "+pw+", loginDir: "+loginDir); } public void logout() { try { client.logout(); } catch (Exception e) { e.printStackTrace(); } } // over-ride CTwriter method to replace file-writes with FTP write protected void writeToStream(String pathname, byte[] bdata) throws IOException { try { if(!File.separator.equals("/")) { // replace Windows back-slash with slash for hopefully universal FTP syntax pathname = pathname.replace(File.separator.charAt(0), '/'); } int delim = pathname.lastIndexOf('/'); String filename = pathname.substring(delim+1); String filepath = pathname.substring(0,delim); if(!filepath.equals(currentDir)) { // create or change to new directory if changed from previous if(pathname.startsWith("/")) client.changeWorkingDirectory("/"); else client.changeWorkingDirectory(loginDir); // new dirs relative to loginDir ftpCreateDirectoryTree(client,filepath); // mkdirs as needed, leaves working dir @ new currentDir = filepath; } // OutputStream ostream = client.storeFileStream(filename+".tmp"); OutputStream ostream = client.storeFileStream(filename); // try without tmp file CTinfo.debugPrint("ftp pathname: "+pathname+", filename: "+filename+", filepath: "+filepath); if(ostream==null) { throw new IOException("Unable to FTP file: " + client.getReplyString()); } ostream.write(bdata); ostream.close(); if(!client.completePendingCommand()) throw new IOException("Unable to FTP file: " + client.getReplyString()); // if(!client.rename(filename+".tmp", filename)) // throw new IOException("Unable to rename file: " + client.getReplyString()); } catch (Exception e) { e.printStackTrace(); } } /** * utility to create an arbitrary directory hierarchy on the remote ftp server * @param client * @param dirTree the directory tree only delimited with / chars. No file name! * @throws Exception */ private static void ftpCreateDirectoryTree( FTPClient client, String dirTree ) throws IOException { boolean dirExists = true; //tokenize the string and attempt to change into each directory level. If you cannot, then start creating. String[] directories = dirTree.split("/"); for (String dir : directories ) { if (!dir.isEmpty() ) { if (dirExists) { dirExists = client.changeWorkingDirectory(dir); } if (!dirExists) { try { if (!client.makeDirectory(dir)) { throw new IOException("Unable to create remote directory: " + dir + ", error=" + client.getReplyString()); } if (!client.changeWorkingDirectory(dir)) { throw new IOException("Unable to change into newly created remote directory: " +dir+ ", error=" + client.getReplyString()); } } catch(IOException ioe) { System.err.println("ftpCreateDir exception on dirTree: "+dirTree+", dir: "+dir+", error: "+ioe.getMessage()); throw ioe; } } } } } }
package tankattack; import Sprites.*; import java.util.*; import javafx.animation.*; import javafx.event.*; import javafx.geometry.*; import javafx.scene.*; import javafx.scene.control.*; import javafx.scene.image.*; import javafx.scene.input.*; import javafx.scene.layout.*; import javafx.scene.paint.*; import javafx.scene.shape.*; import javafx.scene.text.*; import javafx.stage.*; import javafx.util.*; /** * * @author Ruslan */ public abstract class World { public static boolean isListeningForInput = true; private Stage myStage; public static World sharedInstance; private Scene scene; private Group root; private Circle myEnemy; private Point2D myEnemyVelocity; private Random myGenerator = new Random(); private ArrayList<Sprite> sprites; private ArrayList<Sprite> spritesToRemove; private ArrayList<Bullet> bullets; private ArrayList<Bullet> bulletsToRemove; private Player playerSprite; private Timeline timeline; // Setters, Getters public void addSprite(Sprite s) { if (s instanceof Bullet) { if (bullets == null) { bullets = new ArrayList(); } bullets.add((Bullet)s); } else { if (sprites == null) { sprites = new ArrayList(); } sprites.add(s); } root.getChildren().add(s); } public void removeSprite(Sprite s) { if (sprites == null) { return; } sprites.remove(s); root.getChildren().remove(s); } public void setPlayerSprite(Player player) { playerSprite = player; } public Player getPlayerSprite() { return playerSprite; } public Group getGroup() { return this.root; } public void setGroup(Group root) { this.root = root; } public Scene getScene() { return this.scene; } public void setScene(Scene scene) { this.scene = scene; } // Real Methods // Constructors // Create Scene, Then Init Animation. Rest of methods are helpers. public World() { throw new UnsupportedOperationException("need to pass in a stage"); } public World(Stage stage) { this.myStage = stage; World.sharedInstance = this; } public Scene createScene() { root = new Group(); createInitialSprites(); scene = new Scene(root, TankAttack.gameWidth, TankAttack.gameHeight, Color.CORNFLOWERBLUE); scene.setOnKeyPressed(e -> handleKeyInput(e)); scene.setOnKeyReleased(e -> handleKeyRelease(e)); return scene; } public void initAnimation() { KeyFrame frame = new KeyFrame(Duration.millis(1000 / TankAttack.NUM_FRAMES_PER_SECOND), e -> updateSprites()); if (timeline == null) { timeline = new Timeline(); } timeline.setCycleCount(Animation.INDEFINITE); timeline.getKeyFrames().add(frame); timeline.play(); } public abstract void createInitialSprites(); public void createPlayerSprite() { Player player = new Player(TankAttack.gameWidth/2 , TankAttack.gameHeight / 2, this); setPlayerSprite(player); } private void updateSprites() { // System.out.println("All is well. Printing animation 60 times a second."); ////// DONE //////////////////////////// playerSprite.updateLocation(); // Handle Player Firing handleFiring(); // Other Updates updateEnemySprites(); // also handles enemy fire // Bullet Movement updateBulletMovements(); ////// DONE //////////////////////////// ////// IMPLEMENT //////////////////////////// // Register Collisions With Tanks handleCollision(); // Register Collisions Between Sprites & Bullets handleCollisionBullets(); updateAllSpritesToCheckForDeath(); // Check for win checkForWin(); ////// IMPLEMENT //////////////////////////// } private void endOfLevelSuccess() { timeline.pause(); // TODO: Display level success. showEndOfLevelTextSuccess(); Timeline fiveSecondDelay = new Timeline(new KeyFrame(Duration.seconds(5), new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { // Tell TankAttack to put up the next world. signalEndOfLevel(); } })); fiveSecondDelay.setCycleCount(1); fiveSecondDelay.play(); } public void endOfLevelFailure() { timeline.pause(); // TODO: Display level failure. showEndOfLevelFailure(); Timeline fiveSecondDelay = new Timeline(new KeyFrame(Duration.seconds(5), new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { // Display Main Menu TankAttack.sharedInstance.displayStartMenu(); } })); fiveSecondDelay.setCycleCount(1); fiveSecondDelay.play(); } public void showEndOfLevelTextSuccess() { Label l = new Label("SUCCESS"); l.setFont(new Font("Arial", 60)); l.setTextFill(Color.GREEN); l.setTranslateY(TankAttack.gameHeight / 2.5); // TODO The x is hardcoded. fix it in case game dimensions change l.setTranslateX(180); root.getChildren().add(l); } private void showEndOfLevelFailure() { Label l = new Label("FAILURE"); l.setFont(new Font("Arial", 60)); l.setTextFill(Color.RED); l.setTranslateY(TankAttack.gameHeight / 2.5); // TODO The x is hardcoded. fix it in case game dimensions change l.setTranslateX(180); root.getChildren().add(l); } public abstract void signalEndOfLevel(); public void handleKeyInput(KeyEvent e) { modifyDirControllerState(e, true); } public void handleKeyRelease(KeyEvent e) { modifyDirControllerState(e, false); } private void modifyDirControllerState(KeyEvent key, boolean newState) { KeyCode keyCode = key.getCode(); if (keyCode == KeyCode.RIGHT) { DirController.rightPressed = newState; } else if (keyCode == KeyCode.LEFT) { DirController.leftPressed = newState; } else if (keyCode == KeyCode.UP) { DirController.upPressed = newState; } else if (keyCode == KeyCode.DOWN) { DirController.downPressed = newState; } else if (keyCode == KeyCode.SPACE) { DirController.spacePressed = newState; } // TODO: Implement space bar to shoot, and cheat codes, here. } private void checkForWin() { // Temporary end to game if (playerSprite.getTranslateX() < 10) { System.out.println("updateSprites calling finish."); endOfLevel(); // TODO Implement this. // Player is left all alone. Stop animation. Level defeated. } } private void handleCollision() { for (Sprite s : sprites) { if (!s.equals(playerSprite)) { if (playerSprite.getBoundsInParent().intersects(s.getBoundsInParent())){ System.out.println("COLLISION WITH SPRITE: " + s); System.out.println("TODO: Implement player dying here"); } } } } private void updateEnemySprites() { Enemy enemy; for (Sprite s : sprites) { if (s instanceof Enemy) { enemy = (Enemy)s; // Movement enemy.updateEnemyXY(); // Firing if (enemy.isFiring()) { handleEnemyFiring(enemy); } } } } // Player firing, NOT enemy firing. private void handleFiring() { // Check if space bar pressed, create new bullets for Player if (DirController.spacePressed) { new Bullet(playerSprite.getBulletOffsetX(), playerSprite.getBulletOffsetY(), this, true); } } private void handleEnemyFiring(Enemy enemy) { new Bullet(enemy.getBulletOffsetX(), enemy.getBulletOffsetY(), this, false); } private void updateBulletMovements() { Bullet b; if (bullets == null) { bullets = new ArrayList<Bullet>(); return; } for (Sprite s : bullets) { if (s instanceof Bullet) { b = (Bullet)s; b.updateXY(); } } removeOutOfBoundaryBullets(); } private void removeOutOfBoundaryBullets() { if (bulletsToRemove == null) { return; } for (Bullet b : bulletsToRemove) { bullets.remove(b); root.getChildren().remove(b); } bulletsToRemove.clear(); } public void addToOutOfBoundaryBulletsArray(Bullet b) { if (bulletsToRemove == null) { bulletsToRemove = new ArrayList<Bullet>(); } bulletsToRemove.add(b); } private void handleCollisionBullets() { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
/* * $Log: JdbcFacade.java,v $ * Revision 1.18 2007-05-24 09:50:58 europe\L190409 * fixed applying of datetime parameters * * Revision 1.17 2007/05/23 09:08:53 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added productType detector * * Revision 1.16 2007/05/16 11:40:17 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * apply datetime parameters using corresponding methods * * Revision 1.15 2007/02/12 13:56:18 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * Logger from LogUtil * * Revision 1.14 2006/12/12 09:57:37 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * restore jdbc package * * Revision 1.12 2005/09/22 15:58:05 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added warning in comment for getParameterMetadata * * Revision 1.11 2005/08/24 15:47:25 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * try to prefix with java:comp/env/ to find datasource (Tomcat compatibility) * * Revision 1.10 2005/08/17 16:10:56 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * test for empty strings using StringUtils.isEmpty() * * Revision 1.9 2005/08/09 15:53:11 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * improved exception construction * * Revision 1.8 2005/07/19 12:36:32 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * moved applyParameters to JdbcFacade * * Revision 1.7 2005/06/13 09:57:03 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * cosmetic changes * * Revision 1.6 2005/05/31 09:53:35 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * corrected version * * Revision 1.5 2005/05/31 09:53:00 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * introduction of attribute 'connectionsArePooled' * * Revision 1.4 2005/03/31 08:11:28 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * corrected typo in logging * * Revision 1.3 2004/03/26 10:43:09 Johan Verrips <johan.verrips@ibissource.org> * added @version tag in javadoc * * Revision 1.2 2004/03/26 09:50:52 Johan Verrips <johan.verrips@ibissource.org> * Updated javadoc * * Revision 1.1 2004/03/24 13:28:20 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * initial version * */ package nl.nn.adapterframework.jdbc; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Timestamp; import java.util.Date; import javax.naming.NamingException; import javax.sql.DataSource; import nl.nn.adapterframework.core.HasPhysicalDestination; import nl.nn.adapterframework.core.INamedObject; import nl.nn.adapterframework.core.IXAEnabled; import nl.nn.adapterframework.core.SenderException; import nl.nn.adapterframework.jms.JNDIBase; import nl.nn.adapterframework.parameters.Parameter; import nl.nn.adapterframework.parameters.ParameterValue; import nl.nn.adapterframework.parameters.ParameterValueList; import nl.nn.adapterframework.util.LogUtil; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; /** * Provides functions for JDBC connections. * * @version Id * @author Gerrit van Brakel * @since 4.1 */ public class JdbcFacade extends JNDIBase implements INamedObject, HasPhysicalDestination, IXAEnabled { public static final String version="$RCSfile: JdbcFacade.java,v $ $Revision: 1.18 $ $Date: 2007-05-24 09:50:58 $"; protected Logger log = LogUtil.getLogger(this); public final static int DATABASE_GENERIC=0; public final static int DATABASE_ORACLE=1; private String name; private String username=null; private String password=null; private DataSource datasource = null; private String datasourceName = null; private String datasourceNameXA = null; private boolean transacted = false; private boolean connectionsArePooled=true; private int databaseType=-1; protected String getLogPrefix() { return "["+this.getClass().getName()+"] ["+getName()+"] "; } /** * Returns either {@link #getDatasourceName() datasourceName} or {@link #getDatasourceNameXA() datasourceNameXA}, * depending on the value of {@link #isTransacted()}. * If the right one is not specified, the other is used. */ public String getDataSourceNameToUse() throws JdbcException { String result = isTransacted() ? getDatasourceNameXA() : getDatasourceName(); if (StringUtils.isEmpty(result)) { // try the alternative... result = isTransacted() ? getDatasourceName() : getDatasourceNameXA(); if (StringUtils.isEmpty(result)) { throw new JdbcException(getLogPrefix()+"neither datasourceName nor datasourceNameXA are specified"); } log.warn(getLogPrefix()+"correct datasourceName attribute not specified, will use ["+result+"]"); } return result; } protected DataSource getDatasource() throws JdbcException { if (datasource==null) { String dsName = getDataSourceNameToUse(); try { log.debug(getLogPrefix()+"looking up Datasource ["+dsName+"]"); datasource =(DataSource) getContext().lookup( dsName ); log.debug(getLogPrefix()+"looked up Datasource ["+dsName+"]: ["+datasource+"]"); } catch (NamingException e) { try { String tomcatDsName="java:comp/env/"+dsName; log.debug(getLogPrefix()+"could not find ["+dsName+"], now trying ["+tomcatDsName+"]"); datasource =(DataSource) getContext().lookup( tomcatDsName ); log.debug(getLogPrefix()+"looked up Datasource ["+tomcatDsName+"]: ["+datasource+"]"); } catch (NamingException e2) { throw new JdbcException(getLogPrefix()+"cannot find Datasource ["+dsName+"]", e); } } } return datasource; } public void setDatabaseType(int type) { databaseType=type; } public int getDatabaseType() throws SQLException, JdbcException { if (databaseType<0) { Connection conn=getConnection(); try { DatabaseMetaData md=conn.getMetaData(); String product=md.getDatabaseProductName(); String driver=md.getDriverName(); log.info("Database Metadata: product ["+product+"] driver ["+driver+"]"); if ("Oracle".equals(product)) { log.debug("Setting databasetype to ORACLE"); databaseType=DATABASE_ORACLE; } else { log.debug("Setting databasetype to GENERIC"); databaseType=DATABASE_GENERIC; } } finally { conn.close(); } } return databaseType; } /** * Obtains a connection to the datasource. */ // TODO: consider making this one protected. public Connection getConnection() throws JdbcException { try { if (StringUtils.isNotEmpty(getUsername())) { return getDatasource().getConnection(getUsername(),getPassword()); } else { return getDatasource().getConnection(); } } catch (SQLException e) { throw new JdbcException(getLogPrefix()+"cannot open connection on datasource ["+getDataSourceNameToUse()+"]", e); } } /** * Returns the name and location of the database that this objects operates on. * * @see nl.nn.adapterframework.core.HasPhysicalDestination#getPhysicalDestinationName() */ public String getPhysicalDestinationName() { String result="unknown"; try { Connection connection = getConnection(); DatabaseMetaData metadata = connection.getMetaData(); result = metadata.getURL(); String catalog=null; catalog=connection.getCatalog(); result += catalog!=null ? ("/"+catalog):""; connection.close(); } catch (Exception e) { log.warn(getLogPrefix()+"exception retrieving PhysicalDestinationName", e); } return result; } protected void applyParameters(PreparedStatement statement, ParameterValueList parameters) throws SQLException, SenderException { // statement.clearParameters(); /* // getParameterMetaData() is not supported on the WebSphere java.sql.PreparedStatement implementation. int senderParameterCount = parameters.size(); int statementParameterCount = statement.getParameterMetaData().getParameterCount(); if (statementParameterCount<senderParameterCount) { throw new SenderException(getLogPrefix()+"statement has more ["+statementParameterCount+"] parameters defined than sender ["+senderParameterCount+"]"); } */ for (int i=0; i< parameters.size(); i++) { ParameterValue pv = parameters.getParameterValue(i); String paramType = pv.getDefinition().getType(); Object value = pv.getValue(); // log.debug("applying parameter ["+(i+1)+","+parameters.getParameterValue(i).getDefinition().getName()+"], value["+parameterValue+"]"); if (Parameter.TYPE_DATE.equals(paramType)) { statement.setDate(i+1, new java.sql.Date(((Date)value).getTime())); } else if (Parameter.TYPE_DATETIME.equals(paramType)) { statement.setTimestamp(i+1, new Timestamp(((Date)value).getTime())); } else if (Parameter.TYPE_TIME.equals(paramType)) { statement.setTime(i+1, new java.sql.Time(((Date)value).getTime())); } else { statement.setString(i+1, (String)value); } } } /** * Sets the name of the object. */ public void setName(String name) { this.name = name; } public String getName() { return name; } /** * Sets the JNDI name of datasource that is used when {@link #isTransacted()} returns <code>false</code> */ public void setDatasourceName(String datasourceName) { this.datasourceName = datasourceName; } public String getDatasourceName() { return datasourceName; } /** * Sets the JNDI name of datasource that is used when {@link #isTransacted()} returns <code>true</code> */ public void setDatasourceNameXA(String datasourceNameXA) { this.datasourceNameXA = datasourceNameXA; } public String getDatasourceNameXA() { return datasourceNameXA; } /** * Sets the user name that is used to open the database connection. * If a value is set, it will be used together with the (@link #setPassword(String) specified password} * to open the connection to the database. */ public void setUsername(String username) { this.username = username; } public String getUsername() { return username; } /** * Sets the password that is used to open the database connection. * @see #setPassword(String) */ public void setPassword(String password) { this.password = password; } protected String getPassword() { return password; } /** * controls the use of transactions */ public void setTransacted(boolean transacted) { this.transacted = transacted; } public boolean isTransacted() { return transacted; } public boolean isConnectionsArePooled() { return connectionsArePooled || isTransacted(); } public void setConnectionsArePooled(boolean b) { connectionsArePooled = b; } }
/* * $Log: ClassUtils.java,v $ * Revision 1.15 2008-08-18 11:22:03 europe\L190409 * changed system.err.printline to log.error * * Revision 1.14 2007/12/10 10:22:30 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * void NPE in classOf * * Revision 1.13 2007/09/13 12:39:05 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * cosmetic improvement * * Revision 1.12 2007/09/10 11:20:15 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added default getResourceURL() * * Revision 1.11 2007/07/18 13:35:30 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * try to get a resource as a URL * no replacemen of space to %20 for jar-entries * * Revision 1.10 2007/05/09 09:25:54 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added nameOf() * * Revision 1.9 2007/02/12 14:09:05 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * Logger from LogUtil * * Revision 1.8 2006/09/14 11:44:51 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * correctede logger definition * * Revision 1.7 2005/09/26 15:29:33 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * change %20 to space and back * * Revision 1.6 2005/08/30 16:06:27 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * escape spaces in URL using %20 * * Revision 1.5 2005/08/18 13:34:19 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * try to prefix resource with 'java:comp/env/', for TomCat compatibility * * Revision 1.4 2004/11/08 08:31:17 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added log-keyword in comments * */ package nl.nn.adapterframework.util; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Constructor; import java.net.MalformedURLException; import java.net.URL; import org.apache.log4j.Logger; /** * A collection of class management utility methods. * @version Id * @author Johan Verrips * */ public class ClassUtils { public static final String version = "$RCSfile: ClassUtils.java,v $ $Revision: 1.15 $ $Date: 2008-08-18 11:22:03 $"; private static Logger log = LogUtil.getLogger(ClassUtils.class); /** * Return the context classloader. * BL: if this is command line operation, the classloading issues * are more sane. During servlet execution, we explicitly set * the ClassLoader. * * @return The context classloader. */ public static ClassLoader getClassLoader() { return Thread.currentThread().getContextClassLoader(); } /** * Retrieves the constructor of a class, based on the parameters * **/ public static Constructor getConstructorOnType(Class clas, Class[] parameterTypes) { Constructor theConstructor = null; try { theConstructor = clas.getDeclaredConstructor(parameterTypes); } catch (java.lang.NoSuchMethodException e) { log.error("cannot create constructor for Class [" + clas.getName() + "]", e); for (int i = 0; i < parameterTypes.length; i++) log.error("Parameter " + i + " type " + parameterTypes[i].getName()); } return theConstructor; } /** * Return a resource URL. * BL: if this is command line operation, the classloading issues * are more sane. During servlet execution, we explicitly set * the ClassLoader. * * @return The context classloader. * @deprecated Use getResourceURL().openStream instead. */ public static InputStream getResourceAsStream(Class klass, String resource) throws IOException { InputStream stream=null; URL url=getResourceURL(klass, resource); stream=url.openStream(); return stream; } static public URL getResourceURL(String resource) { return getResourceURL(null,resource); } /** * Get a resource-URL, first from Class then from ClassLoader * if not found with class. * * @deprecated Use getResourceURL(Object, resource) instead. * */ static public URL getResourceURL(Class klass, String resource) { resource=Misc.replace(resource,"%20"," "); URL url = null; if (klass == null) { klass = ClassUtils.class; } // first try to get the resoure as a resource url = klass.getResource(resource); if (url == null) { url = klass.getClassLoader().getResource(resource); } // then try to get it as a URL if (url == null) { try { url = new URL(resource); } catch(MalformedURLException e) { log.debug("Could not find resource as URL ["+resource+"]: "+e.getMessage()); } } // then try to get it in java:comp/env if (url == null && resource!=null && !resource.startsWith("java:comp/env/")) { log.debug("cannot find URL for resource ["+resource+"], now trying [java:comp/env/"+resource+"] (e.g. for TomCat)"); String altResource = "java:comp/env/"+resource; url = klass.getResource(altResource); // to make things work under tomcat if (url == null) { url = klass.getClassLoader().getResource(altResource); } } if (url==null) log.warn("cannot find URL for resource ["+resource+"]"); else { // Spaces must be escaped to %20. But ClassLoader.getResource(String) // has a bug in Java 1.3 and 1.4 and doesn't do this escaping. // See also: // Escaping spaces to %20 if spaces are found. String urlString = url.toString(); if (urlString.indexOf(' ')>=0 && !urlString.startsWith("jar:")) { urlString=Misc.replace(urlString," ","%20"); try { URL escapedURL = new URL(urlString); log.debug("resolved resource-string ["+resource+"] to URL ["+escapedURL.toString()+"]"); return escapedURL; } catch(MalformedURLException e) { log.warn("Could not find URL from space-escaped url ["+urlString+"], will use unescaped original version ["+url.toString()+"] "); } } } return url; } /** * Get a resource-URL, first from Class then from ClassLoader * if not found with class. * */ static public URL getResourceURL(Object obj, String resource) { return getResourceURL(obj.getClass(), resource); } /** * Tests if a class implements a given interface * * @return true if class implements given interface. */ public static boolean implementsInterface(Class class1, Class iface) { return iface.isAssignableFrom (class1); } /** * Tests if a class implements a given interface * * @return true if class implements given interface. */ public static boolean implementsInterface(String className, String iface) throws Exception { Class class1 = ClassUtils.loadClass (className); Class class2 = ClassUtils.loadClass (iface); return ClassUtils.implementsInterface(class1, class2); } public static long lastModified(Class aClass) throws IOException, IllegalArgumentException { URL url = aClass.getProtectionDomain().getCodeSource().getLocation(); if (!url.getProtocol().equals("file")) { throw new IllegalArgumentException("Class was not loaded from a file url"); } File directory = new File(url.getFile()); if (!directory.isDirectory()) { throw new IllegalArgumentException("Class was not loaded from a directory"); } String className = aClass.getName(); String basename = className.substring(className.lastIndexOf(".") + 1); File file = new File(directory, basename + ".class"); return file.lastModified(); } /** * Load a class given its name. * BL: We wan't to use a known ClassLoader--hopefully the heirarchy * is set correctly. * * @param className A class name * @return The class pointed to by <code>className</code> * @exception ClassNotFoundException If a loading error occurs */ public static Class loadClass(String className) throws ClassNotFoundException { return ClassUtils.getClassLoader().loadClass(className); } /** * Create a new instance given a class name. The constructor of the class * does NOT have parameters. * * @param className A class name * @return A new instance * @exception Exception If an instantiation error occurs */ public static Object newInstance(String className) throws Exception { return ClassUtils.loadClass(className).newInstance(); } /** * creates a new instance of an object, based on the classname as string, the classes * and the actual parameters. */ public static Object newInstance(String className, Class[] parameterClasses, Object[] parameterObjects) { // get a class object Class clas = null; try { clas=ClassUtils.loadClass(className); } catch (java.lang.ClassNotFoundException C) {System.err.println(C);} Constructor con; con= ClassUtils.getConstructorOnType(clas, parameterClasses); Object theObject=null; try { theObject=con.newInstance(parameterObjects); } catch(java.lang.InstantiationException E) {System.err.println(E);} catch(java.lang.IllegalAccessException A) {System.err.println(A);} catch(java.lang.reflect.InvocationTargetException T) {System.err.println(T);} return theObject; } /** * Creates a new instance from a class, while it looks for a constructor * that matches the parameters, and initializes the object (by calling the constructor) * Notice: this does not work when the instantiated object uses an interface class * as a parameter, as the class names are, in that case, not the same.. * * @param className a class Name * @param parameterObjects the parameters for the constructor * @return A new Instance * **/ public static Object newInstance(String className, Object[] parameterObjects) { Class parameterClasses[] = new Class[parameterObjects.length]; for (int i = 0; i < parameterObjects.length; i++) parameterClasses[i] = parameterObjects[i].getClass(); return newInstance(className, parameterClasses, parameterObjects); } /** * Gets the absolute pathname of the class file * containing the specified class name, as prescribed * by the current classpath. * * @param aClass A class */ public static String which(Class aClass) { String path = null; try { path = aClass.getProtectionDomain().getCodeSource().getLocation().toString(); } catch (Throwable t){ } return path; } /** * returns the classname of the object, without the pacakge name. */ public static String nameOf(Object o) { if (o==null) { return "<null>"; } String name=o.getClass().getName(); int pos=name.lastIndexOf('.'); if (pos<0) { return name; } else { return name.substring(pos+1); } } }
package ti.modules.titanium; import java.io.IOException; import java.util.Date; import java.util.HashMap; import java.util.Timer; import java.util.TimerTask; import org.appcelerator.titanium.TiContext; import org.appcelerator.titanium.TiDict; import org.appcelerator.titanium.TiModule; import org.appcelerator.titanium.kroll.KrollCallback; import org.appcelerator.titanium.util.Log; public class TitaniumModule extends TiModule { private static final String LCAT = "TitaniumModule"; private static TiDict constants; public TitaniumModule(TiContext tiContext) { super(tiContext); } @Override public TiDict getConstants() { if (constants == null) { constants = new TiDict(); constants.put("version", "0.9.0"); } return constants; } public void include(Object[] files) { for(Object filename : files) { try { getTiContext().evalFile((String)filename); } catch (IOException e) { Log.e(LCAT, "Error while evaluating: " + filename, e); } } } private HashMap<Integer, Timer> timers = new HashMap<Integer, Timer>(); private int currentTimerId; private int createTimer(Object fn, long timeout, final Object[] args, boolean interval) throws IllegalArgumentException { // TODO: we should handle evaluatable code eventually too.. if (fn instanceof KrollCallback) { final KrollCallback callback = (KrollCallback) fn; Timer timer = new Timer(); final int timerId = currentTimerId++; timers.put(timerId, timer); TimerTask task = new TimerTask() { @Override public void run() { Log.d(LCAT, "calling interval timer " + timerId + " @" + new Date().getTime()); callback.call(args); } }; if (interval) { timer.schedule(task, timeout, timeout); } else { timer.schedule(task, timeout); } return timerId; } else throw new IllegalArgumentException("Don't know how to call callback of type: " + fn.getClass().getName()); } public int setTimeout(Object fn, long timeout, final Object[] args) throws IllegalArgumentException { return createTimer(fn, timeout, args, false); } public void clearTimeout(int timerId) { if (timers.containsKey(timerId)) { Timer timer = timers.remove(timerId); timer.cancel(); } } public int setInterval(Object fn, long timeout, final Object[] args) throws IllegalArgumentException { return createTimer(fn, timeout, args, true); } public void clearInterval(int timerId) { clearTimeout(timerId); } }
package ec.edu.espe.edu.educat.model; import java.io.Serializable; import java.util.Date; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * * @author jeffe */ @Entity @Table(name = "alumno") @NamedQueries({ @NamedQuery(name = "Alumno.findAll", query = "SELECT a FROM Alumno a")}) public class Alumno implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Size(min = 1, max = 10) @Column(name = "COD_ALUMNO", nullable = false, length = 10) private String codAlumno; @Basic(optional = false) @NotNull @Size(min = 1, max = 150) @Column(name = "NOMBRE", nullable = false, length = 150) private String nombre; @Basic(optional = false) @NotNull @Size(min = 1, max = 200) @Column(name = "DIRECCION", nullable = false, length = 200) private String direccion; @Basic(optional = false) @NotNull @Size(min = 1, max = 15) @Column(name = "TELEFONO", nullable = false, length = 15) private String telefono; @Basic(optional = false) @NotNull @Size(min = 1, max = 128) @Column(name = "CORREO_ELECTRONICO", nullable = false, length = 128) private String correoElectronico; @Basic(optional = false) @NotNull @Column(name = "FECHA_NACIMIENTO", nullable = false) @Temporal(TemporalType.DATE) private Date fechaNacimiento; @Basic(optional = false) @NotNull @Size(min = 1, max = 1) @Column(name = "GENERO", nullable = false, length = 1) private String genero; @OneToMany(cascade = CascadeType.ALL, mappedBy = "alumno") private List<CapacitacionAlumno> capacitacionAlumnoList; @OneToMany(cascade = CascadeType.ALL, mappedBy = "alumno") private List<ProgramaAlumno> programaAlumnoList; public Alumno() { } public Alumno(String codAlumno) { this.codAlumno = codAlumno; } public Alumno(String codAlumno, String nombre, String direccion, String telefono, String correoElectronico, Date fechaNacimiento, String genero) { this.codAlumno = codAlumno; this.nombre = nombre; this.direccion = direccion; this.telefono = telefono; this.correoElectronico = correoElectronico; this.fechaNacimiento = fechaNacimiento; this.genero = genero; } public String getCodAlumno() { return codAlumno; } public void setCodAlumno(String codAlumno) { this.codAlumno = codAlumno; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getDireccion() { return direccion; } public void setDireccion(String direccion) { this.direccion = direccion; } public String getTelefono() { return telefono; } public void setTelefono(String telefono) { this.telefono = telefono; } public String getCorreoElectronico() { return correoElectronico; } public void setCorreoElectronico(String correoElectronico) { this.correoElectronico = correoElectronico; } public Date getFechaNacimiento() { return fechaNacimiento; } public void setFechaNacimiento(Date fechaNacimiento) { this.fechaNacimiento = fechaNacimiento; } public String getGenero() { return genero; } public void setGenero(String genero) { this.genero = genero; } public List<CapacitacionAlumno> getCapacitacionAlumnoList() { return capacitacionAlumnoList; } public void setCapacitacionAlumnoList(List<CapacitacionAlumno> capacitacionAlumnoList) { this.capacitacionAlumnoList = capacitacionAlumnoList; } public List<ProgramaAlumno> getProgramaAlumnoList() { return programaAlumnoList; } public void setProgramaAlumnoList(List<ProgramaAlumno> programaAlumnoList) { this.programaAlumnoList = programaAlumnoList; } @Override public int hashCode() { int hash = 0; hash += (codAlumno != null ? codAlumno.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Alumno)) { return false; } Alumno other = (Alumno) object; if ((this.codAlumno == null && other.codAlumno != null) || (this.codAlumno != null && !this.codAlumno.equals(other.codAlumno))) { return false; } return true; } @Override public String toString() { return "ec.edu.espe.edu.educat.model.Alumno[ codAlumno=" + codAlumno + " ]"; } }
package com.example.habitrack; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.util.Base64; import java.io.ByteArrayOutputStream; /** * Handles the acceptance and compression of Images */ public class ImageHandler { //public static class Compressor extends AsyncTask<Bitmap, Void, String> { public static class Compressor extends AsyncTask<HabitEvent, Void, Void> { private final int COMPRESSION_QUALITY = 100; private String encodedImage; ByteArrayOutputStream byteArrayBitmapStream = new ByteArrayOutputStream(); @Override protected Void doInBackground(HabitEvent... habitEvents) { for(HabitEvent he : habitEvents){ Bitmap photo = he.getDecodedPhoto(); he.setDecodedPhoto(null); photo.compress(Bitmap.CompressFormat.PNG, COMPRESSION_QUALITY, byteArrayBitmapStream); byte[] b = byteArrayBitmapStream.toByteArray(); encodedImage = Base64.encodeToString(b, Base64.DEFAULT); he.setEncodedPhoto(encodedImage); } return null; } } /** * Decompresses the image */ public static class Decompressor extends AsyncTask<String, Void, Bitmap>{ private Bitmap decodedByte; @Override protected Bitmap doInBackground(String... strings) { for (String stringPicture : strings) { byte[] decodedString = Base64.decode(stringPicture, Base64.DEFAULT); decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); } return decodedByte; } } }
package com.dmdirc.parser.irc; import com.dmdirc.parser.common.BaseSocketAwareParser; import com.dmdirc.parser.common.ChannelJoinRequest; import com.dmdirc.parser.common.ChildImplementations; import com.dmdirc.parser.common.CompositionState; import com.dmdirc.parser.common.IgnoreList; import com.dmdirc.parser.common.MyInfo; import com.dmdirc.parser.common.ParserError; import com.dmdirc.parser.common.QueuePriority; import com.dmdirc.parser.common.SRVRecord; import com.dmdirc.parser.common.SystemEncoder; import com.dmdirc.parser.events.ConnectErrorEvent; import com.dmdirc.parser.events.DebugInfoEvent; import com.dmdirc.parser.events.ErrorInfoEvent; import com.dmdirc.parser.events.PingFailureEvent; import com.dmdirc.parser.events.PingSentEvent; import com.dmdirc.parser.events.PingSuccessEvent; import com.dmdirc.parser.events.ServerErrorEvent; import com.dmdirc.parser.events.ServerReadyEvent; import com.dmdirc.parser.events.SocketCloseEvent; import com.dmdirc.parser.interfaces.ChannelInfo; import com.dmdirc.parser.interfaces.Encoder; import com.dmdirc.parser.interfaces.EncodingParser; import com.dmdirc.parser.interfaces.SecureParser; import com.dmdirc.parser.irc.IRCReader.ReadLine; import com.dmdirc.parser.irc.events.IRCDataInEvent; import com.dmdirc.parser.irc.events.IRCDataOutEvent; import com.dmdirc.parser.irc.outputqueue.OutputQueue; import com.dmdirc.parser.irc.outputqueue.PriorityOutputQueue; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Timer; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicBoolean; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import dagger.ObjectGraph; import static com.google.common.base.Preconditions.checkNotNull; /** * IRC Parser. */ @ChildImplementations({ IRCChannelClientInfo.class, IRCChannelInfo.class, IRCClientInfo.class }) public class IRCParser extends BaseSocketAwareParser implements SecureParser, EncodingParser { /** Max length an outgoing line should be (NOT including \r\n). */ public static final int MAX_LINELENGTH = 510; /** General Debug Information. */ public static final int DEBUG_INFO = 1; /** Socket Debug Information. */ public static final int DEBUG_SOCKET = 2; /** Processing Manager Debug Information. */ public static final int DEBUG_PROCESSOR = 4; /** List Mode Queue Debug Information. */ public static final int DEBUG_LMQ = 8; /** Attempt to update user host all the time, not just on Who/Add/NickChange. */ public static final boolean ALWAYS_UPDATECLIENT = true; /** Byte used to show that a non-boolean mode is a list (b). */ public static final byte MODE_LIST = 1; /** Byte used to show that a non-boolean mode is not a list, and requires a parameter to set (lk). */ static final byte MODE_SET = 2; /** Byte used to show that a non-boolean mode is not a list, and requires a parameter to unset (k). */ public static final byte MODE_UNSET = 4; /** server-time time format */ private static final DateTimeFormatter serverTimeFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX"); /** * Default channel prefixes if none are specified by the IRCd. * * <p>These are the RFC 2811 specified prefixes: '#', '&amp;', '!' and '+'. */ private static final String DEFAULT_CHAN_PREFIX = " /** * This is what the user wants settings to be. * Nickname here is *not* always accurate.<br><br> * ClientInfo variable tParser.getMyself() should be used for accurate info. */ private MyInfo me = new MyInfo(); /** Should PINGs be sent to the server to check if its alive? */ private boolean checkServerPing = true; /** Timer for server ping. */ private Timer pingTimer; /** Semaphore for access to pingTimer. */ private final Semaphore pingTimerSem = new Semaphore(1); /** Is a ping needed? */ private final AtomicBoolean pingNeeded = new AtomicBoolean(false); /** Time last ping was sent at. */ private long pingTime; /** Current Server Lag. */ private long serverLag; /** Last value sent as a ping argument. */ private String lastPingValue = ""; /** * Count down to next ping. * The timer fires every 10 seconds, this value is decreased every time the * timer fires.<br> * Once it reaches 0, we send a ping, and reset it to 6, this means we ping * the server every minute. * * @see #setPingTimerInterval */ private int pingCountDown; /** Network name. This is "" if no network name is provided */ public String networkName; /** This is what we think the nickname should be. */ public String thinkNickname; /** Have we received the 001. */ public boolean got001; /** Have we fired post005? */ boolean post005; /** Has the thread started execution yet, (Prevents run() being called multiple times). */ boolean hasBegan; /** Manager used to handle prefix modes. */ private final PrefixModeManager prefixModes = new PrefixModeManager(); /** Manager used to handle user modes (owxis etc). */ private final ModeManager userModes = new ModeManager(); /** * Manager used to handle channel boolean modes. * <p> * Channel modes discovered but not listed in 005 are stored as boolean modes automatically (and a ERROR_WARNING Error is called) */ private final ModeManager chanModesBool = new ModeManager(); /** * Hashtable storing known non-boolean chan modes (klbeI etc). * Non Boolean Modes (for Channels) are stored together in this hashtable, the value param * is used to show the type of variable. (List (1), Param just for set (2), Param for Set and Unset (2+4=6))<br><br> * <br> * see MODE_LIST<br> * see MODE_SET<br> * see MODE_UNSET<br> */ public final Map<Character, Byte> chanModesOther = new HashMap<>(); /** The last line of input received from the server */ private ReadLine lastLine; /** Should the lastline (where given) be appended to the "data" part of any onErrorInfo call? */ private boolean addLastLine; /** Channel Prefixes (ie # + etc). */ private String chanPrefix = DEFAULT_CHAN_PREFIX; /** Hashtable storing all known clients based on nickname (in lowercase). */ private final Map<String, IRCClientInfo> clientList = new HashMap<>(); /** Hashtable storing all known channels based on chanel name (inc prefix - in lowercase). */ private final Map<String, IRCChannelInfo> channelList = new HashMap<>(); /** Reference to the ClientInfo object that references ourself. */ private IRCClientInfo myself; /** Hashtable storing all information gathered from 005. */ public final Map<String, String> h005Info = new HashMap<>(); /** difference in ms between our time and the servers time (used for timestampedIRC). */ private long tsdiff; /** Reference to the Processing Manager. */ private final ProcessingManager myProcessingManager; /** Should we automatically disconnect on fatal errors?. */ private boolean disconnectOnFatal = true; /** Current Socket State. */ protected SocketState currentSocketState = SocketState.NULL; /** * The underlying socket connected to the IRC server. For SSL connections this socket will be * wrapped, and should therefore not be used to send or receive data. */ private Socket rawSocket; /** The socket connected to the IRC server, used for sending or receiving data. */ private Socket socket; /** Used for writing to the server. */ private OutputQueue out; /** The encoder to use to encode incoming lines. */ private Encoder encoder = new SystemEncoder(); /** Used for reading from the server. */ private IRCReader in; /** This is the default TrustManager for SSL Sockets, it trusts all ssl certs. */ private final TrustManager[] trustAllCerts = {new TrustingTrustManager()}; /** Should channels automatically request list modes? */ private boolean autoListMode = true; /** Should part/quit/kick callbacks be fired before removing the user internally? */ private boolean removeAfterCallback = true; /** This is the TrustManager used for SSL Sockets. */ private TrustManager[] myTrustManager = trustAllCerts; /** The KeyManagers used for client certificates for SSL sockets. */ private KeyManager[] myKeyManagers; /** This is list containing 001 - 005 inclusive. */ private final List<String> serverInformationLines = new LinkedList<>(); /** Map of capabilities and their state. */ private final Map<String, CapabilityState> capabilities = new HashMap<>(); /** Handler for whois responses. */ private final WhoisResponseHandler whoisHandler; /** Used to synchronize calls to resetState. */ private final Object resetStateSync = new Object(); /** * Default constructor, ServerInfo and MyInfo need to be added separately (using IRC.me and IRC.server). */ public IRCParser() { this((MyInfo) null); } /** * Constructor with ServerInfo, MyInfo needs to be added separately (using IRC.me). * * @param uri The URI to connect to */ public IRCParser(final URI uri) { this(null, uri); } /** * Constructor with MyInfo, ServerInfo needs to be added separately (using IRC.server). * * @param myDetails Client information. */ public IRCParser(final MyInfo myDetails) { this(myDetails, null); } /** * Creates a new IRCParser with the specified client details which will * connect to the specified URI. * * @since 0.6.3 * @param myDetails The client details to use * @param uri The URI to connect to */ public IRCParser(final MyInfo myDetails, final URI uri) { super(uri); setCallbackManager(new IRCParserCallbackManager(this::handleCallbackError)); // TODO: There should be a factory or builder for parsers that can construct the graph final ObjectGraph graph = ObjectGraph.create(new IRCParserModule(this, prefixModes, userModes, chanModesBool)); myProcessingManager = graph.get(ProcessingManager.class); myself = new IRCClientInfo(this, userModes, "myself").setFake(true); out = new PriorityOutputQueue(); if (myDetails != null) { this.me = myDetails; } this.whoisHandler = new WhoisResponseHandler(this, getCallbackManager()); setIgnoreList(new IgnoreList()); setPingTimerInterval(10000); setPingTimerFraction(6); resetState(); } /** * Get the current OutputQueue * * @return the current OutputQueue */ public OutputQueue getOutputQueue() { return out; } /** * Sets the output queue that this parser will use. * * <p>Any existing items in the queue will be removed. * * @param queue The queue to be added. */ public void setOutputQueue(final OutputQueue queue) throws IOException { checkNotNull(queue); out.clearQueue(); if (socket != null) { queue.setOutputStream(socket.getOutputStream()); } out = queue; } @Override public boolean compareURI(final URI uri) { // Get the old URI. final URI oldURI = getURI(); // Check that protocol, host and port are the same. // Anything else won't change the server we connect to just what we // would do after connecting, so is not relevent. return uri.getScheme().equalsIgnoreCase(oldURI.getScheme()) && uri.getHost().equalsIgnoreCase(oldURI.getHost()) && (uri.getUserInfo() == null || uri.getUserInfo().isEmpty() || uri.getUserInfo().equalsIgnoreCase(oldURI.getUserInfo() == null ? "" : oldURI.getUserInfo())) && uri.getPort() == oldURI.getPort(); } /** * From the given URI, get a URI to actually connect to. * This function will check for DNS SRV records for the given URI and use * those if found. * If no SRV records exist, then fallback to using the URI as-is but with * a default port specified if none is given. * * @param uri Requested URI. * @return A connectable version of the given URI. */ private URI getConnectURI(final URI uri) { if (uri == null) { return null; } final boolean isSSL = uri.getScheme().endsWith("s"); final int defaultPort = isSSL ? IrcConstants.DEFAULT_SSL_PORT : IrcConstants.DEFAULT_PORT; // Default to what the URI has already.. int port = uri.getPort(); String host = uri.getHost(); // Look for SRV records if no port is specified. if (port == -1) { List<SRVRecord> recordList = new ArrayList<>(); if (isSSL) { // There are a few possibilities for ssl... final String[] protocols = {"_ircs._tcp.", "_irc._tls."}; for (final String protocol : protocols) { recordList = SRVRecord.getRecords(protocol + host); if (!recordList.isEmpty()) { break; } } } else { recordList = SRVRecord.getRecords("_irc._tcp." + host); } if (!recordList.isEmpty()) { host = recordList.get(0).getHost(); port = recordList.get(0).getPort(); } } // Fix the port if required. if (port == -1) { port = defaultPort; } // Return the URI to connect to based on the above. try { return new URI(uri.getScheme(), uri.getUserInfo(), host, port, uri.getPath(), uri.getQuery(), uri.getFragment()); } catch (URISyntaxException ex) { // Shouldn't happen - but return the URI as-is if it does. return uri; } } @Override public Collection<? extends ChannelJoinRequest> extractChannels(final URI uri) { if (uri == null) { return Collections.<ChannelJoinRequest>emptyList(); } String channelString = uri.getPath(); if (uri.getRawQuery() != null && !uri.getRawQuery().isEmpty()) { channelString += '?' + uri.getRawQuery(); } if (uri.getRawFragment() != null && !uri.getRawFragment().isEmpty()) { channelString += '#' + uri.getRawFragment(); } if (!channelString.isEmpty() && channelString.charAt(0) == '/') { channelString = channelString.substring(1); } return extractChannels(channelString); } /** * Extracts a set of channels and optional keys from the specified String. * Channels are separated by commas, and keys are separated from their * channels by a space. * * @since 0.6.4 * @param channels The string of channels to parse * @return A corresponding collection of join request objects */ protected Collection<? extends ChannelJoinRequest> extractChannels(final String channels) { final Collection<ChannelJoinRequest> res = new ArrayList<>(); for (String channel : channels.split(",")) { final String[] parts = channel.split(" ", 2); if (parts.length == 2) { res.add(new ChannelJoinRequest(parts[0], parts[1])); } else { res.add(new ChannelJoinRequest(parts[0])); } } return res; } /** * Get the current Value of autoListMode. * * @return Value of autoListMode (true if channels automatically ask for list modes on join, else false) */ public boolean getAutoListMode() { return autoListMode; } /** * Set the current Value of autoListMode. * * @param newValue New value to set autoListMode */ public void setAutoListMode(final boolean newValue) { autoListMode = newValue; } /** * Get the current Value of removeAfterCallback. * * @return Value of removeAfterCallback (true if kick/part/quit callbacks are fired before internal removal) */ public boolean getRemoveAfterCallback() { return removeAfterCallback; } /** * Get the current Value of removeAfterCallback. * * @param newValue New value to set removeAfterCallback */ public void setRemoveAfterCallback(final boolean newValue) { removeAfterCallback = newValue; } /** * Get the current Value of addLastLine. * * @return Value of addLastLine (true if lastLine info will be automatically * added to the errorInfo data line). This should be true if lastLine * isn't handled any other way. */ public boolean getAddLastLine() { return addLastLine; } /** * Get the current Value of addLastLine. * * @param newValue New value to set addLastLine */ public void setAddLastLine(final boolean newValue) { addLastLine = newValue; } /** * Get the current socket State. * * @since 0.6.3m1 * @return Current {@link SocketState} */ public SocketState getSocketState() { return currentSocketState; } /** * Get a reference to the Processing Manager. * * @return Reference to the CallbackManager */ public ProcessingManager getProcessingManager() { return myProcessingManager; } /** * Get a reference to the default TrustManager for SSL Sockets. * * @return a reference to trustAllCerts */ public TrustManager[] getDefaultTrustManager() { return Arrays.copyOf(trustAllCerts, trustAllCerts.length); } /** * Get a reference to the current TrustManager for SSL Sockets. * * @return a reference to myTrustManager; */ public TrustManager[] getTrustManager() { return Arrays.copyOf(myTrustManager, myTrustManager.length); } @Override public void setTrustManagers(final TrustManager... managers) { myTrustManager = managers == null ? null : Arrays.copyOf(managers, managers.length); } @Override public void setKeyManagers(final KeyManager... managers) { myKeyManagers = managers == null ? null : Arrays.copyOf(managers, managers.length); } // Start Callbacks /** * Callback to all objects implementing the ServerError Callback. * * @param message The error message */ protected void callServerError(final String message) { getCallbackManager().publish(new ServerErrorEvent(this, LocalDateTime.now(), message)); } /** * Callback to all objects implementing the DataIn Callback. * * @param line Incoming Line. */ protected void callDataIn(final ReadLine line) { getCallbackManager().publish(new IRCDataInEvent(this, LocalDateTime.now(), line)); } /** * Callback to all objects implementing the DataOut Callback. * * @param data Outgoing Data * @param fromParser True if parser sent the data, false if sent using .sendLine */ protected void callDataOut(final String data, final boolean fromParser) { getCallbackManager().publish(new IRCDataOutEvent(this, LocalDateTime.now(), data)); } /** * Callback to all objects implementing the DebugInfo Callback. * * @param level Debugging Level (DEBUG_INFO, DEBUG_SOCKET etc) * @param data Debugging Information as a format string * @param args Formatting String Options */ public void callDebugInfo(final int level, final String data, final Object... args) { callDebugInfo(level, String.format(data, args)); } /** * Callback to all objects implementing the DebugInfo Callback. * * @param level Debugging Level (DEBUG_INFO, DEBUG_SOCKET etc) * @param data Debugging Information */ protected void callDebugInfo(final int level, final String data) { getCallbackManager().publish(new DebugInfoEvent(this, LocalDateTime.now(), level, data)); } /** * Callback to all objects implementing the IErrorInfo Interface. * * @param errorInfo ParserError object representing the error. */ public void callErrorInfo(final ParserError errorInfo) { getCallbackManager().publish(new ErrorInfoEvent(this, LocalDateTime.now(), errorInfo)); } /** * Callback to all objects implementing the IConnectError Interface. * * @param errorInfo ParserError object representing the error. */ protected void callConnectError(final ParserError errorInfo) { getCallbackManager().publish(new ConnectErrorEvent(this, LocalDateTime.now(), errorInfo)); } /** * Callback to all objects implementing the SocketClosed Callback. */ protected void callSocketClosed() { // Don't allow state resetting whilst there may be handlers requiring // state. synchronized (resetStateSync) { getCallbackManager().publish(new SocketCloseEvent(this, LocalDateTime.now())); } } /** * Callback to all objects implementing the PingFailed Callback. */ protected void callPingFailed() { getCallbackManager().publish(new PingFailureEvent(this, LocalDateTime.now())); } /** * Callback to all objects implementing the PingSent Callback. */ protected void callPingSent() { getCallbackManager().publish(new PingSentEvent(this, LocalDateTime.now())); } /** * Callback to all objects implementing the PingSuccess Callback. */ protected void callPingSuccess() { getCallbackManager().publish(new PingSuccessEvent(this, LocalDateTime.now())); } /** * Callback to all objects implementing the Post005 Callback. */ protected synchronized void callPost005() { if (post005) { return; } post005 = true; if (!h005Info.containsKey(IrcConstants.ISUPPORT_CHANNEL_USER_PREFIXES)) { parsePrefixModes(); } if (!h005Info.containsKey(IrcConstants.ISUPPORT_USER_MODES)) { parseUserModes(); } if (!h005Info.containsKey(IrcConstants.ISUPPORT_CHANNEL_MODES)) { parseChanModes(); } whoisHandler.start(); getCallbackManager().publish(new ServerReadyEvent(this, LocalDateTime.now())); } // End Callbacks /** Reset internal state (use before doConnect). */ private void resetState() { synchronized (resetStateSync) { // Reset General State info got001 = false; post005 = false; // Clear the hash tables channelList.clear(); clientList.clear(); h005Info.clear(); prefixModes.clear(); chanModesOther.clear(); chanModesBool.clear(); userModes.clear(); chanPrefix = DEFAULT_CHAN_PREFIX; // Clear output queue. out.clearQueue(); setServerName(""); networkName = ""; lastLine = null; myself = new IRCClientInfo(this, userModes, "myself").setFake(true); synchronized (serverInformationLines) { serverInformationLines.clear(); } stopPingTimer(); currentSocketState = SocketState.CLOSED; setEncoding(IRCEncoding.RFC1459); whoisHandler.stop(); } } /** * Called after other error callbacks. * CallbackOnErrorInfo automatically calls this *AFTER* any registered callbacks * for it are called. * * @param errorInfo ParserError object representing the error. * @param called True/False depending on the the success of other callbacks. */ public void onPostErrorInfo(final ParserError errorInfo, final boolean called) { if (errorInfo.isFatal() && disconnectOnFatal) { disconnect("Fatal Parser Error"); } } /** * Get the current Value of disconnectOnFatal. * * @return Value of disconnectOnFatal (true if the parser automatically disconnects on fatal errors, else false) */ public boolean getDisconnectOnFatal() { return disconnectOnFatal; } /** * Set the current Value of disconnectOnFatal. * * @param newValue New value to set disconnectOnFatal */ public void setDisconnectOnFatal(final boolean newValue) { disconnectOnFatal = newValue; } /** * Connect to IRC. * * @throws IOException if the socket can not be connected * @throws NoSuchAlgorithmException if SSL is not available * @throws KeyManagementException if the trustManager is invalid */ private void doConnect() throws IOException, NoSuchAlgorithmException, KeyManagementException { if (getURI() == null || getURI().getHost() == null) { throw new UnknownHostException("Unspecified host."); } resetState(); callDebugInfo(DEBUG_SOCKET, "Connecting to " + getURI().getHost() + ':' + getURI().getPort()); currentSocketState = SocketState.OPENING; final URI connectUri = getConnectURI(getURI()); rawSocket = getSocketFactory().createSocket(connectUri.getHost(), connectUri.getPort()); if (getURI().getScheme().endsWith("s")) { callDebugInfo(DEBUG_SOCKET, "Server is SSL."); if (myTrustManager == null) { myTrustManager = trustAllCerts; } final SSLContext sc = SSLContext.getInstance("SSL"); sc.init(myKeyManagers, myTrustManager, new SecureRandom()); final SSLSocketFactory socketFactory = sc.getSocketFactory(); socket = socketFactory.createSocket(rawSocket, getURI().getHost(), getURI() .getPort(), false); // Manually start a handshake so we get proper SSL errors here, // and so that we can control the connection timeout final int timeout = socket.getSoTimeout(); socket.setSoTimeout(10000); ((SSLSocket) socket).startHandshake(); socket.setSoTimeout(timeout); currentSocketState = SocketState.OPENING; } else { socket = rawSocket; } callDebugInfo(DEBUG_SOCKET, "\t-> Opening socket output stream PrintWriter"); out.setOutputStream(socket.getOutputStream()); out.setQueueEnabled(true); currentSocketState = SocketState.OPEN; callDebugInfo(DEBUG_SOCKET, "\t-> Opening socket input stream BufferedReader"); in = new IRCReader(socket.getInputStream(), encoder); callDebugInfo(DEBUG_SOCKET, "\t-> Socket Opened"); } /** * Send server connection strings (NICK/USER/PASS). */ protected void sendConnectionStrings() { sendString("CAP LS"); if (getURI().getUserInfo() != null && !getURI().getUserInfo().isEmpty()) { sendString("PASS " + getURI().getUserInfo()); } sendString("NICK " + me.getNickname()); thinkNickname = me.getNickname(); String localhost; try { localhost = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException uhe) { localhost = "*"; } sendString("USER " + me.getUsername() + ' ' + localhost + ' ' + getURI().getHost() + " :" + me.getRealname()); } /** * Handle an onConnect error. * * @param e Exception to handle * @param isUserError Is this a user error? */ private void handleConnectException(final Exception e, final boolean isUserError) { callDebugInfo(DEBUG_SOCKET, "Error Connecting (" + e.getMessage() + "), Aborted"); final ParserError ei = new ParserError( ParserError.ERROR_ERROR + (isUserError ? ParserError.ERROR_USER : 0), "Exception with server socket", getLastLine()); ei.setException(e); callConnectError(ei); if (currentSocketState != SocketState.CLOSED) { currentSocketState = SocketState.CLOSED; callSocketClosed(); } resetState(); } /** * Begin execution. * Connect to server, and start parsing incoming lines */ @Override public void run() { callDebugInfo(DEBUG_INFO, "Begin Thread Execution"); if (hasBegan) { return; } else { hasBegan = true; } try { doConnect(); } catch (IOException e) { handleConnectException(e, true); return; } catch (NoSuchAlgorithmException | KeyManagementException e) { handleConnectException(e, false); return; } callDebugInfo(DEBUG_SOCKET, "Socket Connected"); sendConnectionStrings(); while (true) { try { lastLine = in.readLine(); // Blocking :/ if (lastLine == null) { if (currentSocketState != SocketState.CLOSED) { currentSocketState = SocketState.CLOSED; callSocketClosed(); } resetState(); break; } else if (currentSocketState != SocketState.CLOSING) { processLine(lastLine); } } catch (IOException e) { callDebugInfo(DEBUG_SOCKET, "Exception in main loop (" + e.getMessage() + "), Aborted"); if (currentSocketState != SocketState.CLOSED) { currentSocketState = SocketState.CLOSED; callSocketClosed(); } resetState(); break; } } callDebugInfo(DEBUG_INFO, "End Thread Execution"); } @Override public void shutdown() { try { // See note at disconnect() method for why we close rawSocket. if (rawSocket != null) { rawSocket.close(); socket = null; rawSocket = null; } } catch (IOException e) { callDebugInfo(DEBUG_SOCKET, "Could not close socket"); } super.shutdown(); } /** * Get the trailing parameter for a line. * The parameter is everything after the first occurrence of " :" to the last token in the line after a space. * * @param line Line to get parameter for * @return Parameter of the line */ public static String getParam(final String line) { final String[] params = line.split(" :", 2); return params[params.length - 1]; } /** * Tokenise a line. * splits by " " up to the first " :" everything after this is a single token * * @param line Line to tokenise * @return Array of tokens */ public static String[] tokeniseLine(final String line) { if (line == null || line.isEmpty()) { return new String[]{""}; } int lastarg = line.indexOf(" :"); String[] tokens; // Check for IRC Tags. if (line.charAt(0) == '@') { // We have tags. boolean hasIRCv3Tags = true; tokens = line.split(" ", 2); final int tsEnd = tokens[0].indexOf('@', 1); if (tsEnd > -1) { try { final long ts = Long.parseLong(tokens[0].substring(1, tsEnd)); // We might have both IRCv3 tags and TSIRC, with TSIRC first, eg: // @123@@tag=value :test ing hasIRCv3Tags = tokens[0].length() > tsEnd && tokens[0].charAt(tsEnd) == '@'; } catch (final NumberFormatException nfe) { /* Not a timestamp. */ } } if (hasIRCv3Tags) { // IRCv3 Tags, last arg is actually the second " :" lastarg = line.indexOf(" :", lastarg+1); } } if (lastarg > -1) { final String[] temp = line.substring(0, lastarg).split(" "); tokens = new String[temp.length + 1]; System.arraycopy(temp, 0, tokens, 0, temp.length); tokens[temp.length] = line.substring(lastarg + 2); } else { tokens = line.split(" "); } if (tokens.length < 1) { tokens = new String[]{""}; } return tokens; } @Override public IRCClientInfo getClient(final String details) { final String sWho = getStringConverter().toLowerCase(IRCClientInfo.parseHost(details)); if (clientList.containsKey(sWho)) { return clientList.get(sWho); } else { return new IRCClientInfo(this, userModes, details).setFake(true); } } public boolean isKnownClient(final String host) { final String sWho = getStringConverter().toLowerCase(IRCClientInfo.parseHost(host)); return clientList.containsKey(sWho); } @Override public IRCChannelInfo getChannel(final String channel) { synchronized (channelList) { return channelList.get(getStringConverter().toLowerCase(channel)); } } @Override public void sendInvite(final String channel, final String user) { sendRawMessage("INVITE " + user + ' ' + channel); } @Override public void sendWhois(final String nickname) { sendRawMessage("WHOIS " + nickname); } @Override public void sendRawMessage(final String message) { sendString(message, QueuePriority.NORMAL, false); } @Override public void sendRawMessage(final String message, final QueuePriority priority) { sendString(message, priority, false); } /** * Send a line to the server and add proper line ending. * * @param line Line to send (\r\n termination is added automatically) * @return True if line was sent, else false. */ public boolean sendString(final String line) { return sendString(line, QueuePriority.NORMAL, true); } /** * Send a line to the server and add proper line ending. * If a non-empty argument is given, it is appended as a trailing argument * (i.e., separated by " :"); otherwise, the line is sent as-is. * * @param line Line to send * @param argument Trailing argument for the command, if any * @return True if line was sent, else false. */ protected boolean sendString(final String line, final String argument) { return sendString(argument.isEmpty() ? line : line + " :" + argument); } /** * Send a line to the server and add proper line ending. * * @param line Line to send (\r\n termination is added automatically) * @param priority Priority of this line. * @return True if line was sent, else false. */ public boolean sendString(final String line, final QueuePriority priority) { return sendString(line, priority, true); } /** * Send a line to the server and add proper line ending. * * @param line Line to send (\r\n termination is added automatically) * @param priority Priority of this line. * @param fromParser is this line from the parser? (used for callDataOut) * @return True if line was sent, else false. */ protected boolean sendString(final String line, final QueuePriority priority, final boolean fromParser) { if (getSocketState() != SocketState.OPEN) { return false; } callDataOut(line, fromParser); out.sendLine(line, priority); parseOutgoingLine(line); return true; } /** * Parses a line that has been sent to the server in order to track state. * * @param line The line to be parsed. */ private void parseOutgoingLine(final String line) { final String[] newLine = tokeniseLine(line); if ("away".equalsIgnoreCase(newLine[0]) && newLine.length > 1) { myself.setAwayReason(newLine[newLine.length - 1]); } else if ("mode".equalsIgnoreCase(newLine[0]) && newLine.length == 3) { final IRCChannelInfo channel = getChannel(newLine[1]); if (channel != null) { // This makes sure we don't add the same item to the LMQ twice, // even if its requested twice, as the ircd will only reply once final Queue<Character> foundModes = new LinkedList<>(); final Queue<Character> listModeQueue = channel.getListModeQueue(); for (int i = 0; i < newLine[2].length(); ++i) { final Character mode = newLine[2].charAt(i); callDebugInfo(DEBUG_LMQ, "Intercepted mode request for " + channel + " for mode " + mode); if (chanModesOther.containsKey(mode) && chanModesOther.get(mode) == MODE_LIST) { if (foundModes.contains(mode)) { callDebugInfo(DEBUG_LMQ, "Already added to LMQ"); } else { listModeQueue.offer(mode); foundModes.offer(mode); callDebugInfo(DEBUG_LMQ, "Added to LMQ"); } } } } } } @Override public String getNetworkName() { return networkName; } @Override public String getLastLine() { return lastLine == null ? "" : lastLine.getLine(); } @Override public List<String> getServerInformationLines() { synchronized (serverInformationLines) { return new LinkedList<>(serverInformationLines); } } /** * Process a line and call relevant methods for handling. * * @param line Line read from the IRC server */ @SuppressWarnings("fallthrough") protected void processLine(final ReadLine line) { callDataIn(line); final String[] token = line.getTokens(); LocalDateTime lineTS = LocalDateTime.now(); if (line.getTags().containsKey("tsirc date")) { try { final long ts = Long.parseLong(line.getTags().get("tsirc date")) - tsdiff; lineTS = LocalDateTime.ofInstant(Instant.ofEpochSecond(ts / 1000L, (int) (ts % 1000L)), ZoneId.systemDefault()); } catch (final NumberFormatException nfe) { /* Do nothing. */ } } else if (line.getTags().containsKey("time")) { try { lineTS = OffsetDateTime.parse(line.getTags().get("time"), serverTimeFormat) .atZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime(); } catch (final DateTimeParseException pe) { /* Do nothing. */ } } setPingNeeded(false); if (token.length < 2) { return; } try { final String sParam = token[1]; if ("PING".equalsIgnoreCase(token[0]) || "PING".equalsIgnoreCase(token[1])) { sendString("PONG :" + sParam, QueuePriority.HIGH); } else if ("PONG".equalsIgnoreCase(token[0]) || "PONG".equalsIgnoreCase(token[1])) { if (!lastPingValue.isEmpty() && lastPingValue.equals(token[token.length - 1])) { lastPingValue = ""; serverLag = System.currentTimeMillis() - pingTime; callPingSuccess(); } } else if ("ERROR".equalsIgnoreCase(token[0])) { final StringBuilder errorMessage = new StringBuilder(); for (int i = 1; i < token.length; ++i) { errorMessage.append(token[i]); } callServerError(errorMessage.toString()); } else if ("TSIRC".equalsIgnoreCase(token[1]) && token.length > 3) { if ("1".equals(token[2])) { try { final long ts = Long.parseLong(token[3]); tsdiff = ts - System.currentTimeMillis(); } catch (final NumberFormatException nfe) { /* Do nothing. */ } } } else { int nParam; if (got001) { // Freenode sends a random notice in a stupid place, others might do aswell // These shouldn't cause post005 to be fired, so handle them here. if ("NOTICE".equalsIgnoreCase(token[0]) || token.length > 2 && "NOTICE".equalsIgnoreCase(token[2])) { try { myProcessingManager.process(lineTS, "Notice Auth", token); } catch (ProcessorNotFoundException e) { } return; } if (!post005) { try { nParam = Integer.parseInt(token[1]); } catch (NumberFormatException e) { nParam = -1; } if (nParam < 0 || nParam > 5) { callPost005(); } else { // Store 001 - 005 for informational purposes. synchronized (serverInformationLines) { serverInformationLines.add(line.getLine()); } } } // After 001 we potentially care about everything! try { myProcessingManager.process(lineTS, sParam, token); } catch (ProcessorNotFoundException e) { } } else { // Before 001 we don't care about much. try { nParam = Integer.parseInt(token[1]); } catch (NumberFormatException e) { nParam = -1; } switch (nParam) { case 1: // 001 - Welcome to IRC synchronized (serverInformationLines) { serverInformationLines.add(line.getLine()); } // Fallthrough case IrcConstants.NUMERIC_ERROR_PASSWORD_MISMATCH: case IrcConstants.NUMERIC_ERROR_NICKNAME_IN_USE: try { myProcessingManager.process(lineTS, sParam, token); } catch (ProcessorNotFoundException e) { } break; default: // Unknown - Send to Notice Auth // Some networks send a CTCP during the auth process, handle it if (token.length > 3 && !token[3].isEmpty() && token[3].charAt(0) == (char) 1 && token[3].charAt(token[3].length() - 1) == (char) 1) { try { myProcessingManager.process(lineTS, sParam, token); } catch (ProcessorNotFoundException e) { } break; } // Some networks may send a NICK message if you nick change before 001 // Eat it up so that it isn't treated as a notice auth. if ("NICK".equalsIgnoreCase(token[1])) { break; } // CAP also happens here, so try that. if ("CAP".equalsIgnoreCase(token[1])) { myProcessingManager.process(lineTS, sParam, token); break; } // Otherwise, send to Notice Auth try { myProcessingManager.process(lineTS, "Notice Auth", token); } catch (ProcessorNotFoundException e) { } break; } } } } catch (Exception e) { final ParserError ei = new ParserError(ParserError.ERROR_FATAL, "Fatal Exception in Parser.", getLastLine()); ei.setException(e); callErrorInfo(ei); } } /** The IRCStringConverter for this parser */ private IRCStringConverter stringConverter; @Override public IRCStringConverter getStringConverter() { if (stringConverter == null) { stringConverter = new IRCStringConverter(IRCEncoding.RFC1459); } return stringConverter; } /** * Sets the encoding that this parser's string converter should use. * * @param encoding The encoding to use */ public void setEncoding(final IRCEncoding encoding) { stringConverter = new IRCStringConverter(encoding); } /** * Check the state of the requested capability. * * @param capability The capability to check the state of. * @return State of the requested capability. */ public CapabilityState getCapabilityState(final String capability) { synchronized (capabilities) { if (capabilities.containsKey(capability.toLowerCase())) { return capabilities.get(capability.toLowerCase()); } else { return CapabilityState.INVALID; } } } /** * Set the state of the requested capability. * * @param capability Requested capability * @param state State to set for capability */ public void setCapabilityState(final String capability, final CapabilityState state) { synchronized (capabilities) { if (capabilities.containsKey(capability.toLowerCase())) { capabilities.put(capability.toLowerCase(), state); } } } /** * Add the given capability as a supported capability by the server. * * @param capability Requested capability */ public void addCapability(final String capability) { synchronized (capabilities) { capabilities.put(capability.toLowerCase(), CapabilityState.DISABLED); } } /** * Get the server capabilities and their current state. * * @return Server capabilities and their current state. */ public Map<String, CapabilityState> getCapabilities() { synchronized (capabilities) { return new HashMap<>(capabilities); } } /** * Process CHANMODES from 005. */ public void parseChanModes() { final StringBuilder sDefaultModes = new StringBuilder("b,k,l,"); String modeStr; if (h005Info.containsKey(IrcConstants.ISUPPORT_USER_CHANNEL_MODES)) { if (getServerType() == ServerType.DANCER) { sDefaultModes.insert(0, "dqeI"); } else if (getServerType() == ServerType.AUSTIRC) { sDefaultModes.insert(0, 'e'); } modeStr = h005Info.get(IrcConstants.ISUPPORT_USER_CHANNEL_MODES); for (int i = 0; i < modeStr.length(); ++i) { final char mode = modeStr.charAt(i); if (!prefixModes.isPrefixMode(mode) && sDefaultModes.indexOf(Character.toString(mode)) < 0) { sDefaultModes.append(mode); } } } else { sDefaultModes.append("imnpstrc"); } if (h005Info.containsKey(IrcConstants.ISUPPORT_CHANNEL_MODES)) { modeStr = h005Info.get(IrcConstants.ISUPPORT_CHANNEL_MODES); } else { modeStr = sDefaultModes.toString(); h005Info.put(IrcConstants.ISUPPORT_CHANNEL_MODES, modeStr); } String[] bits = modeStr.split(",", 5); if (bits.length < 4) { modeStr = sDefaultModes.toString(); callErrorInfo(new ParserError(ParserError.ERROR_ERROR, "CHANMODES String not valid. " + "Using default string of \"" + modeStr + '"', getLastLine())); h005Info.put(IrcConstants.ISUPPORT_CHANNEL_MODES, modeStr); bits = modeStr.split(",", 5); } // resetState chanModesOther.clear(); // List modes. for (int i = 0; i < bits[0].length(); ++i) { final Character cMode = bits[0].charAt(i); callDebugInfo(DEBUG_INFO, "Found List Mode: %c", cMode); if (!chanModesOther.containsKey(cMode)) { chanModesOther.put(cMode, MODE_LIST); } } // Param for Set and Unset. final Byte nBoth = MODE_SET + MODE_UNSET; for (int i = 0; i < bits[1].length(); ++i) { final Character cMode = bits[1].charAt(i); callDebugInfo(DEBUG_INFO, "Found Set/Unset Mode: %c", cMode); if (!chanModesOther.containsKey(cMode)) { chanModesOther.put(cMode, nBoth); } } // Param just for Set for (int i = 0; i < bits[2].length(); ++i) { final Character cMode = bits[2].charAt(i); callDebugInfo(DEBUG_INFO, "Found Set Only Mode: %c", cMode); if (!chanModesOther.containsKey(cMode)) { chanModesOther.put(cMode, MODE_SET); } } // Boolean Mode chanModesBool.set(bits[3]); callDebugInfo(DEBUG_INFO, "Found boolean modes: %s", bits[3]); } @Override public String getChannelUserModes() { return prefixModes.getPrefixes(); } @Override public String getBooleanChannelModes() { return chanModesBool.getModes(); } @Override public String getListChannelModes() { return getOtherModeString(MODE_LIST); } @Override public String getParameterChannelModes() { return getOtherModeString(MODE_SET); } @Override public String getDoubleParameterChannelModes() { return getOtherModeString((byte) (MODE_SET + MODE_UNSET)); } @Override public String getChannelPrefixes() { return chanPrefix; } /** * Get modes from hChanModesOther that have a specific value. * Modes are returned in alphabetical order * * @param value Value mode must have to be included * @return All the currently known Set-Unset modes */ protected String getOtherModeString(final byte value) { final char[] modes = new char[chanModesOther.size()]; int i = 0; for (char cTemp : chanModesOther.keySet()) { final Byte nTemp = chanModesOther.get(cTemp); if (nTemp == value) { modes[i] = cTemp; i++; } } // Alphabetically sort the array Arrays.sort(modes); return new String(modes).trim(); } @Override public String getUserModes() { if (h005Info.containsKey(IrcConstants.ISUPPORT_USER_MODES)) { return h005Info.get(IrcConstants.ISUPPORT_USER_MODES); } else { return ""; } } /** * Process USERMODES from 004. */ public void parseUserModes() { final String modeStr; if (h005Info.containsKey(IrcConstants.ISUPPORT_USER_MODES)) { modeStr = h005Info.get(IrcConstants.ISUPPORT_USER_MODES); } else { final String sDefaultModes = "nwdoi"; modeStr = sDefaultModes; h005Info.put(IrcConstants.ISUPPORT_USER_MODES, sDefaultModes); } userModes.set(modeStr); } /** * Resets the channel prefix property to the default, RFC specified value. */ public void resetChanPrefix() { chanPrefix = DEFAULT_CHAN_PREFIX; } /** * Sets the set of possible channel prefixes to those in the given value. * * @param value The new set of channel prefixes. */ public void setChanPrefix(final String value) { chanPrefix = value; } /** * Process PREFIX from 005. */ public void parsePrefixModes() { final String sDefaultModes = "(ohv)@%+"; String modeStr; if (h005Info.containsKey(IrcConstants.ISUPPORT_CHANNEL_USER_PREFIXES)) { modeStr = h005Info.get(IrcConstants.ISUPPORT_CHANNEL_USER_PREFIXES); } else { modeStr = sDefaultModes; } if ("(".equals(modeStr.substring(0, 1))) { modeStr = modeStr.substring(1); } else { modeStr = sDefaultModes.substring(1); h005Info.put(IrcConstants.ISUPPORT_CHANNEL_USER_PREFIXES, sDefaultModes); } int closingIndex = modeStr.indexOf(')'); if (closingIndex * 2 + 1 != modeStr.length()) { callErrorInfo(new ParserError(ParserError.ERROR_ERROR, "PREFIX String not valid. Using default string of \"" + modeStr + '"', getLastLine())); h005Info.put(IrcConstants.ISUPPORT_CHANNEL_USER_PREFIXES, sDefaultModes); modeStr = sDefaultModes.substring(1); closingIndex = modeStr.indexOf(')'); } // The modes passed from the server are in descending order of importance, we want to // store them in ascending, so reverse them: final String reversedModes = new StringBuilder(modeStr).reverse().toString(); prefixModes.setModes(reversedModes.substring(closingIndex + 1), reversedModes.substring(0, closingIndex)); } @Override public void joinChannels(final ChannelJoinRequest... channels) { // We store a map from key->channels to allow intelligent joining of // channels using as few JOIN commands as needed. final Map<String, StringBuffer> joinMap = new HashMap<>(); for (ChannelJoinRequest channel : channels) { // Make sure we have a list to put stuff in. StringBuffer list = joinMap.computeIfAbsent(channel.getPassword(), k -> new StringBuffer()); // Add the channel to the list. If the name is invalid and // autoprefix is off we will just skip this channel. if (!channel.getName().isEmpty()) { if (list.length() > 0) { list.append(','); } if (!isValidChannelName(channel.getName())) { if (chanPrefix.isEmpty()) { // TODO: This is wrong - empty chan prefix means the // IRCd supports no channels. list.append(' } else { list.append(chanPrefix.charAt(0)); } } list.append(channel.getName()); } } for (Map.Entry<String, StringBuffer> entrySet : joinMap.entrySet()) { final String thisKey = entrySet.getKey(); final String channelString = entrySet.getValue().toString(); if (!channelString.isEmpty()) { if (thisKey == null || thisKey.isEmpty()) { sendString("JOIN " + channelString); } else { sendString("JOIN " + channelString + ' ' + thisKey); } } } } /** * Leave a Channel. * * @param channel Name of channel to part * @param reason Reason for leaving (Nothing sent if sReason is "") */ public void partChannel(final String channel, final String reason) { if (getChannel(channel) == null) { return; } sendString("PART " + channel, reason); } /** * Set Nickname. * * @param nickname New nickname wanted. */ public void setNickname(final String nickname) { if (getSocketState() == SocketState.OPEN) { if (!myself.isFake() && myself.getRealNickname().equals(nickname)) { return; } sendString("NICK " + nickname); } else { me.setNickname(nickname); } thinkNickname = nickname; } @Override public int getMaxLength(final String type, final String target) { // If my host is "nick!user@host" and we are sending "#Channel" // a "PRIVMSG" this will find the length of ":nick!user@host PRIVMSG #channel :" // and subtract it from the MAX_LINELENGTH. This should be sufficient in most cases. // Lint = the 2 ":" at the start and end and the 3 separating " "s int length = 0; if (type != null) { length += type.length(); } if (target != null) { length += target.length(); } return getMaxLength(length); } /** * Get the max length a message can be. * * @param length Length of stuff. (Ie "PRIVMSG"+"#Channel") * @return Max Length message should be. */ public int getMaxLength(final int length) { final int lineLint = 5; if (myself.isFake()) { callErrorInfo(new ParserError(ParserError.ERROR_ERROR + ParserError.ERROR_USER, "getMaxLength() called, but I don't know who I am?", getLastLine())); return MAX_LINELENGTH - length - lineLint; } else { return MAX_LINELENGTH - myself.toString().length() - length - lineLint; } } @Override public int getMaxListModes(final char mode) { // MAXLIST=bdeI:50 // MAXLIST=b:60,e:60,I:60 // MAXBANS=30 callDebugInfo(DEBUG_INFO, "Looking for maxlistmodes for: " + mode); // Try in MAXLIST int result = -2; if (h005Info.get(IrcConstants.ISUPPORT_MAXIMUM_LIST_MODES) != null) { if (h005Info.get(IrcConstants.ISUPPORT_MAXIMUM_BANS) == null) { result = 0; } final String maxlist = h005Info.get(IrcConstants.ISUPPORT_MAXIMUM_LIST_MODES); callDebugInfo(DEBUG_INFO, "Found maxlist (" + maxlist + ')'); final String[] bits = maxlist.split(","); for (String bit : bits) { final String[] parts = bit.split(":", 2); callDebugInfo(DEBUG_INFO, "Bit: " + bit + " | parts.length = " + parts.length + " (" + parts[0] + " -> " + parts[0].indexOf(mode) + ')'); if (parts.length == 2 && parts[0].indexOf(mode) > -1) { callDebugInfo(DEBUG_INFO, "parts[0] = '" + parts[0] + "' | parts[1] = '" + parts[1] + '\''); try { result = Integer.parseInt(parts[1]); break; } catch (NumberFormatException nfe) { result = -1; } } } } // If not in max list, try MAXBANS if (result == -2 && h005Info.get(IrcConstants.ISUPPORT_MAXIMUM_BANS) != null) { callDebugInfo(DEBUG_INFO, "Trying max bans"); try { result = Integer.parseInt(h005Info.get(IrcConstants.ISUPPORT_MAXIMUM_BANS)); } catch (NumberFormatException nfe) { result = -1; } } else if (result == -2 && getServerType() == ServerType.WEIRCD) { result = 50; } else if (result == -2 && getServerType() == ServerType.OTHERNET) { result = 30; } else if (result == -2) { result = -1; callDebugInfo(DEBUG_INFO, "Failed"); callErrorInfo(new ParserError(ParserError.ERROR_ERROR + ParserError.ERROR_USER, "Unable to discover max list modes.", getLastLine())); } callDebugInfo(DEBUG_INFO, "Result: " + result); return result; } @Override public void sendMessage(final String target, final String message) { if (target == null || message == null) { return; } if (target.isEmpty()) { return; } sendString("PRIVMSG " + target, message); } @Override public void sendNotice(final String target, final String message) { if (target == null || message == null) { return; } if (target.isEmpty()) { return; } sendString("NOTICE " + target, message); } @Override public void sendAction(final String target, final String message) { sendCTCP(target, "ACTION", message); } @Override public void sendCTCP(final String target, final String type, final String message) { if (target == null || message == null) { return; } if (target.isEmpty() || type.isEmpty()) { return; } final char char1 = (char) 1; sendString("PRIVMSG " + target, char1 + type.toUpperCase() + ' ' + message + char1); } @Override public void sendCTCPReply(final String target, final String type, final String message) { if (target == null || message == null) { return; } if (target.isEmpty() || type.isEmpty()) { return; } final char char1 = (char) 1; sendString("NOTICE " + target, char1 + type.toUpperCase() + ' ' + message + char1); } @Override public void requestGroupList(final String searchTerms) { sendString("LIST", searchTerms); } @Override public void quit(final String reason) { // Don't attempt to send anything further. getOutputQueue().clearQueue(); final String output = (reason == null || reason.isEmpty()) ? "QUIT" : "QUIT :" + reason; sendString(output, QueuePriority.IMMEDIATE, true); // Don't bother queueing anything else. getOutputQueue().setDiscarding(true); } @Override public void disconnect(final String message) { super.disconnect(message); if (currentSocketState == SocketState.OPENING || currentSocketState == SocketState.OPEN) { if (got001) { quit(message); } currentSocketState = SocketState.CLOSING; } try { // SSLSockets try to close nicely and read data from the socket, // which seems to hang indefinitely in some circumstances. We don't // like indefinite hangs, so just close the underlying socket // direct. if (rawSocket != null) { rawSocket.close(); } } catch (IOException e) { /* Do Nothing */ } finally { if (currentSocketState != SocketState.CLOSED) { currentSocketState = SocketState.CLOSED; callSocketClosed(); } resetState(); } } /** {@inheritDoc} * * - Before channel prefixes are known (005/noMOTD/MOTDEnd), this checks * that the first character is either #, &amp;, ! or + * - Assumes that any channel that is already known is valid, even if * 005 disagrees. */ @Override public boolean isValidChannelName(final String name) { // Check sChannelName is not empty or null if (name == null || name.isEmpty()) { return false; } // Check its not ourself (PM recieved before 005) if (getStringConverter().equalsIgnoreCase(getMyNickname(), name)) { return false; } // Check if we are already on this channel if (getChannel(name) != null) { return true; } // Otherwise return true if: // Channel equals "0" // first character of the channel name is a valid channel prefix. return chanPrefix.indexOf(name.charAt(0)) >= 0 || "0".equals(name); } @Override public boolean isUserSettable(final char mode) { final String validmodes = h005Info.containsKey(IrcConstants.ISUPPORT_USER_CHANNEL_MODES) ? h005Info.get(IrcConstants.ISUPPORT_USER_CHANNEL_MODES) : "bklimnpstrc"; return validmodes.indexOf(mode) > -1; } /** * Get the 005 info. * * @return 005Info hashtable. */ public Map<String, String> get005() { return Collections.unmodifiableMap(h005Info); } /** * Get the ServerType for this IRCD. * * @return The ServerType for this IRCD. */ public ServerType getServerType() { return ServerType.findServerType(h005Info.get("004IRCD"), networkName, h005Info.get("003IRCD"), h005Info.get("002IRCD")); } @Override public String getServerSoftware() { final String version = h005Info.get("004IRCD"); return version == null ? "" : version; } @Override public String getServerSoftwareType() { return getServerType().getType(); } /** * Get the value of checkServerPing. * * @return value of checkServerPing. * @see #setCheckServerPing */ public boolean getCheckServerPing() { return checkServerPing; } /** * Set the value of checkServerPing. * * @param newValue New value to use. */ public void setCheckServerPing(final boolean newValue) { checkServerPing = newValue; if (checkServerPing) { startPingTimer(); } else { stopPingTimer(); } } @Override public void setEncoder(final Encoder encoder) { this.encoder = encoder; } @Override public void setPingTimerInterval(final long newValue) { super.setPingTimerInterval(newValue); startPingTimer(); } /** * Start the pingTimer. */ public void startPingTimer() { pingTimerSem.acquireUninterruptibly(); try { setPingNeeded(false); if (pingTimer != null) { pingTimer.cancel(); } pingTimer = new Timer("IRCParser pingTimer"); pingTimer.schedule(new PingTimer(this, pingTimer), 0, getPingTimerInterval()); pingCountDown = 1; } finally { pingTimerSem.release(); } } /** * Stop the pingTimer. */ protected void stopPingTimer() { pingTimerSem.acquireUninterruptibly(); if (pingTimer != null) { pingTimer.cancel(); pingTimer = null; } pingTimerSem.release(); } /** * This is called when the ping Timer has been executed. * As the timer is restarted on every incomming message, this will only be * called when there has been no incomming line for 10 seconds. * * @param timer The timer that called this. */ protected void pingTimerTask(final Timer timer) { // If user no longer wants server ping to be checked, or the socket is // closed then cancel the time and do nothing else. if (!getCheckServerPing() || getSocketState() != SocketState.OPEN) { pingTimerSem.acquireUninterruptibly(); if (pingTimer != null && pingTimer.equals(timer)) { pingTimer.cancel(); } pingTimerSem.release(); return; } if (getPingNeeded()) { callPingFailed(); } else { --pingCountDown; if (pingCountDown < 1) { pingTime = System.currentTimeMillis(); setPingNeeded(true); pingCountDown = getPingTimerFraction(); lastPingValue = String.valueOf(System.currentTimeMillis()); if (sendString("PING " + lastPingValue, QueuePriority.HIGH)) { callPingSent(); } } } } @Override public long getServerLatency() { return serverLag; } /** * Updates the name of the server that this parser is connected to. * * @param serverName The discovered server name */ public void updateServerName(final String serverName) { setServerName(serverName); } /** * Get the current server lag. * * @param actualTime if True the value returned will be the actual time the ping was sent * else it will be the amount of time sinse the last ping was sent. * @return Time last ping was sent */ public long getPingTime(final boolean actualTime) { if (actualTime) { return pingTime; } else { return System.currentTimeMillis() - pingTime; } } @Override public long getPingTime() { return getPingTime(false); } /** * Set if a ping is needed or not. * * @param newStatus new value to set pingNeeded to. */ private void setPingNeeded(final boolean newStatus) { pingNeeded.set(newStatus); } /** * Get if a ping is needed or not. * * @return value of pingNeeded. */ boolean getPingNeeded() { return pingNeeded.get(); } @Override public IRCClientInfo getLocalClient() { return myself; } /** * Get the current nickname. * After 001 this returns the exact same as getLocalClient().getRealNickname(); * Before 001 it returns the nickname that the parser Thinks it has. * * @return Current nickname. */ public String getMyNickname() { if (myself.isFake()) { return thinkNickname; } else { return myself.getRealNickname(); } } /** * Retrieves the local user information that this parser was configured * with. * * @return This parser's local user configuration */ public MyInfo getMyInfo() { return me; } /** * Get the current username (Specified in MyInfo on construction). * Get the username given in MyInfo * * @return My username. */ public String getMyUsername() { return me.getUsername(); } /** * Add a client to the ClientList. * * @param client Client to add */ public void addClient(final IRCClientInfo client) { clientList.put(getStringConverter().toLowerCase(client.getRealNickname()), client); } /** * Remove a client from the ClientList. * This WILL NOT allow cMyself to be removed from the list. * * @param client Client to remove */ public void removeClient(final IRCClientInfo client) { if (client != myself) { forceRemoveClient(client); } } /** * Remove a client from the ClientList. * This WILL allow cMyself to be removed from the list * * @param client Client to remove */ public void forceRemoveClient(final IRCClientInfo client) { clientList.remove(getStringConverter().toLowerCase(client.getRealNickname())); } /** * Get the number of known clients. * * @return Count of known clients */ public int knownClients() { return clientList.size(); } /** * Get the known clients as a collection. * * @return Known clients as a collection */ public Collection<IRCClientInfo> getClients() { return clientList.values(); } /** * Clear the client list. */ public void clearClients() { clientList.clear(); addClient(getLocalClient()); } /** * Add a channel to the ChannelList. * * @param channel Channel to add */ public void addChannel(final IRCChannelInfo channel) { synchronized (channelList) { channelList.put(getStringConverter().toLowerCase(channel.getName()), channel); } } /** * Remove a channel from the ChannelList. * * @param channel Channel to remove */ public void removeChannel(final ChannelInfo channel) { synchronized (channelList) { channelList.remove(getStringConverter().toLowerCase(channel.getName())); } } /** * Get the number of known channel. * * @return Count of known channel */ public int knownChannels() { synchronized (channelList) { return channelList.size(); } } @Override public Collection<IRCChannelInfo> getChannels() { synchronized (channelList) { return channelList.values(); } } /** * Clear the channel list. */ public void clearChannels() { synchronized (channelList) { channelList.clear(); } } @Override public String[] parseHostmask(final String hostmask) { return IRCClientInfo.parseHostFull(hostmask); } @Override public int getMaxTopicLength() { if (h005Info.containsKey(IrcConstants.ISUPPORT_TOPIC_LENGTH)) { try { return Integer.parseInt(h005Info.get(IrcConstants.ISUPPORT_TOPIC_LENGTH)); } catch (NumberFormatException ex) { // Do nothing } } return 0; } @Override public int getMaxLength() { return MAX_LINELENGTH; } @Override public void setCompositionState(final String host, final CompositionState state) { // Do nothing } @Override protected void handleSocketDebug(final String message) { super.handleSocketDebug(message); callDebugInfo(DEBUG_SOCKET, message); } }
/* * $Log: ActionBase.java,v $ * Revision 1.8 2008-05-22 07:29:29 europe\L190409 * added error and warn methods * * Revision 1.7 2007/12/10 10:24:53 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added getAndSetProperty * * Revision 1.6 2007/10/16 09:12:28 Tim van der Leeuw <tim.van.der.leeuw@ibissource.org> * Merge with changes from EJB branch in preparation for creating new EJB brance * * Revision 1.5 2007/10/10 07:29:54 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * execute control via IbisManager * * Revision 1.4 2007/02/12 14:34:16 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * Logger from LogUtil * */ package nl.nn.adapterframework.webcontrol.action; import java.io.IOException; import java.util.Locale; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import nl.nn.adapterframework.configuration.Configuration; import nl.nn.adapterframework.configuration.IbisManager; import nl.nn.adapterframework.util.AppConstants; import nl.nn.adapterframework.util.ClassUtils; import nl.nn.adapterframework.util.LogUtil; import nl.nn.adapterframework.util.XmlUtils; import nl.nn.adapterframework.webcontrol.ConfigurationServlet; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.struts.action.Action; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessages; import org.apache.struts.action.DynaActionForm; import org.apache.struts.util.MessageResources; /** * Implementation of <strong>Action</strong><br/>. * * This action is ment to be extended by individual actions in the project. * * @version Id * @author Johan Verrips * @see org.apache.struts.action.Action */ public abstract class ActionBase extends Action { public static final String version="$RCSfile: ActionBase.java,v $ $Revision: 1.8 $ $Date: 2008-05-22 07:29:29 $"; protected Logger log = LogUtil.getLogger(this); protected Locale locale; protected MessageResources messageResources; protected ActionErrors errors; protected HttpSession session; /** *the <code>Configuration</code> object * @see nl.nn.adapterframework.configuration.Configuration */ protected Configuration config; /** * the <code>IbisManager</code> object through which * adapters can be controlled. */ protected IbisManager ibisManager; protected ActionMessages messages; /** * This proc should start with <code>initAction(request)</code> * @see Action */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Forward control to the specified success URI log.debug("forward to success"); return (mapping.findForward("success")); } public String getCommandIssuedBy(HttpServletRequest request){ String commandIssuedBy= " remoteHost ["+request.getRemoteHost()+"]"; commandIssuedBy+=" remoteAddress ["+request.getRemoteAddr()+"]"; commandIssuedBy+=" remoteUser ["+request.getRemoteUser()+"]"; return commandIssuedBy; } /** * looks under the session for an attribute named forward. Returns it as an ActionForward */ public ActionForward getDefaultActionForward(HttpServletRequest request) { HttpSession session = request.getSession(); ActionForward definedForward = (ActionForward) session.getAttribute("forward"); return definedForward; } public String getAndSetProperty(HttpServletRequest request, DynaActionForm form, String propertyName) { return getAndSetProperty(request, form, propertyName, ""); } public String getAndSetProperty(HttpServletRequest request, DynaActionForm form, String propertyName, String defaultValue) { String result=request.getParameter(propertyName); if (StringUtils.isNotEmpty(result)) { form.set(propertyName,result); log.debug("set property ["+propertyName+"] to ["+result+"] from request"); } else { result=(String)form.get(propertyName); if (StringUtils.isNotEmpty(result)) { log.debug("get property ["+propertyName+"] value ["+result+"] from form"); } else { if (StringUtils.isNotEmpty(defaultValue)) { result=defaultValue; form.set(propertyName,result); log.debug("get property ["+propertyName+"] value ["+result+"] from default"); } else { log.debug("get property ["+propertyName+"] value empty, no default"); } } } return result; } /** * Gets the full request Uri, that is, the reference suitable for ActionForwards.<br/> * Queryparameters of the request are added to it. */ public String getFullRequestUri (HttpServletRequest request) { String ctxtPath = request.getContextPath(); String reqUri = request.getRequestURI(); reqUri = reqUri.substring(ctxtPath.length(), reqUri.length()); String queryString = request.getQueryString(); if (null != queryString) { reqUri += "?" + request.getQueryString(); } return reqUri; } protected DynaActionForm getPersistentForm(ActionMapping mapping, ActionForm form, HttpServletRequest request) { if (form == null) { log.debug( " Creating new FormBean under key " + mapping.getAttribute()); form = new DynaActionForm(); if ("request".equals(mapping.getScope())) { request.setAttribute(mapping.getAttribute(), form); } else { session.setAttribute(mapping.getAttribute(), form); } } return (DynaActionForm) form; } /** * Initializes the fields in the <code>Action</code> for this specific * application. Most important: it retrieves the Configuration object * from the servletContext. * @see nl.nn.adapterframework.configuration.Configuration */ public void initAction(HttpServletRequest request) { locale = getLocale(request); messageResources = getResources(request); errors = new ActionErrors(); session = request.getSession(); String attributeKey=AppConstants.getInstance().getProperty(ConfigurationServlet.KEY_MANAGER); ibisManager = (IbisManager) getServlet().getServletContext().getAttribute(attributeKey); log.debug("retrieved ibisManager ["+ClassUtils.nameOf(ibisManager)+"]["+ibisManager+"] from servlet context attribute ["+attributeKey+"]"); // TODO: explain why this shouldn't happen too early config = ibisManager.getConfiguration(); // NB: Hopefully this doesn't happen too early on in the game log = LogUtil.getLogger(this); // logging category for this class if (null == config) { log.info("initAction(): configuration not present in context. Configuration probably has errors. see log"); } } /** * removes formbean <br/> * removes what is defined under the Attribute of a mapping from either the * request or the session */ public void removeFormBean(ActionMapping mapping, HttpServletRequest request) { HttpSession session = request.getSession(); if (mapping.getAttribute() != null) { if ("request".equals(mapping.getScope())) request.removeAttribute(mapping.getAttribute()); else session.removeAttribute(mapping.getAttribute()); } } /** * Sets under the session an attribute named forward with an ActionForward to the current * request. */ public ActionForward setDefaultActionForward(HttpServletRequest request) { HttpSession session = request.getSession(); // store the request uri with query parameters in an actionforward String reqUri=getFullRequestUri(request); ActionForward forward = new ActionForward(); forward.setPath(reqUri); log.info("default forward set to :" + reqUri); session.setAttribute("forward", forward); return forward; } protected void warn(String message) { warn(message,null); } protected void warn(Throwable t) { warn(null,t); } protected void warn(String message, Throwable t) { if (t!=null) { if (StringUtils.isEmpty(message)) { message=ClassUtils.nameOf(t)+" "+t.getMessage(); } else { message+=": "+ClassUtils.nameOf(t)+" "+t.getMessage(); } } log.warn(message); errors.add("", new ActionError("errors.generic", XmlUtils.encodeChars(message))); } protected void error(String message, Throwable t) { error("","errors.generic",message,t); } protected void error(String category, String message, Throwable t) { error("",category,message,t); } protected void error(String key, String category, String message, Throwable t) { log.error(message,t); if (t!=null) { if (StringUtils.isEmpty(message)) { message=ClassUtils.nameOf(t)+" "+t.getMessage(); } else { message+=": "+ClassUtils.nameOf(t)+" "+t.getMessage(); } } errors.add(key, new ActionError(category, XmlUtils.encodeChars(message))); } }
package yami.servlets; import java.io.IOException; import java.io.PrintWriter; import java.net.InetAddress; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import yami.YamiVersion; import yami.configuration.ConfigurationManager; import yami.configuration.GlobalConfiguration; import yami.model.Constants; import yami.model.DataStore; import yami.model.DataStoreRetriever; public class AggregateNodesServlet extends HttpServlet { private static final Logger log = Logger.getLogger(AggregateNodesServlet.class); private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { log.debug("aggregate request"); ConfigurationManager cm = ConfigurationManager.getInstance(); GlobalConfiguration gc = cm.getCurrentGlobalConfiguration(); String hostname = gc.server_dns_name != null ? gc.server_dns_name : InetAddress.getLocalHost().getCanonicalHostName(); DataStore ds = getDataStore(); PrintWriter writer = res.getWriter(); writer.println("<!DOCTYPE html PUBLIC \"- writer.println("<html xmlns=\"http: writer.println("<head>"); writer.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />"); // writer.println("<meta http-equiv=\"refresh\" content=\"5\" />"); writer.println("<title>yami aggregate - " + cm.getConfiguredProject().name + "</title>"); writer.println("<link rel=\"stylesheet\" href=\"../style.css\" type=\"text/css\" />"); writer.println("<script src=\"../dashboard.js\" type=\"text/javascript\" ></script>"); writer.println(""); writer.println("</head>"); writer.println("<body>"); writer.println("<div id=\"container\">"); writer.println(" <div id=\"header\">"); writer.println(" <h1><a href=\"/\">yami</a></h1>"); writer.println(" <h2>" + YamiVersion.get() + "</h2>"); writer.println(" <div class=\"clear\"></div>"); writer.println(" </div>"); writer.println(" <div id=\"nav\">"); writer.println(" <ul>"); writer.println(" <li class=\"start\"><a href=\"http://" + hostname + ":" + gc.getServerPort() + Constants.DASHBOARD_CONTEXT + "\">Dashboard</a></li>"); writer.println(" <li class=\"last\"><a href=\"http://" + hostname + ":" + gc.getServerPort() + Constants.AGGREGATE_NODE_CONTEXT + "\">Aggregate</a></li>"); writer.println(" <li class=\"last\"><a href=\"http://" + hostname + ":" + gc.getServerPort() + Constants.PEERS_DASHBOARD_CONTEXT + "\">Peers</a></li>"); writer.println(" </ul>"); writer.println(" </div>"); writer.println(" <div id=\"body\">"); writer.println(" <div id=\"content\">"); NodeAggregator aggregator = new NodeAggregator(); for (VersionItem item : aggregator.aggregate().values()) { // start building monitored instance line: String line = " <alert><div class=\"alertbar\"><ul>"; String version = item.version(); String className = "g"; String versionClass = "version" + className ; if (null != version) { line += "<li><a class=\"" + versionClass + "\" href=\"none\">"+version+"</a></li>"; line += "<li><a class=\"" + versionClass + "\" href=\"none\">"+item.count()+"</a></li>"; } if (gc.isSwitchVersionEnabled()) { String link = "none";//node.peer.getPeerSwitchVersionLink(node.name, ""); line += "<li>" + "<input class=\"version\" type=\"text\" id=\""+version+"_input\" >"+item.count()+"</input>" + "</li>" + "<li>" + "<button class=\"command\" onClick=\"viewDashboard('"+version+"')\">View</button>" + "</li>"; } line += "</ul><br style=\"clear:left\"/></div></alert>"; writer.println(line); } writer.println(" </div> "); writer.println(" <div class=\"clear\"></div>"); writer.println(" </div>"); writer.println(" <div id='footer'>"); writer.println(" <div class='footer-content'>"); writer.println(" </div>"); writer.println(" </div>"); writer.println(" </div>"); writer.println("</div>"); writer.println("</body>"); writer.println("</html>"); writer.close(); } // private String getVersion(DataStore ds, Node node) // CollectorOnNodeState result = ds.getResult(node, new VersionCollector()); // if (null == result) // return null; // return result.getLast().output; // private String getLink(HttpCollector collector, Node node) // return Constants.CLIENT_LINK.replace(Constants.PEER_NAME, node.peer.dnsName()). // replace(Constants.NODE_NAME, node.name). // replace(Constants.COLLECTOR_NAME, collector.name). // replace(Constants.CLIENT_PORT, ConfigurationManager.getInstance().getCurrentGlobalConfiguration().getClientPort() + ""); private DataStore getDataStore() { return DataStoreRetriever.getD(); } }
package org.cytoscape.data.reader.kgml; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.JCheckBoxMenuItem; import javax.swing.JMenu; import javax.swing.JMenuItem; import org.cytoscape.data.reader.kgml.util.PathwayDragAndDropManager; import org.cytoscape.kegg.browser.KEGGNetworkListener; import cytoscape.Cytoscape; import cytoscape.data.ImportHandler; import cytoscape.plugin.CytoscapePlugin; import cytoscape.view.CytoscapeDesktop; /** * KGML Reader Main class * * @author kono * */ public class KGMLReaderPlugin extends CytoscapePlugin { // For now, Metabolic pathways only. private static final String KEGG_PATHWAY_WEB = "http://www.genome.jp/kegg-bin/get_htext?htext=br08901.keg&filedir=/files&extend=A1&open=A2 static Boolean importAnnotation = true; public KGMLReaderPlugin() { final ImportHandler importHandler = new ImportHandler(); importHandler.addFilter(new KGMLFilter()); // Add context menu listeners. Cytoscape.getSwingPropertyChangeSupport().addPropertyChangeListener( CytoscapeDesktop.NETWORK_VIEW_CREATED, new KEGGNetworkListener()); // Setup drop target PathwayDragAndDropManager.getManager().activateTarget(); // Add menu to poen KEGG Pathway Web Site addMenu(); } private void addMenu() { final JMenu menu = new JMenu("KGML Reader"); final JMenu optionMenu = new JMenu("Options"); Cytoscape.getDesktop().getCyMenus().getMenuBar().getMenu("Plugins") .add(menu); menu.add(new JMenuItem(new AbstractAction("Open KEGG Browser") { public void actionPerformed(ActionEvent e) { cytoscape.util.OpenBrowser.openURL(KEGG_PATHWAY_WEB); } })); // Sub menu for options final JCheckBoxMenuItem isAutomaticImportEnabled = new JCheckBoxMenuItem(); isAutomaticImportEnabled.setSelected(true); isAutomaticImportEnabled.setAction(new AbstractAction("Automatic Annotation Import from TogoWS") { public void actionPerformed(ActionEvent e) { importAnnotation = isAutomaticImportEnabled.isSelected(); System.out.println("## Auto annotation import is " + importAnnotation); } }); optionMenu.add(isAutomaticImportEnabled); menu.add(optionMenu); } }
package mapeditor; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; public class CollisionPanel extends JPanel { JButton[] buttons = new JButton[8]; boolean[] selected = new boolean[8]; byte result = 0; static JLabel preview = new JLabel(); public CollisionPanel() { addButtons(); add(preview); updatePreview(); setPreferredSize(new Dimension(80, 608)); } private void addButtons() { for (int i = 0; i < 8; i++) { addButton(i + 1); } } int squareSize = 20; int glowRadius = 5; private void addButton(int i) { int width = squareSize+2*glowRadius; int rsq = glowRadius*glowRadius; BufferedImage img = new BufferedImage(width, width, BufferedImage.TYPE_INT_ARGB); Graphics2D g = (Graphics2D) img.getGraphics(); g.setColor(Color.LIGHT_GRAY); g.fillRect(0, 0, width, width); for (int x = 0; x < (width); x++) { for (int y = 0; y < (width); y++) { double cx = x - glowRadius; double cy = y - glowRadius; if (i == 1) {// BIT 1 = BASE SQUARE COLLISION cx = Math.max(0, Math.min(squareSize-1, cx)); cy = Math.max(0, Math.min(squareSize-1, cy)); } if (i == 2) {// BIT 2 = TOP LEFT NO COLLISION if (cx + cy < squareSize) { cy = cy - squareSize; double scalar = (cx / Math.sqrt(2) - cy / Math.sqrt(2)); cx = scalar / Math.sqrt(2); // c = length * normaliserad vektor (1,-1) cy = -scalar / Math.sqrt(2); cy = cy + squareSize; } } if (i == 3) {// BIT 3 = TOP RIGHT NO COLLISION if ((squareSize - cx) + cy < squareSize) { double scalar = (cx / Math.sqrt(2) + cy / Math.sqrt(2)); cx = scalar / Math.sqrt(2); // c = length * normaliserad vektor (1,1) cy = scalar / Math.sqrt(2); } } if (i == 4) {// BIT 4 = BOTTOM LEFT NO COLLISION if (cx + (squareSize - cy) < squareSize) { double scalar = (cx / Math.sqrt(2) + cy / Math.sqrt(2)); cx = scalar / Math.sqrt(2); // c = length * normaliserad vektor (1,1) cy = scalar / Math.sqrt(2); } } if (i == 5) {// BIT 5 = BOTTOM RIGHT NO COLLISION if ((squareSize - cx) + (squareSize - cy) < squareSize) { cy = cy - squareSize; double scalar = (cx / Math.sqrt(2) - cy / Math.sqrt(2)); cx = scalar / Math.sqrt(2); // c = length * normaliserad vektor (1,-1) cy = -scalar / Math.sqrt(2); cy = cy + squareSize; } } if (i == 6) {// BIT 6 = LEFT EDGE NO COLLISION cx = Math.max(0, Math.min(width, cx)); if (cx < 1) { Point.Double collisionVector = new Point.Double(x - cx - glowRadius, y - cy - glowRadius); double sqDist = collisionVector.x * collisionVector.x + collisionVector.y * collisionVector.y; if (sqDist < rsq) { if (sqDist == 0) { g.setColor(new Color(255, 255, 255, 64)); } else { //int k = (int) (255*(Math.sqrt(sqDist)/(16))); int k = (int) (255 * (sqDist / (rsq))); g.setColor(new Color(255, 255-k, 255-k, 255 - k)); } g.fillRect(x, y, 1, 1); } cx = 100000; } } if (i == 7) {// BIT 7 = RIGHT EDGE NO COLLISION cx = Math.max(-glowRadius, Math.min(squareSize-1, cx)); if (cx > squareSize-2) { Point.Double collisionVector = new Point.Double(x - cx - glowRadius, y - cy - glowRadius); double sqDist = collisionVector.x * collisionVector.x + collisionVector.y * collisionVector.y; if (sqDist < rsq) { if (sqDist == 0) { g.setColor(new Color(255, 255, 255, 64)); } else { //int k = (int) (255*(Math.sqrt(sqDist)/(16))); int k = (int) (255 * (sqDist / (rsq))); g.setColor(new Color(255, 255-k, 255-k, 255 - k)); } g.fillRect(x, y, 1, 1); } cx = 100000; } } if (i == 8) {// BIT 8 = TOP EDGE NO COLLISION cy = Math.max(0, Math.min(width, cy)); if (cy < 1) { Point.Double collisionVector = new Point.Double(x - cx - glowRadius, y - cy - glowRadius); double sqDist = collisionVector.x * collisionVector.x + collisionVector.y * collisionVector.y; if (sqDist < rsq) { if (sqDist == 0) { g.setColor(new Color(255, 255, 255, 64)); } else { //int k = (int) (255*(Math.sqrt(sqDist)/(16))); int k = (int) (255 * (sqDist / (rsq))); g.setColor(new Color(255, 255-k, 255-k, 255 - k)); } g.fillRect(x, y, 1, 1); } cy = 100000; } } Point.Double collisionVector = new Point.Double(x - cx - glowRadius, y - cy - glowRadius); double sqDist = collisionVector.x * collisionVector.x + collisionVector.y * collisionVector.y; if (sqDist < rsq) { if (sqDist == 0) { g.setColor(new Color(255, 255, 255, 64)); } else { //int k = (int) (255*(Math.sqrt(sqDist)/(16))); int k = (int) (255 * (sqDist / (rsq))); g.setColor(new Color(255-k, 255, 255, 255 - k)); } g.fillRect(x, y, 1, 1); } } } JButton button = new JButton(new ImageIcon(img)); button.setFocusPainted(false); final int ID = i; button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // if ((result & (1 << (ID-1))) == (1 << (ID-1))) { // result -= Math.pow(2, ID-1); // } else { // result += Math.pow(2, ID-1); pressed(ID); } }); button.setPreferredSize(new Dimension(30, 30)); buttons[i - 1] = button; button.setPreferredSize(new Dimension(width, width)); add(button); } private void pressed(int ID) { selected[ID] = !selected[ID]; } public static void updatePreview() { BufferedImage img = new BufferedImage(32, 32, BufferedImage.TYPE_INT_ARGB); Graphics g = img.getGraphics(); g.setColor(Color.MAGENTA); g.fillRect(0, 0, 32, 32); preview.setIcon(new ImageIcon(img)); } }
package com.cloud.agent.manager; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; import java.nio.channels.SocketChannel; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import javax.net.ssl.SSLEngine; import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; import com.cloud.agent.Listener; import com.cloud.agent.api.Command; import com.cloud.agent.transport.Request; import com.cloud.exception.AgentUnavailableException; import com.cloud.host.Status; import com.cloud.utils.nio.Link; public class ClusteredAgentAttache extends ConnectedAgentAttache implements Routable { private final static Logger s_logger = Logger.getLogger(ClusteredAgentAttache.class); private static ClusteredAgentManagerImpl s_clusteredAgentMgr; protected ByteBuffer _buffer = ByteBuffer.allocate(2048); private boolean _forward = false; protected final LinkedList<Request> _transferRequests; protected boolean _transferMode = false; static public void initialize(ClusteredAgentManagerImpl agentMgr) { s_clusteredAgentMgr = agentMgr; } public ClusteredAgentAttache(AgentManager agentMgr, long id) { super(agentMgr, id, null, false); _forward = true; _transferRequests = new LinkedList<Request>(); } public ClusteredAgentAttache(AgentManager agentMgr, long id, Link link, boolean maintenance) { super(agentMgr, id, link, maintenance); _forward = link == null; _transferRequests = new LinkedList<Request>(); } @Override public boolean isClosed() { return _forward ? false : super.isClosed(); } @Override public boolean forForward() { return _forward; } protected void checkAvailability(final Command[] cmds) throws AgentUnavailableException { if (_transferMode) { // need to throw some other exception while agent is in rebalancing mode for (final Command cmd : cmds) { if (!cmd.allowCaching()) { throw new AgentUnavailableException("Unable to send " + cmd.getClass().toString() + " because agent is in Rebalancing mode", _id); } } } else { super.checkAvailability(cmds); } } @Override public void cancel(long seq) { if (forForward()) { Listener listener = getListener(seq); if (listener != null && listener instanceof SynchronousListener) { SynchronousListener synchronous = (SynchronousListener)listener; String peerName = synchronous.getPeer(); if (peerName != null) { s_logger.debug(log(seq, "Forwarding to peer to cancel due to timeout")); s_clusteredAgentMgr.cancel(peerName, _id, seq, "Timed Out"); } } } super.cancel(seq); } @Override public void routeToAgent(byte[] data) throws AgentUnavailableException { if (s_logger.isDebugEnabled()) { s_logger.debug(log(Request.getSequence(data), "Routing from " + Request.getManagementServerId(data))); } if (_link == null) { if (s_logger.isDebugEnabled()) { s_logger.debug(log(Request.getSequence(data), "Link is closed")); } throw new AgentUnavailableException("Link is closed", _id); } try { _link.send(data); } catch (ClosedChannelException e) { if (s_logger.isDebugEnabled()) { s_logger.debug(log(Request.getSequence(data), "Channel is closed")); } throw new AgentUnavailableException("Channel to agent is closed", _id); } catch (NullPointerException e) { if (s_logger.isDebugEnabled()) { s_logger.debug(log(Request.getSequence(data), "Link is closed")); } // Note: since this block is not in synchronized. It is possible for _link to become null. throw new AgentUnavailableException("Channel to agent is null", _id); } } @Override public void send(Request req, Listener listener) throws AgentUnavailableException { if (_link != null) { super.send(req, listener); return; } long seq = req.getSequence(); if (listener != null) { registerListener(req.getSequence(), listener); } if (_transferMode) { if (s_logger.isDebugEnabled()) { s_logger.debug(log(seq, "Holding request as the corresponding agent is in transfer mode: ")); } synchronized (this) { addRequestToTransfer(req); return; } } int i = 0; SocketChannel ch = null; boolean error = true; try { while (i++ < 5) { String peerName = s_clusteredAgentMgr.findPeer(_id); if (peerName == null) { throw new AgentUnavailableException("Unable to find peer", _id); } ch = s_clusteredAgentMgr.connectToPeer(peerName, ch); if (ch == null) { if (s_logger.isDebugEnabled()) { s_logger.debug(log(seq, "Unable to forward " + req.toString())); } continue; } SSLEngine sslEngine = s_clusteredAgentMgr.getSSLEngine(peerName); if (sslEngine == null) { throw new AgentUnavailableException("Unable to get SSLEngine of peer " + peerName, _id); } try { if (s_logger.isDebugEnabled()) { s_logger.debug(log(seq, "Forwarding " + req.toString() + " to " + peerName)); } if (req.executeInSequence() && listener != null && listener instanceof SynchronousListener) { SynchronousListener synchronous = (SynchronousListener)listener; synchronous.setPeer(peerName); } Link.write(ch, req.toBytes(), sslEngine); error = false; return; } catch (IOException e) { if (s_logger.isDebugEnabled()) { s_logger.debug(log(seq, "Error on connecting to management node: " + req.toString() + " try = " + i)); } if(s_logger.isInfoEnabled()) { s_logger.info("IOException " + e.getMessage() + " when sending data to peer " + peerName + ", close peer connection and let it re-open"); } } } } finally { if (error) { unregisterListener(seq); } } throw new AgentUnavailableException("Unable to reach the peer that the agent is connected", _id); } public synchronized void setTransferMode(final boolean transfer) { _transferMode = transfer; } public boolean getTransferMode() { return _transferMode; } public Request getRequestToTransfer() { if (_transferRequests.isEmpty()) { return null; } else { return _transferRequests.pop(); } } protected synchronized void addRequestToTransfer(Request req) { int index = findTransferRequest(req); assert (index < 0) : "How can we get index again? " + index + ":" + req.toString(); _transferRequests.add(-index - 1, req); } @Override //need separate method in order to cancel transfer requests protected synchronized int findRequest(long seq) { int result = Collections.binarySearch(_transferRequests, seq, s_seqComparator); if (result < 0) { return Collections.binarySearch(_requests, seq, s_seqComparator); } return result; } protected synchronized int findTransferRequest(Request req) { return Collections.binarySearch(_transferRequests, req, s_reqComparator); } @Override public void disconnect(final Status state) { super.disconnect(state); _transferRequests.clear(); } public void cleanup(final Status state) { super.cleanup(state); _transferRequests.clear(); } }
package ctci; /*Implementation of Singly Linked List Data Structure*/ public class _2linkedList { private Node presentNode; private Node headNode; private int noOfElements=0; public _2linkedList() { } public int get(int position){ return 0; } public boolean add(int value,int position){ //check for posn number using noOFelements if(position>noOfElements) return false; if(position==0){ add(value); return true; } //go from header till that position Node pointerNode=new Node(); pointerNode=headNode; int elementCount=0; while(position!=elementCount){ //conditions,its at last pointerNode=pointerNode.next; elementCount++; //not at last } Node newNode=new Node(); newNode.data=value; newNode.next=pointerNode.next; pointerNode.next=newNode; noOfElements++; return true; } public int size(){ return noOfElements; } public void add(int value){ if(presentNode==null){ headNode=new Node(); headNode.next=null; headNode.data=value; presentNode=headNode; } else{ Node newNode=new Node(); presentNode.next=newNode; newNode.next=null; newNode.data=value; presentNode=newNode; } noOfElements++; } public boolean delete(){ if(headNode==null) return false; headNode=headNode.next; return true; } public boolean delete(int position){ if(position>noOfElements) return false; if(position==0){ delete(); return true; } //go from header till that position Node pointerNode=new Node(); pointerNode=headNode; int elementCount=0; while(position!=elementCount){ //conditions,its at last pointerNode=pointerNode.next; elementCount++; //not at last } pointerNode.next=pointerNode.next.next; pointerNode.data=pointerNode.next.data; return true; } } class Node{ int data; Node next; public int getData() { return data; } public void setData(int data) { this.data = data; } }
package io.spine.server.event.enrich; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSet; import com.google.protobuf.Message; import io.spine.type.TypeName; import java.util.Optional; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static io.spine.server.event.enrich.EnrichmentFunction.activeOnly; import static io.spine.server.event.enrich.SupportsFieldConversion.supportsConversion; /** * Enrichment multimap provides an enrichment function for a Java class. */ final class Schema { /** Available enrichment functions per Java class. */ private final ImmutableMultimap<Class<?>, EnrichmentFunction<?, ?, ?>> multimap; static Schema create(Enricher enricher, EnricherBuilder builder) { Builder schemaBuilder = new Builder(enricher, builder); return schemaBuilder.build(); } private Schema(ImmutableMultimap<Class<?>, EnrichmentFunction<?, ?, ?>> multimap) { this.multimap = checkNotNull(multimap); } void activate() { multimap.values() .forEach(EnrichmentFunction::activate); } Optional<EnrichmentFunction<?, ?, ?>> transition(Class<?> fieldClass, Class<?> enrichmentFieldClass) { Optional<EnrichmentFunction<?, ?, ?>> result = multimap.values() .stream() .filter(supportsConversion(fieldClass, enrichmentFieldClass)) .findFirst(); return result; } /** * Obtains active-only functions for enriching the passed message class. */ ImmutableSet<EnrichmentFunction<?, ?, ?>> get(Class<? extends Message> messageClass) { ImmutableCollection<EnrichmentFunction<?, ?, ?>> unfiltered = multimap.get(messageClass); ImmutableSet<EnrichmentFunction<?, ?, ?>> result = unfiltered.stream() .filter(activeOnly()) .collect(toImmutableSet()); return result; } boolean supports(Class<?> sourceClass) { boolean result = multimap.containsKey(sourceClass); return result; } /** * Creates new {@code Schema} * * <p>{@link MessageEnrichment} requires reference to a parent {@link Enricher}. * This class uses the reference to the {@code Enricher} being constructed for this. */ private static final class Builder { private final Enricher enricher; private final EnricherBuilder builder; private final ImmutableMultimap.Builder<Class<?>, EnrichmentFunction<?, ?, ?>> multimap; private Builder(Enricher enricher, EnricherBuilder builder) { this.enricher = enricher; this.builder = builder; this.multimap = ImmutableMultimap.builder(); } private Schema build() { addFieldEnrichments(); loadMessageEnrichments(); Schema result = new Schema(multimap.build()); return result; } private void addFieldEnrichments() { for (EnrichmentFunction<?, ?, ?> fn : builder.functions()) { multimap.put(fn.sourceClass(), fn); } } private void loadMessageEnrichments() { EnrichmentMap map = EnrichmentMap.load(); for (TypeName enrichment : map.enrichmentTypes()) { map.sourceClasses(enrichment) .forEach(sourceClass -> addMessageEnrichment(sourceClass, enrichment)); } } private void addMessageEnrichment(Class<Message> sourceClass, TypeName enrichment) { Class<Message> enrichmentClass = enrichment.getMessageClass(); MessageEnrichment fn = MessageEnrichment.create(enricher, sourceClass, enrichmentClass); multimap.put(sourceClass, fn); } } }
package dae.util; import com.jme3.math.FastMath; import com.jme3.math.Matrix4f; import com.jme3.math.Quaternion; import com.jme3.math.Vector2f; import com.jme3.math.Vector3f; import com.jme3.scene.Node; import dae.components.TransformComponent; import dae.prefabs.AxisEnum; /** * This class offers a couple of useful functions , mostly related to difficult * rotation transformations. * * @author Koen Samyn */ public class MathUtil { /** * Creates a new reference frame starting from a single normal. * * @param normal the normal to create a new rotation from. * @param mainAxis the axis of the object to align the normal with. * @return a new Quaternion. */ public static Quaternion createRotationFromNormal(Vector3f normal, AxisEnum mainAxis) { Vector3f x; Vector3f y; Quaternion result = new Quaternion(); if (normal.x > normal.y && normal.x > normal.z) { x = normal.cross(Vector3f.UNIT_Y); x.normalizeLocal(); y = normal.cross(x); y.normalizeLocal(); } else if (normal.y > normal.x && normal.y > normal.z) { x = normal.cross(Vector3f.UNIT_Z); x.normalizeLocal(); y = normal.cross(x); y.normalizeLocal(); } else { x = normal.cross(Vector3f.UNIT_X); x.normalizeLocal(); y = normal.cross(x); y.normalizeLocal(); } switch (mainAxis) { case X: result.fromAxes(normal, x, y); break; case Y: result.fromAxes(y, normal, x); break; case Z: result.fromAxes(x, y, normal); break; } return result; } /** * Creates a two degree freedom rotation from the provided normal. * * @param from the start point of the rotation. * @param to the point to rotate the from point to over the two axis. * @param axis1 the first degree of freedom. * @param axis2 the second degree of freedom. * @param q the quaternion to store the result in. If null, a new quaternion * will be created. * @return The quaternion with the DOF2 rotation. */ public static Quaternion createDof2Rotation(Vector3f from, Vector3f to, Vector3f axis1, Vector3f axis2, Quaternion q, Vector2f angleOut) { if (q == null) { q = new Quaternion(); } float phi = calculateDof1Rotation(from, to, axis1); q.fromAngleAxis(phi, axis1); Vector3f p2 = q.mult(from); Vector3f axis2r = q.mult(axis2); float theta = calculateDof1Rotation(p2, to, axis2r); System.out.println("phi : " + FastMath.RAD_TO_DEG * phi); System.out.println("theta : " + FastMath.RAD_TO_DEG * theta); angleOut.x = phi; angleOut.y = theta; q.fromAngles(0, phi, theta); return q; } /** * Calculates the angle of rotation to rotate the from point to the to * point. * * @param from the point to rotate. * @param to the point to rotate to. * @param axis the axis over which to rotate. * @return the angle of the rotation. */ public static float calculateDof1Rotation(Vector3f from, Vector3f to, Vector3f axis) { float dot1 = axis.dot(from); Vector3f pFrom = from.subtract(axis.mult(dot1)); pFrom.normalizeLocal(); float dot2 = axis.dot(to); Vector3f pTo = to.subtract(axis.mult(dot2)); pTo.normalizeLocal(); float angle = FastMath.acos(pFrom.dot(pTo)); Vector3f dir = pFrom.cross(pTo); angle = dir.dot(axis) > 0 ? angle : -angle; return angle; } /** * Projects a vector onto the plane going through point [0,0,0] and with a * normal defined by the normal parameter. * * @param toProject the point to project. * @param normal the normal of the plane. */ public static void project(Vector3f toProject, Vector3f normal) { float dot = normal.dot(toProject); toProject.x = toProject.x - dot * normal.x; toProject.y = toProject.y - dot * normal.y; toProject.z = toProject.z - dot * normal.z; } /** * Changes the parent of a prefab while keeping the world transformation of * the prefab. * @param toChange the prefab to change. * @param newParent the new parent of the prefab. * @return the local transformation of the child, relative to the new parent. */ public static Matrix4f changeParent(Node toChange, Node newParent) { Matrix4f parentMatrix = new Matrix4f(); parentMatrix.setTranslation(newParent.getWorldTranslation()); parentMatrix.setRotationQuaternion(newParent.getWorldRotation()); parentMatrix.setScale(newParent.getWorldScale()); parentMatrix.invertLocal(); Vector3f wtrans = toChange.getWorldTranslation().clone(); Quaternion wrot = toChange.getWorldRotation().clone(); Vector3f wscale = toChange.getWorldScale().clone(); Matrix4f childMatrix = new Matrix4f(); childMatrix.setTranslation(wtrans); childMatrix.setRotationQuaternion(wrot); childMatrix.setScale(wscale); Matrix4f local = parentMatrix.mult(childMatrix); return local; } }
package org.jboss.seam.forge.shell; import static org.mvel2.DataConversion.addConversionHandler; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.event.Event; import javax.enterprise.event.Observes; import javax.inject.Inject; import jline.console.ConsoleReader; import jline.console.completer.AggregateCompleter; import jline.console.completer.Completer; import jline.console.completer.FileNameCompleter; import jline.console.history.MemoryHistory; import org.fusesource.jansi.Ansi; import org.jboss.seam.forge.project.Project; import org.jboss.seam.forge.project.dependencies.Dependency; import org.jboss.seam.forge.project.facets.JavaSourceFacet; import org.jboss.seam.forge.project.services.ResourceFactory; import org.jboss.seam.forge.resources.DirectoryResource; import org.jboss.seam.forge.resources.FileResource; import org.jboss.seam.forge.resources.Resource; import org.jboss.seam.forge.resources.java.JavaResource; import org.jboss.seam.forge.shell.command.PromptTypeConverter; import org.jboss.seam.forge.shell.command.convert.BooleanConverter; import org.jboss.seam.forge.shell.command.convert.DependencyIdConverter; import org.jboss.seam.forge.shell.command.convert.FileConverter; import org.jboss.seam.forge.shell.command.fshparser.FSHRuntime; import org.jboss.seam.forge.shell.completer.CompletedCommandHolder; import org.jboss.seam.forge.shell.completer.OptionAwareCompletionHandler; import org.jboss.seam.forge.shell.completer.PluginCommandCompleter; import org.jboss.seam.forge.shell.events.AcceptUserInput; import org.jboss.seam.forge.shell.events.PostStartup; import org.jboss.seam.forge.shell.events.PreShutdown; import org.jboss.seam.forge.shell.events.Shutdown; import org.jboss.seam.forge.shell.events.Startup; import org.jboss.seam.forge.shell.exceptions.AbortedException; import org.jboss.seam.forge.shell.exceptions.CommandExecutionException; import org.jboss.seam.forge.shell.exceptions.CommandParserException; import org.jboss.seam.forge.shell.exceptions.PluginExecutionException; import org.jboss.seam.forge.shell.exceptions.ShellExecutionException; import org.jboss.seam.forge.shell.plugins.builtin.Echo; import org.jboss.seam.forge.shell.project.CurrentProject; import org.jboss.seam.forge.shell.util.Files; import org.jboss.seam.forge.shell.util.GeneralUtils; import org.jboss.seam.forge.shell.util.JavaPathspecParser; import org.jboss.seam.forge.shell.util.OSUtils; import org.jboss.seam.forge.shell.util.ResourceUtil; import org.jboss.weld.environment.se.bindings.Parameters; import org.mvel2.ConversionHandler; import org.mvel2.DataConversion; import org.mvel2.util.StringAppender; import sun.misc.Signal; import sun.misc.SignalHandler; /** * @author <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a> */ @ApplicationScoped @SuppressWarnings("restriction") public class ShellImpl implements Shell { private static final String PROP_PROMPT = "PROMPT"; private static final String PROP_PROMPT_NO_PROJ = "PROMPT_NOPROJ"; private static final String DEFAULT_PROMPT = "[\\c{green}$PROJECT_NAME\\c] \\c{white}\\W\\c \\c{green}\\$\\c "; private static final String DEFAULT_PROMPT_NO_PROJ = "[\\c{red}no project\\c] \\c{white}\\W\\c \\c{red}\\$\\c "; private static final String PROP_DEFAULT_PLUGIN_REPO = "DEFFAULT_PLUGIN_REPO"; private static final String DEFAULT_PLUGIN_REPO = "http://seamframework.org/service/File/148617"; private static final String PROP_VERBOSE = "VERBOSE"; public static final String FORGE_CONFIG_DIR = System.getProperty("user.home") + "/.forge/"; public static final String FORGE_COMMAND_HISTORY_FILE = "cmd_history"; public static final String FORGE_CONFIG_FILE = "config"; private final Map<String, Object> properties = new HashMap<String, Object>(); @Inject @Parameters private List<String> parameters; @Inject private Event<PostStartup> postStartup; @Inject private CurrentProject projectContext; @Inject private ResourceFactory resourceFactory; private Resource<?> lastResource; @Inject private FSHRuntime fshRuntime; @Inject private PromptTypeConverter promptTypeConverter; @Inject private CompletedCommandHolder commandHolder; private ConsoleReader reader; private Completer completer; private boolean pretend = false; private boolean exitRequested = false; private InputStream inputStream; private Writer outputWriter; private OutputStream historyOutstream; private final boolean colorEnabled = Boolean.getBoolean("seam.forge.shell.colorEnabled"); private final ConversionHandler resourceConversionHandler = new ConversionHandler() { @Override @SuppressWarnings("rawtypes") public Resource[] convertFrom(final Object obl) { return GeneralUtils.parseSystemPathspec(resourceFactory, lastResource, getCurrentResource(), obl instanceof String[] ? (String[]) obl : new String[] { obl.toString() }); } @SuppressWarnings("rawtypes") @Override public boolean canConvertFrom(final Class aClass) { return true; } }; private final ConversionHandler javaResourceConversionHandler = new ConversionHandler() { @Override public JavaResource[] convertFrom(final Object obj) { if (getCurrentProject().hasFacet(JavaSourceFacet.class)) { String[] strings = obj instanceof String[] ? (String[]) obj : new String[] { obj.toString() }; List<Resource<?>> resources = new ArrayList<Resource<?>>(); for (String string : strings) { resources.addAll(new JavaPathspecParser(getCurrentProject().getFacet(JavaSourceFacet.class), string).resolve()); } List<JavaResource> filtered = new ArrayList<JavaResource>(); for (Resource<?> resource : resources) { if (resource instanceof JavaResource) { filtered.add((JavaResource) resource); } } JavaResource[] result = new JavaResource[filtered.size()]; result = filtered.toArray(result); return result; } else return null; } @SuppressWarnings("rawtypes") @Override public boolean canConvertFrom(final Class aClass) { return true; } }; private boolean exitOnNextSignal = false; void init(@Observes final Startup event, final PluginCommandCompleter pluginCompleter) throws Exception { BooleanConverter booleanConverter = new BooleanConverter(); addConversionHandler(boolean.class, booleanConverter); addConversionHandler(Boolean.class, booleanConverter); addConversionHandler(File.class, new FileConverter()); addConversionHandler(Dependency.class, new DependencyIdConverter()); addConversionHandler(JavaResource[].class, javaResourceConversionHandler); addConversionHandler(JavaResource.class, new ConversionHandler() { @Override public Object convertFrom(final Object obj) { JavaResource[] res = (JavaResource[]) javaResourceConversionHandler.convertFrom(obj); if (res.length > 1) { throw new RuntimeException("ambiguous paths"); } else if (res.length == 0) { if (getCurrentProject().hasFacet(JavaSourceFacet.class)) { JavaSourceFacet java = getCurrentProject().getFacet(JavaSourceFacet.class); try { JavaResource resource = java.getJavaResource(obj.toString()); return resource; } catch (FileNotFoundException e) { throw new RuntimeException(e); } } return null; } else { return res[0]; } } @Override @SuppressWarnings("rawtypes") public boolean canConvertFrom(final Class type) { return javaResourceConversionHandler.canConvertFrom(type); } }); addConversionHandler(Resource[].class, resourceConversionHandler); addConversionHandler(Resource.class, new ConversionHandler() { @Override public Object convertFrom(final Object o) { Resource<?>[] res = (Resource<?>[]) resourceConversionHandler.convertFrom(o); if (res.length > 1) { throw new RuntimeException("ambiguous paths"); } else if (res.length == 0) { return ResourceUtil.parsePathspec(resourceFactory, getCurrentResource(), o.toString()).get(0); } else { return res[0]; } } @Override @SuppressWarnings("rawtypes") public boolean canConvertFrom(final Class aClass) { return resourceConversionHandler.canConvertFrom(aClass); } }); projectContext.setCurrentResource(resourceFactory.getResourceFrom(event.getWorkingDirectory())); properties.put("CWD", getCurrentDirectory().getFullyQualifiedName()); initStreams(); initCompleters(pluginCompleter); initParameters(); initSignalHandlers(); if (event.isRestart()) { // suppress the MOTD if this is a restart. properties.put("NO_MOTD", true); } else { properties.put("NO_MOTD", false); } properties.put("OS_NAME", OSUtils.getOsName()); properties.put("FORGE_CONFIG_DIR", FORGE_CONFIG_DIR); properties.put(PROP_PROMPT, "> "); properties.put(PROP_PROMPT_NO_PROJ, "> "); loadConfig(); postStartup.fire(new PostStartup()); } private static void initSignalHandlers() { try { // check to see if we have something to work with. Class.forName("sun.misc.SignalHandler"); SignalHandler signalHandler = new SignalHandler() { @Override public void handle(final Signal signal) { // TODO implement smart shutdown (if they keep pressing CTRL-C) } }; Signal.handle(new Signal("INT"), signalHandler); } catch (ClassNotFoundException e) { // signal trapping not supported. Oh well, switch to a Sun-based JVM, loser! } } private void loadConfig() { File configDir = new File(FORGE_CONFIG_DIR); if (!configDir.exists()) { if (!configDir.mkdirs()) { System.err.println("could not create config directory: " + configDir.getAbsolutePath()); return; } } File historyFile = new File(configDir.getPath() + "/" + FORGE_COMMAND_HISTORY_FILE); try { if (!historyFile.exists()) { if (!historyFile.createNewFile()) { System.err.println("could not create config file: " + historyFile.getAbsolutePath()); } } } catch (IOException e) { throw new RuntimeException("could not create config file: " + historyFile.getAbsolutePath()); } MemoryHistory history = new MemoryHistory(); try { StringAppender buf = new StringAppender(); InputStream instream = new BufferedInputStream(new FileInputStream(historyFile)); byte[] b = new byte[25]; int read; while ((read = instream.read(b)) != -1) { for (int i = 0; i < read; i++) { if (b[i] == '\n') { history.add(buf.toString()); buf.reset(); } else { buf.append(b[i]); } } } instream.close(); reader.setHistory(history); } catch (IOException e) { throw new RuntimeException("error loading file: " + historyFile.getAbsolutePath()); } File configFile = new File(configDir.getPath() + "/" + FORGE_CONFIG_FILE); if (!configFile.exists()) { try { /** * Create a default config file. */ configFile.createNewFile(); OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(configFile)); String defaultConfig = getDefaultConfig(); for (int i = 0; i < defaultConfig.length(); i++) { outputStream.write(defaultConfig.charAt(i)); } outputStream.flush(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("error loading file: " + historyFile.getAbsolutePath()); } } try { /** * Load the config file script. */ execute(configFile); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("error loading file: " + historyFile.getAbsolutePath()); } try { historyOutstream = new BufferedOutputStream(new FileOutputStream(historyFile, true)); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { historyOutstream.flush(); historyOutstream.close(); } catch (Exception e) { } } }); } catch (IOException e) { } } private void writeToHistory(final String command) { try { for (int i = 0; i < command.length(); i++) { historyOutstream.write(command.charAt(i)); } historyOutstream.write('\n'); } catch (IOException e) { } } private void initCompleters(final PluginCommandCompleter pluginCompleter) { List<Completer> completers = new ArrayList<Completer>(); completers.add(pluginCompleter); completer = new AggregateCompleter(completers); this.reader.addCompleter(completer); this.reader.setCompletionHandler(new OptionAwareCompletionHandler(commandHolder, this)); } private void initStreams() throws IOException { if (inputStream == null) { inputStream = System.in; } if (outputWriter == null) { outputWriter = new PrintWriter(System.out); } this.reader = new ConsoleReader(inputStream, outputWriter); this.reader.setHistoryEnabled(true); this.reader.setBellEnabled(false); } private void initParameters() { properties.put(PROP_VERBOSE, String.valueOf(parameters.contains("--verbose"))); if (parameters.contains("--pretend")) { pretend = true; } if ((parameters != null) && !parameters.isEmpty()) { // this is where we will initialize other parameters... e.g. accepting // a path } } private String getDefaultConfig() { return "@/* Automatically generated config file */;\n" + "if (!$NO_MOTD) { " + " echo \" ____ _____ \";\n" + " echo \" / ___| ___ __ _ _ __ ___ | ___|__ _ __ __ _ ___ \";\n" + " echo \" \\\\___ \\\\ / _ \\\\/ _` | '_ ` _ \\\\ | |_ / _ \\\\| '__/ _` |/ _ \\\\ \\c{yellow}\\\\\\\\\\c\";\n" + " echo \" ___) | __/ (_| | | | | | | | _| (_) | | | (_| | __/ \\c{yellow} " echo \" |____/ \\\\___|\\\\__,_|_| |_| |_| |_| \\\\___/|_| \\\\__, |\\\\___| \";\n" + " echo \" |___/ \";\n\n" + "}\n" + "\n" + "if ($OS_NAME.startsWith(\"Windows\")) {\n" + " echo \" Windows? Really? Okay...\\n\"\n" + "}\n" + "\n" + "set " + PROP_PROMPT + " \"" + DEFAULT_PROMPT + "\";\n" + "set " + PROP_PROMPT_NO_PROJ + " \"" + DEFAULT_PROMPT_NO_PROJ + "\";\n" + "set " + PROP_DEFAULT_PLUGIN_REPO + " \"" + DEFAULT_PLUGIN_REPO + "\"\n"; } void teardown(@Observes final Shutdown shutdown, final Event<PreShutdown> preShutdown) { preShutdown.fire(new PreShutdown(shutdown.getStatus())); exitRequested = true; } void doShell(@Observes final AcceptUserInput event) { String line; reader.setPrompt(getPrompt()); while (!exitRequested) { try { line = readLineShell(); if (line != null) { if (!"".equals(line.trim())) { writeToHistory(line); execute(line); } reader.setPrompt(getPrompt()); } } catch (Exception e) { handleException(e); } } println(); } private void handleException(final Exception original) { try { // unwrap any aborted exceptions Throwable cause = original; while (cause != null) { if (cause instanceof AbortedException) throw (AbortedException) cause; cause = cause.getCause(); } throw original; } catch (AbortedException e) { ShellMessages.info(this, "Aborted."); if (isVerbose()) { e.printStackTrace(); } } catch (CommandExecutionException e) { ShellMessages.error(this, formatSourcedError(e.getCommand()) + e.getMessage()); if (isVerbose()) { e.printStackTrace(); } } catch (CommandParserException e) { ShellMessages.error(this, "[" + formatSourcedError(e.getCommand()) + "] " + e.getMessage()); if (isVerbose()) { e.printStackTrace(); } } catch (PluginExecutionException e) { ShellMessages.error(this, "[" + formatSourcedError(e.getPlugin()) + "] " + e.getMessage()); if (isVerbose()) { e.printStackTrace(); } } catch (ShellExecutionException e) { ShellMessages.error(this, e.getMessage()); if (isVerbose()) { e.printStackTrace(); } } catch (Exception e) { if (!isVerbose()) { ShellMessages.error(this, "Exception encountered: " + e.getMessage() + " (type \"set VERBOSE true\" to enable stack traces)"); } else { ShellMessages.error(this, "Exception encountered: (type \"set VERBOSE false\" to disable stack traces)"); e.printStackTrace(); } } } private String formatSourcedError(final Object obj) { return (obj == null ? "" : ("[" + obj.toString() + "] ")); } @Override public String readLine() throws IOException { String line = reader.readLine(); if (line == null) { reader.println(); reader.flush(); throw new AbortedException(); } exitOnNextSignal = false; return line; } private String readLineShell() throws IOException { String line = reader.readLine(); if (line == null) { if (this.exitOnNextSignal == false) { println(); println("(Press CTRL-D again or type 'exit' to quit.)"); this.exitOnNextSignal = true; } else { print("exit"); this.exitRequested = true; } reader.flush(); } else { exitOnNextSignal = false; } return line; } @Override public int scan() { try { return reader.readVirtualKey(); } catch (IOException e) { return -1; } } @Override public void clearLine() { print(new Ansi().eraseLine(Ansi.Erase.ALL).toString()); } @Override public void cursorLeft(final int x) { print(new Ansi().cursorLeft(x).toString()); } @Override public void execute(final String line) { try { fshRuntime.run(line); } catch (Exception e) { handleException(e); } } @Override public void execute(final File file) throws IOException { StringBuilder buf = new StringBuilder(); InputStream instream = new BufferedInputStream(new FileInputStream(file)); try { byte[] b = new byte[25]; int read; while ((read = instream.read(b)) != -1) { for (int i = 0; i < read; i++) { buf.append((char) b[i]); } } instream.close(); execute(buf.toString()); } finally { instream.close(); } } @Override public void execute(final File file, final String... args) throws IOException { StringBuilder buf = new StringBuilder(); String funcName = file.getName().replaceAll("\\.", "_") + "_" + String.valueOf(hashCode()).replaceAll("\\-", "M"); buf.append("def ").append(funcName).append('('); if (args != null) { for (int i = 0; i < args.length; i++) { buf.append("_").append(String.valueOf(i)); if (i + 1 < args.length) { buf.append(", "); } } } buf.append(") {\n"); if (args != null) { buf.append("@_vararg = new String[").append(args.length).append("];\n"); for (int i = 0; i < args.length; i++) { buf.append("@_vararg[").append(String.valueOf(i)).append("] = ") .append("_").append(String.valueOf(i)).append(";\n"); } } InputStream instream = new BufferedInputStream(new FileInputStream(file)); try { byte[] b = new byte[25]; int read; while ((read = instream.read(b)) != -1) { for (int i = 0; i < read; i++) { buf.append((char) b[i]); } } buf.append("\n}; \n@").append(funcName).append('('); if (args != null) { for (int i = 0; i < args.length; i++) { buf.append("\"").append(args[i].replaceAll("\\\"", "\\\\\\\"")).append("\""); if (i + 1 < args.length) { buf.append(", "); } } } buf.append(");\n"); // System.out.println("\nexec:" + buf.toString()); execute(buf.toString()); } finally { properties.remove(funcName); instream.close(); } } /* * Shell Print Methods */ @Override public void printlnVerbose(final String line) { if (isVerbose()) { System.out.println(line); } } @Override public void print(final String output) { System.out.print(output); } @Override public void println(final String output) { System.out.println(output); } @Override public void println() { System.out.println(); } @Override public void print(final ShellColor color, final String output) { print(renderColor(color, output)); } @Override public void println(final ShellColor color, final String output) { println(renderColor(color, output)); } @Override public void printlnVerbose(final ShellColor color, final String output) { printlnVerbose(renderColor(color, output)); } @Override public String renderColor(final ShellColor color, final String output) { if (!colorEnabled) { return output; } Ansi ansi = new Ansi(); switch (color) { case BLACK: ansi.fg(Ansi.Color.BLACK); break; case BLUE: ansi.fg(Ansi.Color.BLUE); break; case CYAN: ansi.fg(Ansi.Color.CYAN); break; case GREEN: ansi.fg(Ansi.Color.GREEN); break; case MAGENTA: ansi.fg(Ansi.Color.MAGENTA); break; case RED: ansi.fg(Ansi.Color.RED); break; case WHITE: ansi.fg(Ansi.Color.WHITE); break; case YELLOW: ansi.fg(Ansi.Color.YELLOW); break; case BOLD: ansi.a(Ansi.Attribute.INTENSITY_BOLD); break; default: ansi.fg(Ansi.Color.WHITE); } return ansi.render(output).reset().toString(); } @Override public void write(final byte b) { System.out.print((char) b); } @Override public void clear() { print(new Ansi().cursor(0, 0).eraseScreen().toString()); } @Override public boolean isVerbose() { Object s = properties.get(PROP_VERBOSE); return (s != null) && "true".equals(s); } @Override public void setVerbose(final boolean verbose) { properties.put(PROP_VERBOSE, String.valueOf(verbose)); } @Override public boolean isPretend() { return pretend; } @Override public void setInputStream(final InputStream is) throws IOException { this.inputStream = is; initStreams(); } @Override public void setOutputWriter(final Writer os) throws IOException { this.outputWriter = os; initStreams(); } @Override public void setProperty(final String name, final Object value) { properties.put(name, value); } @Override public Object getProperty(final String name) { return properties.get(name); } @Override public Map<String, Object> getProperties() { return properties; } @Override public void setDefaultPrompt() { setPrompt(""); } @Override public void setPrompt(final String prompt) { setProperty(PROP_PROMPT, prompt); } @Override public String getPrompt() { if (projectContext.getCurrent() != null) { return Echo.echo(this, Echo.promptExpressionParser(this, (String) properties.get(PROP_PROMPT))); } else { return Echo.echo(this, Echo.promptExpressionParser(this, (String) properties.get(PROP_PROMPT_NO_PROJ))); } } @Override public DirectoryResource getCurrentDirectory() { Resource<?> r = getCurrentResource(); return ResourceUtil.getContextDirectory(r); } @Override public Resource<?> getCurrentResource() { Resource<?> result = this.projectContext.getCurrentResource(); if (result == null) { result = this.resourceFactory.getResourceFrom(Files.getWorkingDirectory()); properties.put("CWD", result.getFullyQualifiedName()); } return result; } @Override @SuppressWarnings("unchecked") public Class<? extends Resource<?>> getCurrentResourceScope() { return (Class<? extends Resource<?>>) getCurrentResource().getClass(); } @Override public void setCurrentResource(final Resource<?> resource) { lastResource = getCurrentResource(); projectContext.setCurrentResource(resource); properties.put("CWD", resource.getFullyQualifiedName()); } @Override public Project getCurrentProject() { return this.projectContext.getCurrent(); } /* * Shell Prompts */ @Override public String prompt() { return prompt(""); } @Override public String promptAndSwallowCR() { int c; StringBuilder buf = new StringBuilder(); while (((c = scan()) != '\n') && (c != '\r')) { if (c == 127) { if (buf.length() > 0) { buf.deleteCharAt(buf.length() - 1); cursorLeft(1); print(" "); cursorLeft(1); } continue; } write((byte) c); buf.append((char) c); } return buf.toString(); } @Override public String prompt(final String message) { return promptWithCompleter(message, null); } private String promptWithCompleter(String message, final Completer tempCompleter) { if (!message.isEmpty() && message.matches("^.*\\S$")) { message = message + " "; } try { reader.removeCompleter(this.completer); if (tempCompleter != null) { reader.addCompleter(tempCompleter); } reader.setHistoryEnabled(false); reader.setPrompt(message); String line = readLine(); return line; } catch (IOException e) { throw new IllegalStateException("Shell input stream failure", e); } finally { if (tempCompleter != null) { reader.removeCompleter(tempCompleter); } reader.addCompleter(this.completer); reader.setHistoryEnabled(true); reader.setPrompt(""); } } @Override public String promptRegex(final String message, final String regex) { String input; do { input = prompt(message); } while (!input.matches(regex)); return input; } @Override public String promptRegex(final String message, final String pattern, final String defaultIfEmpty) { if (!defaultIfEmpty.matches(pattern)) { throw new IllegalArgumentException("Default value [" + defaultIfEmpty + "] does not match required pattern [" + pattern + "]"); } String input; do { input = prompt(message + " [" + defaultIfEmpty + "]"); if ("".equals(input.trim())) { input = defaultIfEmpty; } } while (!input.matches(pattern)); return input; } @Override @SuppressWarnings("unchecked") public <T> T prompt(final String message, final Class<T> clazz) { Object result; Object input; do { input = prompt(message); try { result = DataConversion.convert(input, clazz); } catch (Exception e) { result = InvalidInput.INSTANCE; } } while ((result instanceof InvalidInput)); return (T) result; } @Override @SuppressWarnings("unchecked") public <T> T prompt(final String message, final Class<T> clazz, final T defaultIfEmpty) { Object result; String input; do { input = prompt(message); if ((input == null) || "".equals(input.trim())) { result = defaultIfEmpty; } else { input = input.trim(); try { result = DataConversion.convert(input, clazz); } catch (Exception e) { result = InvalidInput.INSTANCE; } } } while ((result instanceof InvalidInput)); return (T) result; } @Override public boolean promptBoolean(final String message) { return promptBoolean(message, true); } @Override public boolean promptBoolean(final String message, final boolean defaultIfEmpty) { String query = " [Y/n] "; if (!defaultIfEmpty) { query = " [y/N] "; } return prompt(message + query, Boolean.class, defaultIfEmpty); } @Override public int promptChoice(final String message, final Object... options) { return promptChoice(message, Arrays.asList(options)); } @Override public int promptChoice(final String message, final List<?> options) { if ((options == null) || options.isEmpty()) { throw new IllegalArgumentException( "promptChoice() Cannot ask user to select from a list of nothing. Ensure you have values in your options list."); } int count = 1; println(message); Object result = InvalidInput.INSTANCE; while (result instanceof InvalidInput) { println(); for (Object entry : options) { println(" " + count + " - [" + entry + "]"); count++; } println(); int input = prompt("Choose an option by typing the number of the selection: ", Integer.class) - 1; if (input < options.size()) { return input; } else { println("Invalid selection, please try again."); } } return -1; } @Override public <T> T promptChoiceTyped(final String message, final T... options) { return promptChoiceTyped(message, Arrays.asList(options)); } @Override @SuppressWarnings("unchecked") public <T> T promptChoiceTyped(final String message, final List<T> options) { if ((options == null) || options.isEmpty()) { throw new IllegalArgumentException( "promptChoice() Cannot ask user to select from a list of nothing. Ensure you have values in your options list."); } if (options.size() == 1) { return options.get(0); } int count = 1; println(message); Object result = InvalidInput.INSTANCE; while (result instanceof InvalidInput) { println(); for (T entry : options) { println(" " + count + " - [" + entry + "]"); count++; } println(); int input = prompt("Choose an option by typing the number of the selection: ", Integer.class) - 1; if ((input >= 0) && (input < options.size())) { result = options.get(input); } else { println("Invalid selection, please try again."); } } return (T) result; } @Override public int getHeight() { return reader.getTerminal().getHeight(); } @Override public int getWidth() { return reader.getTerminal().getWidth(); } public String escapeCode(final int code, final String value) { return new Ansi().a(value).fg(Ansi.Color.BLUE).toString(); } @Override @SuppressWarnings("unchecked") public <T> T promptChoice(final String message, final Map<String, T> options) { int count = 1; println(message); List<Entry<String, T>> entries = new ArrayList<Map.Entry<String, T>>(); entries.addAll(options.entrySet()); Object result = InvalidInput.INSTANCE; while (result instanceof InvalidInput) { println(); for (Entry<String, T> entry : entries) { println(" " + count + " - [" + entry.getKey() + "]"); count++; } println(); String input = prompt("Choose an option by typing the name or number of the selection: "); if (options.containsKey(input)) { result = options.get(input); } } return (T) result; } @Override public String promptCommon(final String message, final PromptType type) { String result = promptRegex(message, type.getPattern()); result = promptTypeConverter.convert(type, result); return result; } @Override public String promptCommon(final String message, final PromptType type, final String defaultIfEmpty) { String result = promptRegex(message, type.getPattern(), defaultIfEmpty); result = promptTypeConverter.convert(type, result); return result; } @Override public FileResource<?> promptFile(final String message) { String path = ""; while ((path == null) || path.trim().isEmpty()) { path = promptWithCompleter(message, new FileNameCompleter()); } path = Files.canonicalize(path); Resource<File> resource = resourceFactory.getResourceFrom(new File(path)); if (resource instanceof FileResource) { return (FileResource<?>) resource; } return null; } @Override public FileResource<?> promptFile(final String message, final FileResource<?> defaultIfEmpty) { FileResource<?> result = defaultIfEmpty; String path = promptWithCompleter(message, new FileNameCompleter()); if (!"".equals(path) && (path != null) && !path.trim().isEmpty()) { path = Files.canonicalize(path); Resource<File> resource = resourceFactory.getResourceFrom(new File(path)); if (resource instanceof FileResource) { result = (FileResource<?>) resource; } else { result = null; } } return result; } }
package de.sonumina.simpledance; import java.awt.Polygon; import de.sonumina.simpledance.graphics.Color; import de.sonumina.simpledance.graphics.Context; import de.sonumina.simpledance.graphics.Point; import de.sonumina.simpledance.graphics.RGB; /** * This class is responsible for actually drawing the scene * on a given context. * * @author Sebastian Bauer */ public class Render { private Color leftFeetColor; private Color leftFeetSelectedColor; private Color leftFeetBorderColor; private Color rightFeetColor; private Color rightFeetSelectedColor; private Color rightFeetBorderColor; private Color femaleLeftColor; private Color femaleRightColor; private Color maleLeftColor; private Color maleRightColor; private Color darkGreyColor; private Color shineGreyColor; private Color ballroomColor; private Color lineColor; private Color animationColor; private Color animationSelectedColor; private Color countColor; private Color gridColor; private Color yellowColor; private Color redColor; private Context context; /** Graphics data for male and femals feet */ static private GraphicsData [] graphicsData = new GraphicsData [] { new GraphicsData(0), new GraphicsData(1), }; private GraphicsData getGraphicsData(Step step, int footNumber) { int graphicsNum; if (step.isFemaleFoot(footNumber)) graphicsNum = 1; else graphicsNum = 0; return graphicsData[graphicsNum]; } /** * Construct a new render object with the context being the target * of all operations. * * @param context */ public Render(Context context) { this.context = context; leftFeetColor = context.allocateColor(5,5,5); leftFeetSelectedColor = context.allocateColor(250,250,170); leftFeetBorderColor = context.allocateColor(15,15,15); rightFeetColor = context.allocateColor(5,5,5); rightFeetSelectedColor = context.allocateColor(80,80,0); rightFeetBorderColor = context.allocateColor(15,15,15); darkGreyColor = context.allocateColor(70,70,70); shineGreyColor = context.allocateColor(180,180,180); ballroomColor = context.allocateColor(240,240,200); lineColor = context.allocateColor(200,200,0); yellowColor = context.allocateColor(240,240,0); redColor = context.allocateColor(240,0,0); animationColor = context.allocateColor(200,200,54); animationSelectedColor = context.allocateColor(200,200,54); gridColor = context.allocateColor(0,0,0); countColor = context.allocateColor(255,255,255); femaleLeftColor = context.allocateColor(244,231,240); femaleRightColor = context.allocateColor(244,61,195); maleLeftColor = context.allocateColor(228,229,240); maleRightColor = context.allocateColor(61,78,240); } /** * Free all resources */ void dispose() { context.deallocateColor(femaleLeftColor); context.deallocateColor(femaleRightColor); context.deallocateColor(maleLeftColor); context.deallocateColor(maleRightColor); context.deallocateColor(leftFeetColor); context.deallocateColor(darkGreyColor); context.deallocateColor(shineGreyColor); context.deallocateColor(rightFeetColor); context.deallocateColor(ballroomColor); context.deallocateColor(lineColor); context.deallocateColor(animationColor); context.deallocateColor(animationSelectedColor); context.deallocateColor(yellowColor); context.deallocateColor(redColor); context.deallocateColor(gridColor); context.deallocateColor(countColor); // context.deallocateColor(countFont); context.deallocateColor(leftFeetSelectedColor); context.deallocateColor(leftFeetColor); context.deallocateColor(leftFeetBorderColor); context.deallocateColor(rightFeetSelectedColor); context.deallocateColor(rightFeetColor); context.deallocateColor(rightFeetBorderColor); } static public enum FootPart { NO, BALE, HEEL } static public class CoordinateInfo { Point rotationCenterBallroomPoint; int feetIndex = -1; FootPart feetPart = FootPart.NO; int waypoint = -1; int distance; }; static public class RenderSceneArgs { /** Coordinates of the ballroom coord system */ public Point visibleLeftTop; public Point visibleRightTop; public Point visibleLeftBottom; public Point visibleRightBottom; public int pixelWidth; public int pixelHeight; public Pattern pattern; public int stepNumber; public boolean showGradients; public boolean showPrevStep; public boolean insideAnimation; public boolean showLady; public boolean showGent; public boolean showAnimationOutline; public boolean selectedArray[] = new boolean[4]; public int animationMaxNumber; public int animationNumber; }; /** * Transform given ballroom waypoint to a waypoint representing pixel positions. * * @param rsa * @param feetCoord * @return */ private WayPoint transformBallroomToPixel(RenderSceneArgs rsa, WayPoint feetCoord) { Point p = transformBallroomToPixel(rsa, feetCoord.x, feetCoord.y); return new WayPoint(p.x, p.y, feetCoord.a); } /** * Transform given ballroom coordinates to the actual view coordinates. * * @param rsa * @param x * @param y * @return */ private Point transformBallroomToPixel(RenderSceneArgs rsa, int x, int y) { int visibleLeft = rsa.visibleLeftTop.x; int visibleTop = rsa.visibleLeftTop.y; int visibleWidth = rsa.visibleRightBottom.x - visibleLeft + 1; int visibleHeight = rsa.visibleRightBottom.y - visibleTop + 1; x = (x - visibleLeft) * rsa.pixelWidth / visibleWidth; y = (visibleTop - y) * rsa.pixelHeight / visibleHeight; return new Point(x,y); } /** * * @param x0 * @param y0 * @param angle * @param px defines the x coordinate of the to be transformed point * @param py defines the y coordinate of the to be transformed point * @return */ private Point transformCoords(int x0, int y0, int angle, int px, int py) { int x = x0; int y = y0; int a = angle; double cosa = Math.cos(Math.toRadians(a)); double sina = Math.sin(Math.toRadians(a)); int newx = (int)(px * cosa - py * sina) + x; int newy = (int)(-px * sina + py * cosa) + y; Point p = new Point(newx,newy); return p; } private void myDrawPolygon(RenderSceneArgs rsa, WayPoint feetCoord, boolean mirror, int [] data, int pixSize, int ballroomSize, boolean closed) { context.pushCurrentTransform(); WayPoint transFeetCoord = transformBallroomToPixel(rsa, feetCoord); int visibleLeft = rsa.visibleLeftTop.x; int visibleWidth = rsa.visibleRightBottom.x - visibleLeft + 1; float scale = (float)rsa.pixelWidth / pixSize / (float)visibleWidth * ballroomSize; context.applyTranslationTransformation(transFeetCoord.x, transFeetCoord.y); context.applyRotateTransformation(-feetCoord.a); context.applyScaleTransformation(scale); if (mirror) context.applyScaleXTransformation(-1.f); if (closed) context.drawPolygon(data); else context.drawPolyline(data); context.popCurrentTransform(); } private void myFillPolygon(RenderSceneArgs rsa, WayPoint feetCoord, boolean mirror, int [] data, int pixSize, int ballroomSize) { context.pushCurrentTransform(); WayPoint transFeetCoord = transformBallroomToPixel(rsa, feetCoord); int visibleLeft = rsa.visibleLeftTop.x; int visibleWidth = rsa.visibleRightBottom.x - visibleLeft + 1; float scale = (float)rsa.pixelWidth / pixSize / (float)visibleWidth * ballroomSize; context.applyTranslationTransformation(transFeetCoord.x, transFeetCoord.y); context.applyRotateTransformation(-feetCoord.a); context.applyScaleTransformation(scale); if (mirror) context.applyScaleXTransformation(-1.f); context.fillPolygon(data); context.popCurrentTransform(); } private void myGradientPolygon(RenderSceneArgs rsa, RGB startRGB, RGB endRGB, WayPoint feetCoord, boolean mirror, int [] data, int pixSize, int ballroomSize) { context.pushCurrentTransform(); WayPoint transFeetCoord = transformBallroomToPixel(rsa, feetCoord); int visibleLeft = rsa.visibleLeftTop.x; int visibleWidth = rsa.visibleRightBottom.x - visibleLeft + 1; float scale = (float)rsa.pixelWidth / pixSize / (float)visibleWidth * ballroomSize; context.applyTranslationTransformation(transFeetCoord.x, transFeetCoord.y); context.applyRotateTransformation(-feetCoord.a); context.applyScaleTransformation(scale); if (mirror) context.applyScaleXTransformation(-1.f); context.gradientPolygon(data,startRGB,endRGB,feetCoord.a); context.popCurrentTransform(); } private void myDrawText(RenderSceneArgs rsa, WayPoint feetCoord, String text) { feetCoord = transformBallroomToPixel(rsa,feetCoord); int x = feetCoord.x; int y = feetCoord.y; context.setFont(null); x -= context.stringExtent(text).x/2; y -= context.stringExtent(text).y/2; context.drawText(text,x,y,true); } /** * Draws an oval around ballroomCoord * * @param rsa * @param ballroomCoord * @param mx (in ballroom coordinates) * @param my (in ballroom coordinates) */ private void myDrawOval(RenderSceneArgs rsa, WayPoint ballroomCoord, int mx, int my) { Point p = transformCoords(ballroomCoord.x,ballroomCoord.y,ballroomCoord.a,mx,my); p = transformBallroomToPixel(rsa,p.x,p.y); context.drawOval(p.x,p.y,2,2); } /** * Checks whether the given pixel coordinates (tx, ty) are in a given polygon subject to specified coordinate transformation. * * @param rsa render scene arguments. * @param center defines the center of the shape in ballroom space. * @param mirror whether the polygon should be additionally mirrored. * @param data the data that defines the polygon. * @param pixSize the size of the object in pixels (e.g., the y extend) * @param ballroomSize the equivalent size of the object in ballroom space. * @param tx the x part of the location to check * @param ty the y part of the location to check * @return whether (tx,ty) is inside the polygon. */ private boolean myPolygonTest(RenderSceneArgs rsa, WayPoint center, boolean mirror, int [] data, int pixSize, int ballroomSize, int tx, int ty) { context.pushCurrentTransform(); WayPoint transFeetCoord = transformBallroomToPixel(rsa, center); int visibleLeft = rsa.visibleLeftTop.x; int visibleWidth = rsa.visibleRightBottom.x - visibleLeft + 1; float scale = (float)rsa.pixelWidth / pixSize / (float)visibleWidth * ballroomSize; context.applyTranslationTransformation(transFeetCoord.x, transFeetCoord.y); context.applyRotateTransformation(-center.a); context.applyScaleTransformation(scale); if (mirror) context.applyScaleXTransformation(-1.f); int [] transformedData = new int[data.length]; context.applyTransformation(data, transformedData); context.popCurrentTransform(); Polygon polygon = new Polygon(); for (int i=0; i<data.length; i+=2) polygon.addPoint(transformedData[i], transformedData[i+1]); return polygon.contains(tx,ty); } /** * Tests whether a given point (px, py) realtive to a given center is nearby by a * point (tx, ty) that given in the view space. * * @param rsa * @param center * @param px * @param py * @param tx * @param ty * @return */ private boolean myPointRangeTest(RenderSceneArgs rsa, WayPoint center, int px, int py, int tx, int ty) { Point p = transformCoords(center.x, center.y, center.a, px, py); p = transformBallroomToPixel(rsa, p.x, p.y); if (Math.abs(p.x - tx) < 5 && Math.abs(p.y - ty) < 5) return true; return false; } /** * Draw a given foot * * @param rsa * @param step * @param pixelCoord * @param footNumber * @param isSelected */ private void drawFoot(RenderSceneArgs rsa, Step step, WayPoint ballroomCoord, int footNumber, boolean isSelected) { boolean fillBale = true; boolean fillHeel = true; boolean showGradients = rsa.showGradients; Color backgroundColor; Color borderColor; if (step.isFeetLeft(footNumber)) { if (isSelected) backgroundColor = leftFeetSelectedColor; else backgroundColor = leftFeetColor; borderColor = leftFeetBorderColor; } else { if (isSelected) backgroundColor = rightFeetSelectedColor; else backgroundColor = rightFeetColor; borderColor = rightFeetBorderColor; } GraphicsData graphicsData = getGraphicsData(step,footNumber); int lw = context.getLineWidth(); int type = step.getFoot(footNumber).getType(); if (type == Foot.STAND_ON_FOOT) { context.setForeground(yellowColor); context.setLineWidth(2); } else { context.setForeground(borderColor); } if (type == Foot.BALL_STEP_STAY || type == Foot.BALL_STAY || type == Foot.TAP) { fillBale = false; fillHeel = false; } context.setBackground(backgroundColor); Color heelColor; if (step.isFemaleFoot(footNumber)) { if (step.isFeetLeft(footNumber)) heelColor = femaleLeftColor; else heelColor = femaleRightColor; } else { if (step.isFeetLeft(footNumber)) heelColor = maleLeftColor; else heelColor = maleRightColor; } context.setBackground(heelColor); if (fillBale) { if (showGradients) myGradientPolygon(rsa,heelColor.getRGB(),new RGB(0,0,0),ballroomCoord,step.isFeetLeft(footNumber),graphicsData.baleData,graphicsData.feetDataYSize,graphicsData.realYSize); else myFillPolygon(rsa,ballroomCoord,step.isFeetLeft(footNumber),graphicsData.baleData,graphicsData.feetDataYSize,graphicsData.realYSize); } myDrawPolygon(rsa,ballroomCoord,step.isFeetLeft(footNumber),graphicsData.baleData,graphicsData.feetDataYSize,graphicsData.realYSize,true); context.setBackground(heelColor); if (fillHeel) myFillPolygon(rsa,ballroomCoord,step.isFeetLeft(footNumber),graphicsData.heelData,graphicsData.feetDataYSize,graphicsData.realYSize); myDrawPolygon(rsa,ballroomCoord,step.isFeetLeft(footNumber),graphicsData.heelData,graphicsData.feetDataYSize,graphicsData.realYSize,true); if (type == Foot.BALL_STEP || type == Foot.BALL_STEP_STAY || type == Foot.BALL_STAY) { if (type != Foot.BALL_STAY) { context.setForeground(redColor); context.setLineWidth(2); } if (type != Foot.BALL_STEP) myFillPolygon(rsa,ballroomCoord,step.isFeetLeft(footNumber),graphicsData.getBale(),graphicsData.feetDataYSize,graphicsData.realYSize); myDrawPolygon(rsa,ballroomCoord,step.isFeetLeft(footNumber),graphicsData.getBale(),graphicsData.feetDataYSize,graphicsData.realYSize,false); } if (type == Foot.HEEL_STEP) { context.setForeground(redColor); context.setLineWidth(2); myDrawPolygon(rsa,ballroomCoord,step.isFeetLeft(footNumber),graphicsData.getHeel(),graphicsData.feetDataYSize,graphicsData.realYSize,false); } if (type == Foot.TAP) { context.setBackground(redColor); context.setLineWidth(2); myFillPolygon(rsa,ballroomCoord,step.isFeetLeft(footNumber),graphicsData.getBaleTap(),graphicsData.feetDataYSize,graphicsData.realYSize); } context.setLineWidth(lw); context.setForeground(borderColor); if (step.isFeetLeft(footNumber)) myDrawText(rsa,ballroomCoord,"L"); else myDrawText(rsa,ballroomCoord,"R"); myDrawOval(rsa,ballroomCoord,0,0); int ballroomBaleX = graphicsData.baleX * graphicsData.realYSize / graphicsData.feetDataYSize; int ballroomBaleY = -graphicsData.baleY * graphicsData.realYSize / graphicsData.feetDataYSize; int ballroomHeelX = graphicsData.heelX * graphicsData.realYSize / graphicsData.feetDataYSize; int ballroomHeelY = -graphicsData.heelY * graphicsData.realYSize / graphicsData.feetDataYSize; myDrawOval(rsa,ballroomCoord,ballroomBaleX,ballroomBaleY); myDrawOval(rsa,ballroomCoord,ballroomHeelX,ballroomHeelY); } /** * Render the scene according to the given rsa * * @param rsa */ public void renderScence(RenderSceneArgs rsa) { Pattern pattern = rsa.pattern; if (pattern == null) return; Step step = pattern.getStep(rsa.stepNumber); if (step == null) return; Step previousStep; if (rsa.stepNumber > 0) previousStep = pattern.getStep(rsa.stepNumber-1); else previousStep = null; Step nextStep; if (rsa.stepNumber < pattern.getStepLength()-1) nextStep = pattern.getStep(rsa.stepNumber+1); else nextStep = null; /* Show the previous step if not inside an animation */ if (previousStep != null && !rsa.insideAnimation) { if (rsa.showPrevStep) { for (int i=0;i<previousStep.getNumberOfFeets();i++) { if (previousStep.isFemaleFoot(i) && !rsa.showLady) continue; if (!previousStep.isFemaleFoot(i) && !rsa.showGent) continue; GraphicsData graphicsData = getGraphicsData(step,i); WayPoint wayPoint = previousStep.getStartingWayPoint(i); if (previousStep.getFoot(i).isLeft()) context.setBackground(shineGreyColor); else context.setBackground(darkGreyColor); myFillPolygon(rsa,wayPoint,step.isFeetLeft(i),graphicsData.baleData,graphicsData.feetDataYSize,graphicsData.realYSize); myFillPolygon(rsa,wayPoint,step.isFeetLeft(i),graphicsData.heelData,graphicsData.feetDataYSize,graphicsData.realYSize); } } /* Show the animation outline */ if (rsa.showAnimationOutline) { for (int j=1;j<6;j++) { for (int i=0;i<previousStep.getNumberOfFeets();i++) { if (previousStep.isFemaleFoot(i) && !rsa.showLady) continue; if (!previousStep.isFemaleFoot(i) && !rsa.showGent) continue; if (rsa.selectedArray[i]) context.setForeground(animationSelectedColor); else context.setForeground(animationColor); GraphicsData graphicsData = getGraphicsData(previousStep,i); WayPoint feetCoord = previousStep.getFoot(i).getInterpolatedWayPoint(step.getStartingWayPoint(i),step.getFoot(i).isLongRotation(),j,6); myDrawPolygon(rsa,feetCoord,previousStep.isFeetLeft(i),graphicsData.heelData,graphicsData.feetDataYSize,graphicsData.realYSize, true); myDrawPolygon(rsa,feetCoord,previousStep.isFeetLeft(i),graphicsData.baleData,graphicsData.feetDataYSize,graphicsData.realYSize, true); } } } } /* Show every foot */ for (int i=0;i<step.getNumberOfFeets();i++) { boolean isSelected = rsa.selectedArray[i]; if (step.isFemaleFoot(i) && !rsa.showLady) continue; if (!step.isFemaleFoot(i) && !rsa.showGent) continue; WayPoint ballroomCoord; /* If inside an animation interpolate the position of the foot */ if (rsa.insideAnimation && nextStep != null) ballroomCoord = step.getFoot(i).getInterpolatedWayPoint(nextStep.getStartingWayPoint(i),nextStep.getFoot(i).isLongRotation(),rsa.animationNumber,rsa.animationMaxNumber); else ballroomCoord = step.getStartingWayPoint(i); drawFoot(rsa,step,ballroomCoord,i,isSelected); /* Draw the move line of the foot */ if (rsa.showPrevStep && previousStep != null && !rsa.insideAnimation) { context.setForeground(lineColor); ballroomCoord = previousStep.getStartingWayPoint(i); Point p1 = transformBallroomToPixel(rsa,ballroomCoord.x,ballroomCoord.y); Point p2; WayPoint wayPoint; for (int k=1;k<previousStep.getFoot(i).getNumOfWayPoints();k++) { wayPoint = previousStep.getFoot(i).getWayPoint(k); p2 = transformBallroomToPixel(rsa,wayPoint.x,wayPoint.y); context.drawLine(p1.x,p1.y,p2.x,p2.y); context.drawOval(p1.x-1,p1.y-1,2,2); p1 = p2; } wayPoint = step.getFoot(i).getStartingWayPoint(); p2 = transformBallroomToPixel(rsa,wayPoint.x,wayPoint.y); context.drawLine(p1.x,p1.y,p2.x,p2.y); context.drawOval(p1.x-1,p1.y-1,2,2); } } } /** * Return the coordinate info for a point given in view space. * * @param rsa * @param x * @param y * @param step * @return */ public CoordinateInfo getPixCoordinateInfo(RenderSceneArgs rsa, int x, int y, Step step) { CoordinateInfo ci = new CoordinateInfo(); for (int i=0;i<step.getNumberOfFeets();i++) { GraphicsData graphicsData = getGraphicsData(step,i); WayPoint feetCoord = step.getStartingWayPoint(i); int ballroomBaleX = graphicsData.baleX * graphicsData.realYSize / graphicsData.feetDataYSize; int ballroomBaleY = -graphicsData.baleY * graphicsData.realYSize / graphicsData.feetDataYSize; int ballroomHeelX = graphicsData.heelX * graphicsData.realYSize / graphicsData.feetDataYSize; int ballroomHeelY = -graphicsData.heelY * graphicsData.realYSize / graphicsData.feetDataYSize; if (myPolygonTest(rsa, feetCoord,step.isFeetLeft(i),graphicsData.baleData,graphicsData.feetDataYSize,graphicsData.realYSize,x,y)) { if (myPointRangeTest(rsa, feetCoord, ballroomBaleX, ballroomBaleY, x, y)) { Point p = transformCoords(feetCoord.x, feetCoord.y, feetCoord.a, ballroomHeelX, ballroomHeelY); Point p2 = transformCoords(feetCoord.x, feetCoord.y, feetCoord.a, 0, 0); p2.x -= p.x; p2.y -= p.y; ci.feetPart = FootPart.BALE; ci.rotationCenterBallroomPoint = p; ci.distance = Math.abs(ballroomBaleY); ci.feetIndex = i; break; } } else if (myPolygonTest(rsa, feetCoord,step.isFeetLeft(i),graphicsData.heelData,graphicsData.feetDataYSize,graphicsData.realYSize,x,y)) { if (myPointRangeTest(rsa, feetCoord,ballroomHeelX,ballroomHeelY,x,y)) { Point p = transformCoords(feetCoord.x, feetCoord.y, feetCoord.a, ballroomBaleX, ballroomBaleY); Point p2 = transformCoords(feetCoord.x, feetCoord.y, feetCoord.a, 0, 0); p2.x -= p.x; p2.y -= p.y; ci.feetPart = FootPart.HEEL; ci.rotationCenterBallroomPoint = p; ci.distance = Math.abs(ballroomHeelY); ci.feetIndex = i; break; } } for (int j=0;j<step.getFoot(i).getNumOfWayPoints();j++) { WayPoint waypoint = step.getFoot(i).getWayPoint(j); if (myPointRangeTest(rsa, waypoint, 0, 0, x, y)) { ci.feetIndex = i; ci.waypoint = j; break; } } } return ci; } }
package com.bls; import com.bls.AugmentedConfiguration.DbType; import com.bls.auth.basic.BasicAuthenticator; import com.bls.client.opendata.OpenDataClientModule; import com.bls.core.user.User; import com.bls.dao.ResetPasswordTokenDao; import com.bls.dao.UserDao; import com.bls.mongodb.MongodbModule; import com.bls.rdbms.RdbmsModule; import com.bls.resetpwd.InvalidateTokenTask; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.JSR310Module; import com.google.inject.Injector; import com.google.inject.Stage; import com.hubspot.dropwizard.guice.GuiceBundle; import com.hubspot.dropwizard.guice.GuiceBundle.Builder; import io.dropwizard.Application; import io.dropwizard.auth.AuthFactory; import io.dropwizard.auth.CachingAuthenticator; import io.dropwizard.auth.basic.BasicAuthFactory; import io.dropwizard.configuration.SubstitutingSourceProvider; import io.dropwizard.db.DataSourceFactory; import io.dropwizard.jersey.jackson.JacksonMessageBodyProvider; import io.dropwizard.migrations.MigrationsBundle; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import org.apache.commons.lang3.text.StrLookup; import org.apache.commons.lang3.text.StrSubstitutor; import org.glassfish.hk2.utilities.Binder; import static com.bls.AugmentedConfiguration.DBTYPE_PROPERTY_NAME; import static com.bls.AugmentedConfiguration.RDBMS_ENTITIES_PACKAGE; public class AugmentedApplication extends Application<AugmentedConfiguration> { private Injector injector; public static void main(final String[] args) throws Exception { new AugmentedApplication().run(args); } private static boolean isDbTypeSetToMongodb(final String dbTypePropertyValue) { return dbTypePropertyValue == null || DbType.MONGODB.name().equalsIgnoreCase(dbTypePropertyValue); } @Override public String getName() { return this.getClass().getSimpleName(); } @Override public void initialize(final Bootstrap<AugmentedConfiguration> bootstrap) { // Enable configuration variable substitution with system property values final StrSubstitutor systemPropertyStrSubstitutor = new StrSubstitutor(StrLookup.systemPropertiesLookup()); bootstrap.setConfigurationSourceProvider( new SubstitutingSourceProvider(bootstrap.getConfigurationSourceProvider(), systemPropertyStrSubstitutor)); // setup guice builder final Builder<AugmentedConfiguration> guiceConfiguration = GuiceBundle.<AugmentedConfiguration>newBuilder() .addModule(new AugmentedModule()) .addModule(new OpenDataClientModule()) .enableAutoConfig(getClass().getPackage().getName()) .setConfigClass(AugmentedConfiguration.class); // setup db backend based - choice i based on system property value if (isDbTypeSetToMongodb(systemPropertyStrSubstitutor.getVariableResolver().lookup(DBTYPE_PROPERTY_NAME))) { guiceConfiguration.addModule(new MongodbModule()); } else { bootstrap.addBundle(createMigrationBundle()); guiceConfiguration.addModule(new RdbmsModule<AugmentedConfiguration>(bootstrap) { @Override public DataSourceFactory getRealDataSourceFactory(final AugmentedConfiguration configuration) { return configuration.getRdbmsConfig(); } @Override public String getPackagesToScanForEntities() { return RDBMS_ENTITIES_PACKAGE; } }); } // eagerly inject all dependencies: note Stage.DEVELOPMENT it's a hack final GuiceBundle<AugmentedConfiguration> guiceBundle = guiceConfiguration.build(Stage.DEVELOPMENT); bootstrap.addBundle(guiceBundle); injector = guiceBundle.getInjector(); } private MigrationsBundle<AugmentedConfiguration> createMigrationBundle() { return new MigrationsBundle<AugmentedConfiguration>() { @Override public DataSourceFactory getDataSourceFactory(final AugmentedConfiguration configuration) { return configuration.getRdbmsConfig(); } }; } @Override public void run(final AugmentedConfiguration augmentedConfiguration, final Environment environment) throws Exception { registerAuthorizationProviders(augmentedConfiguration, environment); registerInvalidateTokensTask(augmentedConfiguration, environment); } private void registerAuthorizationProviders(final AugmentedConfiguration augmentedConfiguration, final Environment environment) { final UserDao userDao = injector.getInstance(UserDao.class); final BasicAuthenticator basicAuthenticator = new BasicAuthenticator(userDao); final CachingAuthenticator cachingAuthenticator = new CachingAuthenticator(environment.metrics(), basicAuthenticator, augmentedConfiguration.getAuthCacheBuilder()); final Binder authBinder = AuthFactory.binder(new BasicAuthFactory(cachingAuthenticator, "Basic auth", User.class)); environment.jersey().register(authBinder); } private void registerInvalidateTokensTask(final AugmentedConfiguration augmentedConfiguration, final Environment environment) { final ResetPasswordTokenDao tokenDao = injector.getInstance(ResetPasswordTokenDao.class); environment.admin().addTask(new InvalidateTokenTask(tokenDao)); } }
package bisq.apitest; import java.net.InetAddress; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import org.junit.jupiter.api.TestInfo; import static java.util.Arrays.stream; import static java.util.concurrent.TimeUnit.MILLISECONDS; import bisq.apitest.config.ApiTestConfig; import bisq.apitest.config.BisqAppConfig; import bisq.apitest.method.BitcoinCliHelper; import bisq.cli.GrpcStubs; public class ApiTestCase { protected static Scaffold scaffold; protected static ApiTestConfig config; protected static BitcoinCliHelper bitcoinCli; // gRPC service stubs are used by method & scenario tests, but not e2e tests. private static final Map<BisqAppConfig, GrpcStubs> grpcStubsCache = new HashMap<>(); public static void setUpScaffold(Enum<?>... supportingApps) throws InterruptedException, ExecutionException, IOException { scaffold = new Scaffold(stream(supportingApps).map(Enum::name) .collect(Collectors.joining(","))) .setUp(); config = scaffold.config; bitcoinCli = new BitcoinCliHelper((config)); } public static void setUpScaffold(String[] params) throws InterruptedException, ExecutionException, IOException { // Test cases needing to pass more than just an ApiTestConfig // --supportingApps option will use this setup method, but the // --supportingApps option will need to be passed too, with its comma // delimited app list value, e.g., "bitcoind,seednode,arbdaemon". scaffold = new Scaffold(params).setUp(); config = scaffold.config; bitcoinCli = new BitcoinCliHelper((config)); } public static void tearDownScaffold() { scaffold.tearDown(); } protected static GrpcStubs grpcStubs(BisqAppConfig bisqAppConfig) { if (grpcStubsCache.containsKey(bisqAppConfig)) { return grpcStubsCache.get(bisqAppConfig); } else { GrpcStubs stubs = new GrpcStubs(InetAddress.getLoopbackAddress().getHostAddress(), bisqAppConfig.apiPort, config.apiPassword); grpcStubsCache.put(bisqAppConfig, stubs); return stubs; } } protected static void genBtcBlocksThenWait(int numBlocks, long wait) { bitcoinCli.generateBlocks(numBlocks); sleep(wait); } protected static void sleep(long ms) { try { MILLISECONDS.sleep(ms); } catch (InterruptedException ignored) { // empty } } protected final String testName(TestInfo testInfo) { return testInfo.getTestMethod().isPresent() ? testInfo.getTestMethod().get().getName() : "unknown test name"; } }
package alignment.alignment_v2; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.json.JSONObject; import com.tinkerpop.rexster.client.RexProException; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class AlignTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AlignTest( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( AlignTest.class ); } /** * Tests loading, querying, and other basic operations for vertices, edges, properties. */ public void testLoad() { Align a = new Align(); a.removeAllVertices(); //a.removeAllEdges(); String test_graphson_verts = " {\"vertices\":[" + "{" + "\"_id\":\"CVE-1999-0002\"," + "\"_type\":\"vertex\","+ "\"source\":\"CVE\","+ "\"description\":\"Buffer overflow in NFS mountd gives root access to remote attackers, mostly in Linux systems.\","+ "\"references\":["+ "\"CERT:CA-98.12.mountd\","+ "\"http: "\"http: "\"XF:linux-mountd-bo\"],"+ "\"status\":\"Entry\","+ "\"score\":1.0"+ "},{"+ "\"_id\":\"CVE-1999-nnnn\"," + "\"_type\":\"vertex\","+ "\"source\":\"CVE\","+ "\"description\":\"test description asdf.\","+ "\"references\":["+ "\"http: "\"status\":\"Entry\","+ "\"score\":1.0"+ "}"+ "],"+ "\"edges\":["+ "{"+ "\"_id\":\"asdf\"," + "\"_inV\":\"CVE-1999-0002\"," + "\"_outV\":\"CVE-1999-nnnn\"," + "\"_label\":\"some_label_asdf\","+ "\"some_property\":\"some_value\""+ "}"+ "]}"; a.load(test_graphson_verts); try { //find this node, check some properties. String id = a.findVertId("CVE-1999-0002"); Map<String, Object> query_ret_map = a.getVertByID(id); assertEquals("Buffer overflow in NFS mountd gives root access to remote attackers, mostly in Linux systems.", query_ret_map.get("description")); String[] expectedRefs = {"CERT:CA-98.12.mountd","http: String[] actualRefs = ((ArrayList<String>)query_ret_map.get("references")).toArray(new String[0]); assertTrue(Arrays.equals(expectedRefs, actualRefs)); //find the other node, check its properties. String id2 = a.findVertId("CVE-1999-nnnn"); query_ret_map = a.getVertByID(id2); assertEquals("test description asdf.", query_ret_map.get("description")); expectedRefs = new String[]{"http: actualRefs = ((ArrayList<String>)query_ret_map.get("references")).toArray(new String[0]); assertTrue(Arrays.equals(expectedRefs, actualRefs)); //and now test the edge between them Object query_ret; query_ret = a.getClient().execute("g.v("+id2+").outE().inV();"); List<Map<String, Object>> query_ret_list = (List<Map<String, Object>>)query_ret; query_ret_map = query_ret_list.get(0); assertEquals(id, query_ret_map.get("_id")); a.removeAllVertices(); } catch (RexProException e) { fail("RexProException"); e.printStackTrace(); } catch (IOException e) { fail("IOException"); e.printStackTrace(); } } /** * Tests updating vertex properties */ public void testUpdate() { Align a = new Align(); a.removeAllVertices(); //a.removeAllEdges(); a.execute("g.commit();v = g.addVertex();v.setProperty(\"z\",55);v.setProperty(\"name\",\"testvert_55\");g.commit()"); String id = a.findVertId("testvert_55"); Map<String, Object> query_ret_map = a.getVertByID(id); assertEquals( "55", query_ret_map.get("z").toString()); Map<String, Object> newProps = new HashMap<String, Object>(); newProps.put("y", "33"); newProps.put("z", "44"); a.updateVert(id, newProps); query_ret_map = a.getVertByID(id); assertEquals("33", query_ret_map.get("y").toString()); assertEquals("44", query_ret_map.get("z").toString()); a.removeAllVertices(); } /** * Testing the keepNew option for AlignVertProps */ public void testAlignVertPropsKeepNew() { Align a = new Align(); a.removeAllVertices(); //a.removeAllEdges(); a.execute("g.commit();v = g.addVertex();v.setProperty(\"z\",55);v.setProperty(\"name\",\"testvert_align_props\");g.commit()"); String id = a.findVertId("testvert_align_props"); Map<String, String> mergeMethods = new HashMap<String,String>(); Map<String, Object> newProps = new HashMap<String,Object>(); String testVal, testProp; //add a new prop testVal = "aaaa"; newProps.put("testprop", testVal); a.alignVertProps(id, newProps, mergeMethods); testProp = (String)a.getVertByID(id).get("testprop"); assertEquals(testVal, testProp); //update a prop (keepNew) (always updates) mergeMethods.put("testprop", "keepNew"); testVal = "bbbb"; newProps.put("testprop", testVal); a.alignVertProps(id, newProps, mergeMethods); testProp = (String)a.getVertByID(id).get("testprop"); assertEquals(testVal, testProp); a.removeAllVertices(); } /** * Testing the appendList option for AlignVertProps */ public void testAlignVertPropsAppendList() { Align a = new Align(); a.removeAllVertices(); //a.removeAllEdges(); a.execute("g.commit();v = g.addVertex();v.setProperty(\"z\",55);v.setProperty(\"name\",\"testvert_align_props\");g.commit()"); String id = a.findVertId("testvert_align_props"); Map<String, String> mergeMethods = new HashMap<String,String>(); Map<String, Object> newProps = new HashMap<String,Object>(); String testVal, testProp; //update a prop (appendList) (always updates) (list/list case) mergeMethods.put("testproparray", "keepNew"); String[] testArrayVal = {"aaa", "bbb"}; newProps.put("testproparray", Arrays.asList(testArrayVal)); a.alignVertProps(id, newProps, mergeMethods); String[] testproparray = ((ArrayList<String>)a.getVertByID(id).get("testproparray")).toArray(new String[0]); assertTrue(Arrays.equals(testArrayVal, testproparray)); mergeMethods.put("testproparray", "appendList"); testArrayVal = new String[]{"ccc"}; newProps.put("testproparray", Arrays.asList(testArrayVal)); a.alignVertProps(id, newProps, mergeMethods); testproparray = ((ArrayList<String>)a.getVertByID(id).get("testproparray")).toArray(new String[0]); testArrayVal = new String[]{"aaa", "bbb", "ccc"}; assertTrue(Arrays.equals(testArrayVal, testproparray)); //update a prop (appendList) (always updates) (list/val case) mergeMethods.put("testproparray", "keepNew"); testArrayVal = new String[]{"aaa", "bbb"}; newProps.put("testproparray", Arrays.asList(testArrayVal)); a.alignVertProps(id, newProps, mergeMethods); testproparray = ((ArrayList<String>)a.getVertByID(id).get("testproparray")).toArray(new String[0]); assertTrue(Arrays.equals(testArrayVal, testproparray)); mergeMethods.put("testproparray", "appendList"); testVal = "ccc"; newProps.put("testproparray", testVal); a.alignVertProps(id, newProps, mergeMethods); testproparray = ((ArrayList<String>)a.getVertByID(id).get("testproparray")).toArray(new String[0]); testArrayVal = new String[]{"aaa", "bbb", "ccc"}; assertTrue(Arrays.equals(testArrayVal, testproparray)); //update a prop (appendList) (always updates) (val/list case) mergeMethods.put("testproparray", "keepNew"); testVal = "aaa"; newProps.put("testproparray", testVal); a.alignVertProps(id, newProps, mergeMethods); testProp = (String)a.getVertByID(id).get("testproparray"); assertTrue(Arrays.equals(testArrayVal, testproparray)); mergeMethods.put("testproparray", "appendList"); testArrayVal = new String[]{"bbb", "ccc"}; newProps.put("testproparray", Arrays.asList(testArrayVal)); a.alignVertProps(id, newProps, mergeMethods); testproparray = ((ArrayList<String>)a.getVertByID(id).get("testproparray")).toArray(new String[0]); testArrayVal = new String[]{"aaa", "bbb", "ccc"}; assertTrue(Arrays.equals(testArrayVal, testproparray)); //update a prop (appendList) (always updates) (val/val case) mergeMethods.put("testproparray", "keepNew"); testVal = "aaa"; newProps.put("testproparray", testVal); a.alignVertProps(id, newProps, mergeMethods); testProp = (String)a.getVertByID(id).get("testproparray"); assertTrue(Arrays.equals(testArrayVal, testproparray)); mergeMethods.put("testproparray", "appendList"); testVal = "bbb"; newProps.put("testproparray", testVal); a.alignVertProps(id, newProps, mergeMethods); testproparray = ((ArrayList<String>)a.getVertByID(id).get("testproparray")).toArray(new String[0]); testArrayVal = new String[]{"aaa", "bbb"}; assertTrue(Arrays.equals(testArrayVal, testproparray)); a.removeAllVertices(); } /** * Testing the keepUpdates option for AlignVertProps */ public void testAlignVertPropsKeepUpdates() { Align a = new Align(); a.removeAllVertices(); //a.removeAllEdges(); a.execute("g.commit();v = g.addVertex();v.setProperty(\"timestamp\",1000L);v.setProperty(\"name\",\"testvert_align_props\");g.commit()"); String id = a.findVertId("testvert_align_props"); Map<String, String> mergeMethods = new HashMap<String,String>(); Map<String, Object> newProps = new HashMap<String,Object>(); String testVal, testProp; //add a new prop testVal = "aaaa"; newProps.put("testprop", testVal); a.alignVertProps(id, newProps, mergeMethods); testProp = (String)a.getVertByID(id).get("testprop"); assertEquals(testVal, testProp); //update a prop (keepUpdates) (update case) mergeMethods.put("testprop", "keepUpdates"); testVal = "bbbb"; newProps.put("testprop", testVal); newProps.put("timestamp", 1001L); a.alignVertProps(id, newProps, mergeMethods); testProp = (String)a.getVertByID(id).get("testprop"); assertEquals(testVal, testProp); //update a prop (keepUpdates) (no update case) mergeMethods.put("testprop", "keepUpdates"); testVal = "cccc"; newProps.put("testprop", testVal); newProps.put("timestamp", 999L); a.alignVertProps(id, newProps, mergeMethods); testProp = (String)a.getVertByID(id).get("testprop"); testVal = "bbbb"; assertEquals(testVal, testProp); a.removeAllVertices(); } /** * Testing the keepConfidence option for AlignVertProps */ public void testAlignVertPropsKeepConfidence() { Align a = new Align(); a.removeAllVertices(); //a.removeAllEdges(); a.execute("g.commit();v = g.addVertex();v.setProperty(\"timestamp\",1000L);v.setProperty(\"name\",\"testvert_align_props\");g.commit()"); String id = a.findVertId("testvert_align_props"); Map<String, String> mergeMethods = new HashMap<String,String>(); Map<String, Object> newProps = new HashMap<String,Object>(); String testVal, testProp; //add a new prop testVal = "aaaa"; newProps.put("testprop", testVal); a.alignVertProps(id, newProps, mergeMethods); testProp = (String)a.getVertByID(id).get("testprop"); assertEquals(testVal, testProp); //update a prop (keepConfidence) (update case) mergeMethods.put("testprop", "keepConfidence"); //update a prop (keepConfidence) (no update case) mergeMethods.put("testprop", "keepConfidence"); //TODO: this test seems unfinished?? a.removeAllVertices(); } /** * Testing the keepConfidence option for AlignVertProps */ public void testMergeMethodsFromSchema() { Align a = new Align(); String ontologyStrTest = "{"+ " \"description\":\"The top level of the graph\","+ " \"type\":\"object\","+ " \"$schema\": \"http://json-schema.org/draft-03/schema\","+ " \"id\": \"gov.ornl.sava.stucco/graph\","+ " \"required\":false,"+ " \"properties\":{"+ " \"mode\": {"+ " \"type\": \"gov.ornl.sava.graphson.normal/graph/mode\""+ " },"+ " \"edges\": {"+ " \"title\":\"edges\","+ " \"description\":\"The list of edges in this graph\","+ " \"type\":\"array\","+ " \"id\": \"gov.ornl.sava.stucco/graph/edges\","+ " \"required\":false,"+ " \"items\":[ "+ " {"+ " \"id\": \"gov.ornl.sava.stucco/graph/edges/logsInTo\","+ " \"extends\": \"gov.ornl.sava.graphson.normal/graph/edges/base\","+ " \"title\":\"logsInTo\","+ " \"description\":\"'account' -'logsInTo'-> 'host'\","+ " \"properties\":{"+ " \"inVType\":{"+ " \"required\":true,"+ " \"enum\":[\"host\"]"+ " },"+ " \"outVType\":{"+ " \"required\":true,"+ " \"enum\":[\"account\"]"+ " }"+ " }"+ " }"+ " ]"+ " },"+ " \"vertices\": {"+ " \"title\":\"vertices\","+ " \"description\":\"The list of vertices in this graph\","+ " \"type\":\"array\","+ " \"id\": \"gov.ornl.sava.stucco/graph/vertices\","+ " \"required\":false,"+ " \"items\":["+ " {"+ " \"id\": \"gov.ornl.sava.stucco/graph/vertices/software\","+ " \"extends\": \"gov.ornl.sava.graphson.normal/graph/vertices/base\","+ " \"title\":\"software\","+ " \"description\":\"Any software components on a system, including OSes, applications, services, and libraries.\","+ " \"properties\":{"+ " \"vertexType\":{"+ " \"required\":true,"+ " \"enum\":[\"software\"]"+ " },"+ //merge fields here are all arbitrary, will not match the real ontology... " \"source\":{"+ " \"merge\":\"timestamp\","+ " \"required\":false"+ " },"+ " \"description\":{"+ " \"merge\":\"keepNew\","+ " \"required\":false"+ " },"+ " \"modifiedDate\":{"+ " \"merge\":\"keepUpdates\","+ " \"required\":false"+ " },"+ " \"vendor\":{"+ " \"merge\":\"timestamp\","+ " \"required\":false"+ " },"+ " \"product\":{"+ " \"merge\":\"appendList\","+ " \"required\":false"+ " },"+ " \"version\":{"+ //" \"merge\":\"keepNew\","+ " \"required\":false"+ " }"+ " }"+ " }"+ " ]"+ " }"+ " }"+ "}"; JSONObject ontology = new JSONObject(ontologyStrTest); Map<String, Map<String,String>> mergeMethods = Align.mergeMethodsFromSchema(ontology); assertEquals("timestamp", mergeMethods.get("software").get("source")); assertEquals("keepNew", mergeMethods.get("software").get("description")); assertEquals("keepUpdates", mergeMethods.get("software").get("modifiedDate")); assertEquals("timestamp", mergeMethods.get("software").get("vendor")); assertEquals("appendList", mergeMethods.get("software").get("product")); assertEquals("keepNew", mergeMethods.get("software").get("version")); a.removeAllVertices(); } /** * Tests loading & querying from realistic graphson file (~2M file) * @throws IOException */ public void testGraphsonFile() throws IOException { Align a = new Align(); a.removeAllVertices(); //a.removeAllEdges(); String test_graphson_verts = org.apache.commons.io.FileUtils.readFileToString(new File("resources/metasploit.json"), "UTF8"); //System.out.println(test_graphson_verts); a.load(test_graphson_verts); //test_graphson_verts = org.apache.commons.io.FileUtils.readFileToString(new File("resources/nvdcve-2.0-2002.json"), "UTF8"); //System.out.println(test_graphson_verts); //a.load(test_graphson_verts); try { //find this node, check some properties. String id = a.findVertId("CVE-2006-3459"); Map<String, Object> query_ret_map = a.getVertByID(id); assertEquals("Metasploit", query_ret_map.get("source")); assertEquals("vulnerability", query_ret_map.get("vertexType")); //find this other node, check its properties. String id2 = a.findVertId("exploit/apple_ios/email/mobilemail_libtiff"); query_ret_map = a.getVertByID(id2); assertEquals("Metasploit", query_ret_map.get("source")); assertEquals("malware", query_ret_map.get("vertexType")); assertEquals("exploit", query_ret_map.get("malwareType")); assertEquals("2006-08-01 00:00:00", query_ret_map.get("discoveryDate")); assertEquals("Apple iOS MobileMail LibTIFF Buffer Overflow", query_ret_map.get("shortDescription")); assertEquals("This module exploits a buffer overflow in the version of libtiff shipped with firmware versions 1.00, 1.01, 1.02, and 1.1.1 of the Apple iPhone. iPhones which have not had the BSD tools installed will need to use a special payload.", query_ret_map.get("fullDescription")); //and now test the edge between them Object query_ret; query_ret = a.getClient().execute("g.v("+id2+").outE().inV();"); List<Map<String, Object>> query_ret_list = (List<Map<String, Object>>)query_ret; query_ret_map = query_ret_list.get(0); assertEquals(id, query_ret_map.get("_id")); a.removeAllVertices(); } catch (RexProException e) { fail("RexProException"); e.printStackTrace(); } catch (IOException e) { fail("IOException"); e.printStackTrace(); } } }
package com.ztory.lib.sleek.layout; @Deprecated public class SL { @Deprecated public enum X { ABSOLUTE, WEST_OF, EAST_OF, POS_CENTER, PERCENT, PERCENT_CANVAS, COMPUTE, PARENT_LEFT, PARENT_RIGHT, PARENT_PERCENT } @Deprecated public enum Y { ABSOLUTE, NORTH_OF, SOUTH_OF, POS_CENTER, PERCENT, PERCENT_CANVAS, COMPUTE, PARENT_TOP, PARENT_BOTTOM, PARENT_PERCENT } @Deprecated public enum W { ABSOLUTE, MATCH_PARENT, PERCENT, PERCENT_CANVAS, COMPUTE } @Deprecated public enum H { ABSOLUTE, MATCH_PARENT, PERCENT, PERCENT_CANVAS, COMPUTE } }
package fr.insee.rmes.api.geo; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import fr.insee.rmes.api.AbstractApiTest; import fr.insee.rmes.modeles.geo.Commune; import fr.insee.rmes.modeles.geo.Country; import fr.insee.rmes.modeles.geo.Region; @ExtendWith(MockitoExtension.class) public class GeoAPITest extends AbstractApiTest { @InjectMocks private GeoAPI geoApi; private Commune commune = new Commune(); private Country country = new Country(); private Region region = new Region(); @Test public void givenGetCommune_whenCorrectRequest_andHeaderContentIsJson_thenResponseIsOk() { // Mock methods commune.setUri("something"); this.mockUtilsMethodsThenReturnOnePojo(commune, Boolean.TRUE); // Call method geoApi.getCommune("something", MediaType.APPLICATION_JSON, null); verify(mockResponseUtils, times(1)).produceResponse(Mockito.any(), Mockito.any()); } @Test public void givenGetCommune_whenCorrectRequest_andHeaderContentIsXml_thenResponseIsOk() { // Mock methods commune.setUri("something"); this.mockUtilsMethodsThenReturnOnePojo(commune, Boolean.TRUE); // Call method geoApi.getCommune("something", MediaType.APPLICATION_XML, null); verify(mockResponseUtils, times(1)).produceResponse(Mockito.any(), Mockito.any()); } @Test public void givenGetCountry_whenCorrectRequest_andHeaderContentIsJson_thenResponseIsOk() { // Call method country.setUri("something"); this.mockUtilsMethodsThenReturnOnePojo(country, Boolean.TRUE); // Call method geoApi.getCountry("something", MediaType.APPLICATION_JSON); verify(mockResponseUtils, times(1)).produceResponse(Mockito.any(), Mockito.any()); } @Test public void givenGetCountry_whenCorrectRequest_andHeaderContentIsXml_thenResponseIsOk() { // Call method country.setUri("something"); this.mockUtilsMethodsThenReturnOnePojo(country, Boolean.TRUE); // Mock methods geoApi.getCountry("something", MediaType.APPLICATION_XML); verify(mockResponseUtils, times(1)).produceResponse(Mockito.any(), Mockito.any()); } @Test public void givenGetRegion_whenCorrectRequestt_andHeaderContentIsJson_thenResponseIsOk() { // Mock methods region.setUri("something"); this.mockUtilsMethodsThenReturnOnePojo(region, Boolean.TRUE); // Call method geoApi.getRegion("something", MediaType.APPLICATION_JSON); verify(mockResponseUtils, times(1)).produceResponse(Mockito.any(), Mockito.any()); } @Test public void givenGetRegion_whenCorrectRequestt_andHeaderContentIsXml_thenResponseIsOk() { // Mock methods region.setUri("something"); this.mockUtilsMethodsThenReturnOnePojo(region, Boolean.TRUE); // Call method geoApi.getRegion("something", MediaType.APPLICATION_XML); verify(mockResponseUtils, times(1)).produceResponse(Mockito.any(), Mockito.any()); } @Test public void givenGetCommune_WhenCorrectRequest_thenResponseIsNotFound() { // Mock methods this.mockUtilsMethodsThenReturnOnePojo(commune, Boolean.FALSE); // Call method header content = xml Response response = geoApi.getCommune("something", MediaType.APPLICATION_XML, null); Assertions.assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus()); // Call method header content = json response = geoApi.getCommune("something", MediaType.APPLICATION_JSON, null); Assertions.assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus()); verify(mockResponseUtils, never()).produceResponse(Mockito.any(), Mockito.any()); } @Test public void givenGetCountry_WhenCorrectRequest_thenResponseIsNotFound() { // Mock methods this.mockUtilsMethodsThenReturnOnePojo(country, Boolean.FALSE); // Call method header content = xml Response response = geoApi.getCountry("something", MediaType.APPLICATION_XML); Assertions.assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus()); // Call method header content = json response = geoApi.getCountry("something", MediaType.APPLICATION_JSON); Assertions.assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus()); verify(mockResponseUtils, never()).produceResponse(Mockito.any(), Mockito.any()); } @Test public void givenGetRegion_WhenCorrectRequest_thenResponseIsNotFound() { // Mock methods this.mockUtilsMethodsThenReturnOnePojo(region, Boolean.FALSE); // Call method header content = xml Response response = geoApi.getRegion("something", MediaType.APPLICATION_XML); Assertions.assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus()); // Call method header content = json response = geoApi.getRegion("something", MediaType.APPLICATION_JSON); Assertions.assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus()); verify(mockResponseUtils, never()).produceResponse(Mockito.any(), Mockito.any()); } }
package net.sf.mzmine.util; import java.util.logging.Logger; import net.sf.mzmine.MZmineTest; import net.sf.mzmine.datamodel.DataPoint; import net.sf.mzmine.datamodel.RawDataFile; import net.sf.mzmine.datamodel.Scan; import org.junit.Assert; import org.junit.Test; public class ScanUtilsTest extends MZmineTest { private static final Logger logger = Logger.getLogger(ScanUtilsTest.class .getName()); /** * Test the isCentroided() method */ @Test public void testIsCentroided() throws Exception { RawDataFile files[] = project.getDataFiles(); Assert.assertNotEquals(0, files.length); int filesTested = 0; for (RawDataFile file : files) { boolean isCentroided; if (file.getName().startsWith("centroid")) isCentroided = true; else if (file.getName().startsWith("profile")) isCentroided = false; else continue; logger.finest("Checking autodetection of centroid/profile scans on file " + file.getName()); int scanNumbers[] = file.getScanNumbers(1); for (int scanNumber : scanNumbers) { Scan scan = file.getScan(scanNumber); DataPoint dataPoints[] = scan.getDataPoints(); boolean isCentroidedAutoDetection = ScanUtils .isCentroided(dataPoints); Assert.assertEquals("Scan " + file.getName() + "#" + scanNumber + " wrongly detected as " + (isCentroidedAutoDetection ? "centroid" : "profile") + ".", isCentroided, isCentroidedAutoDetection); } filesTested++; } // make sure we tested 10+ files Assert.assertTrue(filesTested > 10); } }
package org.amc.game.chess; import static org.junit.Assert.*; import org.amc.game.chess.view.ChessBoardView; import org.junit.Before; import org.junit.Test; import java.text.ParseException; public class EnPassantTest { private ChessGame chessGame; private ChessBoard board; private EnPassantRule enPassantRule; private ChessBoardFactory factory; private ChessGameFactory chessGamefactory; private ChessGamePlayer whitePlayer; private ChessGamePlayer blackPlayer; @Before public void setUp() { chessGamefactory = new StandardChessGameFactory(); whitePlayer = new RealChessGamePlayer(new HumanPlayer("White Player"), Colour.WHITE); blackPlayer = new RealChessGamePlayer(new HumanPlayer("Black Player"), Colour.BLACK); enPassantRule = EnPassantRule.getInstance(); factory = new ChessBoardFactoryImpl(new SimpleChessBoardSetupNotation()); chessGame = chessGamefactory.getChessGame(new ChessBoard(), whitePlayer, blackPlayer); board = chessGame.getChessBoard(); } @Test public void testIsEnPassantCapture() throws Exception { board = factory.getChessBoard("ke1:Ke8:pe5:Pf7"); chessGame = chessGamefactory.getChessGame(board, whitePlayer, blackPlayer); chessGame.changePlayer(); chessGame.move(blackPlayer, createMove("f7", "f5")); chessGame.changePlayer(); assertTrue(enPassantRule.isEnPassantCapture(chessGame, createMove("e5", "f6"))); } @Test public void testIsNotEnPassantCapture() { final String whitePawnStartPosition = "E5"; final String blackBishopStartPosition = "F7"; final String blackBishopEndPosition = "F5"; addPawnPieceToBoard(Colour.WHITE, whitePawnStartPosition); addChessPieceToBoard(BishopPiece.getBishopPiece(Colour.BLACK), blackBishopEndPosition); Move blackMove = createMove(blackBishopStartPosition, blackBishopEndPosition); Move whiteEnPassantMove = createMove(whitePawnStartPosition, "F6"); chessGame.allGameMoves.add(blackMove); assertFalse(enPassantRule.isEnPassantCapture(chessGame, whiteEnPassantMove)); } private void addPawnPieceToBoard(Colour colour, String location) { addChessPieceToBoard(PawnPiece.getPawnPiece(colour), location); } private void addChessPieceToBoard(ChessPiece piece, String location) { board.putPieceOnBoardAt(piece, new Location(location)); } private Move createMove(String start, String end) { return new Move(start + Move.MOVE_SEPARATOR + end); } private ChessPiece getPieceOnBoard(String location) { return board.getPieceFromBoardAt(new Location(location)); } @Test public void testIsNotEnPassantCaptureMoveLessTwo() { final String whitePawnStartPosition = "E5"; final String blackPawnStartPosition = "F7"; final String blackPawnEndPosition = "F6"; addPawnPieceToBoard(Colour.WHITE, whitePawnStartPosition); addPawnPieceToBoard(Colour.BLACK, blackPawnEndPosition); Move blackMove = createMove(blackPawnStartPosition, blackPawnEndPosition); Move whiteEnPassantMove = createMove(whitePawnStartPosition, "F6"); chessGame.allGameMoves.add(blackMove); assertFalse(enPassantRule.isEnPassantCapture(chessGame, whiteEnPassantMove)); } @Test public void testIsNotEnPassantCaptureAfterTwoSquareMove() { final String whitePawnStartPosition = "E5"; final String blackPawnStartPosition = "F7"; final String blackPawnEndPosition = "F5"; addPawnPieceToBoard(Colour.WHITE, whitePawnStartPosition); addPawnPieceToBoard(Colour.BLACK, blackPawnEndPosition); Move blackMove = createMove(blackPawnStartPosition, blackPawnEndPosition); Move whiteEnPassantMove = createMove(whitePawnStartPosition, "D6"); chessGame.allGameMoves.add(blackMove); assertFalse(enPassantRule.isEnPassantCapture(chessGame, whiteEnPassantMove)); } @Test public void testIsNotEnPassantCaptureAfterTwoSeparateSquareMove() { final String whitePawnStartPosition = "E5"; final String blackPawnStartPosition = "F6"; final String blackPawnEndPosition = "F5"; addPawnPieceToBoard(Colour.WHITE, whitePawnStartPosition); addPawnPieceToBoard(Colour.BLACK, blackPawnEndPosition); Move blackMove = createMove(blackPawnStartPosition, blackPawnEndPosition); Move whiteEnPassantMove = createMove(whitePawnStartPosition, "D6"); chessGame.allGameMoves.add(blackMove); assertFalse(enPassantRule.isEnPassantCapture(chessGame, whiteEnPassantMove)); } @Test public void TestWhiteEnPassantCapture() throws IllegalMoveException { final String whitePawnStartPosition = "E5"; final String whitePawnEndPosition = "F6"; final String blackPawnStartPosition = "F7"; final String blackPawnEndPosition = "F5"; final PawnPiece whitePawn = PawnPiece.getPawnPiece(Colour.WHITE); addChessPieceToBoard(whitePawn, whitePawnStartPosition); addPawnPieceToBoard(Colour.BLACK, blackPawnEndPosition); Move blackMove = createMove(blackPawnStartPosition, blackPawnEndPosition); Move whiteEnPassantMove = createMove(whitePawnStartPosition, "F6"); chessGame.allGameMoves.add(blackMove); enPassantRule.applyRule(chessGame, whiteEnPassantMove); assertTrue(getPieceOnBoard(whitePawnEndPosition) .equals(whitePawn.moved())); assertNull(getPieceOnBoard(blackPawnEndPosition)); } @Test public void TestBlackEnPassantCapture() throws IllegalMoveException { PawnPiece blackPawn = PawnPiece.getPawnPiece(Colour.BLACK); final String whitePawnStartPosition = "F2"; final String whitePawnEndPosition = "F4"; final String blackPawnStartPosition = "G4"; final String blackPawnEndPosition = "F3"; addChessPieceToBoard(blackPawn, blackPawnStartPosition); addPawnPieceToBoard(Colour.WHITE, whitePawnEndPosition); Move blackEnPassantMove = createMove(blackPawnStartPosition, blackPawnEndPosition); Move whiteMove = createMove(whitePawnStartPosition, whitePawnEndPosition); chessGame.allGameMoves.add(whiteMove); enPassantRule.applyRule(chessGame, blackEnPassantMove); assertTrue(getPieceOnBoard(blackPawnEndPosition).equals(blackPawn.moved())); assertNull(getPieceOnBoard(whitePawnEndPosition)); } @Test public void notMoveEnPassantCapture() { BishopPiece bishop = BishopPiece.getBishopPiece(Colour.WHITE); final String startSquare = "A2"; final String endSquare = "B3"; Move move = createMove(startSquare, endSquare); addChessPieceToBoard(bishop, startSquare); assertFalse(enPassantRule.isEnPassantCapture(chessGame, move)); } @Test public void enpassantCaptureNotPossibleAsKingWouldBeInCheck() throws ParseException, IllegalMoveException { chessGame = new StandardChessGameFactory().getChessGame( factory.getChessBoard("Ke8:Rd8:Rf8:Pd7:Pf7:Pe4:qe1:kd1:pd2"), whitePlayer, blackPlayer); board = chessGame.getChessBoard(); ChessBoardView view = new ChessBoardView(board); try { chessGame.move(whitePlayer, createMove("D2", "D4")); chessGame.move(blackPlayer, createMove("E4", "D3")); } catch (IllegalMoveException e) { view.displayTheBoard(); } assertEquals(getPieceOnBoard("E4").getClass(), PawnPiece.class); assertEquals(getPieceOnBoard("D4").getClass(), PawnPiece.class); } }
package org.iiitb.os.os_proj; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import org.iiitb.os.os_proj.commands.Cat; import org.iiitb.os.os_proj.commands.Cd; import org.iiitb.os.os_proj.commands.File; import org.iiitb.os.os_proj.commands.Filesize; import org.iiitb.os.os_proj.commands.Head; import org.iiitb.os.os_proj.commands.ICommand; import org.iiitb.os.os_proj.commands.Locate; import org.iiitb.os.os_proj.commands.Ls; import org.iiitb.os.os_proj.commands.Mkdir; import org.iiitb.os.os_proj.commands.Mv; import org.iiitb.os.os_proj.commands.Pwd; import org.iiitb.os.os_proj.commands.Rmdir; import org.iiitb.os.os_proj.commands.Tail; import org.iiitb.os.os_proj.commands.Touch; import org.iiitb.os.os_proj.controller.Controller; import org.junit.Ignore; import org.junit.Test; @Ignore public class TestCommand{ @Test public void testLocate(){ Locate locate=new Locate(); ArrayList<String> searchPath=new ArrayList<String>(); ArrayList<String> result=new ArrayList<String>(); UserFile u=new UserFile(); u.setName("abcdefgh"); u.setPath("iiitb"); u.setDirectory(true); ICommand.mongoConnect.createFile(u); searchPath.add("abcdefgh"); result=locate.runCommand(searchPath); if(result.get(0)==ICommand.SUCCESS){ assertEquals(ICommand.SUCCESS,result.get(0)); assertEquals(u.getPath(),result.get(1)); } else assertEquals(ICommand.FAILURE,result.get(0)); } @Test public void testMv(){ Mv m=new Mv(); ArrayList<String> al=new ArrayList<String>(); ArrayList<String> result=new ArrayList<String>(); al.add("kanchu17"); al.add("neetika"); result=m.runCommand(al); if(result.get(0)==ICommand.SUCCESS) assertEquals(ICommand.SUCCESS,result.get(0)); //assertEquals(); else assertEquals(ICommand.FAILURE,result.get(0)); } @Test public void testMkdir(){ Mkdir m=new Mkdir(); ArrayList<String> al=new ArrayList<String>(); ArrayList<String> result=new ArrayList<String>(); al.add("neetika"); result=m.runCommand(al); ArrayList<UserFile> receivedFile = new ArrayList<UserFile>(); Map<String, String> constraints = new HashMap<String, String>(); constraints.put("name", "neetika"); constraints.put("path", Controller.CURRENT_PATH); constraints.put("isDirectory", "true"); receivedFile = ICommand.mongoConnect.getFiles(constraints); if(result.get(0)==ICommand.SUCCESS){ assertEquals(ICommand.SUCCESS,result.get(0)); assertTrue(receivedFile.size()>0);} else assertEquals(ICommand.FAILURE,result.get(0)); } @Test public void testRmdir(){ Rmdir m=new Rmdir(); ArrayList<String> al=new ArrayList<String>(); ArrayList<String> result=new ArrayList<String>(); al.add("kanchu17"); result=m.runCommand(al); ArrayList<UserFile> receivedFile = new ArrayList<UserFile>(); Map<String, String> constraints = new HashMap<String, String>(); constraints.put("name", "kanchu17"); constraints.put("path", Controller.CURRENT_PATH); constraints.put("isDirectory", "true"); receivedFile = ICommand.mongoConnect.getFiles(constraints); if(result.get(0)==ICommand.SUCCESS){ assertEquals(ICommand.SUCCESS,result.get(0)); assertTrue(receivedFile.size()==0);} else assertEquals(ICommand.FAILURE,result.get(0)); } @Test public void testCat(){ Cat c=new Cat(); ArrayList<UserFile> receivedFile = new ArrayList<UserFile>(); Map<String, String> constraints = new HashMap<String, String>(); constraints.put("name", "navin"); constraints.put("path", "/home/kanchan"); constraints.put("isDirectory", "false"); receivedFile = ICommand.mongoConnect.getFiles(constraints); System.out.println(receivedFile.get(0)); String expecteddata = receivedFile.get(0).getData(); System.out.println(expecteddata); ArrayList<String> al=new ArrayList<String>(); ArrayList<String> result=new ArrayList<String>(); al.add("navin"); result=c.runCommand(al); if(result.get(0)==ICommand.SUCCESS){ assertEquals(ICommand.SUCCESS,result.get(0)); assertEquals(expecteddata,result.get(1));} else assertEquals(ICommand.FAILURE,result.get(0)); } @Test public void testFile(){ File f=new File(); ArrayList<String> al=new ArrayList<String>(); ArrayList<String> result=new ArrayList<String>(); ArrayList<UserFile> receivedFile = new ArrayList<UserFile>(); Map<String, String> constraints = new HashMap<String, String>(); constraints.put("name", "kanchu17"); constraints.put("path", Controller.CURRENT_PATH); constraints.put("isDirectory", "false"); receivedFile = ICommand.mongoConnect.getFiles(constraints); String s=String.valueOf(receivedFile.get(0).getFiletypeId()); al.add("kanchu17"); result=f.runCommand(al); if(result.get(0)==ICommand.SUCCESS){ assertEquals(ICommand.SUCCESS,result.get(0)); assertEquals(s,result.get(1));} else assertEquals(ICommand.FAILURE,result.get(0)); } @Test public void testFileSize(){ Filesize f=new Filesize(); ArrayList<String> al=new ArrayList<String>(); ArrayList<String> result=new ArrayList<String>(); ArrayList<UserFile> receivedFile = new ArrayList<UserFile>(); Map<String, String> constraints = new HashMap<String, String>(); constraints.put("name", "kanchu17"); constraints.put("path", Controller.CURRENT_PATH); constraints.put("isDirectory", "false"); receivedFile = ICommand.mongoConnect.getFiles(constraints); String s=String.valueOf(receivedFile.get(0).getFile_size()); al.add("kanchu17"); result=f.runCommand(al); if(result.get(0)==ICommand.SUCCESS){ assertEquals(ICommand.SUCCESS,result.get(0)); assertEquals(s,result.get(1));} else assertEquals(ICommand.FAILURE,result.get(0)); } @Test public void testHead(){ Head h=new Head(); ArrayList<String> al=new ArrayList<String>(); ArrayList<String> result=new ArrayList<String>(); Map<String, String> constraints = new HashMap<String, String>(); constraints.put("path", Controller.CURRENT_PATH); constraints.put("name", "kanchu17"); constraints.put("isDirectory", "false"); String expecteddata = null; ArrayList<UserFile> resFiles = ICommand.mongoConnect.getFiles(constraints); if(resFiles != null) //File exists... display data { String data = resFiles.get(0).getData(); String split_data[] = data.split("\n"); if(split_data.length <= 100) expecteddata=data; else { String data_head = ""; for(int i = 0; i < 100; i++) data_head += split_data[i]; expecteddata=data_head; } } al.add("kanchu17"); result=h.runCommand(al); if(result.get(0)==ICommand.SUCCESS){ assertEquals(ICommand.SUCCESS,result.get(0)); assertEquals(expecteddata,result.get(1)); } else assertEquals(ICommand.FAILURE,result.get(0)); } @Test public void testTail(){ Tail t=new Tail(); ArrayList<String> al=new ArrayList<String>(); ArrayList<String> result=new ArrayList<String>(); //Search if file exists Map<String, String> constraints = new HashMap<String, String>(); constraints.put("path", Controller.CURRENT_PATH); constraints.put("name", "kanchu17"); constraints.put("isDirectory", "false"); ArrayList<UserFile> resFiles = ICommand.mongoConnect.getFiles(constraints); String expecteddata=null; if(resFiles != null) //File exists... display data { String data = resFiles.get(0).getData(); String split_data[] = data.split("\n"); if(split_data.length <= 100) expecteddata=data; else { String data_head = ""; for(int i = (split_data.length - 100); i < split_data.length; i++) data_head += split_data[i]; expecteddata=data_head; } } al.add("kanchu17"); result=t.runCommand(al); if(result.get(0)==ICommand.SUCCESS){ assertEquals(ICommand.SUCCESS,result.get(0)); assertEquals(expecteddata,result.get(1)); } else assertEquals(ICommand.FAILURE,result.get(0)); } @Test public void testPwd(){ Pwd p=new Pwd(); ArrayList<String> al=new ArrayList<String>(); ArrayList<String> result=new ArrayList<String>(); result=p.runCommand(al); if(result.get(0)==ICommand.SUCCESS){ assertEquals(ICommand.SUCCESS,result.get(0)); assertEquals(Controller.CURRENT_PATH,result.get(1));} else assertEquals(ICommand.FAILURE,result.get(0)); } @Test public void testTouch(){ Touch t=new Touch(); ArrayList<String> al=new ArrayList<String>(); ArrayList<String> result=new ArrayList<String>(); ArrayList<UserFile> receivedFile = new ArrayList<UserFile>(); Map<String, String> constraints = new HashMap<String, String>(); al.add("kanchu17"); result=t.runCommand(al); constraints.put("name", "kanchu17"); constraints.put("path", Controller.CURRENT_PATH); receivedFile = ICommand.mongoConnect.getFiles(constraints); if(result.get(0)==ICommand.SUCCESS){ assertEquals(ICommand.SUCCESS,result.get(0)); assertTrue(receivedFile.size()>0);} else assertEquals(ICommand.FAILURE,result.get(0)); } @Test public void testCd(){ Cd c=new Cd(); ArrayList<String> al=new ArrayList<String>(); ArrayList<String> result=new ArrayList<String>(); Map<String, String> constraints = new HashMap<String, String>(); constraints.put("path", Controller.CURRENT_PATH); constraints.put("name", "kanchu17");; constraints.put("isDirectory", "true"); ArrayList<UserFile> resFiles = ICommand.mongoConnect.getFiles(constraints); al.add("kanchu17"); result=c.runCommand(al); if(result.get(0)==ICommand.SUCCESS){ assertEquals(ICommand.SUCCESS,result.get(0)); assertEquals(Controller.CURRENT_PATH += "/" + resFiles.get(0).getPath(),result.get(1)); } else assertEquals(ICommand.FAILURE,result.get(0)); } @Test public void testLs(){ Ls l=new Ls(); ArrayList<String> al = new ArrayList<String>(); ArrayList<String> result = new ArrayList<String>(); Map<String, String> constraints = new HashMap<String, String>(); constraints.put("path", Controller.CURRENT_PATH); ArrayList<UserFile> resFiles = ICommand.mongoConnect.getFiles(constraints); ArrayList<String> actual = new ArrayList<String>(); while(resFiles != null){ for(UserFile u: resFiles) actual.add(u.getName()); } result=l.runCommand(al); if(result.get(0)==ICommand.SUCCESS){ assertEquals(ICommand.SUCCESS,result.get(0)); assertEquals(actual,result); } else assertEquals(ICommand.FAILURE,result.get(0)); } }
package org.jdbdt; import static org.junit.Assert.*; import static org.jdbdt.JDBDT.*; import static org.jdbdt.TestUtil.*; import java.sql.SQLException; import java.util.function.Consumer; import org.junit.Before; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import org.junit.runners.MethodSorters; @SuppressWarnings("javadoc") @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class DataSetBuilderCoreTest extends DBTestCase { @Rule public TestName testName = new TestName(); private static Table table; private static final ColumnFiller<?> DUMMY_FILLER = new ColumnFiller<Object>() { @Override public Object next() { return null; } }; @BeforeClass public static void globalSetup() throws SQLException { table = getDB().table(UserDAO.TABLE_NAME).columns(UserDAO.COLUMNS); } DataSetBuilder theSUT; @Before public void setUp() { theSUT = builder(table); } private static void assertEmptyDataSet(DataSetBuilder sut) { assertEquals("filler count", 0, sut.fillerCount()); assertEquals("empty row list", 0, sut.data().size()); } @Test public void testConstruction() { assertEmptyDataSet(theSUT); } private static void invalidUse (DataSetBuilder sut, Consumer<DataSetBuilder> operation, Consumer<DataSetBuilder> assertions) { expectException(InvalidOperationException.class, () -> operation.accept(sut)); assertions.accept(sut); } private void invalidFiller(String c, ColumnFiller<?> f) { invalidUse(theSUT, sut -> sut.set(c,f), DataSetBuilderCoreTest::assertEmptyDataSet ); } @Test public void testInvalidFiller1() { invalidFiller("InvalidField", DUMMY_FILLER); } @Test public void testInvalidFiller2() { invalidFiller("login", null); } @Test public void testInvalidFiller3() { invalidFiller(null, DUMMY_FILLER); } @Test public void testValidFiller() { theSUT.value("login", "root"); assertEquals("fillers set", 1, theSUT.fillerCount()); } @Test public void testFillerReset() { theSUT.value("login", "root"); theSUT.reset(); assertEquals("fillers set", 0, theSUT.fillerCount()); } @Test public void testAllFillersSet() throws SQLException { User u = getDAO().query(EXISTING_DATA_ID1); Object[] row = getConversion().convert(u); for (int c = 0; c < row.length; c++) { theSUT.value(UserDAO.COLUMNS[c], row[c]); } assertEquals("fillers set", UserDAO.COLUMNS.length, theSUT.fillerCount()); assertEquals("no rows", 0, theSUT.data().size()); } private void checkMissingFillers(int N) { invalidUse (theSUT, sut -> sut.generate(1), sut -> { assertEquals("fillers set", N, sut.fillerCount()); assertEquals("no rows", 0, sut.data().size()); }); } @Test public void testMissingFillers0() throws SQLException { checkMissingFillers(0); } @Test public void testMissingFillers1() throws SQLException { theSUT.value("login", "root"); checkMissingFillers(1); } @Test public void testMissingFillersAllButOne() throws SQLException { User u = getDAO().query(EXISTING_DATA_ID1); Object[] row = getConversion().convert(u); for (int c = 0; c < row.length-1; c++) { theSUT.value(UserDAO.COLUMNS[c], row[c]); } checkMissingFillers(row.length-1); } @Test public void testGenerate0() throws SQLException { User u = getDAO().query(EXISTING_DATA_ID1); Object[] row = getConversion().convert(u); for (int c = 0; c < row.length; c++) { theSUT.value(UserDAO.COLUMNS[c], row[c]); } invalidUse (theSUT, sut -> sut.generate(0), sut -> { assertEquals("fillers set", UserDAO.COLUMNS.length, sut.fillerCount()); assertEquals("no rows", 0, sut.data().size()); }); } @Test public void testGenerateMinus1() throws SQLException { User u = getDAO().query(EXISTING_DATA_ID1); Object[] row = getConversion().convert(u); for (int c = 0; c < row.length; c++) { theSUT.value(UserDAO.COLUMNS[c], row[c]); } invalidUse (theSUT, sut -> sut.generate(-1), sut -> { assertEquals("fillers set", UserDAO.COLUMNS.length, sut.fillerCount()); assertEquals("no rows", 0, sut.data().size()); }); } private void testSimpleGeneration(final int N) throws SQLException { User u = getDAO().query(EXISTING_DATA_ID1); Object[] rowData = getConversion().convert(u); DataSet expectedRows = new DataSet(table); for (int i=0; i < N; i++) { expectedRows.addRow(new RowImpl(rowData)); } for (int col = 0; col < rowData.length; col++) { theSUT.value(UserDAO.COLUMNS[col], rowData[col]); } theSUT.generate(N); assertEquals("fillers set", UserDAO.COLUMNS.length, theSUT.fillerCount()); assertTrue(expectedRows.sameDataAs(theSUT.data())); } @Test public void testGenerateOneRow() throws SQLException { testSimpleGeneration(1); } @Test public void testGenerate100Rows() throws SQLException { testSimpleGeneration(100); } }
package org.myrobotlab.test; import java.io.IOException; import java.text.ParseException; import java.util.Set; import java.util.TreeSet; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.rules.TestName; import org.myrobotlab.framework.Platform; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.service.Runtime; import org.slf4j.Logger; public class AbstractTest { private static long coolDownTimeMs = 2000; /** * cached internet test value for tests */ static Boolean hasInternet = null; public final static Logger log = LoggerFactory.getLogger(AbstractTest.class); static private boolean logWarnTestHeader = false; private static boolean releaseRemainingServices = true; private static boolean releaseRemainingThreads = false; static transient Set<Thread> threadSetStart = null; protected boolean printMethods = true; // private static boolean useDeprecatedThreadStop = false; @Rule public final TestName testName = new TestName(); static public String simpleName; private static boolean lineFeedFooter = true; private static Platform platform = Platform.getLocalInstance(); public String getSimpleName() { return simpleName; } protected String getName() { return testName.getMethodName(); } static public boolean hasInternet() { if (hasInternet == null) { hasInternet = Runtime.hasInternet(); } return hasInternet; } static public boolean isHeadless() { return Runtime.isHeadless(); } static public void setVirtual(boolean b) { platform.setVirtual(b); } static public boolean isVirtual() { return platform.isVirtual(); } public static void main(String[] args) { try { AbstractTest test = new AbstractTest(); // LoggingFactory.init("INFO"); ChaosMonkey.giveToMonkey(test, "testFunction"); ChaosMonkey.giveToMonkey(test, "testFunction"); ChaosMonkey.giveToMonkey(test, "testFunction"); ChaosMonkey.startMonkeys(); ChaosMonkey.monkeyReport(); log.info("here"); } catch (Exception e) { log.error("main threw", e); } } // super globals - probably better not to use the mixin - but just initialize // statics in the // constructor of the AbstractTest @BeforeClass public static void setUpAbstractTest() throws Exception { // make testing environment "virtual" setVirtual(true); String junitLogLevel = System.getProperty("junit.logLevel"); if (junitLogLevel != null) { Runtime.setLogLevel(junitLogLevel); } else { Runtime.setLogLevel("warn"); // error instead ? } log.info("setUpAbstractTest"); if (threadSetStart == null) { threadSetStart = Thread.getAllStackTraces().keySet(); } } static public void sleep(int sleepMs) { try { Thread.sleep(sleepMs); } catch (InterruptedException e) { // don't care } } public static void sleep(long sleepTimeMs) { try { Thread.sleep(coolDownTimeMs); } catch (Exception e) { } } @AfterClass public static void tearDownAbstractTest() throws Exception { log.info("tearDownAbstractTest"); if (releaseRemainingServices) { releaseServices(); } if (logWarnTestHeader) { log.warn("=========== finished test {} ===========", simpleName); } if (lineFeedFooter) { System.out.println(); } } protected void installAll() throws ParseException, IOException { Runtime.install(); } public static void releaseServices() { // services to be cleaned up/released String[] services = Runtime.getServiceNames(); Set<String> releaseServices = new TreeSet<>(); for (String service : services) { // don't kill runtime - although in the future i hope this is possible if (!"runtime".equals(service)) { releaseServices.add(service); log.info("service {} left in registry - releasing", service); Runtime.releaseService(service); } } if (releaseServices.size() > 0) { log.warn("attempted to release the following {} services [{}]", releaseServices.size(), String.join(",", releaseServices)); log.warn("cooling down for {}ms for dependencies with asynchronous shutdown", coolDownTimeMs); sleep(coolDownTimeMs); } // check threads - kill stragglers // Set<Thread> stragglers = new HashSet<Thread>(); Set<Thread> threadSetEnd = Thread.getAllStackTraces().keySet(); Set<String> threadsRemaining = new TreeSet<>(); for (Thread thread : threadSetEnd) { if (!threadSetStart.contains(thread) && !"runtime_outbox_0".equals(thread.getName()) && !"runtime".equals(thread.getName())) { if (releaseRemainingThreads) { log.warn("interrupting thread {}", thread.getName()); thread.interrupt(); /* * if (useDeprecatedThreadStop) { thread.stop(); } */ } else { // log.warn("thread {} marked as straggler - should be killed", // thread.getName()); threadsRemaining.add(thread.getName()); } } } if (threadsRemaining.size() > 0) { log.warn("{} straggling threads remain [{}]", threadsRemaining.size(), String.join(",", threadsRemaining)); } log.info("finished the killing ..."); } public AbstractTest() { simpleName = this.getClass().getSimpleName(); if (logWarnTestHeader) { log.warn("=========== starting test {} ===========", this.getClass().getSimpleName()); } } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } public void testFunction() { log.info("tested testFunction"); } }
package org.osiam.client; import com.github.springtestdbunit.DbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseSetup; import com.github.springtestdbunit.annotation.DatabaseTearDown; import com.github.springtestdbunit.annotation.ExpectedDatabase; import com.github.springtestdbunit.assertion.DatabaseAssertionMode; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.osiam.resources.scim.Extension; import org.osiam.resources.scim.User; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertEquals; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/context.xml") @TestExecutionListeners({DependencyInjectionTestExecutionListener.class, DbUnitTestExecutionListener.class}) @DatabaseSetup(value = "/database_seed_extensions.xml") //@DatabaseTearDown(value = "/database_seed_extensions.xml", type = DatabaseOperation.DELETE_ALL) public class ScimExtensionIT extends AbstractIntegrationTestBase { private static final String URN = "extension"; private static final String EXISTING_USER_UUID = "df7d06b2-b6ee-42b1-8c1b-4bd1176cc8d4"; private Map<String, String> extensionData; private Map<String, String> extensionDataToPatch; @Before public void setUp() { extensionData = new HashMap<>(); extensionData.put("gender", "male"); extensionData.put("size", "1337"); extensionData.put("birth", "Wed Oct 30 16:54:00 CET 1985"); extensionData.put("newsletter", "false"); extensionData.put("married", "false"); extensionDataToPatch = new HashMap<>(); extensionDataToPatch.put("gender", "female"); extensionDataToPatch.put("size", "0000"); extensionDataToPatch.put("birth", "Wed Nov 30 18:34:00 CET 1979"); extensionDataToPatch.put("newsletter", "true"); extensionDataToPatch.put("married", "true"); } @Test @ExpectedDatabase(value = "/database_expected_extensions.xml", assertionMode = DatabaseAssertionMode.NON_STRICT) public void adding_a_user_with_extension_data_to_database_works() { Extension extension = new Extension(URN, extensionData); User user = new User.Builder("userName") .setPassword("password") .addExtension(URN, extension) .build(); String uuid = oConnector.createUser(user, accessToken).getId(); User storedUser = oConnector.getUser(uuid, accessToken); Extension storedExtension = storedUser.getExtension(URN); for (Map.Entry<String, String> entry : extensionData.entrySet()) { assertEquals(entry.getValue(), storedExtension.getField(entry.getKey())); } } @Test public void replacing_a_user_with_extension_data_to_database_works() { User existingUser = oConnector.getUser(EXISTING_USER_UUID, accessToken); extensionData.put("gender", "female"); Extension extension = existingUser.getExtension(URN); extension.setField("gender", "female"); oConnector.replaceUser(existingUser, accessToken); User storedUser = oConnector.getUser(EXISTING_USER_UUID, accessToken); Extension storedExtension = storedUser.getExtension(URN); for (Map.Entry<String, String> entry : extensionData.entrySet()) { assertEquals(entry.getValue(), storedExtension.getField(entry.getKey())); } } @Test public void updating_a_user_with_extension_data_to_database_works() { Extension extension = new Extension(URN, extensionDataToPatch); User patchUser = new User.Builder() .addExtension(URN, extension) .build(); oConnector.updateUser(EXISTING_USER_UUID, patchUser, accessToken); User storedUser = oConnector.getUser(EXISTING_USER_UUID, accessToken); Extension storedExtension = storedUser.getExtension(URN); for (Map.Entry<String, String> entry : extensionDataToPatch.entrySet()) { assertEquals(entry.getValue(), storedExtension.getField(entry.getKey())); } } }
package org.apache.lucene.search; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.index.Term; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.store.RAMDirectory; import org.apache.lucene.analysis.SimpleAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import junit.framework.TestCase; import java.io.IOException; public class TestWildcard extends TestCase { public TestWildcard(String name) { super(name); } public void testAsterisk() throws IOException { RAMDirectory indexStore = new RAMDirectory(); IndexWriter writer = new IndexWriter(indexStore, new SimpleAnalyzer(), true); Document doc1 = new Document(); Document doc2 = new Document(); doc1.add(Field.Text("body", "metal")); doc2.add(Field.Text("body", "metals")); writer.addDocument(doc1); writer.addDocument(doc2); writer.optimize(); IndexSearcher searcher = new IndexSearcher(indexStore); Query query1 = new TermQuery(new Term("body", "metal")); Query query2 = new WildcardQuery(new Term("body", "metal*")); Query query3 = new WildcardQuery(new Term("body", "m*tal")); Query query4 = new WildcardQuery(new Term("body", "m*tal*")); Hits result; result = searcher.search(query1); assertEquals(1, result.length()); result = searcher.search(query2); assertEquals(2, result.length()); result = searcher.search(query3); assertEquals(1, result.length()); result = searcher.search(query4); assertEquals(2, result.length()); writer.close(); } public void testQuestionmark() throws IOException { RAMDirectory indexStore = new RAMDirectory(); IndexWriter writer = new IndexWriter(indexStore, new SimpleAnalyzer(), true); Document doc1 = new Document(); Document doc2 = new Document(); Document doc3 = new Document(); Document doc4 = new Document(); doc1.add(Field.Text("body", "metal")); doc2.add(Field.Text("body", "metals")); doc3.add(Field.Text("body", "mXtals")); doc4.add(Field.Text("body", "mXtXls")); writer.addDocument(doc1); writer.addDocument(doc2); writer.addDocument(doc3); writer.addDocument(doc4); writer.optimize(); IndexSearcher searcher = new IndexSearcher(indexStore); Query query1 = new WildcardQuery(new Term("body", "m?tal")); Query query2 = new WildcardQuery(new Term("body", "metal?")); Query query3 = new WildcardQuery(new Term("body", "metals?")); Query query4 = new WildcardQuery(new Term("body", "m?t?ls")); Hits result; result = searcher.search(query1); assertEquals(1, result.length()); result = searcher.search(query2); assertEquals(2, result.length()); result = searcher.search(query3); assertEquals(1, result.length()); result = searcher.search(query4); assertEquals(3, result.length()); writer.close(); } }
package org.apache.xmlrpc; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Tests XmlRpc run-time. * * @author <a href="mailto:dlr@finemaltcoding.com">Daniel Rall</a> * @version $Id$ */ public class ClientServerRpcTest extends TestCase { /** * The name of our RPC handler. */ private static final String HANDLER_NAME = "TestHandler"; /** * The identifier or fully qualified class name of the SAX driver * to use. This is generally <code>uk.co.wilson.xml.MinML</code>, * but could be changed to * <code>org.apache.xerces.parsers.SAXParser</code> for timing * comparisons. */ private static final String SAX_DRIVER = "uk.co.wilson.xml.MinML"; /** * The number of RPCs to make for each test. */ private static final int NBR_REQUESTS = 1000; /** * The value to use in our request parameter. */ private static final String REQUEST_PARAM_VALUE = "foobar"; /** * The value to use in our request parameter. */ private static final String REQUEST_PARAM_XML = "<value>" + REQUEST_PARAM_VALUE + "</value>"; /** * A RPC request of our echo server in XML. */ private static final String RPC_REQUEST = "<?xml version=\"1.0\"?>\n" + "<methodCall>\n" + " <methodName>" + HANDLER_NAME + ".echo</methodName>\n" + " <params><param>" + REQUEST_PARAM_XML + "</param></params>\n" + "</methodCall>\n"; private WebServer webServer; private XmlRpcServer server; private XmlRpcClient client; private XmlRpcClientLite liteClient; /** * Constructor */ public ClientServerRpcTest(String testName) { super(testName); } /** * Return the Test */ public static Test suite() { return new TestSuite(ClientServerRpcTest.class); } /** * Setup the server and clients. */ public void setUp() { XmlRpc.setDebug(true); try { XmlRpc.setDriver(SAX_DRIVER); } catch (ClassNotFoundException e) { fail(e.toString()); } // WebServer //webServer = new WebServer(); // Server server = new XmlRpcServer(); server.addHandler(HANDLER_NAME, new TestHandler()); // HELP: What port and url space does this run on? // Standard Client //client = new XmlRpcClient(); // Supposedly light-weight client //liteClient = new XmlRpcClientLite(); } /** * Tear down the test. */ public void tearDown() { liteClient = null; client = null; // TODO: Shut down server server = null; // TODO: Shut down web server webServer = null; XmlRpc.setDebug(false); } /** * Tests server's RPC capabilities directly. */ public void testServer() { try { long time = System.currentTimeMillis(); for (int i = 0; i < NBR_REQUESTS; i++) { InputStream in = new ByteArrayInputStream(RPC_REQUEST.getBytes()); String response = new String(server.execute(in)); assertTrue("Response did not contain " + REQUEST_PARAM_XML, response.indexOf(REQUEST_PARAM_XML) != -1); } time = System.currentTimeMillis() - time; System.out.println("Total time elapsed for " + NBR_REQUESTS + " iterations: " + time + " milliseconds"); System.out.println("Average time: " + (time / NBR_REQUESTS) + " milliseconds"); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } /** * Tests client/server RPC. */ public void testRpc() { int nbrIterations = 300; try { throw new Exception("testRpc() not implemented"); // TODO: Test the Server // TODO: Test the clients } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } protected class TestHandler { public String echo(String message) { return message; } } }
package ui.issuepanel.comments; import handler.IssueDetailsContentHandler; import java.lang.ref.WeakReference; import javafx.application.Platform; import javafx.concurrent.Task; import javafx.concurrent.WorkerStateEvent; import javafx.event.EventHandler; import javafx.scene.control.ProgressIndicator; import javafx.scene.layout.VBox; import model.TurboIssue; import ui.StatusBar; public class IssueDetailsDisplay extends VBox { // public enum DisplayType{ // COMMENTS, // LOG // private TabPane detailsTab; private IssueDetailsContentHandler contentHandler; private TurboIssue issue; private int loadFailCount = 0; DetailsPanel commentsDisplay; Thread backgroundThread; public IssueDetailsDisplay(TurboIssue issue){ this.issue = issue; setupDetailsContents(); setupDisplay(); } private void setupDetailsContents(){ contentHandler = new IssueDetailsContentHandler(issue); } private void setupCommentsView(){ commentsDisplay = new DetailsPanel(issue, contentHandler); } // private void setupDetailsTab(){ // this.detailsTab = new TabPane(); // Tab commentsTab = createCommentsTab(); // detailsTab.getTabs().add(commentsTab); private void setupDisplay(){ // setupDetailsTab(); setupCommentsView(); this.getChildren().add(commentsDisplay); } public void show(){ if(issue == null || issue.getId() <= 0){ return; } loadIssueDetailsInBackground(); } private ProgressIndicator createProgressIndicator(){ ProgressIndicator indicator = new ProgressIndicator(); indicator.setPrefSize(50, 50); indicator.setMaxSize(50, 50); return indicator; } private void loadIssueDetailsInBackground(){ Task<Boolean> bgTask = new Task<Boolean>(){ @Override protected Boolean call() throws Exception { contentHandler.startContentUpdate(); return true; } }; ProgressIndicator indicator = createProgressIndicator(); indicator.progressProperty().bind(bgTask.progressProperty()); WeakReference<IssueDetailsDisplay> selfRef = new WeakReference<>(this); bgTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() { @Override public void handle(WorkerStateEvent t) { IssueDetailsDisplay self = selfRef.get(); if(self != null){ self.hideProgressIndicator(indicator); self.scrollDisplayToBottom(); self.loadFailCount = 0; } } }); bgTask.setOnFailed(new EventHandler<WorkerStateEvent>() { @Override public void handle(WorkerStateEvent t) { IssueDetailsDisplay self = selfRef.get(); if(self != null){ self.loadFailCount += 1; if(loadFailCount <= 3){ contentHandler.stopContentUpdate(); self.show(); }else{ //Notify user of load failure and reset count loadFailCount = 0; StatusBar.displayMessage("An error occured while loading the issue's comments. Comments partially loaded"); self.hideProgressIndicator(indicator); } } } }); displayProgressIndicator(indicator); backgroundThread = new Thread(bgTask); backgroundThread.start(); } private void displayProgressIndicator(ProgressIndicator indicator){ Platform.runLater(() -> { commentsDisplay.addItemToDisplay(indicator); }); } private void hideProgressIndicator(ProgressIndicator indicator){ Platform.runLater(() -> { commentsDisplay.removeItemFromDisplay(indicator); }); } private void scrollDisplayToBottom(){ Platform.runLater(new Runnable() { @Override public void run() { commentsDisplay.scrollToBottom(); } }); } public void hide(){ contentHandler.stopContentUpdate(); } public void cleanup(){ contentHandler.stopContentUpdate(); } public void refresh(){ contentHandler.restartContentUpdate(); } // private DetailsPanel createTabContentsDisplay(){ // return new DetailsPanel(issue, contentHandler); // private Tab createCommentsTab(){ // Tab comments = new Tab(); // comments.setText("Comments"); // comments.setClosable(false); // commentsDisplay = createTabContentsDisplay(); // VBox.setVgrow(commentsDisplay, Priority.ALWAYS); // comments.setContent(commentsDisplay); // return comments; }
package dades; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; @SuppressWarnings("unchecked") /** Table class used to store elements and load and save data from Serializable objects */ public class Table<E extends Serializable> extends ArrayList<E> { /** Constructs an empty table **/ public Table() {} /** Constructs an empty Table with the specified initial capacity and with its capacity increment equal to zero */ public Table(int initialCapacity) { super (initialCapacity); } /** * Constructs a table containing the elements of the specified collection, in the order they are returned by the * collection's iterator */ public Table(Collection<? extends E> c) { super (c); } /** * Load all the data from the Stream, this method overwrites all data in the table */ public void load(ObjectInputStream in) { this.clear(); int size = 0; try { size = in.readInt(); this.ensureCapacity(size); for (int i = 0; i < size; ++i) { this.add((E) in.readObject()); } } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); System.err.println(e.getMessage()); } } /** * Save all the data to the Stream */ public void save(ObjectOutputStream out) { try { out.writeInt(this.size()); for(E aux : this) out.writeObject(aux); } catch (IOException e) { e.printStackTrace(); System.err.println(e.getMessage()); } } }
package mil.nga.giat.mage.sdk.http; import android.app.Application; import android.preference.PreferenceManager; import android.util.Log; import java.io.IOException; import java.net.CookieManager; import java.net.CookiePolicy; import java.util.Collection; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import mil.nga.giat.mage.sdk.R; import mil.nga.giat.mage.sdk.event.IEventDispatcher; import mil.nga.giat.mage.sdk.event.ISessionEventListener; import mil.nga.giat.mage.sdk.utils.UserUtility; import okhttp3.Interceptor; import okhttp3.JavaNetCookieJar; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import static java.net.HttpURLConnection.HTTP_NOT_FOUND; import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED; /** * Always use the {@link HttpClientManager#httpClient} for making ALL * requests to the server. This class adds request and response interceptors to * pass things like a token and handle errors like 403 and 401. * * @author newmanw */ public class HttpClientManager implements IEventDispatcher<ISessionEventListener> { private static final String LOG_NAME = HttpClientManager.class.getName(); private static HttpClientManager instance; private Application context; private String userAgent; private CookieManager cookieManager; private OkHttpClient client; private Collection<ISessionEventListener> listeners = new CopyOnWriteArrayList<>(); public static synchronized HttpClientManager initialize(Application context) { if (instance != null) { throw new Error("attempt to initialize " + HttpClientManager.class.getName() + " singleton more than once"); } String userAgent = System.getProperty("http.agent"); userAgent = userAgent == null ? "" : userAgent; CookieManager cookieManager = new CookieManager(); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER); instance = new HttpClientManager(context, userAgent, cookieManager); return instance; } public static HttpClientManager getInstance() { return instance; } private HttpClientManager(Application context, String userAgent, CookieManager cookieManager) { this.context = context; this.userAgent = userAgent; this.cookieManager = cookieManager; initializeClient(); } private void initializeClient() { OkHttpClient.Builder builder = new OkHttpClient.Builder() .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS) .cookieJar(new JavaNetCookieJar(cookieManager)); builder.addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request.Builder builder = chain.request().newBuilder(); // add token String token = PreferenceManager.getDefaultSharedPreferences(context).getString(context.getString(R.string.tokenKey), null); if (token != null && !token.trim().isEmpty()) { builder.addHeader("Authorization", "Bearer " + token); } // add Accept-Encoding:gzip builder.addHeader("Accept-Encoding", "gzip") .addHeader("User-Agent", userAgent); Response response = chain.proceed(builder.build()); int statusCode = response.code(); if (statusCode == HTTP_UNAUTHORIZED) { UserUtility userUtility = UserUtility.getInstance(context); // If token has not expired yet, expire it and send notification to listeners if (!userUtility.isTokenExpired()) { UserUtility.getInstance(context).clearTokenInformation(); for (ISessionEventListener listener : listeners) { listener.onTokenExpired(); } } Log.w(LOG_NAME, "TOKEN EXPIRED"); } else if (statusCode == HTTP_NOT_FOUND) { Log.w(LOG_NAME, "404 Not Found."); } return response; } }); client = builder.build(); } public OkHttpClient httpClient() { return client; } @Override public boolean addListener(ISessionEventListener listener) { return listeners.add(listener); } @Override public boolean removeListener(ISessionEventListener listener) { return listeners.remove(listener); } }
package org.xtreemfs.utils; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.FileWriter; import java.net.InetSocketAddress; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.xtreemfs.babudb.config.BabuDBConfig; import org.xtreemfs.common.ReplicaUpdatePolicies; import org.xtreemfs.common.libxtreemfs.AdminClient; import org.xtreemfs.common.libxtreemfs.AdminFileHandle; import org.xtreemfs.common.libxtreemfs.AdminVolume; import org.xtreemfs.common.libxtreemfs.ClientFactory; import org.xtreemfs.common.libxtreemfs.Options; import org.xtreemfs.dir.DIRConfig; import org.xtreemfs.foundation.logging.Logging; import org.xtreemfs.foundation.pbrpc.client.RPCAuthentication; import org.xtreemfs.foundation.pbrpc.client.RPCResponse; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.UserCredentials; import org.xtreemfs.foundation.util.FSUtils; import org.xtreemfs.mrc.MRCConfig; import org.xtreemfs.mrc.MRCRequestDispatcher; import org.xtreemfs.osd.OSD; import org.xtreemfs.osd.OSDConfig; import org.xtreemfs.osd.storage.HashStorageLayout; import org.xtreemfs.osd.storage.MetadataCache; import org.xtreemfs.pbrpc.generatedinterfaces.DIR.ServiceStatus; import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.REPL_FLAG; import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.Replica; import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.SYSTEM_V_FCNTL; import org.xtreemfs.pbrpc.generatedinterfaces.MRC.DirectoryEntries; import org.xtreemfs.pbrpc.generatedinterfaces.MRC.Stat; import org.xtreemfs.test.SetupUtils; import org.xtreemfs.test.TestEnvironment; import org.xtreemfs.utils.xtfs_scrub.xtfs_scrub; public class ScrubberTest { private static MRCRequestDispatcher mrc1; private static MRCConfig mrcCfg1; private static BabuDBConfig mrcDBCfg1; private static OSDConfig osdConfig1, osdConfig2, osdConfig3, osdConfig4; private static DIRConfig dsCfg; private static OSD osd1, osd2, osd3, osd4; private static InetSocketAddress mrc1Address; private static InetSocketAddress dirAddress; private static int accessMode; private static TestEnvironment testEnv; private static AdminClient client; private static byte[] content; private static final UserCredentials userCredentials = xtfs_scrub.credentials; public ScrubberTest() { Logging.start(Logging.LEVEL_DEBUG); } @BeforeClass public static void setUp() throws Exception { System.out.println("TEST: ScrubberTest"); Logging.start(Logging.LEVEL_WARN); accessMode = 0777; // rwxrwxrwx dsCfg = SetupUtils.createDIRConfig(); dirAddress = SetupUtils.getDIRAddr(); mrcCfg1 = SetupUtils.createMRC1Config(); mrcDBCfg1 = SetupUtils.createMRC1dbsConfig(); mrc1Address = SetupUtils.getMRC1Addr(); SetupUtils.CHECKSUMS_ON = true; osdConfig1 = SetupUtils.createOSD1Config(); osdConfig2 = SetupUtils.createOSD2Config(); osdConfig3 = SetupUtils.createOSD3Config(); osdConfig4 = SetupUtils.createOSD4Config(); SetupUtils.CHECKSUMS_ON = false; // cleanup File testDir = new File(SetupUtils.TEST_DIR); FSUtils.delTree(testDir); testDir.mkdirs(); // startup: DIR testEnv = new TestEnvironment(new TestEnvironment.Services[] { TestEnvironment.Services.DIR_SERVICE, TestEnvironment.Services.TIME_SYNC, TestEnvironment.Services.UUID_RESOLVER, TestEnvironment.Services.MRC_CLIENT, TestEnvironment.Services.OSD_CLIENT }); testEnv.start(); // start the OSD osd1 = new OSD(osdConfig1); // start MRC mrc1 = new MRCRequestDispatcher(mrcCfg1, mrcDBCfg1); mrc1.startup(); // create client client = ClientFactory.createAdminClient(dirAddress.getHostName() + ":" + dirAddress.getPort(), userCredentials, null, new Options()); client.start(); // create content String tmp = ""; for (int i = 0; i < 12000; i++) tmp = tmp.concat("Hello World "); content = tmp.getBytes(); } @AfterClass public static void tearDown() throws Exception { client.shutdown(); osd1.shutdown(); testEnv.shutdown(); } @Test public void testNonReplicatedFileOnDeadOSD() throws Exception { final String VOLUME_NAME = "testNonReplicatedFileOnDeadOSD"; final String FILE_NAME = "myDir/test0.txt"; // create Volume client.createVolume(mrc1Address.getHostName() + ":" + mrc1Address.getPort(), RPCAuthentication.authNone, userCredentials, VOLUME_NAME); AdminVolume volume = client.openVolume(VOLUME_NAME, null, new Options()); volume.start(); // create dir and file volume.createDirectory(userCredentials, "myDir", accessMode); AdminFileHandle file = volume.openFile( userCredentials, FILE_NAME, SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_CREAT.getNumber() | SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR.getNumber(), accessMode); // write file file.write(userCredentials, content, content.length, 0); file.close(); DirectoryEntries de = volume.readDir(userCredentials, "/myDir/", 0, 2, true); assertEquals(3, de.getEntriesCount()); // mark OSD as removed client.setOSDServiceStatus(osdConfig1.getUUID().toString(), ServiceStatus.SERVICE_STATUS_REMOVED); // scrub volume xtfs_scrub scrubber = new xtfs_scrub(client, volume, 3, true, true, true); scrubber.scrub(); // file should be removed de = volume.readDir(userCredentials, "/myDir/", 0, 2, true); assertEquals(2, de.getEntriesCount()); // delete volume client.deleteVolume(mrc1Address.getHostName() + ":" + mrc1Address.getPort(), RPCAuthentication.authNone, userCredentials, VOLUME_NAME); // mark OSD as available client.setOSDServiceStatus(osdConfig1.getUUID().toString(), ServiceStatus.SERVICE_STATUS_AVAIL); } @Test public void testNonReplicatedFileWithWrongChecksum() throws Exception { final String VOLUME_NAME = "testNonReplicatedFileWithWrongChecksum"; final String FILE_NAME = "test0.txt"; // create Volume client.createVolume(mrc1Address.getHostName() + ":" + mrc1Address.getPort(), RPCAuthentication.authNone, userCredentials, VOLUME_NAME); AdminVolume volume = client.openVolume(VOLUME_NAME, null, new Options()); volume.start(); // create file AdminFileHandle file = volume.openFile( userCredentials, FILE_NAME, SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_CREAT.getNumber() | SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR.getNumber(), accessMode); // write file file.write(userCredentials, content, file.getStripingPolicy().getStripeSize() * 1024 - 20, 0); // modify first Object on OSD HashStorageLayout hsl = new HashStorageLayout(osdConfig1, new MetadataCache()); String filePath = hsl.generateAbsoluteFilePath(file.getGlobalFileId()); File fileDir = new File(filePath); FileWriter fw = new FileWriter(fileDir.listFiles()[0], true); fw.write("foofoofoofoofoo"); fw.close(); // scrub volume xtfs_scrub scrubber = new xtfs_scrub(client, volume, 3, true, true, true); scrubber.scrub(); // TODO(lukas): add asserts file.close(); // delete volume client.deleteVolume(mrc1Address.getHostName() + ":" + mrc1Address.getPort(), RPCAuthentication.authNone, userCredentials, VOLUME_NAME); } @Test public void testNonReplicatedFileWithWrongFileSizeOnMrc() throws Exception { final String VOLUME_NAME = "testNonReplicatedFileWithWrongFileSizeOnMrc"; final String FILE_NAME = "test0.txt"; // create Volume client.createVolume(mrc1Address.getHostName() + ":" + mrc1Address.getPort(), RPCAuthentication.authNone, userCredentials, VOLUME_NAME); AdminVolume volume = client.openVolume(VOLUME_NAME, null, new Options()); volume.start(); // create file AdminFileHandle file = volume.openFile( userCredentials, FILE_NAME, SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_CREAT.getNumber() | SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR.getNumber(), accessMode); // write file file.write(userCredentials, content, content.length, 0); Stat s = file.getAttr(userCredentials); assertEquals(content.length, s.getSize()); // truncate file on MRC file.truncate(userCredentials, 10, true); s = file.getAttr(userCredentials); assertEquals(10, s.getSize()); // scrub volume xtfs_scrub scrubber = new xtfs_scrub(client, volume, 3, true, true, true); scrubber.scrub(); // file size should be correct from 10 to content.length s = file.getAttr(userCredentials); assertEquals(content.length, s.getSize()); file.close(); // delete volume client.deleteVolume(mrc1Address.getHostName() + ":" + mrc1Address.getPort(), RPCAuthentication.authNone, userCredentials, VOLUME_NAME); } @Test public void testROnlyReplicatedFileWithLostReplica() throws Exception { final String VOLUME_NAME = "testROnlyReplicatedFileWithLostReplica"; final String FILE_NAME = "test0.txt"; // create Volume client.createVolume(mrc1Address.getHostName() + ":" + mrc1Address.getPort(), RPCAuthentication.authNone, userCredentials, VOLUME_NAME); AdminVolume volume = client.openVolume(VOLUME_NAME, null, new Options()); volume.start(); // create file AdminFileHandle file = volume.openFile( userCredentials, FILE_NAME, SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_CREAT.getNumber() | SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR.getNumber(), accessMode); // write file file.write(userCredentials, content, content.length, 0); // start new OSDs and give them some time for start up osd2 = new OSD(osdConfig2); osd3 = new OSD(osdConfig3); osd4 = new OSD(osdConfig4); Thread.sleep(10000); // set replica update Policy RPCResponse<?> r = testEnv.getMrcClient().xtreemfs_set_replica_update_policy(mrc1Address, RPCAuthentication.authNone, userCredentials, file.getGlobalFileId(), ReplicaUpdatePolicies.REPL_UPDATE_PC_RONLY); r.get(); r.freeBuffers(); // create new replicas Replica newRepl = file.getReplica(0).toBuilder().setOsdUuids(0, osdConfig2.getUUID().toString()) .setReplicationFlags(REPL_FLAG.REPL_FLAG_FULL_REPLICA.getNumber() & REPL_FLAG.REPL_FLAG_STRATEGY_RAREST_FIRST.getNumber()).build(); volume.addReplica(userCredentials, FILE_NAME, newRepl); newRepl = file.getReplica(0).toBuilder().setOsdUuids(0, osdConfig3.getUUID().toString()) .setReplicationFlags(REPL_FLAG.REPL_FLAG_FULL_REPLICA.getNumber() & REPL_FLAG.REPL_FLAG_STRATEGY_RAREST_FIRST.getNumber()).build(); volume.addReplica(userCredentials, FILE_NAME, newRepl); // mark OSD3 as removed client.setOSDServiceStatus(osdConfig3.getUUID().toString(), ServiceStatus.SERVICE_STATUS_REMOVED); // scrub volume xtfs_scrub scrubber = new xtfs_scrub(client, volume, 3, true, true, true); scrubber.scrub(); // file has still three replicas assertEquals(3, file.getReplicasList().size()); file.close(); // delete volume client.deleteVolume(mrc1Address.getHostName() + ":" + mrc1Address.getPort(), RPCAuthentication.authNone, userCredentials, VOLUME_NAME); // shut down OSDs osd2.shutdown(); osd3.shutdown(); osd4.shutdown(); } @Test public void testROnlyReplicatedFileWithWrongChecksum() throws Exception { final String VOLUME_NAME = "testROnlyReplicatedFileWithWrongChecksum"; final String FILE_NAME = "test0.txt"; // create Volume client.createVolume(mrc1Address.getHostName() + ":" + mrc1Address.getPort(), RPCAuthentication.authNone, userCredentials, VOLUME_NAME); AdminVolume volume = client.openVolume(VOLUME_NAME, null, new Options()); volume.start(); // create file AdminFileHandle file = volume.openFile( userCredentials, FILE_NAME, SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_CREAT.getNumber() | SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR.getNumber(), accessMode); // write file file.write(userCredentials, content, file.getStripingPolicy().getStripeSize() * 1024 - 20, 0); // start new OSDs osd2 = new OSD(osdConfig2); // set replica update Policy RPCResponse<?> r = testEnv.getMrcClient().xtreemfs_set_replica_update_policy(mrc1Address, RPCAuthentication.authNone, userCredentials, file.getGlobalFileId(), ReplicaUpdatePolicies.REPL_UPDATE_PC_RONLY); r.get(); r.freeBuffers(); // create new replicas Replica newRepl = file.getReplica(0).toBuilder().setOsdUuids(0, osdConfig2.getUUID().toString()) .setReplicationFlags(REPL_FLAG.REPL_FLAG_FULL_REPLICA.getNumber() & REPL_FLAG.REPL_FLAG_STRATEGY_RAREST_FIRST.getNumber()).build(); volume.addReplica(userCredentials, FILE_NAME, newRepl); // modify first Object on OSD HashStorageLayout hsl = new HashStorageLayout(osdConfig1, new MetadataCache()); String filePath = hsl.generateAbsoluteFilePath(file.getGlobalFileId()); File fileDir = new File(filePath); FileWriter fw = new FileWriter(fileDir.listFiles()[0], true); fw.write("foofoofoofoofoo"); fw.close(); // scrub volume xtfs_scrub scrubber = new xtfs_scrub(client, volume, 3, true, true, true); scrubber.scrub(); // TODO(lukas): add asserts file.close(); // delete volume client.deleteVolume(mrc1Address.getHostName() + ":" + mrc1Address.getPort(), RPCAuthentication.authNone, userCredentials, VOLUME_NAME); // shut down OSDs osd2.shutdown(); } @Test public void testRWReplicatedFileWithLostReplica() throws Exception { final String VOLUME_NAME = "testRWReplicatedFileWithLostReplica"; final String FILE_NAME = "test0.txt"; // create Volume client.createVolume(mrc1Address.getHostName() + ":" + mrc1Address.getPort(), RPCAuthentication.authNone, userCredentials, VOLUME_NAME); AdminVolume volume = client.openVolume(VOLUME_NAME, null, new Options()); volume.start(); // create file AdminFileHandle file = volume.openFile( userCredentials, FILE_NAME, SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_CREAT.getNumber() | SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR.getNumber(), accessMode); // start new OSDs and give them some time for start up osd2 = new OSD(osdConfig2); osd3 = new OSD(osdConfig3); osd4 = new OSD(osdConfig4); Thread.sleep(10000); // set replica update Policy RPCResponse<?> r = testEnv.getMrcClient().xtreemfs_set_replica_update_policy(mrc1Address, RPCAuthentication.authNone, userCredentials, file.getGlobalFileId(), ReplicaUpdatePolicies.REPL_UPDATE_PC_WARONE); r.get(); r.freeBuffers(); // write file file.write(userCredentials, content, content.length, 0); // create new replicas Replica newRepl = file.getReplica(0).toBuilder().setOsdUuids(0, osdConfig2.getUUID().toString()) .setReplicationFlags(REPL_FLAG.REPL_FLAG_FULL_REPLICA.getNumber() & REPL_FLAG.REPL_FLAG_STRATEGY_RAREST_FIRST.getNumber()).build(); volume.addReplica(userCredentials, FILE_NAME, newRepl); newRepl = file.getReplica(0).toBuilder().setOsdUuids(0, osdConfig3.getUUID().toString()) .setReplicationFlags(REPL_FLAG.REPL_FLAG_FULL_REPLICA.getNumber() & REPL_FLAG.REPL_FLAG_STRATEGY_RAREST_FIRST.getNumber()).build(); volume.addReplica(userCredentials, FILE_NAME, newRepl); // mark OSD3 as removed client.setOSDServiceStatus(osdConfig3.getUUID().toString(), ServiceStatus.SERVICE_STATUS_REMOVED); // scrub volume xtfs_scrub scrubber = new xtfs_scrub(client, volume, 3, true, true, true); scrubber.scrub(); // file has still three replicas assertEquals(3, file.getReplicasList().size()); file.close(); // delete volume client.deleteVolume(mrc1Address.getHostName() + ":" + mrc1Address.getPort(), RPCAuthentication.authNone, userCredentials, VOLUME_NAME); // shut down OSDs osd2.shutdown(); osd3.shutdown(); osd4.shutdown(); } @Test public void testRWReplicatedFileWithWrongChecksum() throws Exception { final String VOLUME_NAME = "testRWReplicatedFileWithWrongChecksum"; final String FILE_NAME = "test0.txt"; // create Volume client.createVolume(mrc1Address.getHostName() + ":" + mrc1Address.getPort(), RPCAuthentication.authNone, userCredentials, VOLUME_NAME); AdminVolume volume = client.openVolume(VOLUME_NAME, null, new Options()); volume.start(); // create file AdminFileHandle file = volume.openFile( userCredentials, FILE_NAME, SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_CREAT.getNumber() | SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR.getNumber(), accessMode); // start new OSDs osd2 = new OSD(osdConfig2); // set replica update Policy RPCResponse<?> r = testEnv.getMrcClient().xtreemfs_set_replica_update_policy(mrc1Address, RPCAuthentication.authNone, userCredentials, file.getGlobalFileId(), ReplicaUpdatePolicies.REPL_UPDATE_PC_WARONE); r.get(); r.freeBuffers(); // write file file.write(userCredentials, content, file.getStripingPolicy().getStripeSize() * 1024 - 20, 0); // create new replicas Replica newRepl = file.getReplica(0).toBuilder().setOsdUuids(0, osdConfig2.getUUID().toString()) .setReplicationFlags(REPL_FLAG.REPL_FLAG_FULL_REPLICA.getNumber() & REPL_FLAG.REPL_FLAG_STRATEGY_RAREST_FIRST.getNumber()).build(); volume.addReplica(userCredentials, FILE_NAME, newRepl); // modify first Object on OSD HashStorageLayout hsl = new HashStorageLayout(osdConfig1, new MetadataCache()); String filePath = hsl.generateAbsoluteFilePath(file.getGlobalFileId()); File fileDir = new File(filePath); FileWriter fw = new FileWriter(fileDir.listFiles()[0], true); fw.write("foofoofoofoofoo"); fw.close(); // scrub volume xtfs_scrub scrubber = new xtfs_scrub(client, volume, 3, true, true, true); scrubber.scrub(); // TODO(lukas): add asserts file.close(); // delete volume client.deleteVolume(mrc1Address.getHostName() + ":" + mrc1Address.getPort(), RPCAuthentication.authNone, userCredentials, VOLUME_NAME); // shut down OSDs osd2.shutdown(); } // not supported yet public void testRWReplicatedFileWithWrongFileSizeOnMrc() throws Exception { final String VOLUME_NAME = "testRWReplicatedFileWithWrongFileSizeOnMrc"; final String FILE_NAME = "test0.txt"; // create Volume client.createVolume(mrc1Address.getHostName() + ":" + mrc1Address.getPort(), RPCAuthentication.authNone, userCredentials, VOLUME_NAME); AdminVolume volume = client.openVolume(VOLUME_NAME, null, new Options()); volume.start(); // create file AdminFileHandle file = volume.openFile( userCredentials, FILE_NAME, SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_CREAT.getNumber() | SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR.getNumber(), accessMode); // start new OSDs osd2 = new OSD(osdConfig2); // set replica update Policy RPCResponse<?> r = testEnv.getMrcClient().xtreemfs_set_replica_update_policy(mrc1Address, RPCAuthentication.authNone, userCredentials, file.getGlobalFileId(), ReplicaUpdatePolicies.REPL_UPDATE_PC_WARONE); r.get(); r.freeBuffers(); // write file file.write(userCredentials, content, content.length, 0); // create new replicas Replica newRepl = file.getReplica(0).toBuilder().setOsdUuids(0, osdConfig2.getUUID().toString()) .setReplicationFlags(REPL_FLAG.REPL_FLAG_FULL_REPLICA.getNumber() & REPL_FLAG.REPL_FLAG_STRATEGY_RAREST_FIRST.getNumber()).build(); volume.addReplica(userCredentials, FILE_NAME, newRepl); Stat s = file.getAttr(userCredentials); assertEquals(content.length, s.getSize()); // truncate file on MRC file.truncate(userCredentials, 10, true); s = file.getAttr(userCredentials); assertEquals(10, s.getSize()); // scrub volume xtfs_scrub scrubber = new xtfs_scrub(client, volume, 3, true, true, true); scrubber.scrub(); // file size should be correct from 10 to content.length s = file.getAttr(userCredentials); assertEquals(content.length, s.getSize()); file.close(); // delete volume client.deleteVolume(mrc1Address.getHostName() + ":" + mrc1Address.getPort(), RPCAuthentication.authNone, userCredentials, VOLUME_NAME); // shut down OSD osd2.shutdown(); } }
package us.corenetwork.tradecraft; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.plugin.java.JavaPlugin; import us.corenetwork.tradecraft.commands.BaseCommand; import us.corenetwork.tradecraft.commands.ReloadCommand; import us.corenetwork.tradecraft.commands.SaveCommand; import us.corenetwork.tradecraft.db.DbWorker; import java.sql.SQLException; import java.util.HashMap; import java.util.Random; public class TradeCraftPlugin extends JavaPlugin { public static TradeCraftPlugin instance; public static Random random; public static HashMap<String, BaseCommand> commands = new HashMap<String, BaseCommand>(); private Thread dbWorkerThread; @Override public void onEnable() { instance = this; random = new Random(); commands.put("reload", new ReloadCommand()); commands.put("save", new SaveCommand()); getServer().getPluginManager().registerEvents(new TradeCraftListener(), this); IO.LoadSettings(); IO.PrepareDB(); NMSVillagerManager.register(); try { IO.getConnection().commit(); } catch (SQLException e) { e.printStackTrace(); } Villagers.LoadVillagers(); dbWorkerThread = new Thread(new DbWorker()); dbWorkerThread.start(); } @Override public void onDisable() { DbWorker.stopFurtherRequests(); dbWorkerThread.interrupt(); IO.freeConnection(); } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { BaseCommand cmd = commands.get(args[0]); if (cmd != null) return cmd.execute(sender, args, true); else return false; } }
package org.jpos.q2.iso; import org.jdom.Element; import org.jpos.core.ConfigurationException; import org.jpos.iso.*; import org.jpos.q2.QBeanSupport; import org.jpos.q2.QFactory; import org.jpos.space.Space; import org.jpos.space.SpaceFactory; import org.jpos.space.SpaceUtil; import org.jpos.util.LogSource; import org.jpos.util.Loggeable; import org.jpos.util.NameRegistrar; import java.io.IOException; import java.io.PrintStream; import java.net.SocketTimeoutException; import java.util.Date; /** * @author Alejandro Revilla */ @SuppressWarnings("unchecked") public class ChannelAdaptor extends QBeanSupport implements ChannelAdaptorMBean, Channel, Loggeable { Space sp; private ISOChannel channel; String in, out, ready, reconnect; long delay; boolean keepAlive = false; boolean ignoreISOExceptions = false; boolean writeOnly = false; int rx, tx, connects; long lastTxn = 0l; long timeout = 0l; boolean waitForWorkersOnStop; private Thread receiver; private Thread sender; private final Object disconnectLock = Boolean.TRUE; public ChannelAdaptor () { super (); resetCounters(); } public void initService() throws ConfigurationException { initSpaceAndQueues(); NameRegistrar.register (getName(), this); } public void startService () { try { channel = initChannel (); sender = new Thread(new Sender()); sender.start(); if (!writeOnly) { // fixes #426 && jPOS-20 receiver = new Thread(new Receiver()); receiver.start(); } } catch (Exception e) { getLog().warn ("error starting service", e); } } public void stopService () { try { sp.out (in, Boolean.TRUE); if (channel != null) disconnect(); if (waitForWorkersOnStop) { waitForSenderToExit(); if (!writeOnly) { sp.out(ready, new Date()); waitForReceiverToExit(); } } sender = null; receiver = null; } catch (Exception e) { getLog().warn ("error disconnecting from remote host", e); } } private void waitForSenderToExit() { join(sender); } private void waitForReceiverToExit() { join(receiver); SpaceUtil.wipe(sp, ready); } private void join(Thread thread) { try { if (thread != null) thread.join(); } catch (InterruptedException ignored) { } } public void destroyService () { NameRegistrar.unregister (getName ()); NameRegistrar.unregister ("channel." + getName ()); } public synchronized void setReconnectDelay (long delay) { getPersist().getChild ("reconnect-delay") .setText (Long.toString (delay)); this.delay = delay; setModified (true); } public long getReconnectDelay () { return delay; } public synchronized void setInQueue (String in) { String old = this.in; this.in = in; if (old != null) sp.out (old, Boolean.TRUE); getPersist().getChild("in").setText (in); setModified (true); } public String getInQueue () { return in; } public synchronized void setOutQueue (String out) { this.out = out; getPersist().getChild("out").setText (out); setModified (true); } /** * Queue a message to be transmitted by this adaptor * @param m message to send */ public void send (ISOMsg m) { sp.out (in, m); } /** * Queue a message to be transmitted by this adaptor * @param m message to send * @param timeout timeout in millis */ public void send (ISOMsg m, long timeout) { sp.out (in, m, timeout); } /** * Receive message */ public ISOMsg receive () { return (ISOMsg) sp.in (out); } /** * Receive message * @param timeout time to wait for an incoming message */ public ISOMsg receive (long timeout) { return (ISOMsg) sp.in (out, timeout); } /** * @return true if channel is connected */ public boolean isConnected () { return sp != null && sp.rdp (ready) != null; } public String getOutQueue () { return out; } public ISOChannel newChannel (Element e, QFactory f) throws ConfigurationException { String channelName = e.getAttributeValue ("class"); String packagerName = e.getAttributeValue ("packager"); ISOChannel channel = (ISOChannel) f.newInstance (channelName); ISOPackager packager; if (packagerName != null) { packager = (ISOPackager) f.newInstance (packagerName); channel.setPackager (packager); f.setConfiguration (packager, e); } QFactory.invoke (channel, "setHeader", e.getAttributeValue ("header")); f.setLogger (channel, e); f.setConfiguration (channel, e); if (channel instanceof FilteredChannel) { addFilters ((FilteredChannel) channel, e, f); } if (getName () != null) channel.setName (getName ()); return channel; } protected void addFilters (FilteredChannel channel, Element e, QFactory fact) throws ConfigurationException { for (Object o : e.getChildren("filter")) { Element f = (Element) o; String clazz = f.getAttributeValue("class"); ISOFilter filter = (ISOFilter) fact.newInstance(clazz); fact.setLogger(filter, f); fact.setConfiguration(filter, f); String direction = f.getAttributeValue("direction"); if (direction == null) channel.addFilter(filter); else if ("incoming".equalsIgnoreCase(direction)) channel.addIncomingFilter(filter); else if ("outgoing".equalsIgnoreCase(direction)) channel.addOutgoingFilter(filter); else if ("both".equalsIgnoreCase(direction)) { channel.addIncomingFilter(filter); channel.addOutgoingFilter(filter); } } } protected ISOChannel initChannel () throws ConfigurationException { Element persist = getPersist (); Element e = persist.getChild ("channel"); if (e == null) throw new ConfigurationException ("channel element missing"); ISOChannel c = newChannel (e, getFactory()); String socketFactoryString = getSocketFactory(); if (socketFactoryString != null && c instanceof FactoryChannel) { ISOClientSocketFactory sFac = (ISOClientSocketFactory) getFactory().newInstance(socketFactoryString); if (sFac != null && sFac instanceof LogSource) { ((LogSource) sFac).setLogger(log.getLogger(),getName() + ".socket-factory"); } getFactory().setConfiguration (sFac, e); ((FactoryChannel)c).setSocketFactory(sFac); } return c; } protected void initSpaceAndQueues () throws ConfigurationException { Element persist = getPersist (); sp = grabSpace (persist.getChild ("space")); in = persist.getChildTextTrim ("in"); out = persist.getChildTextTrim ("out"); String s = persist.getChildTextTrim ("reconnect-delay"); delay = s != null ? Long.parseLong (s) : 10000; // reasonable default keepAlive = "yes".equalsIgnoreCase (persist.getChildTextTrim ("keep-alive")); ignoreISOExceptions = "yes".equalsIgnoreCase (persist.getChildTextTrim ("ignore-iso-exceptions")); writeOnly = "yes".equalsIgnoreCase (getPersist().getChildTextTrim ("write-only")); String t = persist.getChildTextTrim("timeout"); timeout = t != null && t.length() > 0 ? Long.parseLong(t) : 0l; ready = getName() + ".ready"; reconnect = getName() + ".reconnect"; waitForWorkersOnStop = "yes".equalsIgnoreCase(persist.getChildTextTrim ("wait-for-workers-on-stop")); } @SuppressWarnings("unchecked") public class Sender implements Runnable { public Sender () { super (); } public void run () { Thread.currentThread().setName ("channel-sender-" + in); while (running ()){ try { checkConnection (); if (!running()) break; Object o = sp.in (in, delay); if (o instanceof ISOMsg) { channel.send ((ISOMsg) o); tx++; } else if (keepAlive && channel.isConnected() && channel instanceof BaseChannel) { ((BaseChannel)channel).sendKeepAlive(); } } catch (ISOFilter.VetoException e) { getLog().warn ("channel-sender-"+in, e.getMessage ()); } catch (ISOException e) { getLog().warn ("channel-sender-"+in, e.getMessage ()); if (!ignoreISOExceptions) { disconnect (); } ISOUtil.sleep (1000); // slow down on errors } catch (Exception e) { getLog().warn ("channel-sender-"+in, e.getMessage ()); disconnect (); ISOUtil.sleep (1000); } } } } @SuppressWarnings("unchecked") public class Receiver implements Runnable { public Receiver () { super (); } public void run () { Thread.currentThread().setName ("channel-receiver-"+out); while (running()) { try { Object r = sp.rd (ready, 5000L); if (r == null) continue; ISOMsg m = channel.receive (); rx++; lastTxn = System.currentTimeMillis(); if (timeout > 0) sp.out (out, m, timeout); else sp.out (out, m); } catch (ISOException e) { if (running()) { getLog().warn ("channel-receiver-"+out, e); if (!ignoreISOExceptions) { sp.out (reconnect, Boolean.TRUE, delay); disconnect (); sp.out (in, Boolean.TRUE); // wake-up Sender } ISOUtil.sleep(1000); } } catch (SocketTimeoutException e) { if (running()) { getLog().warn ("channel-receiver-"+out, "Read timeout"); sp.out (reconnect, Boolean.TRUE, delay); disconnect (); sp.out (in, Boolean.TRUE); // wake-up Sender ISOUtil.sleep(1000); } } catch (Exception e) { if (running()) { getLog().warn ("channel-receiver-"+out, e); sp.out (reconnect, Boolean.TRUE, delay); disconnect (); sp.out (in, Boolean.TRUE); // wake-up Sender ISOUtil.sleep(1000); } } } } } protected void checkConnection () { while (running() && sp.rdp (reconnect) != null) { ISOUtil.sleep(1000); } while (running() && !channel.isConnected ()) { SpaceUtil.wipe(sp, ready); try { channel.connect (); } catch (IOException e) { getLog().warn ("check-connection", e.getMessage ()); } if (!channel.isConnected ()) ISOUtil.sleep (delay); else connects++; } if (running() && sp.rdp (ready) == null) sp.out (ready, new Date()); } protected void disconnect () { // do not synchronize on this as both Sender and Receiver can deadlock against a thread calling stop() synchronized (disconnectLock) { try { SpaceUtil.wipe(sp, ready); channel.disconnect(); } catch (Exception e) { getLog().warn("disconnect", e); } } } public synchronized void setHost (String host) { setProperty (getProperties ("channel"), "host", host); setModified (true); } public String getHost () { return getProperty (getProperties ("channel"), "host"); } public synchronized void setPort (int port) { setProperty ( getProperties ("channel"), "port", Integer.toString (port) ); setModified (true); } public int getPort () { int port = 0; try { port = Integer.parseInt ( getProperty (getProperties ("channel"), "port") ); } catch (NumberFormatException e) { getLog().error(e); } return port; } public synchronized void setSocketFactory (String sFac) { setProperty(getProperties("channel"), "socketFactory", sFac); setModified(true); } public void resetCounters () { rx = tx = connects = 0; lastTxn = 0l; } public String getCountersAsString () { StringBuffer sb = new StringBuffer(); append (sb, "tx=", tx); append (sb, ", rx=", rx); append (sb, ", connects=", connects); sb.append (", last="); sb.append(lastTxn); if (lastTxn > 0) { sb.append (", idle="); sb.append(System.currentTimeMillis() - lastTxn); sb.append ("ms"); } return sb.toString(); } public int getTXCounter() { return tx; } public int getRXCounter() { return rx; } public int getConnectsCounter () { return connects; } public long getLastTxnTimestampInMillis() { return lastTxn; } public long getIdleTimeInMillis() { return lastTxn > 0L ? System.currentTimeMillis() - lastTxn : -1L; } public String getSocketFactory() { return getProperty(getProperties ("channel"), "socketFactory"); } public void dump (PrintStream p, String indent) { p.println (indent + getCountersAsString()); } protected Space grabSpace (Element e) { return SpaceFactory.getSpace (e != null ? e.getText() : ""); } protected void append (StringBuffer sb, String name, int value) { sb.append (name); sb.append (value); } }
package com.elmakers.mine.bukkit.utility.help; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import java.util.regex.Pattern; import javax.annotation.Nonnull; import org.apache.commons.lang.StringUtils; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.plugin.Plugin; import com.elmakers.mine.bukkit.ChatUtils; import com.elmakers.mine.bukkit.api.magic.Mage; import com.elmakers.mine.bukkit.utility.ConfigurationUtils; import com.elmakers.mine.bukkit.utility.Messages; public class Help { // It is tempting to ignore two-letter words, but we have things like "sp" public static final int MIN_WORD_LENGTH = 2; private static double DEFAULT_WEIGHT = 0.00001; private static double META_WEIGHT_MAX = 0.95; private static double META_WEIGHT_MIN = 0.75; private static double STOP_WEIGHT = 0; private final Messages messages; private final Map<String, HelpTopic> topics = new HashMap<>(); private final Map<String, HelpTopicWord> words = new HashMap<>(); private final Set<String> stopWords = new HashSet<>(); private final Map<String, String> metaTemplates = new HashMap<>(); // We cheat and use one regex for both <li> and <link ...> private static final Pattern linkPattern = Pattern.compile("([^`])(<li[^>]*>)([^`])"); protected int maxCount = 0; protected int maxTopicCount = 0; protected int maxLength = 0; public Help(Messages messages) { this.messages = messages; } public void reset() { maxCount = 0; maxTopicCount = 0; maxLength = 0; topics.clear(); words.clear(); metaTemplates.clear(); } public void resetStats() { for (HelpTopicWord word : words.values()) { word.reset();; } } public void loadMessages(ConfigurationSection messages) { ConfigurationSection helpSection = messages.getConfigurationSection("help"); ConfigurationSection examplesSection = messages.getConfigurationSection("examples"); ConfigurationSection metaSection = messages.getConfigurationSection("meta"); ConfigurationSection exampleSection = messages.getConfigurationSection("example"); loadMetaTemplates(metaSection); if (examplesSection != null && exampleSection != null) { processExamples(examplesSection, exampleSection); } if (helpSection != null) { ConfigurationSection helpExamples = helpSection.getConfigurationSection("examples"); if (helpExamples != null) { ConfigurationUtils.addConfigurations(helpExamples, examplesSection); } else { helpSection.set("examples", examplesSection); } load(helpSection); } List<String> stopWords = messages.getStringList("stop"); messages.set("stop", null); this.stopWords.addAll(stopWords); } private void processExamples(ConfigurationSection examplesSection, ConfigurationSection exampleSection) { Set<String> examples = examplesSection.getKeys(false); for (String exampleKey : examples) { String instructionsKey = exampleKey + ".instructions"; String instructions = examplesSection.getString(instructionsKey); if (instructions == null) continue; String template = exampleSection.getString("instructions_additional"); instructions += "\n" + template.replace("$example", exampleKey); examplesSection.set(instructionsKey, instructions); } } private void load(ConfigurationSection helpSection) { Collection<String> keys = helpSection.getKeys(true); for (String key : keys) { if (helpSection.isConfigurationSection(key)) continue; String value = helpSection.getString(key); loadTopic(key, value); } } public void loadTopic(String key, String contents) { loadTopic(key, contents, "", "", 1.0); } public void loadTopic(String key, String contents, String tags, String topicType, double weight) { HelpTopic helpTopic = new HelpTopic(messages, key, contents, tags, topicType, weight); topics.put(key, helpTopic); // Index all words Map<String, Integer> wordCounts = helpTopic.getWordCounts(); for (Map.Entry<String, Integer> wordEntry : wordCounts.entrySet()) { String word = wordEntry.getKey(); HelpTopicWord wordCount = words.get(word); if (wordCount == null) { wordCount = new HelpTopicWord(word); words.put(word, wordCount); } wordCount.addTopic(wordEntry.getValue()); maxCount = Math.max(maxCount, wordCount.getCount()); maxTopicCount = Math.max(maxTopicCount, wordCount.getTopicCount()); maxLength = Math.max(maxLength, word.length()); } } private void loadMetaTemplates(ConfigurationSection metaSection) { if (metaSection == null) return; for (String key : metaSection.getKeys(true)) { metaTemplates.put(key, metaSection.getString(key)); } } public void loadMetaActions(Map<String, Map<String, Object>> actions) { loadMetaClassed(actions, "action", "action spell", "reference"); } public void loadMetaEffects(Map<String, Map<String, Object>> effects) { loadMetaClassed(effects, "effect", "effectlib spell", "reference"); } private String convertMetaDescription(String description) { return linkPattern.matcher(description).replaceAll("$1`$2`$3"); } @SuppressWarnings("unchecked") private void loadMetaClassed(Map<String, Map<String, Object>> meta, String metaType, String tags, String topicType) { String typeTemplate = metaTemplates.get(metaType + "_template"); String defaultDescription = metaTemplates.get("default_description"); String defaultParameterDescription = metaTemplates.get("default_parameter_description"); String parameterTemplate = metaTemplates.get("parameter_template"); String parameterExtraLineTemplate = metaTemplates.get("parameter_extra_line"); String parametersTemplate = metaTemplates.get("parameters_template"); String examplesTemplate = metaTemplates.get("examples_template"); String exampleTemplate = metaTemplates.get("example_template"); String descriptionTemplate = metaTemplates.get("description_template"); for (Map.Entry<String, Map<String, Object>> entry : meta.entrySet()) { Map<String, Object> action = entry.getValue(); String key = entry.getKey(); String shortClass = (String)action.get("short_class"); if (shortClass == null) continue; List<String> descriptionList = (List<String>)action.get("description"); if (descriptionList.size() == 1 && descriptionList.get(0).trim().isEmpty()) { descriptionList.isEmpty(); } String description; if (descriptionList.isEmpty()) { description = descriptionTemplate.replace("$description", defaultDescription); } else { for (int i = 0; i < descriptionList.size(); i++) { descriptionList.set(i, descriptionTemplate.replace("$description", descriptionList.get(i))); } description = StringUtils.join(descriptionList, "\n"); } description = typeTemplate.replace("$class", shortClass) .replace("$description", description) .replace("$key", key); String metaCategory = (String)action.get("category"); if (metaCategory != null && !metaCategory.isEmpty()) { tags += " " + metaCategory; } Object rawExamples = action.get("examples"); if (rawExamples != null && rawExamples instanceof List) { List<String> exampleList = (List<String>)rawExamples; for (int i = 0; i < exampleList.size(); i++) { exampleList.set(i, exampleTemplate.replace("$example", exampleList.get(i))); } description += "\n" + examplesTemplate.replace("$examples", StringUtils.join(exampleList, " ")); } int importance = 0; Object rawImportance = action.get("importance"); if (rawImportance != null && rawImportance instanceof Integer) { importance = (Integer)rawImportance; } Object rawParameters = action.get("parameters"); // The conversion process turns empty maps into empty lists if (rawParameters != null && rawParameters instanceof Map) { Map<String, Object> parameters = (Map<String, Object>)rawParameters; if (parameters != null && !parameters.isEmpty()) { List<String> parameterLines = new ArrayList<>(); for (Map.Entry<String, Object> parameterEntry : parameters.entrySet()) { String parameterDescription = parameterEntry.getValue().toString(); if (parameterDescription.isEmpty()) { parameterDescription = defaultParameterDescription; } // This is delimited by an escaped \n String[] descriptionLines = parameterDescription.split("\\\\n"); parameterLines.add(parameterTemplate .replace("$parameter", parameterEntry.getKey()) .replace("$description", descriptionLines[0]) ); for (int i = 1; i < descriptionLines.length; i++) { parameterLines.add(parameterExtraLineTemplate .replace("$parameter", parameterEntry.getKey()) .replace("$description", descriptionLines[i]) ); } } description += "\n" + parametersTemplate.replace("$parameters", StringUtils.join(parameterLines, "\n")); } } description = convertMetaDescription(description); double weight = (Math.min(importance, 100) / 100) * (META_WEIGHT_MAX - META_WEIGHT_MIN) + META_WEIGHT_MIN; // hacky plural here, be warned loadTopic("reference." + metaType + "s." + key, description, tags, topicType, weight); } } public Set<String> getWords() { return words.keySet(); } public double getWeight(String word) { if (maxCount == 0 || maxLength == 0 || maxTopicCount == 0) { return DEFAULT_WEIGHT; } HelpTopicWord wordCount = words.get(word); if (wordCount == null) { return DEFAULT_WEIGHT; } double weight = wordCount.getWeight(this); if (stopWords.contains(word)) { weight *= STOP_WEIGHT; } return weight; } public String getDebugText(String word) { HelpTopicWord wordCount = words.get(word); if (wordCount == null) { return ""; } return wordCount.getDebugText(this); } public boolean showTopic(Mage mage, String key) { HelpTopic topic = topics.get(key); if (topic == null) { return false; } mage.sendMessage(topic.getText()); return true; } public HelpTopic getTopic(String key) { return topics.get(key); } @Nonnull public List<HelpTopicMatch> findMatches(List<String> keywords, int listLength) { List<HelpTopicMatch> matches = new ArrayList<>(); for (HelpTopic topic : topics.values()) { HelpTopicMatch match = topic.match(this, keywords); if (match.isRelevant()) { matches.add(match); } } // Group by topic type, make sure to show at least one topic of each type Map<String, Queue<HelpTopicMatch>> grouped = new HashMap<>(); for (HelpTopicMatch match : matches) { String topicType = match.getTopic().getTopicType(); Queue<HelpTopicMatch> groupedList = grouped.get(topicType); if (groupedList == null) { groupedList = new PriorityQueue<>(); grouped.put(topicType, groupedList); } groupedList.add(match); } // Merge each list in matches.clear(); List<HelpTopicMatch> batch = new ArrayList<>(); Set<String> addedThisPage = new HashSet<>(); int thisPageCount = 0; while (!grouped.isEmpty()) { Iterator<Map.Entry<String, Queue<HelpTopicMatch>>> it = grouped.entrySet().iterator(); if (grouped.size() == 1) { matches.addAll(it.next().getValue()); break; } String bestMatchType = null; HelpTopicMatch bestMatch = null; while (it.hasNext()) { Map.Entry<String, Queue<HelpTopicMatch>> entry = it.next(); Queue<HelpTopicMatch> typeMatches = entry.getValue(); if (typeMatches.isEmpty()) { it.remove(); continue; } HelpTopicMatch match = typeMatches.peek(); if (bestMatch == null || match.getRelevance() > bestMatch.getRelevance()) { bestMatch = match; bestMatchType = entry.getKey(); } } if (bestMatch == null) break; grouped.get(bestMatchType).remove(); addedThisPage.add(bestMatchType); batch.add(bestMatch); thisPageCount++; // See if we should add at least one entry from each type we have not yet added int haveNotAdded = grouped.size() - addedThisPage.size(); // Check for end of page, each page is sorted if (thisPageCount >= listLength - haveNotAdded) { if (haveNotAdded > 0) { for (Map.Entry<String, Queue<HelpTopicMatch>> entry : grouped.entrySet()) { if (!addedThisPage.contains(entry.getKey())) { batch.add(entry.getValue().remove()); } } } Collections.sort(batch); matches.addAll(batch); // Reset state for next page batch.clear(); addedThisPage.clear();; thisPageCount = 0; } } // Add anything remaining Collections.sort(batch); matches.addAll(batch); return matches; } public void search(Mage mage, String[] args, int maxTopics) { // This may seem roundabout, but handles punctuation nicely List<String> keywords = Arrays.asList(ChatUtils.getWords(StringUtils.join(args, " ").toLowerCase())); List<HelpTopicMatch> matches = findMatches(keywords, maxTopics); // This is called async, move back to the main thread to do messaging ShowTopicsTask showTask = new ShowTopicsTask(this, mage, keywords, matches, maxTopics); Plugin plugin = mage.getController().getPlugin(); plugin.getServer().getScheduler().runTask(plugin, showTask); } public boolean isValidWord(String keyword) { if (keyword.length() < MIN_WORD_LENGTH) return false; if (stopWords.contains(keyword)) return false; return true; } }
package com.mj; import org.apache.kafka.clients.producer.Callback; import org.apache.kafka.clients.producer.KafkaProducer ; // import kafka.producer.KeyedMessage; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.clients.producer.RecordMetadata; import java.util.Properties; import java.util.concurrent.Future; public class KafkaProducer082 { public static void main(String[] args) { // TODO Auto-generated method stub Properties props = new Properties(); // props.put("metadata.broker.list", "host2:9092,host3:9092"); props.put("bootstrap.servers", "localhost:9092"); // props.put("serializer.class", "kafka.serializer.StringEncoder"); props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); // props.put("partitioner.class", "example.producer.SimplePartitioner"); props.put("request.required.acks", "1"); KafkaProducer<String, String> producer = new KafkaProducer<String, String>(props); String date = "04092014" ; // String topic = "my-replicated-topic" ; String topic = "mjtopic" ; for (int i = 1 ; i <= 1000000 ; i++) { String msg = date + " This is message " + i ; ProducerRecord<String, String> data = new ProducerRecord<String, String>(topic, String.valueOf(i), msg); Future<RecordMetadata> rs = producer.send(data, new Callback() { @Override public void onCompletion(RecordMetadata recordMetadata, Exception e) { System.out.println("Received ack for partition=" + recordMetadata.partition() + " offset = " + recordMetadata.offset()) ; } }); try { RecordMetadata rm = rs.get(); msg = msg + " partition = " + rm.partition() + " offset =" + rm.offset() ; System.out.println(msg) ; } catch(Exception e) { System.out.println(e) ; } } producer.close(); } }
package com.acmapps.openbrowser; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.*; import android.app.ActionBar; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.view.*; import android.os.*; import android.webkit.*; import android.widget.*; @TargetApi(Build.VERSION_CODES.HONEYCOMB) @SuppressLint("SetJavaScriptEnabled") public class MainActivity extends Activity implements PopupMenu.OnMenuItemClickListener { int version = Build.VERSION.SDK_INT ; public WebView mWebView; String homeURL = "http://google.com/"; @SuppressLint("NewApi") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.new_layout); final ProgressBar loadingProgressBar; mWebView = (WebView) findViewById(R.id.webView); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); boolean incognitoCheckBox = sharedPreferences.getBoolean("incognitoCheckBox", false); if (incognitoCheckBox == true){ mWebView.loadUrl("file:///android_asset/index_private.html"); //webView Settings mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); mWebView.getSettings().setSupportZoom(true); mWebView.getSettings().supportZoom(); mWebView.getSettings().setBuiltInZoomControls(true); mWebView.getSettings().setSaveFormData(false); CookieManager.getInstance().setAcceptCookie(false); mWebView.getSettings().setCacheMode(mWebView.getSettings().LOAD_NO_CACHE); mWebView.getSettings().setAppCacheEnabled(false); Context context = getApplicationContext(); CharSequence text = "Incognito Mode Activated"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); } else { mWebView.loadUrl("file:///android_asset/index.html"); //webView Settings mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); mWebView.getSettings().setSupportZoom(true); mWebView.getSettings().supportZoom(); mWebView.getSettings().setBuiltInZoomControls(true); mWebView.getSettings().setSaveFormData(true); CookieManager.getInstance().setAcceptCookie(true); mWebView.getSettings().setCacheMode(mWebView.getSettings().LOAD_DEFAULT); mWebView.getSettings().setAppCacheEnabled(true); } if (version >= Build.VERSION_CODES.HONEYCOMB){ mWebView.getSettings().setDisplayZoomControls(false); } mWebView.setWebViewClient(new OBWebViewClient()); loadingProgressBar = (ProgressBar) findViewById(R.id.progressBar); mWebView.setWebChromeClient(new WebChromeClient() { //This will be called on page loading progress @Override public void onProgressChanged(WebView view, int newProgress) { TextView mTextView = (TextView) findViewById(R.id.urlTitleText); EditText mEditText = (EditText) findViewById(R.id.addressText); String title = mWebView.getTitle(); super.onProgressChanged(view, newProgress); loadingProgressBar.setProgress(newProgress); if (newProgress == 100) { loadingProgressBar.setVisibility(View.GONE); mTextView.setVisibility(View.VISIBLE); if (title == null){ mTextView.setText("OpenBrowser"); }else if (!title.equals(null)) { mTextView.setText(title + " - OpenBrowser"); } CharSequence address = mWebView.getUrl(); if (!address.equals("file:///android_asset/index.html")){ mEditText.setText(address); } if (address.equals("file:///android_asset/index_private.html")) { mEditText.setText(""); } else { mEditText.setText(""); } mTextView.setVisibility(View.VISIBLE); } else { loadingProgressBar.setVisibility(View.VISIBLE); mTextView.setVisibility(View.INVISIBLE); } } }); hideActionBar(); //Keep Keyboard from auto popping up this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) { mWebView.goBack(); return true; } return super.onKeyDown(keyCode, event); } private class OBWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } } @TargetApi(Build.VERSION_CODES.HONEYCOMB) public void hideActionBar(){ if (version >= Build.VERSION_CODES.HONEYCOMB){ ActionBar actionBar = getActionBar(); if (actionBar != null) { actionBar.hide(); } } } @SuppressWarnings("ConstantConditions") public void goClick(View view){ //Get URL from EditText mWebView = (WebView) findViewById(R.id.webView); EditText mEditText = (EditText) findViewById(R.id.addressText); String url = mEditText.getText().toString(); mWebView.loadUrl("http://" + url); } public void backButton(View view){ mWebView.goBack(); } public void fwdButton(View view){ mWebView.goForward(); } public void stopButton(View view){ mWebView.stopLoading(); Context context = getApplicationContext(); CharSequence text = "Stopping Page Load"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); } public void refreshButton(View view){ mWebView.reload(); } public void homeButton(View view){ mWebView.loadUrl(homeURL); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) public void showPopup(View v) { PopupMenu mypopupmenu = new PopupMenu(this, v); mypopupmenu.setOnMenuItemClickListener(this); MenuInflater inflater = mypopupmenu.getMenuInflater(); inflater.inflate(R.menu.popup_actions, mypopupmenu.getMenu()); mypopupmenu.show(); } @Override public boolean onMenuItemClick(MenuItem arg0) { switch (arg0.getItemId()) { case R.id.settings: Intent intent = new Intent(this, Preferences.class); startActivity(intent); return true; default: return super.onContextItemSelected(arg0); } } @SuppressWarnings("deprecation") public void onLowMemory(){ WebView mWebView = (WebView) findViewById(R.id.webView); if(version <= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1 ){ //Attemts to free memory from the webView mWebView.freeMemory(); } } }
package panowow.pdfscaner; import com.itextpdf.text.error_messages.MessageLocalization; import com.itextpdf.text.pdf.*; import com.itextpdf.text.pdf.parser.FilteredTextRenderListener; import com.itextpdf.text.pdf.parser.MarkedContentRenderFilter; import com.itextpdf.text.pdf.parser.PdfContentStreamProcessor; import com.itextpdf.text.pdf.parser.RenderFilter; import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy; import com.itextpdf.text.pdf.parser.TextExtractionStrategy; import com.itextpdf.text.xml.XMLUtil; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Set; import org.apache.log4j.Logger; /** * Converts a tagged PDF document into an XML file. * * @since 5.0.2 */ public class TaggedPdfParser { /** The reader object from which the content streams are read. */ protected PdfReader reader; /** The writer object to which the XML will be written */ protected PrintWriter out; /** The MeataData object to which the tag counts will be recorded */ protected TagMetaData meatadata; /**Flag to remove UA tags while parsing or just report on UA tags */ private boolean ripouttags = false; protected PdfTextchecker pdfTextchecker; private static Logger logger = Logger.getLogger(TaggedPdfParser.class.getName()); public TaggedPdfParser(PdfTextchecker pdfTextchecker) { this.pdfTextchecker = pdfTextchecker; } /** * Parses a string with structured content. * * @param reader * the PdfReader that has access to the PDF file * @param os * the OutputStream to which the resulting xml will be written * @param charset * the charset to encode the data * @since 5.0.5 */ public void convertToXml(PdfReader reader, OutputStream os, String charset) throws IOException { this.reader = reader; OutputStreamWriter outs = new OutputStreamWriter(os, charset); out = new PrintWriter(outs); // get the StructTreeRoot from the root object PdfDictionary catalog = reader.getCatalog(); PdfDictionary struct = catalog.getAsDict(PdfName.STRUCTTREEROOT); if (struct == null) throw new IOException(MessageLocalization.getComposedMessage("no.structtreeroot.found")); // Inspect the child or children of the StructTreeRoot inspectChild(struct.getDirectObject(PdfName.K)); out.flush(); out.close(); } /** * Parses a string with structured content. The output is done using the current * charset. * * @param reader * the PdfReader that has access to the PDF file * @param os * the OutputStream to which the resulting xml will be written */ public void convertToXml(PdfReader reader, FileOutputStream os) throws IOException { // no tagmetadata is pass, go for it and remove ua tags this.ripouttags = true; convertToXml(reader, os, "UTF-8"); } public void convertToXml(PdfReader reader, FileOutputStream os, TagMetaData md) throws IOException { // tagmetadata is passed so don't rip UA tags this.ripouttags = false; meatadata = md; convertToXml(reader, os, "UTF-8"); } /** * Inspects a child of a structured element. This can be an array or a * dictionary. * * @param k * the child to inspect * @throws IOException */ public void inspectChild(PdfObject k) throws IOException { if (k == null) return; if (k instanceof PdfArray) inspectChildArray((PdfArray) k); else if (k instanceof PdfDictionary) inspectChildDictionary((PdfDictionary) k); } /** * If the child of a structured element is an array, we need to loop over * the elements. * * @param k * the child array to inspect */ public void inspectChildArray(PdfArray k) throws IOException { if (k == null) return; for (int i = 0; i < k.size(); i++) { inspectChild(k.getDirectObject(i)); } } /** * If the child of a structured element is a dictionary, we inspect the * child; we may also draw a tag. * * @param k * the child dictionary to inspect */ public void inspectChildDictionary(PdfDictionary k) throws IOException { inspectChildDictionary(k, false); } /** * If the child of a structured element is a dictionary, we inspect the * child; we may also draw a tag. * * @param k * the child dictionary to inspect */ public void inspectChildDictionary(PdfDictionary k, boolean inspectAttributes) throws IOException { if (k == null) return; PdfName s = k.getAsName(PdfName.S); if (ripouttags) { manipulate(k); } else { recordStructure(k); } if (s != null) { String tagN = PdfName.decodeName(s.toString()); String tag = fixTagName(tagN); out.print("<"); out.print(tag); if (inspectAttributes) { PdfDictionary a = k.getAsDict(PdfName.A); if (a != null) { Set<PdfName> keys = a.getKeys(); for (PdfName key : keys) { out.print(' '); PdfObject value = a.get(key); value = PdfReader.getPdfObject(value); out.print(xmlName(key)); out.print("=\""); out.print(value.toString()); out.print("\""); } } } out.print(">"); PdfObject alt = k.get(PdfName.ALT); if (alt != null && alt.toString() != null) { out.print("<alt><![CDATA["); out.print(alt.toString().replaceAll("[\\000]*", "")); out.print("]]></alt>"); } PdfDictionary dict = k.getAsDict(PdfName.PG); if (dict != null) parseTag(tagN, k.getDirectObject(PdfName.K), dict); inspectChild(k.getDirectObject(PdfName.K)); out.print("</"); out.print(tag); out.println(">"); } else inspectChild(k.getDirectObject(PdfName.K)); } protected String xmlName(PdfName name) { String xmlName = name.toString().replaceFirst("/", ""); xmlName = Character.toLowerCase(xmlName.charAt(0)) + xmlName.substring(1); return xmlName; } private static String fixTagName(String tag) { StringBuilder sb = new StringBuilder(); for (int k = 0; k < tag.length(); ++k) { char c = tag.charAt(k); boolean nameStart = c == ':' || (c >= 'A' && c <= 'Z') || c == '_' || (c >= 'a' && c <= 'z') || (c >= '\u00c0' && c <= '\u00d6') || (c >= '\u00d8' && c <= '\u00f6') || (c >= '\u00f8' && c <= '\u02ff') || (c >= '\u0370' && c <= '\u037d') || (c >= '\u037f' && c <= '\u1fff') || (c >= '\u200c' && c <= '\u200d') || (c >= '\u2070' && c <= '\u218f') || (c >= '\u2c00' && c <= '\u2fef') || (c >= '\u3001' && c <= '\ud7ff') || (c >= '\uf900' && c <= '\ufdcf') || (c >= '\ufdf0' && c <= '\ufffd'); boolean nameMiddle = c == '-' || c == '.' || (c >= '0' && c <= '9') || c == '\u00b7' || (c >= '\u0300' && c <= '\u036f') || (c >= '\u203f' && c <= '\u2040') || nameStart; if (k == 0) { if (!nameStart) c = '_'; } else { if (!nameMiddle) c = '-'; } sb.append(c); } return sb.toString(); } public void manipulate(PdfDictionary element) { if (element == null) return; /* Tables */ if (this.pdfTextchecker.uatable.isSelected()) { if (PdfName.TABLE.equals(element.get(PdfName.S))) { // element.put(PdfName.ALT, new PdfString("Figure without an Alt // description")); logger.debug("Table Found and removed"); element.remove(PdfName.S); } } if (this.pdfTextchecker.uatablerow.isSelected()) { if (PdfName.TABLEROW.equals(element.get(PdfName.S))) { element.remove(PdfName.S); } } if (this.pdfTextchecker.uath.isSelected()) { if (PdfName.TH.equals(element.get(PdfName.S))) { element.remove(PdfName.S); } } /*Headers*/ /* Old Acrobat 7.x headers */ PdfName oldh1 = new PdfName("heading 1"); PdfName oldh2 = new PdfName("heading 2"); PdfName oldh3 = new PdfName("heading 3"); PdfName oldh4 = new PdfName("heading 4"); PdfName oldh5 = new PdfName("heading 5"); if (this.pdfTextchecker.ua7headers.isSelected()) { if (oldh1.equals(element.get(PdfName.S))) { element.remove(PdfName.S); logger.debug("heading 1 Found and removed"); } if (oldh2.equals(element.get(PdfName.S))) { element.remove(PdfName.S); logger.debug("heading 2 Found and removed"); } if (oldh3.equals(element.get(PdfName.S))) { element.remove(PdfName.S); logger.debug("heading 3 Found and removed"); } if (oldh4.equals(element.get(PdfName.S))) { element.remove(PdfName.S); logger.debug("heading 4 Found and removed"); } if (oldh5.equals(element.get(PdfName.S))) { element.remove(PdfName.S); logger.debug("heading 5 Found and removed"); } } /*Headers*/ if (this.pdfTextchecker.uaH2H6.isSelected()) { if (PdfName.H2.equals(element.get(PdfName.S)) || oldh2.equals(element.get(PdfName.S))) { element.remove(PdfName.S); logger.debug("Header H2 Found and removed"); } if (PdfName.H3.equals(element.get(PdfName.S))) { element.remove(PdfName.S); logger.debug("Header H3 Found and removed"); } if (PdfName.H4.equals(element.get(PdfName.S))) { element.remove(PdfName.S); logger.debug("Header H4 Found and removed"); } if (PdfName.H5.equals(element.get(PdfName.S))) { element.remove(PdfName.S); logger.debug("Header H5 Found and removed"); } if (PdfName.H6.equals(element.get(PdfName.S))) { element.remove(PdfName.S); logger.debug("Header H6 Found and removed"); } } /* Lists */ if (this.pdfTextchecker.ual.isSelected()) { if (PdfName.L.equals(element.get(PdfName.S))) { element.remove(PdfName.S); logger.debug("List L Found and removed"); } } if (this.pdfTextchecker.uali.isSelected()) { if (PdfName.LI.equals(element.get(PdfName.S))) { element.remove(PdfName.S); logger.debug("List LI Found and removed"); } } /* Figures */ if (this.pdfTextchecker.uafigure.isSelected()) { if (PdfName.FIGURE.equals(element.get(PdfName.S))) { element.remove(PdfName.S); logger.debug("Figure Found and removed"); } } PdfName captionfig = new PdfName("Caption Figure"); if (captionfig.equals(element.get(PdfName.S))) { element.remove(PdfName.S); logger.debug("Caption Figure Found and removed"); } /* charts */ if (this.pdfTextchecker.uachart.isSelected()) { PdfName chart = new PdfName("Chart"); if (chart.equals(element.get(PdfName.S))) { element.remove(PdfName.S); logger.debug("Chart Found and removed"); } } if (this.pdfTextchecker.uainlineshape.isSelected()) { /* InlineShapes */ PdfName inlineshape = new PdfName("InlineShape"); if (inlineshape.equals(element.get(PdfName.S))) { element.remove(PdfName.S); logger.debug("inlineshape Found and removed"); } } /* Shapes */ if (this.pdfTextchecker.uashape.isSelected()) { PdfName shape = new PdfName("Shape"); if (shape.equals(element.get(PdfName.S))) { element.remove(PdfName.S); logger.debug("shape Found and removed"); } } /*Tables of Contents and Links */ if (this.pdfTextchecker.uatoc.isSelected()) { if (PdfName.TOC.equals(element.get(PdfName.S))) { element.remove(PdfName.S); logger.debug("TOC Found and removed"); } } if (this.pdfTextchecker.uatoci.isSelected()) { if (PdfName.TOCI.equals(element.get(PdfName.S))) { element.remove(PdfName.S); logger.debug("TOCI Found and removed"); } } if (this.pdfTextchecker.ualink.isSelected()) { if (PdfName.LINK.equals(element.get(PdfName.S))) { element.remove(PdfName.S); logger.debug("LINK Found and removed"); } } } public void recordStructure(PdfDictionary element) { if (element == null) return; /*Tables */ if (PdfName.TABLE.equals(element.get(PdfName.S))) { //element.put(PdfName.ALT, new PdfString("Figure without an Alt description")); logger.debug("Table Found and noted."); //write plus one to TagCounts this.meatadata.setNumtableP1(); } if (PdfName.TABLEROW.equals(element.get(PdfName.S))) { //write plus one to TagCounts logger.debug("Table row found"); this.meatadata.setNumtablerowP1(); } if (PdfName.TH.equals(element.get(PdfName.S))) { //write plus one to TagCounts logger.debug("Table header found"); this.meatadata.setNumtableTHP1(); } /*Headers*/ if (PdfName.H2.equals(element.get(PdfName.S))) { //write plus one to TagCounts logger.debug("Header H2 Found and noted."); this.meatadata.setNumH2P1(); } if (PdfName.H3.equals(element.get(PdfName.S))) { //write plus one to TagCounts logger.debug("Header H3 Found and noted."); this.meatadata.setNumH3P1(); } if (PdfName.H4.equals(element.get(PdfName.S))) { //write plus one to TagCounts logger.debug("Header H4 Found and noted."); this.meatadata.setNumH4P1(); } if (PdfName.H5.equals(element.get(PdfName.S))) { //write plus one to TagCounts logger.debug("Header H5 Found and noted."); this.meatadata.setNumH5P1(); } /*Lists*/ if (PdfName.L.equals(element.get(PdfName.S))) { //write plus one to TagCounts logger.debug("List L Found and noted."); this.meatadata.setNumLP1(); } if (PdfName.LI.equals(element.get(PdfName.S))) { //write plus one to TagCounts logger.debug("List LI Found and noted."); this.meatadata.setNumLIP1(); } /*Figures*/ if (PdfName.FIGURE.equals(element.get(PdfName.S))) { this.meatadata.setNumfiguresP1(); //write plus one to TagCounts logger.debug("Figure Found and noted."); } } /** * Searches for a tag in a page. * * @param tag * the name of the tag * @param object * an identifier to find the marked content * @param page * a page dictionary * @throws IOException */ public void parseTag(String tag, PdfObject object, PdfDictionary page) throws IOException { // if the identifier is a number, we can extract the content right away if (object instanceof PdfNumber) { PdfNumber mcid = (PdfNumber) object; RenderFilter filter = new MarkedContentRenderFilter(mcid.intValue()); TextExtractionStrategy strategy = new SimpleTextExtractionStrategy(); FilteredTextRenderListener listener = new FilteredTextRenderListener( strategy, filter); PdfContentStreamProcessor processor = new PdfContentStreamProcessor( listener); processor.processContent(PdfReader.getPageContent(page), page .getAsDict(PdfName.RESOURCES)); out.print(XMLUtil.escapeXML(listener.getResultantText(), true)); } // if the identifier is an array, we call the parseTag method // recursively else if (object instanceof PdfArray) { PdfArray arr = (PdfArray) object; int n = arr.size(); for (int i = 0; i < n; i++) { parseTag(tag, arr.getPdfObject(i), page); if (i < n - 1) out.println(); } } // if the identifier is a dictionary, we get the resources from the // dictionary else if (object instanceof PdfDictionary) { PdfDictionary mcr = (PdfDictionary) object; parseTag(tag, mcr.getDirectObject(PdfName.MCID), mcr .getAsDict(PdfName.PG)); } } }
// This file is part of OpenTSDB. // This program is free software: you can redistribute it and/or modify it // option) any later version. This program is distributed in the hope that it // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser package net.opentsdb.storage; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.mock; import java.io.IOException; import java.lang.reflect.Field; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashSet; import java.util.Map; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import javax.xml.bind.DatatypeConverter; import net.opentsdb.core.TSDB; import net.opentsdb.utils.Config; import org.hbase.async.AtomicIncrementRequest; import org.hbase.async.Bytes; import org.hbase.async.DeleteRequest; import org.hbase.async.GetRequest; import org.hbase.async.HBaseClient; import org.hbase.async.KeyValue; import org.hbase.async.PutRequest; import org.hbase.async.Scanner; import org.junit.Ignore; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import com.stumbleupon.async.Deferred; /** * Mock HBase implementation useful in testing calls to and from storage with * actual pretend data. The underlying data store is the ByteMap from Asyncbase * so it stores and orders byte arrays similar to HBase. * <p> * It's not a perfect mock but is useful for the majority of unit tests. Gets, * puts, cas, deletes and scans are currently supported. See notes for each * inner class below about what does and doesn't work. * <p> * <b>Note:</b> At this time, the implementation does not support multiple * column families since almost all unit tests for OpenTSDB only work with one * CF at a time. There is also only one table and we don't have any timestamps. * <p> * <b>Warning:</b> To use this class, you need to prepare the classes for testing * with the @PrepareForTest annotation. The classes you need to prepare are: * <ul><li>TSDB</li> * <li>HBaseClient</li> * <li>GetRequest</li> * <li>PutRequest</li> * <li>KeyValue</li> * <li>Scanner</li> * <li>DeleteRequest</li> * <li>AtomicIncrementRequest</li></ul> * @since 2.0 */ @Ignore public final class MockBase { private static final Charset ASCII = Charset.forName("ISO-8859-1"); private TSDB tsdb; private Bytes.ByteMap<Bytes.ByteMap<Bytes.ByteMap<byte[]>>> storage = new Bytes.ByteMap<Bytes.ByteMap<Bytes.ByteMap<byte[]>>>(); private HashSet<MockScanner> scanners = new HashSet<MockScanner>(2); private byte[] default_family; /** * Setups up mock intercepts for all of the calls. Depending on the given * flags, some mocks may not be enabled, allowing local unit tests to setup * their own mocks. * @param tsdb A real TSDB (not mocked) that should have it's client set with * the given mock * @param client A mock client that may have been instantiated and should be * captured for use with MockBase * @param default_get Enable the default .get() mock * @param default_put Enable the default .put() and .compareAndSet() mocks * @param default_delete Enable the default .delete() mock * @param default_scan Enable the Scanner mock implementation */ public MockBase( final TSDB tsdb, final HBaseClient client, final boolean default_get, final boolean default_put, final boolean default_delete, final boolean default_scan) { this.tsdb = tsdb; default_family = "t".getBytes(ASCII); // set a default // replace the "real" field objects with mocks Field cl; try { cl = tsdb.getClass().getDeclaredField("client"); cl.setAccessible(true); cl.set(tsdb, client); cl.setAccessible(false); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } // Default get answer will return one or more columns from the requested row if (default_get) { when(client.get((GetRequest)any())).thenAnswer(new MockGet()); } // Default put answer will store the given values in the proper location. if (default_put) { when(client.put((PutRequest)any())).thenAnswer(new MockPut()); when(client.compareAndSet((PutRequest)any(), (byte[])any())) .thenAnswer(new MockCAS()); } if (default_delete) { when(client.delete((DeleteRequest)any())).thenAnswer(new MockDelete()); } if (default_scan) { // to facilitate unit tests where more than one scanner is used (i.e. in a // callback chain) we have to provide a new mock scanner for each new // scanner request. That's the way the mock scanner method knows when a // second call has been issued and it should return a null. when(client.newScanner((byte[]) any())).thenAnswer(new Answer<Scanner>() { @Override public Scanner answer(InvocationOnMock arg0) throws Throwable { final Scanner scanner = mock(Scanner.class); scanners.add(new MockScanner(scanner)); return scanner; } }); } when(client.atomicIncrement((AtomicIncrementRequest)any())) .then(new MockAtomicIncrement()); when(client.bufferAtomicIncrement((AtomicIncrementRequest)any())) .then(new MockAtomicIncrement()); } /** * Setups up mock intercepts for all of the calls. Depending on the given * flags, some mocks may not be enabled, allowing local unit tests to setup * their own mocks. * @param default_get Enable the default .get() mock * @param default_put Enable the default .put() and .compareAndSet() mocks * @param default_delete Enable the default .delete() mock * @param default_scan Enable the Scanner mock implementation */ public MockBase( final boolean default_get, final boolean default_put, final boolean default_delete, final boolean default_scan) throws IOException { this(new TSDB(new Config(false)), mock(HBaseClient.class), default_get, default_put, default_delete, default_scan); } /** @param family Sets the family for calls that need it */ public void setFamily(final byte[] family) { this.default_family = family; } /** * Add a column to the hash table using the default column family. * The proper row will be created if it doesn't exist. If the column already * exists, the original value will be overwritten with the new data * @param key The row key * @param qualifier The qualifier * @param value The value to store */ public void addColumn(final byte[] key, final byte[] qualifier, final byte[] value) { addColumn(key, default_family, qualifier, value); } /** * Add a column to the hash table * The proper row will be created if it doesn't exist. If the column already * exists, the original value will be overwritten with the new data * @param key The row key * @param family The column family to store the value in * @param qualifier The qualifier * @param value The value to store */ public void addColumn(final byte[] key, final byte[] family, final byte[] qualifier, final byte[] value) { Bytes.ByteMap<Bytes.ByteMap<byte[]>> row = storage.get(key); if (row == null) { row = new Bytes.ByteMap<Bytes.ByteMap<byte[]>>(); storage.put(key, row); } Bytes.ByteMap<byte[]> cf = row.get(family); if (cf == null) { cf = new Bytes.ByteMap<byte[]>(); row.put(family, cf); } cf.put(qualifier, value); } /** @return TTotal number of rows in the hash table */ public int numRows() { return storage.size(); } /** * Return the total number of column families for the row * @param key The row to search for * @return -1 if the row did not exist, otherwise the number of column families. */ public int numColumnFamilies(final byte[] key) { final Bytes.ByteMap<Bytes.ByteMap<byte[]>> row = storage.get(key); if (row == null) { return -1; } return row.size(); } /** * Total number of columns in the given row across all column families * @param key The row to search for * @return -1 if the row did not exist, otherwise the number of columns. */ public long numColumns(final byte[] key) { final Bytes.ByteMap<Bytes.ByteMap<byte[]>> row = storage.get(key); if (row == null) { return -1; } long size = 0; for (Map.Entry<byte[], Bytes.ByteMap<byte[]>> entry : row) { size += entry.getValue().size(); } return size; } /** * Return the total number of columns for a specific row and family * @param key The row to search for * @param family The column family to search for * @return -1 if the row did not exist, otherwise the number of columns. */ public int numColumnsInFamily(final byte[] key, final byte[] family) { final Bytes.ByteMap<Bytes.ByteMap<byte[]>> row = storage.get(key); if (row == null) { return -1; } final Bytes.ByteMap<byte[]> cf = row.get(family); if (cf == null) { return -1; } return cf.size(); } /** * Retrieve the contents of a single column with the default family * @param key The row key of the column * @param qualifier The column qualifier * @return The byte array of data or null if not found */ public byte[] getColumn(final byte[] key, final byte[] qualifier) { return getColumn(key, default_family, qualifier); } /** * Retrieve the contents of a single column * @param key The row key of the column * @param family The column family * @param qualifier The column qualifier * @return The byte array of data or null if not found */ public byte[] getColumn(final byte[] key, final byte[] family, final byte[] qualifier) { final Bytes.ByteMap<Bytes.ByteMap<byte[]>> row = storage.get(key); if (row == null) { return null; } final Bytes.ByteMap<byte[]> cf = row.get(family); if (cf == null) { return null; } return cf.get(qualifier); } /** * Returns all of the columns for a given column family * @param key The row key * @param family The column family ID * @return A hash of columns if the CF was found, null if no such CF */ public Bytes.ByteMap<byte[]> getColumnFamily(final byte[] key, final byte[] family) { final Bytes.ByteMap<Bytes.ByteMap<byte[]>> row = storage.get(key); if (row == null) { return null; } return row.get(family); } /** * Return the mocked TSDB object to use for HBaseClient access * @return */ public TSDB getTSDB() { return tsdb; } /** * Clears the entire hash table. Use it if your unit test needs to start fresh */ public void flushStorage() { storage.clear(); } /** * Removes the entire row from the hash table * @param key The row to remove */ public void flushRow(final byte[] key) { storage.remove(key); } /** * Removes the entire column family from the hash table for ALL rows * @param family The family to remove */ public void flushFamily(final byte[] family) { for (Map.Entry<byte[], Bytes.ByteMap<Bytes.ByteMap<byte[]>>> row : storage.entrySet()) { row.getValue().remove(family); } } /** * Removes the given column from the hash map * @param key Row key * @param family Column family * @param qualifier Column qualifier */ public void flushColumn(final byte[] key, final byte[] family, final byte[] qualifier) { final Bytes.ByteMap<Bytes.ByteMap<byte[]>> row = storage.get(key); if (row == null) { return; } final Bytes.ByteMap<byte[]> cf = row.get(family); if (cf == null) { return; } cf.remove(qualifier); } /** * Dumps the entire storage hash to stdout in a sort of tree style format with * all byte arrays hex encoded */ public void dumpToSystemOut() { dumpToSystemOut(false); } /** * Dumps the entire storage hash to stdout in a sort of tree style format * @param ascii Whether or not the values should be converted to ascii */ public void dumpToSystemOut(final boolean ascii) { if (storage.isEmpty()) { System.out.println("Storage is Empty"); return; } for (Map.Entry<byte[], Bytes.ByteMap<Bytes.ByteMap<byte[]>>> row : storage.entrySet()) { System.out.println("[Row] " + (ascii ? new String(row.getKey(), ASCII) : bytesToString(row.getKey()))); for (Map.Entry<byte[], Bytes.ByteMap<byte[]>> cf : row.getValue().entrySet()) { final String family = ascii ? new String(cf.getKey(), ASCII) : bytesToString(cf.getKey()); System.out.println(" [CF] " + family); for (Map.Entry<byte[], byte[]> column : cf.getValue().entrySet()) { System.out.println(" [Qual] " + (ascii ? "\"" + new String(column.getKey(), ASCII) + "\"" : bytesToString(column.getKey()))); System.out.println(" [Value] " + (ascii ? new String(column.getValue(), ASCII) : bytesToString(column.getValue()))); } } } } /** * Helper to convert an array of bytes to a hexadecimal encoded string. * @param bytes The byte array to convert * @return A hex string */ public static String bytesToString(final byte[] bytes) { return DatatypeConverter.printHexBinary(bytes); } public static byte[] stringToBytes(final String bytes) { return DatatypeConverter.parseHexBinary(bytes); } /** @return Returns the ASCII character set */ public static Charset ASCII() { return ASCII; } /** * Concatenates byte arrays into one big array * @param arrays Any number of arrays to concatenate * @return The concatenated array */ public static byte[] concatByteArrays(final byte[]... arrays) { int len = 0; for (final byte[] array : arrays) { len += array.length; } final byte[] result = new byte[len]; len = 0; for (final byte[] array : arrays) { System.arraycopy(array, 0, result, len, array.length); len += array.length; } return result; } /** * Gets one or more columns from a row. If the row does not exist, a null is * returned. If no qualifiers are given, the entire row is returned. */ private class MockGet implements Answer<Deferred<ArrayList<KeyValue>>> { @Override public Deferred<ArrayList<KeyValue>> answer(InvocationOnMock invocation) throws Throwable { final Object[] args = invocation.getArguments(); final GetRequest get = (GetRequest)args[0]; final Bytes.ByteMap<Bytes.ByteMap<byte[]>> row = storage.get(get.key()); if (row == null) { return Deferred.fromResult((ArrayList<KeyValue>)null); } final byte[] family = get.family(); if (family != null && family.length > 0) { if (!row.containsKey(family)) { return Deferred.fromResult((ArrayList<KeyValue>)null); } } // compile a set of qualifiers to use as a filter if necessary Bytes.ByteMap<Object> qualifiers = new Bytes.ByteMap<Object>(); if (get.qualifiers() != null && get.qualifiers().length > 0) { for (byte[] q : get.qualifiers()) { qualifiers.put(q, null); } } final ArrayList<KeyValue> kvs = new ArrayList<KeyValue>(row.size()); for (Map.Entry<byte[], Bytes.ByteMap<byte[]>> cf : row.entrySet()) { // column family filter if (family != null && family.length > 0 && !Bytes.equals(family, cf.getKey())) { continue; } for (Map.Entry<byte[], byte[]> entry : cf.getValue().entrySet()) { // qualifier filter if (!qualifiers.isEmpty() && !qualifiers.containsKey(entry.getKey())) { continue; } KeyValue kv = mock(KeyValue.class); when(kv.value()).thenReturn(entry.getValue()); when(kv.qualifier()).thenReturn(entry.getKey()); when(kv.key()).thenReturn(get.key()); kvs.add(kv); } } return Deferred.fromResult(kvs); } } /** * Stores one or more columns in a row. If the row does not exist, it's * created. */ private class MockPut implements Answer<Deferred<Boolean>> { @Override public Deferred<Boolean> answer(final InvocationOnMock invocation) throws Throwable { final Object[] args = invocation.getArguments(); final PutRequest put = (PutRequest)args[0]; Bytes.ByteMap<Bytes.ByteMap<byte[]>> row = storage.get(put.key()); if (row == null) { row = new Bytes.ByteMap<Bytes.ByteMap<byte[]>>(); storage.put(put.key(), row); } Bytes.ByteMap<byte[]> cf = row.get(put.family()); if (cf == null) { cf = new Bytes.ByteMap<byte[]>(); row.put(put.family(), cf); } for (int i = 0; i < put.qualifiers().length; i++) { cf.put(put.qualifiers()[i], put.values()[i]); } return Deferred.fromResult(true); } } /** * Imitates the compareAndSet client call where a {@code PutRequest} is passed * along with a byte array to compared the stored value against. If the stored * value doesn't match, the put is ignored and a "false" is returned. If the * comparator matches, the new put is recorded. * <b>Warning:</b> While a put works on multiple qualifiers, CAS only works * with one. So if the put includes more than one qualifier, only the first * one will be processed in this CAS call. */ private class MockCAS implements Answer<Deferred<Boolean>> { @Override public Deferred<Boolean> answer(final InvocationOnMock invocation) throws Throwable { final Object[] args = invocation.getArguments(); final PutRequest put = (PutRequest)args[0]; final byte[] expected = (byte[])args[1]; Bytes.ByteMap<Bytes.ByteMap<byte[]>> row = storage.get(put.key()); if (row == null) { if (expected != null && expected.length > 0) { return Deferred.fromResult(false); } row = new Bytes.ByteMap<Bytes.ByteMap<byte[]>>(); storage.put(put.key(), row); } Bytes.ByteMap<byte[]> cf = row.get(put.family()); if (cf == null) { if (expected != null && expected.length > 0) { return Deferred.fromResult(false); } cf = new Bytes.ByteMap<byte[]>(); row.put(put.family(), cf); } // CAS can only operate on one cell, so if the put request has more than // one, we ignore any but the first final byte[] stored = cf.get(put.qualifiers()[0]); if (stored == null && (expected != null && expected.length > 0)) { return Deferred.fromResult(false); } if (stored != null && (expected == null || expected.length < 1)) { return Deferred.fromResult(false); } if (stored != null && expected != null && Bytes.memcmp(stored, expected) != 0) { return Deferred.fromResult(false); } // passed CAS! cf.put(put.qualifiers()[0], put.value()); return Deferred.fromResult(true); } } /** * Deletes one or more columns. If a row no longer has any valid columns, the * entire row will be removed. */ private class MockDelete implements Answer<Deferred<Object>> { @Override public Deferred<Object> answer(InvocationOnMock invocation) throws Throwable { final Object[] args = invocation.getArguments(); final DeleteRequest delete = (DeleteRequest)args[0]; Bytes.ByteMap<Bytes.ByteMap<byte[]>> row = storage.get(delete.key()); if (row == null) { return Deferred.fromResult(null); } // if no qualifiers or family, then delete the row if ((delete.qualifiers() == null || delete.qualifiers().length < 1) && (delete.family() == null || delete.family().length < 1)) { return Deferred.fromResult(new Object()); } final byte[] family = delete.family(); if (family != null && family.length > 0) { if (!row.containsKey(family)) { return Deferred.fromResult(null); } } // compile a set of qualifiers to use as a filter if necessary Bytes.ByteMap<Object> qualifiers = new Bytes.ByteMap<Object>(); if (delete.qualifiers() != null || delete.qualifiers().length > 0) { for (byte[] q : delete.qualifiers()) { qualifiers.put(q, null); } } // if the request only has a column family and no qualifiers, we delete // the entire family if (family != null && qualifiers.isEmpty()) { row.remove(family); if (row.isEmpty()) { storage.remove(delete.key()); } return Deferred.fromResult(new Object()); } ArrayList<byte[]> cf_removals = new ArrayList<byte[]>(row.entrySet().size()); for (Map.Entry<byte[], Bytes.ByteMap<byte[]>> cf : row.entrySet()) { // column family filter if (family != null && family.length > 0 && !Bytes.equals(family, cf.getKey())) { continue; } for (byte[] qualifier : qualifiers.keySet()) { cf.getValue().remove(qualifier); } if (cf.getValue().isEmpty()) { cf_removals.add(cf.getKey()); } } for (byte[] cf : cf_removals) { row.remove(cf); } if (row.isEmpty()) { storage.remove(delete.key()); } return Deferred.fromResult(new Object()); } } /** * This is a limited implementation of the scanner object. The only fields * caputred and acted on are: * <ul><li>KeyRegexp</li> * <li>StartKey</li> * <li>StopKey</li> * <li>Qualifier</li> * <li>Qualifiers</li></ul> * Hence timestamps are ignored as are the max number of rows and qualifiers. * All matching rows/qualifiers will be returned in the first {@code nextRows} * call. The second {@code nextRows} call will always return null. Multiple * qualifiers are supported for matching. * <p> * The KeyRegexp can be set and it will run against the hex value of the * row key. In testing it seems to work nicely even with byte patterns. */ private class MockScanner implements Answer<Deferred<ArrayList<ArrayList<KeyValue>>>> { private byte[] start = null; private byte[] stop = null; private HashSet<String> scnr_qualifiers = null; private byte[] family = null; private String regex = null; private boolean called; public MockScanner(final Scanner mock_scanner) { // capture the scanner fields when set doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { final Object[] args = invocation.getArguments(); regex = (String)args[0]; return null; } }).when(mock_scanner).setKeyRegexp(anyString()); doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { final Object[] args = invocation.getArguments(); regex = (String)args[0]; return null; } }).when(mock_scanner).setKeyRegexp(anyString(), (Charset)any()); doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { final Object[] args = invocation.getArguments(); start = (byte[])args[0]; return null; } }).when(mock_scanner).setStartKey((byte[])any()); doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { final Object[] args = invocation.getArguments(); stop = (byte[])args[0]; return null; } }).when(mock_scanner).setStopKey((byte[])any()); doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { final Object[] args = invocation.getArguments(); family = (byte[])args[0]; return null; } }).when(mock_scanner).setFamily((byte[])any()); doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { final Object[] args = invocation.getArguments(); scnr_qualifiers = new HashSet<String>(1); scnr_qualifiers.add(bytesToString((byte[])args[0])); return null; } }).when(mock_scanner).setQualifier((byte[])any()); doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { final Object[] args = invocation.getArguments(); final byte[][] qualifiers = (byte[][])args[0]; scnr_qualifiers = new HashSet<String>(qualifiers.length); for (byte[] qualifier : qualifiers) { scnr_qualifiers.add(bytesToString(qualifier)); } return null; } }).when(mock_scanner).setQualifiers((byte[][])any()); when(mock_scanner.nextRows()).thenAnswer(this); } @Override public Deferred<ArrayList<ArrayList<KeyValue>>> answer( final InvocationOnMock invocation) throws Throwable { // It's critical to see if this scanner has been processed before, // otherwise the code under test will likely wind up in an infinite loop. // If the scanner has been seen before, we return null. if (called) { return Deferred.fromResult(null); } called = true; Pattern pattern = null; if (regex != null && !regex.isEmpty()) { try { pattern = Pattern.compile(regex); } catch (PatternSyntaxException e) { e.printStackTrace(); } } // return all matches ArrayList<ArrayList<KeyValue>> results = new ArrayList<ArrayList<KeyValue>>(); for (Map.Entry<byte[], Bytes.ByteMap<Bytes.ByteMap<byte[]>>> row : storage.entrySet()) { // if it's before the start row, after the end row or doesn't // match the given regex, continue on to the next row if (start != null && Bytes.memcmp(row.getKey(), start) < 0) { continue; } if (stop != null && Bytes.memcmp(row.getKey(), stop) > 0) { continue; } if (pattern != null) { final String from_bytes = new String(row.getKey(), MockBase.ASCII); if (!pattern.matcher(from_bytes).find()) { continue; } } // loop on the column families final ArrayList<KeyValue> kvs = new ArrayList<KeyValue>(row.getValue().size()); for (Map.Entry<byte[], Bytes.ByteMap<byte[]>> cf : row.getValue().entrySet()) { // column family filter if (family != null && family.length > 0 && !Bytes.equals(family, cf.getKey())) { continue; } for (Map.Entry<byte[], byte[]> entry : cf.getValue().entrySet()) { // if the qualifier isn't in the set, continue if (scnr_qualifiers != null && !scnr_qualifiers.contains(bytesToString(entry.getKey()))) { continue; } KeyValue kv = mock(KeyValue.class); when(kv.key()).thenReturn(row.getKey()); when(kv.value()).thenReturn(entry.getValue()); when(kv.qualifier()).thenReturn(entry.getKey()); when(kv.family()).thenReturn(cf.getKey()); when(kv.toString()).thenReturn("[k '" + bytesToString(row.getKey()) + "' q '" + bytesToString(entry.getKey()) + "' v '" + bytesToString(entry.getValue()) + "']"); kvs.add(kv); } } if (!kvs.isEmpty()) { results.add(kvs); } } if (results.isEmpty()) { return Deferred.fromResult(null); } return Deferred.fromResult(results); } } /** * Creates or increments (possibly decremnts) a Long in the hash table at the * given location. */ private class MockAtomicIncrement implements Answer<Deferred<Long>> { @Override public Deferred<Long> answer(InvocationOnMock invocation) throws Throwable { final Object[] args = invocation.getArguments(); final AtomicIncrementRequest air = (AtomicIncrementRequest)args[0]; final long amount = air.getAmount(); Bytes.ByteMap<Bytes.ByteMap<byte[]>> row = storage.get(air.key()); if (row == null) { row = new Bytes.ByteMap<Bytes.ByteMap<byte[]>>(); storage.put(air.key(), row); } Bytes.ByteMap<byte[]> cf = row.get(air.family()); if (cf == null) { cf = new Bytes.ByteMap<byte[]>(); row.put(air.family(), cf); } if (!cf.containsKey(air.qualifier())) { cf.put(air.qualifier(), Bytes.fromLong(amount)); return Deferred.fromResult(amount); } long incremented_value = Bytes.getLong(cf.get(air.qualifier())); incremented_value += amount; cf.put(air.qualifier(), Bytes.fromLong(incremented_value)); return Deferred.fromResult(incremented_value); } } }
package org.jasig.portal.container.om.common; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.apache.pluto.om.common.ObjectID; /** * Wraps around the internal Object IDs. By holding both * the string and the integer version of an Object ID this class * helps speed up the internal processing. Code copied from Apache Pluto. * @author Ken Weiner, kweiner@unicon.net * @version $Revision$ */ public class ObjectIDImpl implements ObjectID, Serializable { private String stringOID = null; private int intOID; private ObjectIDImpl(int oid) { stringOID = String.valueOf(oid); intOID = oid; } private ObjectIDImpl(int oid, String stringOID) { this.stringOID = stringOID; intOID = oid; } // Internal methods. private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { try { intOID = stream.readInt(); } finally { if (stream != null) stream.close(); } stringOID = String.valueOf(intOID); } private void writeObject(ObjectOutputStream stream) throws IOException { try { stream.write(intOID); } finally { if (stream != null) stream.close(); } } // Addtional methods public boolean equals(Object object) { boolean result = false; if (object instanceof ObjectID) result = (intOID == ((ObjectIDImpl)object).intOID); else if (object instanceof String) result = stringOID.equals(object); else if (object instanceof Integer) result = (intOID == ((Integer)object).intValue()); return result; } public int hashCode() { return intOID; } public String toString() { return stringOID; } public int intValue() { return intOID; } static public ObjectID createFromString(String idStr) { char[] id = idStr.toCharArray(); int _id = 1; for (int i = 0; i < id.length; i++) { if ((i % 2) == 0) _id *= id[i]; else _id ^= id[i]; _id = Math.abs(_id); } return new ObjectIDImpl(_id, idStr); } }
package org.jfree.chart.renderer.category; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.List; import org.jfree.chart.LegendItem; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.category.CategoryDataset; import org.jfree.data.statistics.MultiValueCategoryDataset; import org.jfree.util.BooleanList; import org.jfree.util.BooleanUtilities; import org.jfree.util.ObjectUtilities; import org.jfree.util.PublicCloneable; import org.jfree.util.ShapeUtilities; /** * A renderer that handles the multiple values from a * {@link MultiValueCategoryDataset} by plotting a shape for each value for * each given item in the dataset. * * @since 1.0.7 */ public class ScatterRenderer extends AbstractCategoryItemRenderer implements Cloneable, PublicCloneable, Serializable { /** * A table of flags that control (per series) whether or not shapes are * filled. */ private BooleanList seriesShapesFilled; /** * The default value returned by the getShapeFilled() method. */ private boolean baseShapesFilled; /** * A flag that controls whether the fill paint is used for filling * shapes. */ private boolean useFillPaint; /** * A flag that controls whether outlines are drawn for shapes. */ private boolean drawOutlines; /** * A flag that controls whether the outline paint is used for drawing shape * outlines - if not, the regular series paint is used. */ private boolean useOutlinePaint; /** * A flag that controls whether or not the x-position for each item is * offset within the category according to the series. */ private boolean useSeriesOffset; /** * The item margin used for series offsetting - this allows the positioning * to match the bar positions of the {@link BarRenderer} class. */ private double itemMargin; /** * Constructs a new renderer. */ public ScatterRenderer() { this.seriesShapesFilled = new BooleanList(); this.baseShapesFilled = true; this.useFillPaint = false; this.drawOutlines = false; this.useOutlinePaint = false; this.useSeriesOffset = true; this.itemMargin = 0.20; } /** * Returns the flag that controls whether or not the x-position for each * data item is offset within the category according to the series. * * @return A boolean. * * @see #setUseSeriesOffset(boolean) */ public boolean getUseSeriesOffset() { return this.useSeriesOffset; } /** * Sets the flag that controls whether or not the x-position for each * data item is offset within its category according to the series, and * sends a {@link RendererChangeEvent} to all registered listeners. * * @param offset the offset. * * @see #getUseSeriesOffset() */ public void setUseSeriesOffset(boolean offset) { this.useSeriesOffset = offset; notifyListeners(new RendererChangeEvent(this)); } /** * Returns the item margin, which is the gap between items within a * category (expressed as a percentage of the overall category width). * This can be used to match the offset alignment with the bars drawn by * a {@link BarRenderer}). * * @return The item margin. * * @see #setItemMargin(double) * @see #getUseSeriesOffset() */ public double getItemMargin() { return this.itemMargin; } /** * Sets the item margin, which is the gap between items within a category * (expressed as a percentage of the overall category width), and sends * a {@link RendererChangeEvent} to all registered listeners. * * @param margin the margin (0.0 <= margin < 1.0). * * @see #getItemMargin() * @see #getUseSeriesOffset() */ public void setItemMargin(double margin) { if (margin < 0.0 || margin >= 1.0) { throw new IllegalArgumentException("Requires 0.0 <= margin < 1.0."); } this.itemMargin = margin; notifyListeners(new RendererChangeEvent(this)); } /** * Returns <code>true</code> if outlines should be drawn for shapes, and * <code>false</code> otherwise. * * @return A boolean. * * @see #setDrawOutlines(boolean) */ public boolean getDrawOutlines() { return this.drawOutlines; } /** * Sets the flag that controls whether outlines are drawn for * shapes, and sends a {@link RendererChangeEvent} to all registered * listeners. * <p/> * In some cases, shapes look better if they do NOT have an outline, but * this flag allows you to set your own preference. * * @param flag the flag. * * @see #getDrawOutlines() */ public void setDrawOutlines(boolean flag) { this.drawOutlines = flag; notifyListeners(new RendererChangeEvent(this)); } /** * Returns the flag that controls whether the outline paint is used for * shape outlines. If not, the regular series paint is used. * * @return A boolean. * * @see #setUseOutlinePaint(boolean) */ public boolean getUseOutlinePaint() { return this.useOutlinePaint; } /** * Sets the flag that controls whether the outline paint is used for shape * outlines. * * @param use the flag. * * @see #getUseOutlinePaint() */ public void setUseOutlinePaint(boolean use) { this.useOutlinePaint = use; notifyListeners(new RendererChangeEvent(this)); } // SHAPES FILLED /** * Returns the flag used to control whether or not the shape for an item * is filled. The default implementation passes control to the * <code>getSeriesShapesFilled</code> method. You can override this method * if you require different behaviour. * * @param series the series index (zero-based). * @param item the item index (zero-based). * @return A boolean. */ public boolean getItemShapeFilled(int series, int item) { return getSeriesShapesFilled(series); } /** * Returns the flag used to control whether or not the shapes for a series * are filled. * * @param series the series index (zero-based). * @return A boolean. */ public boolean getSeriesShapesFilled(int series) { Boolean flag = this.seriesShapesFilled.getBoolean(series); if (flag != null) { return flag.booleanValue(); } else { return this.baseShapesFilled; } } /** * Sets the 'shapes filled' flag for a series. * * @param series the series index (zero-based). * @param filled the flag. */ public void setSeriesShapesFilled(int series, Boolean filled) { this.seriesShapesFilled.setBoolean(series, filled); notifyListeners(new RendererChangeEvent(this)); } /** * Sets the 'shapes filled' flag for a series. * * @param series the series index (zero-based). * @param filled the flag. */ public void setSeriesShapesFilled(int series, boolean filled) { this.seriesShapesFilled.setBoolean(series, BooleanUtilities.valueOf(filled)); notifyListeners(new RendererChangeEvent(this)); } /** * Returns the base 'shape filled' attribute. * * @return The base flag. */ public boolean getBaseShapesFilled() { return this.baseShapesFilled; } /** * Sets the base 'shapes filled' flag. * * @param flag the flag. */ public void setBaseShapesFilled(boolean flag) { this.baseShapesFilled = flag; notifyListeners(new RendererChangeEvent(this)); } /** * Returns <code>true</code> if the renderer should use the fill paint * setting to fill shapes, and <code>false</code> if it should just * use the regular paint. * * @return A boolean. */ public boolean getUseFillPaint() { return this.useFillPaint; } /** * Sets the flag that controls whether the fill paint is used to fill * shapes, and sends a {@link RendererChangeEvent} to all * registered listeners. * * @param flag the flag. */ public void setUseFillPaint(boolean flag) { this.useFillPaint = flag; notifyListeners(new RendererChangeEvent(this)); } /** * Draw a single data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the area in which the data is drawn. * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param row the row index (zero-based). * @param column the column index (zero-based). * @param pass the pass index. */ public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, int pass) { // do nothing if item is not visible if (!getItemVisible(row, column)) { return; } PlotOrientation orientation = plot.getOrientation(); MultiValueCategoryDataset d = (MultiValueCategoryDataset) dataset; List values = d.getValues(row, column); if (values == null) { return; } int valueCount = values.size(); for (int i = 0; i < valueCount; i++) { // current data point... double x1; if (this.useSeriesOffset) { x1 = domainAxis.getCategorySeriesMiddle(dataset.getColumnKey( column), dataset.getRowKey(row), dataset, this.itemMargin, dataArea, plot.getDomainAxisEdge()); } else { x1 = domainAxis.getCategoryMiddle(column, getColumnCount(), dataArea, plot.getDomainAxisEdge()); } Number n = (Number) values.get(i); double value = n.doubleValue(); double y1 = rangeAxis.valueToJava2D(value, dataArea, plot.getRangeAxisEdge()); Shape shape = getItemShape(row, column); if (orientation == PlotOrientation.HORIZONTAL) { shape = ShapeUtilities.createTranslatedShape(shape, y1, x1); } else if (orientation == PlotOrientation.VERTICAL) { shape = ShapeUtilities.createTranslatedShape(shape, x1, y1); } if (getItemShapeFilled(row, column)) { if (this.useFillPaint) { g2.setPaint(getItemFillPaint(row, column)); } else { g2.setPaint(getItemPaint(row, column)); } g2.fill(shape); } if (this.drawOutlines) { if (this.useOutlinePaint) { g2.setPaint(getItemOutlinePaint(row, column)); } else { g2.setPaint(getItemPaint(row, column)); } g2.setStroke(getItemOutlineStroke(row, column)); g2.draw(shape); } } } /** * Returns a legend item for a series. * * @param datasetIndex the dataset index (zero-based). * @param series the series index (zero-based). * * @return The legend item. */ public LegendItem getLegendItem(int datasetIndex, int series) { CategoryPlot cp = getPlot(); if (cp == null) { return null; } if (isSeriesVisible(series) && isSeriesVisibleInLegend(series)) { CategoryDataset dataset = cp.getDataset(datasetIndex); String label = getLegendItemLabelGenerator().generateLabel( dataset, series); String description = label; String toolTipText = null; if (getLegendItemToolTipGenerator() != null) { toolTipText = getLegendItemToolTipGenerator().generateLabel( dataset, series); } String urlText = null; if (getLegendItemURLGenerator() != null) { urlText = getLegendItemURLGenerator().generateLabel( dataset, series); } Shape shape = lookupSeriesShape(series); Paint paint = lookupSeriesPaint(series); Paint fillPaint = (this.useFillPaint ? getItemFillPaint(series, 0) : paint); boolean shapeOutlineVisible = this.drawOutlines; Paint outlinePaint = (this.useOutlinePaint ? getItemOutlinePaint(series, 0) : paint); Stroke outlineStroke = lookupSeriesOutlineStroke(series); LegendItem result = new LegendItem(label, description, toolTipText, urlText, true, shape, getItemShapeFilled(series, 0), fillPaint, shapeOutlineVisible, outlinePaint, outlineStroke, false, new Line2D.Double(-7.0, 0.0, 7.0, 0.0), getItemStroke(series, 0), getItemPaint(series, 0)); result.setDataset(dataset); result.setDatasetIndex(datasetIndex); result.setSeriesKey(dataset.getRowKey(series)); result.setSeriesIndex(series); return result; } return null; } /** * Tests this renderer for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * @return A boolean. */ public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof ScatterRenderer)) { return false; } ScatterRenderer that = (ScatterRenderer) obj; if (!ObjectUtilities.equal(this.seriesShapesFilled, that.seriesShapesFilled)) { return false; } if (this.baseShapesFilled != that.baseShapesFilled) { return false; } if (this.useFillPaint != that.useFillPaint) { return false; } if (this.drawOutlines != that.drawOutlines) { return false; } if (this.useOutlinePaint != that.useOutlinePaint) { return false; } if (this.useSeriesOffset != that.useSeriesOffset) { return false; } if (this.itemMargin != that.itemMargin) { return false; } return super.equals(obj); } /** * Returns an independent copy of the renderer. * * @return A clone. * * @throws CloneNotSupportedException should not happen. */ public Object clone() throws CloneNotSupportedException { ScatterRenderer clone = (ScatterRenderer) super.clone(); clone.seriesShapesFilled = (BooleanList) this.seriesShapesFilled.clone(); return clone; } /** * Provides serialization support. * * @param stream the output stream. * @throws java.io.IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); } /** * Provides serialization support. * * @param stream the input stream. * @throws java.io.IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); } }
/** * Used by Simperium to create a WebSocket connection to Simperium. Manages Channels * and listens for channel write events. Notifies channels when the connection is connected * or disconnected. * * WebSocketManager is configured by Simperium and shouldn't need to be access directly * by applications. * */ package com.simperium.android; import java.util.HashMap; import java.util.Locale; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Executor; import org.json.JSONException; import org.json.JSONObject; import com.simperium.BuildConfig; import com.simperium.client.Bucket; import com.simperium.client.Channel; import com.simperium.client.ChannelProvider; import com.simperium.util.Logger; import android.util.Log; public class WebSocketManager implements ChannelProvider, Channel.OnMessageListener { public enum ConnectionStatus { DISCONNECTING, DISCONNECTED, CONNECTING, CONNECTED } public interface Connection { public void close(); public void send(String message); } public interface ConnectionListener { public void onConnect(Connection connection); public void onDisconnect(Exception exception); public void onError(Exception exception); public void onMessage(String message); } public interface ConnectionProvider { public void connect(ConnectionListener connectionListener); } public static final String TAG = "Simperium.WebSocket"; static public final String COMMAND_HEARTBEAT = "h"; static public final String COMMAND_LOG = "log"; static public final String LOG_FORMAT = "%s:%s"; final protected ConnectionProvider mConnectionProvider; protected Connection mConnection = new NullConnection(); protected String mSocketURI; private String mAppId, mSessionId; private boolean mReconnect = true; private HashMap<Channel,Integer> mChannelIndex = new HashMap<Channel,Integer>(); private HashMap<Integer,Channel> mChannels = new HashMap<Integer,Channel>(); static final long HEARTBEAT_INTERVAL = 20000; // 20 seconds static final long DEFAULT_RECONNECT_INTERVAL = 3000; // 3 seconds private Timer mHeartbeatTimer, mReconnectTimer; private int mHeartbeatCount = 0, mLogLevel = 0; private long mReconnectInterval = DEFAULT_RECONNECT_INTERVAL; private ConnectionStatus mConnectionStatus = ConnectionStatus.DISCONNECTED; final protected Channel.Serializer mSerializer; final protected Executor mExecutor; public WebSocketManager(Executor executor, String appId, String sessionId, Channel.Serializer channelSerializer, ConnectionProvider connectionProvider) { mExecutor = executor; mAppId = appId; mSessionId = sessionId; mSerializer = channelSerializer; mConnectionProvider = connectionProvider; } /** * Creates a channel for the bucket. Starts the websocket connection if not connected * */ @Override public Channel buildChannel(Bucket bucket) { // create a channel Channel channel = new Channel(mExecutor, mAppId, mSessionId, bucket, mSerializer, this); int channelId = mChannels.size(); mChannelIndex.put(channel, channelId); mChannels.put(channelId, channel); // If we're not connected then connect, if we don't have a user // access token we'll have to hold off until the user does have one if (!isConnected() && bucket.getUser().hasAccessToken()) { connect(); } else if (isConnected()) { channel.onConnect(); } return channel; } @Override public void log(int level, CharSequence message) { try { JSONObject log = new JSONObject(); log.put(COMMAND_LOG, message.toString()); log(level, log); } catch (JSONException e) { Logger.log(TAG, "Could not send log", e); } } protected void log(int level, JSONObject log) { // no logging if disabled if (mLogLevel == ChannelProvider.LOG_DISABLED) return; boolean send = level <= mLogLevel; if (BuildConfig.DEBUG) Log.d(TAG, "Log " + level + " => " + log); if (send) send(String.format(LOG_FORMAT, COMMAND_LOG, log)); } @Override public int getLogLevel() { return mLogLevel; } public void connect() { // if we have channels, then connect, otherwise wait for a channel cancelReconnect(); Log.d(TAG, "Asked to connect"); if (!isConnected() && !isConnecting() && !mChannels.isEmpty()) { Log.d(TAG, "Connecting"); Logger.log(TAG, String.format(Locale.US, "Connecting to %s", mSocketURI)); setConnectionStatus(ConnectionStatus.CONNECTING); mReconnect = true; mConnectionProvider.connect(new ConnectionListener() { public void onError(Exception exception) { mConnection = new NullConnection(); WebSocketManager.this.onError(exception); } public void onConnect(Connection connection) { mConnection = connection; WebSocketManager.this.onConnect(); } public void onMessage(String message) { WebSocketManager.this.onMessage(message); } public void onDisconnect(Exception exception) { mConnection = new NullConnection(); WebSocketManager.this.onDisconnect(exception); } }); } } protected void send(String message) { if (!isConnected()) return; synchronized(this) { mConnection.send(message); } } public void disconnect() { // disconnect the channel mReconnect = false; cancelReconnect(); if (isConnected()) { setConnectionStatus(ConnectionStatus.DISCONNECTING); Logger.log(TAG, "Disconnecting"); // being told to disconnect so don't automatically reconnect mConnection.close(); } } public boolean isConnected() { return mConnectionStatus == ConnectionStatus.CONNECTED; } public boolean isConnecting() { return mConnectionStatus == ConnectionStatus.CONNECTING; } public boolean isDisconnected() { return mConnectionStatus == ConnectionStatus.DISCONNECTED; } public boolean isDisconnecting() { return mConnectionStatus == ConnectionStatus.DISCONNECTING; } public boolean getConnected() { return isConnected(); } protected void setConnectionStatus(ConnectionStatus status) { mConnectionStatus = status; } private void notifyChannelsConnected() { for(Channel channel : mChannelIndex.keySet()) { channel.onConnect(); } } private void notifyChannelsDisconnected() { for(Channel channel : mChannelIndex.keySet()) { channel.onDisconnect(); } } private void cancelHeartbeat() { if(mHeartbeatTimer != null) mHeartbeatTimer.cancel(); mHeartbeatCount = 0; } private void scheduleHeartbeat() { cancelHeartbeat(); mHeartbeatTimer = new Timer(); mHeartbeatTimer.schedule(new TimerTask() { public void run() { sendHearbeat(); } }, HEARTBEAT_INTERVAL); } synchronized private void sendHearbeat() { mHeartbeatCount ++; String command = String.format(Locale.US, "%s:%d", COMMAND_HEARTBEAT, mHeartbeatCount); send(command); } private void cancelReconnect() { if (mReconnectTimer != null) { mReconnectTimer.cancel(); mReconnectTimer = null; } } private void scheduleReconnect() { // check if we're not already trying to reconnect if (mReconnectTimer != null) return; mReconnectTimer = new Timer(); // exponential backoff long retryIn = nextReconnectInterval(); mReconnectTimer.schedule(new TimerTask() { public void run() { connect(); } }, retryIn); Logger.log(String.format(Locale.US, "Retrying in %d", retryIn)); } // duplicating javascript reconnect interval calculation // doesn't do exponential backoff private long nextReconnectInterval() { long current = mReconnectInterval; if (mReconnectInterval < 4000) { mReconnectInterval ++; } else { mReconnectInterval = 15000; } return current; } /** * * Channel.OnMessageListener event listener * */ @Override public void onMessage(Channel.MessageEvent event) { Channel channel = (Channel)event.getSource(); Integer channelId = mChannelIndex.get(channel); // Prefix the message with the correct channel id String message = String.format(Locale.US, "%d:%s", channelId, event.getMessage()); send(message); } @Override public void onClose(Channel fromChannel) { // if we're allready disconnected we can ignore if (isDisconnected()) return; // check if all channels are disconnected and if so disconnect from the socket for (Channel channel : mChannels.values()) { if (channel.isStarted()) return; } Logger.log(TAG, String.format(Locale.US, "%s disconnect from socket", Thread.currentThread().getName())); disconnect(); } @Override public void onOpen(Channel fromChannel) { connect(); } static public final String BUCKET_NAME_KEY = "bucket"; @Override public void onLog(Channel channel, int level, CharSequence message) { try { JSONObject log = new JSONObject(); log.put(COMMAND_LOG, message); log.put(BUCKET_NAME_KEY, channel.getBucketName()); log(level, log); } catch (JSONException e) { Logger.log(TAG, "Unable to send channel log message", e); } } protected void onConnect() { Logger.log(TAG, String.format("Connected")); setConnectionStatus(ConnectionStatus.CONNECTED); notifyChannelsConnected(); mHeartbeatCount = 0; // reset heartbeat count scheduleHeartbeat(); cancelReconnect(); mReconnectInterval = DEFAULT_RECONNECT_INTERVAL; } protected void onMessage(String message) { if (BuildConfig.DEBUG) { Log.d(TAG, "Received Message: " + message); } scheduleHeartbeat(); String[] parts = message.split(":", 2); if (parts[0].equals(COMMAND_HEARTBEAT)) { mHeartbeatCount = Integer.parseInt(parts[1]); return; } else if (parts[0].equals(COMMAND_LOG)) { mLogLevel = Integer.parseInt(parts[1]); return; } try { int channelId = Integer.parseInt(parts[0]); Channel channel = mChannels.get(channelId); channel.receiveMessage(parts[1]); } catch (NumberFormatException e) { Logger.log(TAG, String.format(Locale.US, "Unhandled message %s", parts[0])); } } protected void onDisconnect(Exception ex) { Logger.log(TAG, String.format(Locale.US, "Disconnect %s", ex)); setConnectionStatus(ConnectionStatus.DISCONNECTED); notifyChannelsDisconnected(); cancelHeartbeat(); if(mReconnect) scheduleReconnect(); } protected void onError(Exception error) { Logger.log(TAG, String.format(Locale.US, "Error: %s", error), error); setConnectionStatus(ConnectionStatus.DISCONNECTED); if (java.io.IOException.class.isAssignableFrom(error.getClass()) && mReconnect) { scheduleReconnect(); } } private class NullConnection implements Connection { @Override public void close() { // noop } @Override public void send(String message) { // noop } } }
package org.seedstack.seed; /** * Any class implementing this interface will be registered as an application lifecycle listener. As the application * starts and stops, these callbacks will be invoked to allow for executing startup and/or shutdown code. */ public interface LifecycleListener { /** * This method is called by Seed just after the application has started up. */ default void started() { // no-op } /** * This method is called by Seed just before the application is shut down. */ default void stopping() { // no-op } }
package org.umlg.sqlg.test.uuid; import org.apache.commons.collections4.set.ListOrderedSet; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.T; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.junit.Assert; import org.junit.Assume; import org.junit.Before; import org.junit.Test; import org.umlg.sqlg.structure.PropertyType; import org.umlg.sqlg.structure.topology.EdgeLabel; import org.umlg.sqlg.structure.topology.PropertyColumn; import org.umlg.sqlg.structure.topology.VertexLabel; import org.umlg.sqlg.test.BaseTest; import java.util.HashMap; import java.util.List; import java.util.Optional; import java.util.UUID; public class TestUUID extends BaseTest { @Before public void before() throws Exception { super.before(); Assume.assumeTrue(this.sqlgGraph.getSqlDialect().supportsUUID()); } @Test public void testUUID() { UUID uuidPerson1 = UUID.randomUUID(); Vertex vertexA = this.sqlgGraph.addVertex(T.label, "Person", "uuid", uuidPerson1); UUID uuidPerson2 = UUID.randomUUID(); Vertex vertexB = this.sqlgGraph.addVertex(T.label, "Person", "uuid", uuidPerson2); UUID uuidEdge = UUID.randomUUID(); Edge edge = vertexA.addEdge("knows", vertexB, "uuid", uuidEdge); vertexA.addEdge("knows", vertexB, "uuid", UUID.randomUUID()); vertexA.addEdge("knows", vertexB, "uuid", UUID.randomUUID()); this.sqlgGraph.tx().commit(); vertexA = this.sqlgGraph.traversal().V(vertexA.id()).next(); UUID uuidFromDB = vertexA.value("uuid"); Assert.assertEquals(uuidPerson1, uuidFromDB); vertexB = this.sqlgGraph.traversal().V(vertexB.id()).next(); uuidFromDB = vertexB.value("uuid"); Assert.assertEquals(uuidPerson2, uuidFromDB); edge = this.sqlgGraph.traversal().E(edge.id()).next(); uuidFromDB = edge.value("uuid"); Assert.assertEquals(uuidEdge, uuidFromDB); List<Vertex> persons = this.sqlgGraph.traversal().V().hasLabel("Person").has("uuid", uuidPerson1).toList(); Assert.assertEquals(1, persons.size()); Assert.assertEquals(uuidPerson1, persons.get(0).value("uuid")); persons = this.sqlgGraph.traversal().V().hasLabel("Person").has("uuid", uuidPerson2).toList(); Assert.assertEquals(1, persons.size()); Assert.assertEquals(uuidPerson2, persons.get(0).value("uuid")); List<Edge> edges = this.sqlgGraph.traversal().E().hasLabel("knows").has("uuid", uuidEdge).toList(); Assert.assertEquals(1, edges.size()); Assert.assertEquals(uuidEdge, edges.get(0).value("uuid")); List<Vertex> vertices = this.sqlgGraph.traversal().V().hasLabel("Person").has("uuid", uuidPerson1) .outE().has("uuid", uuidEdge) .otherV() .toList(); Assert.assertEquals(1, vertices.size()); } @Test public void testUUIDViaTopologyApi() { VertexLabel personVertexLabel = this.sqlgGraph.getTopology().getPublicSchema().ensureVertexLabelExist("Person", new HashMap<>() {{ put("uuid", PropertyType.UUID); }}); personVertexLabel.ensureEdgeLabelExist("knows", personVertexLabel, new HashMap<>() {{ put("uuid", PropertyType.UUID); }}); this.sqlgGraph.tx().commit(); VertexLabel vertexLabel = this.sqlgGraph.getTopology().getPublicSchema().getVertexLabel("Person").orElseThrow(); Optional<PropertyColumn> uuidPropertyColumnOptional = vertexLabel.getProperty("uuid"); Assert.assertTrue(uuidPropertyColumnOptional.isPresent()); Assert.assertEquals(PropertyType.UUID, uuidPropertyColumnOptional.get().getPropertyType()); EdgeLabel edgeLabel = this.sqlgGraph.getTopology().getPublicSchema().getEdgeLabel("knows").orElseThrow(); uuidPropertyColumnOptional = edgeLabel.getProperty("uuid"); Assert.assertTrue(uuidPropertyColumnOptional.isPresent()); Assert.assertEquals(PropertyType.UUID, uuidPropertyColumnOptional.get().getPropertyType()); UUID uuidPerson1 = UUID.randomUUID(); Vertex vertexA = this.sqlgGraph.addVertex(T.label, "Person", "uuid", uuidPerson1); UUID uuidPerson2 = UUID.randomUUID(); Vertex vertexB = this.sqlgGraph.addVertex(T.label, "Person", "uuid", uuidPerson2); UUID uuidEdge = UUID.randomUUID(); Edge edge = vertexA.addEdge("knows", vertexB, "uuid", uuidEdge); vertexA.addEdge("knows", vertexB, "uuid", UUID.randomUUID()); vertexA.addEdge("knows", vertexB, "uuid", UUID.randomUUID()); this.sqlgGraph.tx().commit(); vertexA = this.sqlgGraph.traversal().V(vertexA.id()).next(); UUID uuidFromDB = vertexA.value("uuid"); Assert.assertEquals(uuidPerson1, uuidFromDB); vertexB = this.sqlgGraph.traversal().V(vertexB.id()).next(); uuidFromDB = vertexB.value("uuid"); Assert.assertEquals(uuidPerson2, uuidFromDB); edge = this.sqlgGraph.traversal().E(edge.id()).next(); uuidFromDB = edge.value("uuid"); Assert.assertEquals(uuidEdge, uuidFromDB); List<Vertex> persons = this.sqlgGraph.traversal().V().hasLabel("Person").has("uuid", uuidPerson1).toList(); Assert.assertEquals(1, persons.size()); Assert.assertEquals(uuidPerson1, persons.get(0).value("uuid")); persons = this.sqlgGraph.traversal().V().hasLabel("Person").has("uuid", uuidPerson2).toList(); Assert.assertEquals(1, persons.size()); Assert.assertEquals(uuidPerson2, persons.get(0).value("uuid")); List<Edge> edges = this.sqlgGraph.traversal().E().hasLabel("knows").has("uuid", uuidEdge).toList(); Assert.assertEquals(1, edges.size()); Assert.assertEquals(uuidEdge, edges.get(0).value("uuid")); List<Vertex> vertices = this.sqlgGraph.traversal().V().hasLabel("Person").has("uuid", uuidPerson1) .outE().has("uuid", uuidEdge) .otherV() .toList(); Assert.assertEquals(1, vertices.size()); } @Test public void testUUIDAsIdentifier() { VertexLabel personVertexLabel = this.sqlgGraph.getTopology().getPublicSchema().ensureVertexLabelExist( "Person", new HashMap<>() {{ put("uuid", PropertyType.UUID); }}, ListOrderedSet.listOrderedSet(List.of("uuid")) ); personVertexLabel.ensureEdgeLabelExist( "knows", personVertexLabel, new HashMap<>() {{ put("uuid", PropertyType.UUID); }}, ListOrderedSet.listOrderedSet(List.of("uuid"))); this.sqlgGraph.tx().commit(); Vertex person1 = this.sqlgGraph.addVertex(T.label, "Person", "uuid", UUID.randomUUID()); for (int i = 0; i < 100; i++) { Vertex other = this.sqlgGraph.addVertex(T.label, "Person", "uuid", UUID.randomUUID()); person1.addEdge("knows", other, "uuid", UUID.randomUUID()); } this.sqlgGraph.tx().commit(); List<Vertex> others = this.sqlgGraph.traversal().V().hasId(person1.id()).out("knows").toList(); Assert.assertEquals(100, others.size()); List<Edge> otherEdges = this.sqlgGraph.traversal().V().hasId(person1.id()).outE("knows").toList(); Assert.assertEquals(100, otherEdges.size()); } @Test public void testUUIDViaNormalBatchMode() { this.sqlgGraph.tx().normalBatchModeOn(); for (int i = 0; i < 100; i++) { this.sqlgGraph.addVertex(T.label, "A", "uuid", UUID.randomUUID()); } this.sqlgGraph.tx().commit(); List<UUID> uuids = this.sqlgGraph.traversal().V().hasLabel("A").<UUID>values("uuid").toList(); Assert.assertEquals(100, uuids.size()); } @Test public void testUUIDViaStreamingBatchMode() { Assume.assumeTrue(isPostgres()); this.sqlgGraph.tx().streamingBatchModeOn(); for (int i = 0; i < 100; i++) { this.sqlgGraph.streamVertex(T.label, "A", "uuid", UUID.randomUUID()); } this.sqlgGraph.tx().commit(); List<UUID> uuids = this.sqlgGraph.traversal().V().hasLabel("A").<UUID>values("uuid").toList(); Assert.assertEquals(100, uuids.size()); } }
package com.github.gchudnov.squel; import java.util.ArrayList; import java.util.List; /** * SQL expression builder. * A new expression should be created using `Squel.expr()` call. */ public final class Expression { private enum ExpressionType { AND, OR } private class ExpressionNode { final ExpressionType type; final String expr; final Object param; final ExpressionNode parent; final List<ExpressionNode> nodes = new ArrayList<>(); ExpressionNode() { this.type = null; this.expr = null; this.param = null; this.parent = null; } ExpressionNode(ExpressionType type, String expr, Object param) { this.type = type; this.expr = expr; this.param = param; this.parent = null; } ExpressionNode(ExpressionType type, ExpressionNode parent) { this.type = type; this.expr = null; this.param = null; this.parent = parent; } } private final QueryBuilderOptions mOptions; private ExpressionNode mTree = null; private ExpressionNode mCurrent = null; Expression(QueryBuilderOptions options) { this.mOptions = (options != null ? options : new QueryBuilderOptions()); this.mTree = new ExpressionNode(); this.mCurrent = this.mTree; } /** * Begin AND nested expression. * @return Expression */ public Expression andBegin() { return this.doBegin(ExpressionType.AND); } /** * Begin OR nested expression. * @return Expression */ public Expression orBegin() { return this.doBegin(ExpressionType.OR); } /** * End the current compound expression. * @return Expression */ public Expression end() { assert mCurrent.parent != null; // "begin() needs to be called" mCurrent = mCurrent.parent; return this; } /** * Combine the current expression with the given expression using the intersection operator (AND). * @param expr Expression to combine with. * @return Expression */ public Expression and(String expr) { return this.and(expr, null); } /** * Combine the current expression with the given expression using the intersection operator (AND). * @param expr Expression to combine with. * @param param Value to substitute. * @param <P> Number|String|Boolean|QueryBuilder|Expression|Array|Iterable * @return Expression */ public <P> Expression and(String expr, P param) { ExpressionNode newNode = new ExpressionNode(ExpressionType.AND, expr, param); mCurrent.nodes.add(newNode); return this; } /** * Combine the current expression with the given expression using the union operator (OR). * @param expr Expression to combine with. * @return Expression */ public Expression or(String expr) { return this.or(expr, null); } /** * Combine the current expression with the given expression using the union operator (OR). * @param expr Expression to combine with. * @param param Value to substitute. * @param <P> Number|String|Boolean|QueryBuilder|Expression|Array|Iterable * @return Expression */ public <P> Expression or(String expr, P param) { ExpressionNode newNode = new ExpressionNode(ExpressionType.OR, expr, param); mCurrent.nodes.add(newNode); return this; } /** * Get the Expression string. * @return A String representation of the expression. */ @Override public String toString() { assert mCurrent.parent == null; // "end() needs to be called" return this.doString(mTree); } /** * Begin a nested expression * @param op Operator to combine with the current expression * @return Expression */ private Expression doBegin(ExpressionType op) { ExpressionNode newTree = new ExpressionNode(op, mCurrent); mCurrent.nodes.add(newTree); mCurrent = newTree; return this; } /** * Get a string representation of the given expression tree node. * @param node Node to * @return String */ private String doString(ExpressionNode node) { StringBuilder sb = new StringBuilder(); String nodeStr; for (ExpressionNode child : node.nodes) { if (child.expr != null) { nodeStr = child.expr.replace("?", Validator.formatValue(child.param, mOptions)); } else { nodeStr = this.doString(child); // wrap nested expressions in brackets if (!Util.isEmpty(nodeStr)) { nodeStr = "(" + nodeStr + ")"; } } if (!Util.isEmpty(nodeStr)) { if (sb.length() > 0) { sb.append(" "); sb.append(child.type); sb.append(" "); } sb.append(nodeStr); } } return sb.toString(); } }
package org.opencms.gwt.client.ui.input.form; import org.opencms.gwt.client.ui.input.I_CmsFormField; import org.opencms.gwt.client.ui.input.I_CmsFormWidget; import org.opencms.gwt.client.ui.input.I_CmsValidationHandler; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Widget; /** * * @author Georg Westenberger * * @version $Revision: 1.2 $ * * @since 8.0.0 * */ public class CmsForm extends Composite { /** A map from field ids to the corresponding widgets. */ private Map<String, I_CmsFormField> m_fields = new LinkedHashMap<String, I_CmsFormField>(); /** The main panel for this widget. */ private FlowPanel m_panel = new FlowPanel(); /** The internal list of validation handlers. */ private List<I_CmsValidationHandler> m_validationHandlers = new ArrayList<I_CmsValidationHandler>(); /** * The default constructor.<p> * */ public CmsForm() { initWidget(m_panel); } /** * Adds a form field to the form.<p> * * @param formField the form field which should be added * @param initialValue the initial value of the form field, or null if the field shouldn't have an initial value */ public void addField(I_CmsFormField formField, String initialValue) { String description = formField.getDescription(); String labelText = formField.getLabel(); I_CmsFormWidget widget = formField.getWidget(); m_fields.put(formField.getId(), formField); if (initialValue != null) { formField.getWidget().setFormValueAsString(initialValue); } addRow(labelText, description, (Widget)widget); } /** * Adds a new row with a given label and input widget to the form.<p> * * @param labelText the label text for the form field * @param description the description of the form field * @param widget the widget for the form field * * @return the newly added form row */ public CmsFormRow addRow(String labelText, String description, Widget widget) { CmsFormRow row = new CmsFormRow(); Label label = row.getLabel(); label.setText(labelText); label.setTitle(description); row.getWidgetContainer().add(widget); m_panel.add(row); return row; } /** * Adds a separator below the last added form field.<p> * */ public void addSeparator() { m_panel.add(new CmsSeparator()); } /** * Adds a new validation handler to the form.<p> * * @param handler the validation handler that should be added */ public void addValidationHandler(I_CmsValidationHandler handler) { m_validationHandlers.add(handler); } /** * Collects all values from the form fields.<p> * * This method omits form fields whose values are null. * * @return a map of the form field values */ public Map<String, String> collectValues() { Map<String, String> result = new HashMap<String, String>(); for (Map.Entry<String, I_CmsFormField> entry : m_fields.entrySet()) { String key = entry.getKey(); String value = null; I_CmsFormField field = entry.getValue(); I_CmsFormWidget widget = field.getWidget(); value = widget.getFormValueAsString(); if (value != null) { result.put(key, value); } } return result; } /** * Returns the form field with a given id.<p> * * @param id the id of the form field * * @return the form field with the given id, or null if no field was found */ public I_CmsFormField getField(String id) { return m_fields.get(id); } /** * Validates all fields in the form.<p> * * When the validation is completed, the validation handler passed as a parameter * is notified, unless it's null. * * @param handler the object which should handle the result of the validation */ public void validate(I_CmsValidationHandler handler) { boolean validationSucceeded = validateFields(); if (handler != null) { handler.onValidationComplete(validationSucceeded); } } /** * Validates all fields in the form and returns the result.<p> * * @return true if the validation was successful */ protected boolean validateFields() { boolean validationSucceeded = true; for (Map.Entry<String, I_CmsFormField> entry : m_fields.entrySet()) { I_CmsFormField field = entry.getValue(); if (!field.validate()) { validationSucceeded = false; } } return validationSucceeded; } }
package org.opencms.gwt.client.util; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Style.Unit; /** * Move animation. Moving the given element from it's start to it's end position * and executing the given call-back on complete.<p> * * @author Tobias Herrmann * * @version $Revision: 1.3 $ * * @since 8.0.0 */ public class CmsMoveAnimation extends A_CmsAnimation { /** The element. */ private Element m_element; /** The end left. */ private int m_endLeft; /** The end top. */ private int m_endTop; /** The start left. */ private int m_startLeft; /** The start top. */ private int m_startTop; /** * Constructor. Setting the element to animate, it's start and end position.<p> * * @param element the element * @param startTop the start top * @param startLeft the start left * @param endTop the end top * @param endLeft the end left * @param callback the call-back to execute on complete */ public CmsMoveAnimation( Element element, int startTop, int startLeft, int endTop, int endLeft, I_CmsSimpleCallback<Void> callback) { super(callback); m_element = element; m_startTop = startTop; m_startLeft = startLeft; m_endTop = endTop; m_endLeft = endLeft; } /** * @see com.google.gwt.animation.client.Animation#onUpdate(double) */ @Override protected void onUpdate(double progress) { progress = progress * progress; double newTop = m_startTop + ((m_endTop - m_startTop) * progress); double newLeft = m_startLeft + ((m_endLeft - m_startLeft) * progress); m_element.getStyle().setTop(newTop, Unit.PX); m_element.getStyle().setLeft(newLeft, Unit.PX); } }
package com.example.npakudin.testocr; import android.content.Context; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.util.Log; import android.util.Pair; import com.googlecode.leptonica.android.Binarize; import com.googlecode.leptonica.android.Pix; import com.googlecode.leptonica.android.ReadFile; import com.googlecode.leptonica.android.Rotate; import com.googlecode.leptonica.android.Skew; import com.googlecode.leptonica.android.WriteFile; import com.googlecode.tesseract.android.ResultIterator; import com.googlecode.tesseract.android.TessBaseAPI; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; public class TextRec { private static final String LOGTAG = "TextRecognizer"; public static class Symbol { public String symbol; public List<Pair<String, Double>> choicesAndConf; public Rect rect; } public static class MicrInfo { public int top = 0; public int bottom = 0; public int minimumCharRect = 0; public MicrInfo(int top, int bottom, int minimumCharWidth) { this.top = top; this.bottom = bottom; this.minimumCharRect = minimumCharWidth; } } public static File getCacheDir(Context context) { File maxDir = null; long maxSpace = -1; Log.d(LOGTAG, "getCacheDir()"); for (File dir : context.getExternalCacheDirs()) { if (dir != null) { long space = dir.getFreeSpace(); if (space > maxSpace) { maxSpace = space; maxDir = dir; } } else { Log.w(LOGTAG, "cache dir is null"); } } if (maxDir != null) { return maxDir; } else { return null; } } private static HashMap<Integer, Integer> fillTheMap(HashMap<Integer, Integer> map, Integer rect) { if (map.get(rect) != null) { map.put(rect, map.get(rect) + 1); } else { map.put(rect, 1); } return map; } public static int findMostFrequentItem(HashMap<Integer, Integer> map) { int trueBorder = 0; int freq = 0; for (HashMap.Entry<Integer, Integer> entry : map.entrySet()) { if (entry.getValue() > freq) { trueBorder = entry.getKey(); freq = entry.getValue(); } } return trueBorder; } private static String mcrFilePath = null; public static File init(Context context) { File baseDir = getCacheDir(context); if (baseDir == null) { throw new IllegalStateException("Cannot access temporary dir"); } File tessdata = new File(baseDir, "tessdata"); File file = new File(tessdata, "mcr.traineddata"); if (!file.delete()) { Log.w(LOGTAG, "Cannot delete file"); } if (!tessdata.delete()) { Log.w(LOGTAG, "Cannot delete tessdata"); } Log.w(LOGTAG, "tessdata.exists() :" + tessdata.exists()); if (!tessdata.mkdirs()) { Log.w(LOGTAG, "Cannot mkdirs"); } Log.w(LOGTAG, "filename: " + file.getAbsolutePath()); try { Log.w(LOGTAG, "file.exists: " + file.exists() + " file.canWrite: " + file.canWrite()); FileOutputStream outputStream = new FileOutputStream(file); AssetManager assetManager = context.getAssets(); InputStream inputStream = assetManager.open("tessdata/mcr.traineddata"); try { byte[] buffer = new byte[0x80000]; // Adjust if you want int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); Log.w("MainActivity.onCreate", "bytesRead: " + bytesRead); } } finally { try { outputStream.close(); } catch (IOException ignored) { } try { if (inputStream != null) inputStream.close(); } catch (IOException ignored) { } } } catch (Exception e) { Log.e(LOGTAG, "copy", e); } Log.wtf(LOGTAG, "file: " + file.exists() + " len : " + file.length()); mcrFilePath = baseDir.getAbsolutePath(); return baseDir; } public static TessBaseAPI createTessBaseApi() { TessBaseAPI baseApi = new TessBaseAPI(); baseApi.init(mcrFilePath, "mcr"); return baseApi; } public static List<Symbol> rawRecognize(Bitmap bm) { TessBaseAPI baseApi = createTessBaseApi(); baseApi.setImage(bm); List<Symbol> symbols = new ArrayList<>(); if (baseApi.getUTF8Text().trim().length() > 0) { // in other case app fails on getting iterator on empty image ResultIterator resultIterator = baseApi.getResultIterator(); do { Rect rect = resultIterator.getBoundingRect(TessBaseAPI.PageIteratorLevel.RIL_SYMBOL); List<Pair<String, Double>> choicesAndConf = resultIterator.getChoicesAndConfidence(TessBaseAPI.PageIteratorLevel.RIL_SYMBOL); for (Pair<String, Double> item : resultIterator.getChoicesAndConfidence(TessBaseAPI.PageIteratorLevel.RIL_SYMBOL)) { Symbol symbol = new Symbol(); symbol.symbol = item.first; symbol.choicesAndConf = choicesAndConf; symbol.rect = rect; symbols.add(symbol); } } while (resultIterator.next(TessBaseAPI.PageIteratorLevel.RIL_SYMBOL)); } return symbols; } public static Bitmap prepareImage(Bitmap bm) { float threshold = 0; TessBaseAPI baseApi = createTessBaseApi(); String recognizedText; Bitmap res; do { Pix imag = Binarize.otsuAdaptiveThreshold(ReadFile.readBitmap(bm), 3000, 3000, 3 * Binarize.OTSU_SMOOTH_X, 3 * Binarize.OTSU_SMOOTH_Y, Binarize.OTSU_SCORE_FRACTION + threshold); Float s = Skew.findSkew(imag); res = WriteFile.writeBitmap(Rotate.rotate(imag, s)); baseApi.setImage(res); recognizedText = baseApi.getUTF8Text(); Log.d("rhere", "" + recognizedText); threshold = threshold + (float) 0.1; } while (threshold < (float) 0.6 && !recognizedText.matches("(.*\\n)*.{15,30}(.*\\n*)*")); return res; } public static MicrInfo findBorders(List<Symbol> rawSymbols) { int min = 1000; HashMap<Integer, Integer> bottom = new HashMap<>(); HashMap<Integer, Integer> top = new HashMap<>(); for (Symbol rawSymbol: rawSymbols) { Rect rect = rawSymbol.rect; for (Pair<String, Double> item : rawSymbol.choicesAndConf) { if (item.second > 73) { if ((rect.right - rect.left) < min) { min = rect.right - rect.left; } bottom = fillTheMap(bottom, rect.bottom); top = fillTheMap(top, rect.top); } } } int pogr = (int) (0.6 * (findMostFrequentItem(top) - (findMostFrequentItem(bottom)))); return new MicrInfo(findMostFrequentItem(top) + pogr, findMostFrequentItem(bottom) - pogr, min); } public static CheckData improve(MicrInfo micrInfo, Bitmap bm, List<Symbol> rawSymbols) { List<Symbol> symbols = new ArrayList<>(); TessBaseAPI singleCharRecognitiion = createTessBaseApi(); singleCharRecognitiion.setPageSegMode(TessBaseAPI.PageSegMode.PSM_SINGLE_CHAR); singleCharRecognitiion.setImage(bm); String recognizedText = ""; int right = 0; Rect oneCharRect = new Rect(0, 0, 0, 0); for (Symbol rawSymbol: rawSymbols) { Rect rect = rawSymbol.rect; List<Pair<String, Double>> choicesAndConf = rawSymbol.choicesAndConf; Symbol symbol = new Symbol(); for (Pair<String, Double> item : rawSymbol.choicesAndConf) { if (rect.bottom < micrInfo.bottom && rect.top > micrInfo.top) { if (rect.left <= right) { continue; } else { right = rect.right; } if (rect.right - rect.left < micrInfo.minimumCharRect && oneCharRect.left == 0) { oneCharRect = rect; continue; } else if (rect.right - rect.left >= micrInfo.minimumCharRect) { symbol.symbol = item.first; symbol.choicesAndConf = choicesAndConf; symbol.rect = rect; symbols.add(symbol); } else { if (rect.top < oneCharRect.top) { oneCharRect.top = rect.top; } if (rect.bottom > oneCharRect.bottom) { oneCharRect.bottom = rect.bottom; } oneCharRect.right = rect.right; singleCharRecognitiion.setRectangle(oneCharRect); String s = singleCharRecognitiion.getUTF8Text(); Log.d("s", s); if (s.trim().length() > 0) { if (s.contains("c")) { symbol.symbol = "c"; } else if (s.contains("d")) { symbol.symbol = "d"; } else if (s.contains("b")) { symbol.symbol = "b"; } else { symbol.symbol = "a"; } symbol.choicesAndConf = singleCharRecognitiion.getResultIterator().getChoicesAndConfidence(TessBaseAPI.PageIteratorLevel.RIL_SYMBOL); } else { Log.d(LOGTAG, "Cannot recognize single char at position of " + rawSymbol.symbol); symbol.symbol = "-"; symbol.choicesAndConf = new ArrayList<>(); symbol.choicesAndConf.add(new Pair<>("-", 0.0)); } symbol.rect = oneCharRect; symbols.add(symbol); oneCharRect.left = 0; } recognizedText = recognizedText + symbol.symbol; Log.d("conflog ", "" + symbol.choicesAndConf.get(0).second + "; symbol1 " + symbol.choicesAndConf.get(0).first + "; left " + symbol.rect.left + "; right" + symbol.rect.right + " widh " + (symbol.rect.right - symbol.rect.left) + " top,bottom: " + symbol.rect.top + " , " + symbol.rect.bottom); } } } return new CheckData(bm, recognizedText, symbols); } public static Bitmap drawRecText(Bitmap bm, Float scale, List<Symbol> symbols) { Canvas canvas = new Canvas(bm); float prevRight = 0; float prevBottom = 0; String text = ""; Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG); textPaint.setColor(Color.rgb(0xff, 0, 0)); Log.d("xxx", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); for (Symbol symbol : symbols) { for (int i = 0; i < symbol.choicesAndConf.size(); i++) { textPaint.setTextSize((int) (symbol.rect.height() * scale / 2)); text = text + symbol.choicesAndConf.get(i).first; canvas.drawText(symbol.choicesAndConf.get(i).first, symbol.rect.left, symbol.rect.top - (symbol.rect.height() + 20) * i, textPaint); String conf = String.format(Locale.ENGLISH, "%02.0f", symbol.choicesAndConf.get(i).second); Paint confPaint = new Paint(Paint.ANTI_ALIAS_FLAG); confPaint.setColor(Color.rgb(0, 0, 255)); confPaint.setTextSize((int) (symbol.rect.height() * scale / 4)); // Log.d("conflog ", "" + symbol.choicesAndConf.get(i).second + "; symbol1 " + symbol.choicesAndConf.get(i).first + // "; left " + symbol.rect.left + "; right" + symbol.rect.right + " widh " + // (symbol.rect.right - symbol.rect.left)+" top,bottom: "+symbol.rect.top+" , "+symbol.rect.bottom); canvas.drawText(conf, symbol.rect.left, symbol.rect.top - symbol.rect.height() * (i + 1), confPaint); Paint borderRectPaint = new Paint(Paint.ANTI_ALIAS_FLAG); borderRectPaint.setColor(Color.rgb(0, 0, 0xff)); borderRectPaint.setStyle(Paint.Style.STROKE); if (Math.abs(symbol.rect.bottom - prevBottom) > 20) { prevRight = 0; } //canvas.drawRect(prevRight, symbol.rect.bottom, symbol.rect.right, symbol.rect.bottom + 3, borderRectPaint); canvas.drawRect(symbol.rect, borderRectPaint); prevRight = symbol.rect.right; prevBottom = symbol.rect.bottom; } } return bm; } }
package org.splevo.ui.editors; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.beans.PojoProperties; import org.eclipse.core.databinding.observable.value.IObservableValue; import org.eclipse.core.filesystem.EFS; import org.eclipse.core.filesystem.IFileStore; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.emf.compare.util.ModelUtils; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.eclipse.jface.databinding.swt.WidgetProperties; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.util.LocalSelectionTransfer; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.FileTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.ide.IDE; import org.eclipse.ui.part.EditorPart; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.wb.swt.ResourceManager; import org.eclipse.wb.swt.SWTResourceManager; import org.splevo.project.SPLevoProject; import org.splevo.project.SPLevoProjectUtil; import org.splevo.ui.listeners.DiffSourceModelListener; import org.splevo.ui.listeners.ExtractProjectListener; import org.splevo.ui.listeners.GenerateFeatureModelListener; import org.splevo.ui.listeners.InitVPMListener; import org.splevo.ui.listeners.VPMAnalysisListener; /** * The SPLevo dash board to control the consolidation process as well as editing the SPLevo project * configuration. * * @author Benjamin Klatt * */ public class SPLevoProjectEditor extends EditorPart { /** The logger for this class. */ private Logger logger = Logger.getLogger(SPLevoProjectEditor.class); /** The id of the editor. */ public static final String ID = "org.splevo.ui.editors.SPLevoProjectEditor"; //$NON-NLS-1$ /** The internal index of the process control tab. */ private static final int TABINDEX_PROCESS_CONTROL = 0; /** The internal index of the project info tab. */ private static final int TABINDEX_PROJECT_INFOS = 1; /** The internal index of the project selection tab. */ private static final int TABINDEX_PROJECT_SELECTION = 2; /** The internal index of the source model tab. */ private static final int TABINDEX_SOURCE_MODELS = 3; /** The internal index of the diffing model tab. */ private static final int TABINDEX_DIFFING_MODEL = 4; /** The splevo project manipulated in the editor instance. */ private SPLevoProject splevoProject = null; /** The tab folder element of the editor. */ private TabFolder tabFolder; /** The project selection tab. */ private TabItem tbtmProjectSelection = null; /** The table viewer for the leading source models the variant should be integrated to. */ private TableViewer viewerLeadingProjects; /** The table column for the leading source models the variant should be integrated to. */ private TableColumn tblclmnLeadingProjects; /** The table viewer for the integration source models to be integrated to the leading one. */ private TableViewer viewerIntegrationProjects; /** The text input for the project name. */ private Text projectNameInput; /** The text input for the project description. */ private Text infoInput; /** The text input for the project's workspace path. */ private Text workspaceInput; /** Flag identifying the dirty state of the editor. */ private boolean dirtyFlag = false; /** The available transfer types for the drag and drop support. */ private Transfer[] transferTypes = new Transfer[] { FileTransfer.getInstance(), LocalSelectionTransfer.getTransfer() }; /** The supported drag and drop operations. */ private int dragNDropOperations = DND.DROP_MOVE; /** The text input for the name of the leading variant. */ private Text inputVariantNameLeading; /** The text input for the name of the variant to be integrated. */ private Text inputVariantNameIntegration; /** The text input for the path to the model of the leading variant. */ private Text sourceModelLeadingInput; /** The text input for the path to the model of the variant to be integrated. */ private Text sourceModelIntegrationInput; /** The text input for the path to the diffing model. */ private Text diffingModelInput; /** The text input field for the packages to filter. */ private Text diffingPackageFilterInput; /** Button Project Selection. */ private Button btnSelectSourceProjects; /** Button Extract source models . */ private Button btnExtractSourceModels; /** Button Diffing. */ private Button btnDiffing; /** Button Init VPM. */ private Button btnInitVpm; /** Button Analyze VPM. */ private Button btnRefineVPM; /** Button Generate feature model. */ private Button btnGenerateFeatureModel; /** Button Open Diff. */ private Button btnOpenDiff; /** Button Open VPM. */ private Button btnOpenVPM; /** Enables buttons after clicking model extraction. */ public void enableButtonsAfterExtraction() { btnDiffing.setEnabled(true); } /** Enables buttons after clicking diffing. */ public void enableButtonsAfterDiffing() { enableButtonsAfterExtraction(); btnInitVpm.setEnabled(true); btnOpenDiff.setEnabled(true); } /** Enables buttons after clicking Init VPM . */ public void enableButtonsAfterInitVPM() { enableButtonsAfterDiffing(); btnOpenVPM.setEnabled(true); btnRefineVPM.setEnabled(true); btnGenerateFeatureModel.setEnabled(true); } /** Enables buttons after clicking Analyze VPM. */ public void enableButtonsAfterAnalyzeVPM() { enableButtonsAfterInitVPM(); btnGenerateFeatureModel.setEnabled(true); } /** * Default constructor setting the icon in the editor title. */ public SPLevoProjectEditor() { setTitleImage(ResourceManager.getPluginImage("org.splevo.ui", "icons/splevo.gif")); } @Override public void createPartControl(Composite parent) { parent.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE)); GridLayout glParent = new GridLayout(1, false); glParent.verticalSpacing = 0; glParent.marginWidth = 0; glParent.marginHeight = 0; glParent.horizontalSpacing = 0; parent.setLayout(glParent); // init the data tables tabFolder = new TabFolder(parent, SWT.NONE); tabFolder.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE)); GridData gdTabFolder = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1); gdTabFolder.widthHint = 837; gdTabFolder.heightHint = 353; tabFolder.setLayoutData(gdTabFolder); // create tabs createProcessControlTab(); createProjectInfoTab(); createProjectSelectionTab(); createSourceModelTab(); createDiffingModelTab(); initDataBindings(); enableButtonsIfInformationAvailable(); } /** * Create the tab to handle the source models. */ private void createSourceModelTab() { TabItem tabItemSourceModel = new TabItem(tabFolder, SWT.NONE, TABINDEX_SOURCE_MODELS); tabItemSourceModel.setText("Source Models"); Composite sourceModelTabComposite = new Composite(tabFolder, SWT.NONE); tabItemSourceModel.setControl(sourceModelTabComposite); sourceModelTabComposite.setLayout(null); Label lblTheSoftwareModels = new Label(sourceModelTabComposite, SWT.NONE); lblTheSoftwareModels.setBounds(10, 10, 490, 20); lblTheSoftwareModels.setText("The software models extracted from the source projects."); Label lblLeadingProjectModel = new Label(sourceModelTabComposite, SWT.NONE); lblLeadingProjectModel.setBounds(10, 44, 191, 20); lblLeadingProjectModel.setText("Leading Source Model:"); sourceModelLeadingInput = new Text(sourceModelTabComposite, SWT.BORDER); sourceModelLeadingInput.setBounds(10, 67, 490, 26); Label lblsourceModelIntegration = new Label(sourceModelTabComposite, SWT.NONE); lblsourceModelIntegration.setText("Integration Source Model:"); lblsourceModelIntegration.setBounds(10, 124, 191, 20); sourceModelIntegrationInput = new Text(sourceModelTabComposite, SWT.BORDER); sourceModelIntegrationInput.setBounds(10, 147, 490, 26); } /** * Create the tab to handle the diff model. */ private void createDiffingModelTab() { TabItem tbtmDiffingModel = new TabItem(tabFolder, SWT.NONE, TABINDEX_DIFFING_MODEL); tbtmDiffingModel.setText("Diffing Model"); Composite composite = new Composite(tabFolder, SWT.NONE); tbtmDiffingModel.setControl(composite); Label lblDiffingModelDescription = new Label(composite, SWT.NONE); lblDiffingModelDescription.setText("The diffing model extracted from the source models."); lblDiffingModelDescription.setBounds(10, 10, 490, 20); Label lblDiffingModel = new Label(composite, SWT.NONE); lblDiffingModel.setText("Diffing Model:"); lblDiffingModel.setBounds(10, 44, 191, 20); diffingModelInput = new Text(composite, SWT.BORDER); diffingModelInput.setBounds(10, 67, 490, 26); diffingPackageFilterInput = new Text(composite, SWT.BORDER | SWT.WRAP); diffingPackageFilterInput.setBounds(10, 141, 490, 158); Label lblPackageFilterRules = new Label(composite, SWT.NONE); lblPackageFilterRules.setBounds(10, 115, 266, 20); lblPackageFilterRules.setText("Package Filter Rules (one per line):"); } /** * Create the tab to select the source projects. */ private void createProjectSelectionTab() { // SOURCE PROJECT SELECTION TAB tbtmProjectSelection = new TabItem(tabFolder, SWT.NONE, TABINDEX_PROJECT_SELECTION); tbtmProjectSelection.setText("Source Projects"); Composite composite = new Composite(tabFolder, SWT.NONE); tbtmProjectSelection.setControl(composite); composite.setLayout(null); Label lblNewLabel = new Label(composite, SWT.NONE); lblNewLabel.setToolTipText("Select the source entity models of the leading projects"); lblNewLabel.setBounds(10, 10, 740, 20); lblNewLabel.setText("Define the projects to be consolidated"); Label labelVariantNameLeading = new Label(composite, SWT.NONE); labelVariantNameLeading.setBounds(10, 37, 106, 20); labelVariantNameLeading.setText("Variant Name:"); Label labelVariantNameIntegration = new Label(composite, SWT.NONE); labelVariantNameIntegration.setText("Variant Name:"); labelVariantNameIntegration.setBounds(430, 36, 106, 20); inputVariantNameLeading = new Text(composite, SWT.BORDER); inputVariantNameLeading.setBounds(122, 36, 238, 26); inputVariantNameIntegration = new Text(composite, SWT.BORDER); inputVariantNameIntegration.setBounds(542, 36, 238, 26); // / LEADING PROJECT LIST viewerLeadingProjects = new TableViewer(composite, SWT.BORDER | SWT.FULL_SELECTION); viewerLeadingProjects.setContentProvider(ArrayContentProvider.getInstance()); viewerLeadingProjects.setInput(getSplevoProject().getLeadingProjects()); ProjectDropListener dropListenerLeadingProjects = new ProjectDropListener(this, viewerLeadingProjects, splevoProject.getLeadingProjects(), inputVariantNameLeading); viewerLeadingProjects.addDropSupport(dragNDropOperations, transferTypes, dropListenerLeadingProjects); Table tableLeadingProjects = viewerLeadingProjects.getTable(); tableLeadingProjects.setHeaderVisible(true); tableLeadingProjects.setLinesVisible(true); tableLeadingProjects.setBounds(10, 63, 350, 209); tblclmnLeadingProjects = new TableColumn(tableLeadingProjects, SWT.NONE); tblclmnLeadingProjects.setWidth(tblclmnLeadingProjects.getParent().getBounds().width); tblclmnLeadingProjects.setText("Leading Projects"); // / INTEGRATION PROJECT LIST viewerIntegrationProjects = new TableViewer(composite, SWT.BORDER | SWT.FULL_SELECTION); viewerIntegrationProjects.setContentProvider(ArrayContentProvider.getInstance()); viewerIntegrationProjects.setInput(getSplevoProject().getIntegrationProjects()); ProjectDropListener dropListenerIntegrationProjects = new ProjectDropListener(this, viewerIntegrationProjects, splevoProject.getIntegrationProjects(), inputVariantNameIntegration); viewerIntegrationProjects.addDropSupport(dragNDropOperations, transferTypes, dropListenerIntegrationProjects); Table tableIntegrationProjects = viewerIntegrationProjects.getTable(); tableIntegrationProjects.setHeaderVisible(true); tableIntegrationProjects.setLinesVisible(true); tableIntegrationProjects.setBounds(430, 63, 350, 209); TableColumn tblclmnIntegrationProjects = new TableColumn(tableIntegrationProjects, SWT.NONE); tblclmnIntegrationProjects.setWidth(tblclmnIntegrationProjects.getParent().getBounds().width); tblclmnIntegrationProjects.setText("Integration Projects"); Button btnClear = new Button(composite, SWT.NONE); btnClear.setGrayed(true); btnClear.setImage(ResourceManager.getPluginImage("org.splevo.ui", "icons/cross.png")); btnClear.addMouseListener(new MouseAdapter() { @Override public void mouseUp(MouseEvent e) { getSplevoProject().getLeadingProjects().clear(); viewerLeadingProjects.refresh(); markAsDirty(); } }); btnClear.setBounds(366, 63, 30, 30); Button btnClearList = new Button(composite, SWT.NONE); btnClearList.setToolTipText("Clear the list of source projects to integrate."); btnClearList.setImage(ResourceManager.getPluginImage("org.splevo.ui", "icons/cross.png")); btnClearList.addMouseListener(new MouseAdapter() { @Override public void mouseUp(MouseEvent e) { getSplevoProject().getIntegrationProjects().clear(); viewerIntegrationProjects.refresh(); markAsDirty(); } }); btnClearList.setBounds(786, 63, 30, 30); composite.setTabList(new Control[] { tableLeadingProjects, tableIntegrationProjects }); } /** * Create the tab for project information. */ private void createProjectInfoTab() { TabItem tbtmProjectInfos = new TabItem(tabFolder, SWT.NONE, TABINDEX_PROJECT_INFOS); tbtmProjectInfos.setText("Project Infos"); Composite projectInfoContainer = new Composite(tabFolder, SWT.NONE); tbtmProjectInfos.setControl(projectInfoContainer); projectNameInput = new Text(projectInfoContainer, SWT.BORDER); projectNameInput.setBounds(113, 30, 307, 26); Label lblProjectName = new Label(projectInfoContainer, SWT.NONE); lblProjectName.setBounds(10, 33, 97, 20); lblProjectName.setText("Project Name"); Label lblInfo = new Label(projectInfoContainer, SWT.NONE); lblInfo.setBounds(10, 62, 70, 20); lblInfo.setText("Info"); infoInput = new Text(projectInfoContainer, SWT.BORDER | SWT.WRAP); infoInput.setBounds(113, 62, 307, 112); Label lblWorkspace = new Label(projectInfoContainer, SWT.NONE); lblWorkspace.setBounds(10, 180, 83, 20); lblWorkspace.setText("Workspace"); workspaceInput = new Text(projectInfoContainer, SWT.BORDER); workspaceInput.setBounds(113, 180, 307, 26); } /** * Create the tab for the process control. */ private void createProcessControlTab() { TabItem tbtmProcessControl = new TabItem(tabFolder, SWT.NONE, TABINDEX_PROCESS_CONTROL); tbtmProcessControl.setText("Process Control"); Composite processControlContainer = new Composite(tabFolder, SWT.NONE); tbtmProcessControl.setControl(processControlContainer); Label lblSplevoDashboard = new Label(processControlContainer, SWT.NONE); lblSplevoDashboard.setAlignment(SWT.CENTER); lblSplevoDashboard.setFont(SWTResourceManager.getFont("Arial", 14, SWT.BOLD)); lblSplevoDashboard.setBounds(10, 10, 746, 30); lblSplevoDashboard.setText("SPLevo Dashboard"); Label activityStart = new Label(processControlContainer, SWT.NONE); activityStart.setAlignment(SWT.CENTER); activityStart.setImage(ResourceManager.getPluginImage("org.splevo.ui", "icons/bullet_green.png")); activityStart.setBounds(20, 66, 30, 30); Label activityFlow0 = new Label(processControlContainer, SWT.NONE); activityFlow0.setImage(ResourceManager.getPluginImage("org.splevo.ui", "icons/arrow_right.png")); activityFlow0.setAlignment(SWT.CENTER); activityFlow0.setBounds(44, 66, 30, 30); btnSelectSourceProjects = new Button(processControlContainer, SWT.WRAP); btnSelectSourceProjects.addMouseListener(new GotoTabMouseListener(tabFolder, TABINDEX_PROJECT_SELECTION)); btnSelectSourceProjects.setBounds(75, 59, 78, 45); btnSelectSourceProjects.setText("Project Selection"); Label activityFlow1 = new Label(processControlContainer, SWT.NONE); activityFlow1.setAlignment(SWT.CENTER); activityFlow1.setImage(ResourceManager.getPluginImage("org.splevo.ui", "icons/arrow_right.png")); activityFlow1.setBounds(159, 66, 30, 30); btnExtractSourceModels = new Button(processControlContainer, SWT.WRAP); btnExtractSourceModels.addMouseListener(new ExtractProjectListener(this)); btnExtractSourceModels.setBounds(195, 59, 78, 45); btnExtractSourceModels.setText("Model Extraction"); Label activityFlow3 = new Label(processControlContainer, SWT.NONE); activityFlow3.setImage(ResourceManager.getPluginImage("org.splevo.ui", "icons/arrow_right.png")); activityFlow3.setAlignment(SWT.CENTER); activityFlow3.setBounds(279, 66, 30, 30); btnDiffing = new Button(processControlContainer, SWT.WRAP); btnDiffing.addMouseListener(new DiffSourceModelListener(this)); btnDiffing.setBounds(315, 59, 72, 45); btnDiffing.setText("Diffing"); Label activityFlow4 = new Label(processControlContainer, SWT.NONE); activityFlow4.setImage(ResourceManager.getPluginImage("org.splevo.ui", "icons/arrow_right.png")); activityFlow4.setAlignment(SWT.CENTER); activityFlow4.setBounds(393, 66, 30, 30); btnInitVpm = new Button(processControlContainer, SWT.WRAP); btnInitVpm.addMouseListener(new InitVPMListener(this)); btnInitVpm.setBounds(429, 59, 72, 45); btnInitVpm.setText("Init VPM"); Label activityFlow5 = new Label(processControlContainer, SWT.NONE); activityFlow5.setImage(ResourceManager.getPluginImage("org.splevo.ui", "icons/arrow_right.png")); activityFlow5.setAlignment(SWT.CENTER); activityFlow5.setBounds(507, 66, 30, 30); btnRefineVPM = new Button(processControlContainer, SWT.WRAP); btnRefineVPM.addMouseListener(new VPMAnalysisListener(this)); btnRefineVPM.setText("Analyze VPM"); btnRefineVPM.setBounds(539, 59, 72, 45); Label label = new Label(processControlContainer, SWT.NONE); label.setImage(ResourceManager.getPluginImage("org.splevo.ui", "icons/arrow_right.png")); label.setAlignment(SWT.CENTER); label.setBounds(617, 66, 30, 30); btnGenerateFeatureModel = new Button(processControlContainer, SWT.WRAP); btnGenerateFeatureModel.addMouseListener(new GenerateFeatureModelListener(this)); btnGenerateFeatureModel.setText("Generate Feature Model"); btnGenerateFeatureModel.setBounds(648, 59, 118, 45); btnOpenDiff = new Button(processControlContainer, SWT.NONE); btnOpenDiff.setImage(ResourceManager.getPluginImage("org.splevo.ui", "icons/page_white_go.png")); btnOpenDiff.setBounds(341, 110, 26, 30); btnOpenDiff.addMouseListener(new MouseListener() { @Override public void mouseUp(MouseEvent e) { if (splevoProject.getDiffingModelPath() != null && splevoProject.getDiffingModelPath().length() > 0) { String basePath = getAbsoluteWorkspacePath(); File fileToOpen = new File(basePath + File.separator + splevoProject.getDiffingModelPath()); IFileStore fileStore = EFS.getLocalFileSystem().getStore(fileToOpen.toURI()); IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); try { IDE.openEditorOnFileStore(page, fileStore); } catch (PartInitException pie) { logger.error("failed to open diff file."); } } } @Override public void mouseDown(MouseEvent e) { } @Override public void mouseDoubleClick(MouseEvent e) { } }); btnOpenVPM = new Button(processControlContainer, SWT.NONE); btnOpenVPM.setImage(ResourceManager.getPluginImage("org.splevo.ui", "icons/page_white_go.png")); btnOpenVPM.setBounds(451, 110, 26, 30); btnOpenVPM.addMouseListener(new MouseListener() { @Override public void mouseUp(MouseEvent e) { if (splevoProject.getVpmModelPaths().size() > 0) { String basePath = getAbsoluteWorkspacePath(); File fileToOpen = new File(basePath + File.separator + splevoProject.getVpmModelPaths().get(splevoProject.getVpmModelPaths().size() - 1)); IFileStore fileStore = EFS.getLocalFileSystem().getStore(fileToOpen.toURI()); IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); try { IDE.openEditorOnFileStore(page, fileStore); } catch (PartInitException pie) { logger.error("failed to open diff file."); } } } @Override public void mouseDown(MouseEvent e) { } @Override public void mouseDoubleClick(MouseEvent e) { } }); } @Override public void setFocus() { // Set the focus } /** * Get the editor input resource. This methods overrides the super types method to return a more * specific IFileEditorInput. * * @return The editor input converted to an IFileEditorInput or null if not possible. */ @Override public IFileEditorInput getEditorInput() { if (super.getEditorInput() instanceof IFileEditorInput) { return (IFileEditorInput) super.getEditorInput(); } return null; } /** * Save the project configuration to the currently edited file. * * @param monitor * The progress monitor to report to. */ @Override public void doSave(IProgressMonitor monitor) { // check workspace setting if (getSplevoProject().getWorkspace() == null || getSplevoProject().getWorkspace().equals("")) { Shell shell = getEditorSite().getShell(); MessageDialog.openError(shell, "Workspace Missing", "You need to specify a workspace directory for the project."); return; } String filePath = null; try { filePath = getCurrentFilePath(); ModelUtils.save(splevoProject, filePath); } catch (Exception e) { Shell shell = getEditorSite().getShell(); MessageDialog.openError(shell, "Save error", "Unable to save the project file to " + filePath); e.printStackTrace(); } dirtyFlag = false; firePropertyChange(IEditorPart.PROP_DIRTY); } /** * Get the absolute path of the current editor input file. * * @return The file path derived from the editor input. */ private String getCurrentFilePath() { FileEditorInput fileInput = (FileEditorInput) getEditorInput(); String filePath = fileInput.getFile().getFullPath().toOSString(); return filePath; } @Override public void doSaveAs() { // do save as is not supported } @Override public void init(IEditorSite site, IEditorInput input) throws PartInitException { setSite(site); setInput(input); if (input instanceof IFileEditorInput) { IFileEditorInput fileInput = (IFileEditorInput) input; if (fileInput.getName().endsWith(SPLevoProjectUtil.SPLEVO_FILE_EXTENSION)) { ResourceSet rs = new ResourceSetImpl(); File projectFile = new File(fileInput.getFile().getFullPath().toOSString()); EObject model; try { model = ModelUtils.load(projectFile, rs); } catch (IOException e) { throw new PartInitException("Unable to load SPLevo project file in editor", e); } if (model instanceof SPLevoProject) { this.splevoProject = (SPLevoProject) model; } } } } /** * @return the splevoProject */ public SPLevoProject getSplevoProject() { return splevoProject; } @Override public boolean isDirty() { return dirtyFlag; } @Override public boolean isSaveAsAllowed() { return false; } /** * Mark the editor as dirty. */ public void markAsDirty() { dirtyFlag = true; firePropertyChange(IEditorPart.PROP_DIRTY); enableButtonsIfInformationAvailable(); } /** * Update the ui and present the submitted message in an information dialog. If the provided * message is null, no dialog will be opened. * * @param message * The optional message to be presented. */ public void updateUi(String message) { updateUI(); if (message != null) { Shell shell = getEditorSite().getShell(); MessageDialog.openInformation(shell, "SPLevo Info", message); } } /** * Update the user interface. */ public void updateUI() { if (splevoProject.getSourceModelPathLeading() != null) { sourceModelLeadingInput.setText(splevoProject.getSourceModelPathLeading()); } else { logger.warn("Leading source model path is empty."); } if (splevoProject.getSourceModelPathIntegration() != null) { sourceModelIntegrationInput.setText(splevoProject.getSourceModelPathIntegration()); } else { logger.warn("Integration source model path is empty."); } if (splevoProject.getDiffingModelPath() != null) { diffingModelInput.setText(splevoProject.getDiffingModelPath()); } markAsDirty(); enableButtonsIfInformationAvailable(); } /** * Enable Buttons if the information for the action is available. */ private void enableButtonsIfInformationAvailable() { disableAllButtonsExceptProjectSelection(); if (projectsSelected()) { btnExtractSourceModels.setEnabled(true); } else { return; } if (sourceModelsExtracted()) { enableButtonsAfterExtraction(); } else { return; } if (diffModelAvailable()) { enableButtonsAfterDiffing(); } else { return; } if (vpmAvailable()) { enableButtonsAfterInitVPM(); } else { return; } } /** * Check if at least one variation point model is set and can be accessed. * * @return True if an accessible vpm exists. */ private boolean vpmAvailable() { String basePath = getAbsoluteWorkspacePath(); return splevoProject.getVpmModelPaths().size() > 0 && new File(basePath + splevoProject.getVpmModelPaths().get(0)).canRead(); } /** * Check if a diff model is set in the project file and if it can be read. * * @return true if the diff model is available. */ private boolean diffModelAvailable() { String basePath = getAbsoluteWorkspacePath(); return splevoProject.getDiffingModelPath() != null && new File(basePath + splevoProject.getDiffingModelPath()).canRead(); } /** * Determine the absolute OS specific path of the workspace. * * @return The absolute path. */ private String getAbsoluteWorkspacePath() { IWorkspace workspace = ResourcesPlugin.getWorkspace(); String basePath = workspace.getRoot().getRawLocation().toOSString(); return basePath; } /** * Check if source models have been extracted previously based on the project file content. * * @return True if both models are available. */ private boolean sourceModelsExtracted() { String basePath = getAbsoluteWorkspacePath(); return splevoProject.getSourceModelPathIntegration() != null && new File(basePath + splevoProject.getSourceModelPathIntegration()).canRead() && splevoProject.getSourceModelPathLeading() != null && new File(basePath + splevoProject.getSourceModelPathLeading()).canRead(); } /** * Checks if both input models have more than one project. * * @return true, if both input models have more than one project, else false */ private boolean projectsSelected() { return splevoProject.getLeadingProjects().size() > 0 && splevoProject.getIntegrationProjects().size() > 0; } /** * Disable all buttons except the Project Selection button. */ private void disableAllButtonsExceptProjectSelection() { List<Button> buttons = new ArrayList<Button>(); buttons.add(btnExtractSourceModels); buttons.add(btnDiffing); buttons.add(btnOpenDiff); buttons.add(btnGenerateFeatureModel); buttons.add(btnInitVpm); buttons.add(btnRefineVPM); buttons.add(btnOpenVPM); for (Button button : buttons) { button.setEnabled(false); } } /** * initializing the data bindings for the UI. * * @return The prepared context to be bound to the ui. */ protected DataBindingContext initDataBindings() { DataBindingContext bindingContext = new DataBindingContext(); MarkDirtyListener markDirtyListener = new MarkDirtyListener(this); IObservableValue observeTextProjectNameInputObserveWidget = WidgetProperties.text(SWT.Modify).observe( projectNameInput); IObservableValue nameGetSplevoProjectObserveValue = PojoProperties.value("name").observe(getSplevoProject()); nameGetSplevoProjectObserveValue.addChangeListener(markDirtyListener); bindingContext .bindValue(observeTextProjectNameInputObserveWidget, nameGetSplevoProjectObserveValue, null, null); IObservableValue observeTextInfoInputObserveWidget = WidgetProperties.text(SWT.Modify).observe(infoInput); IObservableValue descriptionGetSplevoProjectObserveValue = PojoProperties.value("description").observe( getSplevoProject()); descriptionGetSplevoProjectObserveValue.addChangeListener(markDirtyListener); bindingContext .bindValue(observeTextInfoInputObserveWidget, descriptionGetSplevoProjectObserveValue, null, null); IObservableValue observeTextWorkspaceInputObserveWidget = WidgetProperties.text(SWT.Modify).observe( workspaceInput); IObservableValue workspaceGetSplevoProjectObserveValue = PojoProperties.value("workspace").observe( getSplevoProject()); workspaceGetSplevoProjectObserveValue.addChangeListener(markDirtyListener); bindingContext.bindValue(observeTextWorkspaceInputObserveWidget, workspaceGetSplevoProjectObserveValue, null, null); IObservableValue observeTextInputVariantNameLeadingObserveWidget = WidgetProperties.text(SWT.Modify).observe( inputVariantNameLeading); IObservableValue variantNameLeadingGetSplevoProjectObserveValue = PojoProperties.value("variantNameLeading") .observe(getSplevoProject()); variantNameLeadingGetSplevoProjectObserveValue.addChangeListener(markDirtyListener); bindingContext.bindValue(observeTextInputVariantNameLeadingObserveWidget, variantNameLeadingGetSplevoProjectObserveValue, null, null); IObservableValue observeTextInputVariantNameIntegrationObserveWidget = WidgetProperties.text(SWT.Modify) .observe(inputVariantNameIntegration); IObservableValue variantNameIntegrationGetSplevoProjectObserveValue = PojoProperties.value( "variantNameIntegration").observe(getSplevoProject()); variantNameIntegrationGetSplevoProjectObserveValue.addChangeListener(markDirtyListener); bindingContext.bindValue(observeTextInputVariantNameIntegrationObserveWidget, variantNameIntegrationGetSplevoProjectObserveValue, null, null); IObservableValue observeTextSourceModelLeadingObserveWidget = WidgetProperties.text(SWT.Modify).observe( sourceModelLeadingInput); IObservableValue sourceModelPathLeadingGetSplevoProjectObserveValue = PojoProperties.value( "sourceModelPathLeading").observe(splevoProject); sourceModelPathLeadingGetSplevoProjectObserveValue.addChangeListener(markDirtyListener); bindingContext.bindValue(observeTextSourceModelLeadingObserveWidget, sourceModelPathLeadingGetSplevoProjectObserveValue, null, null); IObservableValue observeTextSourceModelIntegrationObserveWidget = WidgetProperties.text(SWT.Modify).observe( sourceModelIntegrationInput); IObservableValue sourceModelPathIntegrationGetSplevoProjectObserveValue = PojoProperties.value( "sourceModelPathIntegration").observe(splevoProject); sourceModelPathIntegrationGetSplevoProjectObserveValue.addChangeListener(markDirtyListener); bindingContext.bindValue(observeTextSourceModelIntegrationObserveWidget, sourceModelPathIntegrationGetSplevoProjectObserveValue, null, null); IObservableValue observeTextDiffingModelInputObserveWidget = WidgetProperties.text(SWT.Modify).observe( diffingModelInput); IObservableValue diffingModelPathSplevoProjectObserveValue = PojoProperties.value("diffingModelPath").observe( splevoProject); diffingModelPathSplevoProjectObserveValue.addChangeListener(markDirtyListener); bindingContext.bindValue(observeTextDiffingModelInputObserveWidget, diffingModelPathSplevoProjectObserveValue, null, null); IObservableValue observeTextDiffingPackageFilterInputObserveWidget = WidgetProperties.text(SWT.Modify).observe( diffingPackageFilterInput); IObservableValue diffingFilterRulesSplevoProjectObserveValue = PojoProperties.value("diffingFilterRules") .observe(splevoProject); diffingFilterRulesSplevoProjectObserveValue.addChangeListener(markDirtyListener); bindingContext.bindValue(observeTextDiffingPackageFilterInputObserveWidget, diffingFilterRulesSplevoProjectObserveValue, null, null); return bindingContext; } }
package com.dancingdrone; import android.app.ListActivity; import android.content.ContentResolver; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import com.musicg.wave.Wave; import de.yadrone.android.PlayerActivity; import de.yadrone.android.R; public class MusicSelect extends ListActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_music_select); Wave wave = new Wave(); // Set up list adapter. ContentResolver cr = getContentResolver(); Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; String selection = MediaStore.Audio.Media.IS_MUSIC + "!= 0"; String sortOrder = MediaStore.Audio.Media.TITLE + " ASC"; Cursor cur = cr.query(uri, null, selection, null, sortOrder); startManagingCursor(cur); ListAdapter adapter = new SimpleCursorAdapter( this, // Context. android.R.layout.two_line_list_item, cur, new String[]{MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.DISPLAY_NAME}, new int[]{android.R.id.text1, android.R.id.text2}); setListAdapter(adapter); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { Cursor c = ((SimpleCursorAdapter)l.getAdapter()).getCursor(); c.moveToPosition(position); Intent intent = new Intent(this, PlayerActivity.class); Bundle b = new Bundle(); String uri = c.getString(c.getColumnIndex(MediaStore.Audio.Media.DATA)); String name = c.getString(c.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)); b.putParcelable(PlayerActivity.FILE_URI, Uri.parse(uri)); b.putString(PlayerActivity.SONG_NAME, name); intent.putExtras(b); startActivity(intent); super.onListItemClick(l, v, position, id); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_music_select, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
package tm; import java.io.File; import java.io.FileInputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import dao.DAOTablaClienteFrecuente; import dao.DAOTablaEquivalentes; import dao.DAOTablaIngredientes; import dao.DAOTablaIngredientesPlato; import dao.DAOTablaMenu; import dao.DAOTablaMenuPlato; import dao.DAOTablaPedido; import dao.DAOTablaPedidoMenu; import dao.DAOTablaPedidoPlato; import dao.DAOTablaPlato; import dao.DAOTablaRestaurante; import dao.DAOTablaUsuario; import dao.DAOTablaZona; import dtm.RotondAndesDistributed; import vos.ClienteAux; import vos.ClienteFrecuente; import vos.Funcionamiento; import vos.Informacion; import vos.Ingredientes; import vos.IngredientesPlato; import vos.Menu; import vos.MenuPlato; import vos.Pedido; import vos.PedidoConsolidado; import vos.PedidoMenu; import vos.PedidoPlato; import vos.Plato; import vos.Rentabilidad; import vos.Restaurante; import vos.Usuario; import vos.Zona; import vos.InfoPedido; import vos.InfoPedido.ItemPedido; import java.sql.*; import javax.sql.*; import oracle.jdbc.driver.*; import oracle.jdbc.pool.*; import oracle.jdbc.xa.OracleXid; import oracle.jdbc.xa.OracleXAException; import oracle.jdbc.xa.client.*; import javax.transaction.xa.*; public class RotondAndesTM { /** * Atributo estatico que contiene el path relativo del archivo que tiene los datos de la conexion */ private static final String CONNECTION_DATA_FILE_NAME_REMOTE = "/conexion.properties"; /** * Atributo estatico que contiene el path absoluto del archivo que tiene los datos de la conexion */ private String connectionDataPath; /** * Atributo que guarda el usuario que se va a usar para conectarse a la base de datos. */ private String user; /** * Atributo que guarda la clave que se va a usar para conectarse a la base de datos. */ private String password; /** * Atributo que guarda el URL que se va a usar para conectarse a la base de datos. */ private String url; /** * Atributo que guarda el driver que se va a usar para conectarse a la base de datos. */ private String driver; /** * conexion a la base de datos */ private Connection conn; private RotondAndesDistributed dtm; /** * Metodo constructor de la clase VideoAndesMaster, esta clase modela y contiene cada una de las * transacciones y la logica de negocios que estas conllevan. * <b>post: </b> Se crea el objeto VideoAndesTM, se inicializa el path absoluto del archivo de conexion y se * inicializa los atributos que se usan par la conexion a la base de datos. * @param contextPathP - path absoluto en el servidor del contexto del deploy actual */ public RotondAndesTM(String contextPathP) { connectionDataPath = contextPathP + CONNECTION_DATA_FILE_NAME_REMOTE; initConnectionData(); System.out.println("Instancing DTM... "); dtm=RotondAndesDistributed.getInstance(this); System.out.println("Done..."); } /** * Metodo que inicializa los atributos que se usan para la conexion a la base de datos. * <b>post: </b> Se han inicializado los atributos que se usan par la conexion a la base de datos. */ private void initConnectionData() { try { File arch = new File(this.connectionDataPath); Properties prop = new Properties(); FileInputStream in = new FileInputStream(arch); prop.load(in); in.close(); this.url = prop.getProperty("url"); this.user = prop.getProperty("usuario"); this.password = prop.getProperty("clave"); this.driver = prop.getProperty("driver"); Class.forName(driver); } catch (Exception e) { e.printStackTrace(); } } /** * Metodo que retorna la conexion a la base de datos * @return Connection - la conexion a la base de datos * @throws SQLException - Cualquier error que se genere durante la conexion a la base de datos */ private Connection darConexion() throws SQLException { System.out.println("Connecting to: " + url + " With user: " + user); return DriverManager.getConnection(url, user, password); } ///////Transacciones//////////////////// /** * REQUERIMIENTO FC1 * Metodo que modela la transaccion que retorna todos los platos de la base de datos. * @return ListaVideos - objeto que modela un arreglo de platos. este arreglo contiene el resultado de la busqueda * @throws Exception - cualquier error que se genere durante la transaccion */ public List<Plato> darProductosFiltro(String filtro) throws Exception { List<Plato> platos; DAOTablaPlato daoPlatos = new DAOTablaPlato(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoPlatos.setConn(conn); platos = daoPlatos.darPlatosFiltro(filtro); } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoPlatos.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } return platos; } /** * RFC9 * @param informacionEq * @return * @throws Exception */ public List<Usuario> darUsuariosMayorConsumo(String informacionEq) throws Exception { List<Usuario> usuarios; DAOTablaUsuario daoUsuarios = new DAOTablaUsuario(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoUsuarios.setConn(conn); String info[] = informacionEq.split("-"); //if (info.length < 4) throw new Exception("La informacion dada esta incompleta"); usuarios = daoUsuarios.darUsuariosConsumoAlto(info[0], info[1],info[2], info[3]); } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoUsuarios.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } return usuarios; } /** * RFC10 * @param informacionEq * @return * @throws Exception */ public List<Usuario> darUsuariosMenorConsumo(String informacionEq) throws Exception { List<Usuario> usuarios; DAOTablaUsuario daoUsuarios = new DAOTablaUsuario(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoUsuarios.setConn(conn); String info[] = informacionEq.split("-"); //if (info.length < 4) throw new Exception("La informacion dada esta incompleta"); usuarios = daoUsuarios.darUsuariosConsumoBajo(info[0], info[1],info[2], info[3]); } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoUsuarios.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } return usuarios; } /** * RFC11 * @param informacionEq * @return * @throws Exception */ public List<Funcionamiento> darFuncionamiento() throws Exception { List<Funcionamiento> funcionamiento; DAOTablaPedido daoPedidos = new DAOTablaPedido(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoPedidos.setConn(conn); funcionamiento = daoPedidos.darFuncionamientoRotond(); } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoPedidos.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } return funcionamiento; } /** * RFC11 * @param informacionEq * @return * @throws Exception */ public List<ClienteAux> darBuenosClientes() throws Exception { List<ClienteAux> clientes; DAOTablaClienteFrecuente daoCliente = new DAOTablaClienteFrecuente(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoCliente.setConn(conn); clientes = daoCliente.darBuenosClientes(); } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoCliente.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } return clientes; } /** * REQUERIMIENTO F11 * Agrega una equivalencia entre ingredientes para un restaurante. * @param ingredientes <nombre ing1>-<nombre ing2>-<nombre restaurante> * @throws Exception en caso de que sean el mismo ingrediente, * de que alguno de los ingredientes no exista, o de que el restaurante no exista. */ public void addEquivalenciaIngrediente(String ingredientes) throws Exception { DAOTablaEquivalentes daoEquiv = new DAOTablaEquivalentes(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoEquiv.setConn(conn); daoEquiv.addEquivalente(ingredientes); conn.commit(); } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoEquiv.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } } /** * REQUERIMIENTO F12 * @param productos * @throws Exception */ public void addEquivalenciaPlato(String productos) throws Exception { DAOTablaPlato daoPlatos = new DAOTablaPlato(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoPlatos.setConn(conn); String[] producto = productos.split("-"); Plato plato1 = daoPlatos.getEquivalentePorId(Integer.parseInt(producto[0])); Plato plato2 = daoPlatos.getEquivalentePorId(Integer.parseInt(producto[1])); if (plato1.getRestaurante().equalsIgnoreCase(plato2.getRestaurante()) == false) throw new Exception("Los productos son de restaurantes diferentes"); if(!plato1.getRestaurante().equalsIgnoreCase(producto[2])) throw new Exception("Los productos no son de ese restaurante"); if(!plato1.getCategoria().equalsIgnoreCase(plato2.getCategoria())) throw new Exception("Los productos son de diferente categoria"); daoPlatos.addEquivalentes(productos); conn.commit(); } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoPlatos.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } } /** * REQUERIMIENTO F13 * Surte todos los pruductos del restaurante indicado. * @param nombre nombre del restaurante * @throws Exception en caso de que no se logre re surtir el restaurante. */ public void surtirRestaurante(String nombre) throws Exception { DAOTablaMenu daoMenu = new DAOTablaMenu(); DAOTablaPlato daoPlato = new DAOTablaPlato(); DAOTablaRestaurante daoRestaurante = new DAOTablaRestaurante(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoMenu.setConn(conn); daoPlato.setConn(conn); daoRestaurante.setConn(conn); if(daoRestaurante.buscarRestaurantePorNombre(nombre) == null) { throw new Exception("No exise restaurante con el nombre: " + nombre); } daoMenu.surtir(nombre); daoPlato.surtir(nombre); conn.commit(); } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoMenu.cerrarRecursos(); daoPlato.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } } /** * REQUERIMIENTO F15 * Registra el pedido de productos de una mesa. * @param pedido Pedido de la mesa que se esta registrando. * @param info <Num prods pedido>-(<id producto>-<categoria>)* * @throws Exception en caso de que el pedido ya exista, o que algun producto no exista. */ public void registrarPedidoMesa(Pedido pedido, String info) throws Exception { DAOTablaPedidoMenu daoPedidoMenu = new DAOTablaPedidoMenu(); DAOTablaPedidoPlato daoPedidoPlato = new DAOTablaPedidoPlato(); //DAOTablaMenu daoMenu = new DAOTablaMenu(); //DAOTablaPlato daoPlato = new DAOTablaPlato(); DAOTablaPedido daoPedido = new DAOTablaPedido(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoPedidoMenu.setConn(conn); daoPedidoPlato.setConn(conn); daoPedido.setConn(conn); //daoMenu.setConn(conn); //daoPlato.setConn(conn); daoPedido.addPedido(pedido); String[] params = info.split("-"); int count = Integer.parseInt(params[0]); for(int i = 0; i < count; i++) { if(params[2*i + 2].compareTo("P") == 0) { int idPlato = Integer.parseInt(params[2*i + 1]); //daoPlato.disminuirDisponibilidad(idPlato, 1); daoPedidoPlato.addPedidoPlato(new PedidoPlato(pedido.getNumPedido(), idPlato)); } else { int idMenu = Integer.parseInt(params[2*i + 1]); //daoMenu.disminuirDisponibilidad(idMenu, 1); daoPedidoMenu.addPedidoMenu(new PedidoMenu(pedido.getNumPedido(), idMenu)); } } conn.commit(); } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoPedidoMenu.cerrarRecursos(); daoPedidoPlato.cerrarRecursos(); daoPedido.cerrarRecursos(); //daoMenu.cerrarRecursos(); //daoPlato.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } } /** * REQUERIMIENTO F17 * Cancela un pedido que no se haya servido. * @param pedido Pedido que se esta cancelado. * @throws Exception en caso de que no se pueda cancelar el pedido. */ public void cancelarPedido(Pedido pedido) throws Exception { DAOTablaPedidoMenu daoPedidoMenu = new DAOTablaPedidoMenu(); DAOTablaPedidoPlato daoPedidoPlato = new DAOTablaPedidoPlato(); DAOTablaPedido daoPedido = new DAOTablaPedido(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoPedidoMenu.setConn(conn); daoPedidoPlato.setConn(conn); daoPedido.setConn(conn); daoPedidoMenu.removerPedidos(pedido); daoPedidoPlato.removerPedidos(pedido); daoPedido.removerPedido(pedido); conn.commit(); } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoPedidoMenu.cerrarRecursos(); daoPedidoPlato.cerrarRecursos(); daoPedido.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } } /** * REQUERIMIENTO FC2 * Metodo que modela la transaccion que retorna todos las zonas de la base de datos. * @return ListaVideos - objeto que modela un arreglo de zonas. este arreglo contiene el resultado de la busqueda * @throws Exception - cualquier error que se genere durante la transaccion */ public List<Zona> darZonas() throws Exception { List<Zona> zonas; DAOTablaZona daoZona = new DAOTablaZona(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoZona.setConn(conn); zonas = daoZona.darZonas(); } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoZona.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } return zonas; } /** * REQUERIMIENTO FC3 * Metodo que modela la transaccion que retorna todos los platos de la base de datos. * @return ListaVideos - objeto que modela un arreglo de platos. este arreglo contiene el resultado de la busqueda * @throws Exception - cualquier error que se genere durante la transaccion */ public List<ClienteFrecuente> darClientes() throws Exception { List<ClienteFrecuente> clientes; DAOTablaClienteFrecuente daoCliente = new DAOTablaClienteFrecuente(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoCliente.setConn(conn); clientes = daoCliente.darClientes(); } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoCliente.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } return clientes; } public List<Pedido> darPedidosCliente(String emailCliente) throws Exception { List<Pedido> pedidosCliente; DAOTablaPedido daoPedido = new DAOTablaPedido(); DAOTablaClienteFrecuente daoCliente = new DAOTablaClienteFrecuente(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoCliente.setConn(conn); daoPedido.setConn(conn); pedidosCliente = daoPedido.darPedidosCliente(emailCliente); } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoCliente.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } return pedidosCliente; } public List<Zona> darZonasFiltro(String filtro) throws Exception { List<Zona> zonas; DAOTablaZona daoZona = new DAOTablaZona(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoZona.setConn(conn); zonas = daoZona.darZonasFiltro(filtro); } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoZona.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } return zonas; } /** * RFC5 * @param fecha1 * @param fecha2 * @return * @throws Exception */ public Rentabilidad darRentabilidad(String fecha1, String fecha2, String nomRestaurante) throws Exception { Rentabilidad rent; DAOTablaPlato daoPlatos = new DAOTablaPlato(); DAOTablaRestaurante daoRestaurantes = new DAOTablaRestaurante(); try { //////transaccion this.conn = darConexion(); daoPlatos.setConn(conn); rent = daoRestaurantes.getRentabilidad(fecha1, fecha2, nomRestaurante); } catch (SQLException e) { System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoPlatos.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } return rent; } /** * Metodo no necesario, pero bueno para probar todo * @return * @throws Exception */ public List<Restaurante> darRestaurantes() throws Exception { List<Restaurante> restaurantes; DAOTablaRestaurante daoRestaurante = new DAOTablaRestaurante(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoRestaurante.setConn(conn); restaurantes = daoRestaurante.darRestaurantes(); } catch (SQLException e) { System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoRestaurante.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } return restaurantes; } /** * Metodo no necesario, pero bueno para probar todo * @return * @throws Exception */ public List<Usuario> darUsuarios() throws Exception { List<Usuario> usuarios; DAOTablaUsuario daoUsuario = new DAOTablaUsuario(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoUsuario.setConn(conn); usuarios = daoUsuario.darUsuarios(); } catch (SQLException e) { System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoUsuario.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } return usuarios; } /** * Metodo no necesario, pero bueno para probar todo * @return * @throws Exception */ public List<Menu> darMenus() throws Exception { List<Menu> menus; DAOTablaMenu daoMenu = new DAOTablaMenu(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoMenu.setConn(conn); menus = daoMenu.darMenus(); } catch (SQLException e) { System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoMenu.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } return menus; } /** * Metodo no necesario, pero bueno para probar todo * @return * @throws Exception */ public List<Ingredientes> darIngredientes() throws Exception { List<Ingredientes> ingredientes; DAOTablaIngredientes daoIngredientes = new DAOTablaIngredientes(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoIngredientes.setConn(conn); ingredientes = daoIngredientes.darIngredientes(); } catch (SQLException e) { System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoIngredientes.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } return ingredientes; } /** * Metodo no necesario, pero bueno para probar todo * @return * @throws Exception */ public List<Pedido> darPedidos() throws Exception { List<Pedido> pedidos; DAOTablaPedido daoPedido = new DAOTablaPedido(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoPedido.setConn(conn); pedidos = daoPedido.darPedidos(); } catch (SQLException e) { System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoPedido.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } return pedidos; } /** * Requerimiento C8 */ public PedidoConsolidado darPedidosRestaurante(String restaurante) throws Exception { PedidoConsolidado pedido; DAOTablaRestaurante daoRestaurante = new DAOTablaRestaurante(); DAOTablaPedido daoPedido = new DAOTablaPedido(); try { //////transaccion this.conn = darConexion(); conn.setReadOnly(true);; daoPedido.setConn(conn); daoRestaurante.setConn(conn); if (daoRestaurante.buscarRestaurantePorNombre(restaurante) == null) throw new Exception ("No existe el restaurante con el nombre " + restaurante); pedido = daoPedido.darPedidosConsolidadosRestaurante(restaurante); } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoPedido.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } return pedido; } /** * REQUERIMIENTO FC4 * Metodo que modela la transaccion que retorna el plato mas ofrecido en la base de datos * @return platoMasOfrecido - objeto que modela el plato mas ofrecido. * @throws Exception - cualquier error que se genere durante la transaccion */ public Plato darProductoMasOfrecidos() throws Exception { Plato platoMasOfercido = null; List<Plato> platos; DAOTablaPlato daoPlatos = new DAOTablaPlato(); DAOTablaMenuPlato daoMenuPlato = new DAOTablaMenuPlato(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoPlatos.setConn(conn); daoMenuPlato.setConn(conn); platos = daoPlatos.darPlatos(); int cantMenus = 0; for (Plato p : platos) if (daoMenuPlato.buscarMenuPlatoPorIdPlato(p.getIdPlato()).size() > cantMenus) platoMasOfercido = p; } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoPlatos.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } return platoMasOfercido; } /** * REQUERIMIENTO FC7 * Retorna los platos que ha consumido un cliente frecuente de la rotonda * @return platos - platos que ha consumido el cliente indicado por parametro * @throws Exception - cualquier error que se genere durante la busqueda */ public List<Plato> darProductosConsumidos(ClienteFrecuente cliente) throws Exception { List<Plato> platos; DAOTablaPlato daoPlatos = new DAOTablaPlato(); try { //////transaccion this.conn = darConexion(); conn.setReadOnly(true); daoPlatos.setConn(conn); platos = daoPlatos.darPlatosCliente(cliente); conn.commit(); } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoPlatos.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } return platos; } /** * REQUERIMIENTO F1 * Metodo que modela la transaccion que agrega un solo usuario a la base de datos. * <b> post: </b> se ha agregado el usuario que entra como parametro * @param usuario - el usuario a agregar. usuario != null * @throws Exception - cualquier error que se genere agregando el usuario */ public void addUsuario(Usuario usuario) throws Exception { DAOTablaUsuario daoUsuario = new DAOTablaUsuario(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoUsuario.setConn(conn); daoUsuario.addUsuario(usuario); conn.commit(); } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoUsuario.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } } /** * REQUERIMIENTO F2 * Metodo que modela la transaccion que agrega un solo cliente a la base de datos. * <b> post: </b> se ha cliente el usuario que entra como parametro * @param cliente - el cliente a agregar. cliente != null * @throws Exception - cualquier error que se genere agregando el usuario */ public void addCliente(ClienteFrecuente cliente) throws Exception { DAOTablaClienteFrecuente daoCliente = new DAOTablaClienteFrecuente(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoCliente.setConn(conn); daoCliente.addCliente(cliente); conn.commit(); } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoCliente.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } } /** * REQUERIMIENTO F3 * Metodo que modela la transaccion que agrega un solo restaurante a la base de datos. * <b> post: </b> se ha agregado el restaurante que entra como parametro * @param restaurante - el restaurante a agregar. restaurante != null * @throws Exception - cualquier error que se genere agregando el restaurante */ public void addRestaurante(Restaurante restaurante) throws Exception { DAOTablaRestaurante daoRestaurante = new DAOTablaRestaurante(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoRestaurante.setConn(conn); daoRestaurante.addRestaurante(restaurante); conn.commit(); } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoRestaurante.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } } /** * REQUERIMIENTO F4 * Metodo que modela la transaccion que agrega un solo plato a la base de datos. * <b> post: </b> se ha agregado el plato que entra como parametro * @param plato - el plato a agregar. plato != null * @throws Exception - cualquier error que se genere agregando el restaurante */ public void addPlato(Plato plato) throws Exception { DAOTablaPlato daoPlato = new DAOTablaPlato(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoPlato.setConn(conn); daoPlato.addPlato(plato); conn.commit(); } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoPlato.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } } /** * REQUERIMIENTO F5 * Metodo que modela la transaccion que agrega un solo ingrediente a la base de datos. * <b> post: </b> se ha agregado el ingrediente que entra como parametro * @param ingrediente - el ingrediente a agregar. ingrediente != null * @throws Exception - cualquier error que se genere agregando el ingrediente */ public void addIngrediente(Ingredientes ingrediente) throws Exception { DAOTablaIngredientes daoIngrediente = new DAOTablaIngredientes(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoIngrediente.setConn(conn); daoIngrediente.addIngrediente(ingrediente); conn.commit(); } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoIngrediente.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } } /** * REQUERIMIENTO F6 * Metodo que modela la transaccion que agrega un solo menu a la base de datos. * <b> post: </b> se ha agregado el menu que entra como parametro * @param menu - el menu a agregar. menu != null * @throws Exception - cualquier error que se genere agregando el menu */ public void addMenu(Menu menu) throws Exception { DAOTablaMenu daoMenu = new DAOTablaMenu(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoMenu.setConn(conn); daoMenu.addMenu(menu); conn.commit(); } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoMenu.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } } /** * REQUERIMIENTO F7 * Metodo que modela la transaccion que agrega una sola zona a la base de datos. * <b> post: </b> se ha agregado la zona que entra como parametro * @param zona - la zona a agregar. zona != null * @throws Exception - cualquier error que se genere agregando la zona */ public void addZona(Zona zona) throws Exception { DAOTablaZona daoZona = new DAOTablaZona(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoZona.setConn(conn); daoZona.addZona(zona); conn.commit(); } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoZona.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } } /** * REQUERIMIENTO F8 * Metodo que modela la transaccion que agrega un solo cliente a la base de datos. * <b> post: </b> se ha agregado el cliente que entra como parametro * @param cliente - el cliente a agregar. cliente != null * @throws Exception - cualquier error que se genere agregando el cliente */ public void addPreferenciCliente(ClienteFrecuente cliente) throws Exception { DAOTablaClienteFrecuente daoCliente = new DAOTablaClienteFrecuente(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoCliente.setConn(conn); daoCliente.updateCliente(cliente); conn.commit(); } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoCliente.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } } /** * Metodo que modela la transaccion que agrega un solo pedidoPlato a la base de datos. * <b> post: </b> se ha agregado el pedidoPlato que entra como parametro * @param pedidoPlato - el pedidoPlato a agregar. pedidoPlato != null * @throws Exception - cualquier error que se genere agregando el pedidoPlato */ public void addPedidoMenu(Pedido pedido, int idMenu) throws Exception { DAOTablaPedido daoPedido = new DAOTablaPedido(); DAOTablaPedidoMenu daoPedidoMenu = new DAOTablaPedidoMenu(); DAOTablaMenu daoMenu = new DAOTablaMenu(); DAOTablaPlato daoPlato = new DAOTablaPlato(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoPedido.setConn(conn); daoPedidoMenu.setConn(conn); daoMenu.setConn(conn); daoPlato.setConn(conn); Menu menu = daoMenu.buscarMenuPorId(idMenu); if (menu.getDisponibles() < 1) throw new Exception("No hay disponibilidad del menu " + menu.getNombre()); daoPedido.addPedido(pedido); PedidoMenu pedidoMenu = new PedidoMenu(pedido.getNumPedido(), idMenu); daoPedidoMenu.addPedidoMenu(pedidoMenu); for (int i = 0; i < menu.getProductos().size(); i++) daoPlato.SeVendioProducto((int) menu.getProductos().get(i)); daoMenu.SeVendioMenu(idMenu); conn.commit(); } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoPedido.cerrarRecursos(); daoPedidoMenu.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } } /** * RF14 * @param pedido * @param idMenu * @param equivalencia * @throws Exception */ public void addPedidoMenuEquivalencia(Pedido pedido, int idMenu, String equivalencia) throws Exception { DAOTablaPedido daoPedido = new DAOTablaPedido(); DAOTablaPedidoMenu daoPedidoMenu = new DAOTablaPedidoMenu(); DAOTablaMenu daoMenu = new DAOTablaMenu(); DAOTablaPlato daoPlato = new DAOTablaPlato(); try { String[]eq = equivalencia.split("-"); //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoPedido.setConn(conn); daoPedidoMenu.setConn(conn); daoMenu.setConn(conn); daoPlato.setConn(conn); Plato plato1 = daoPlato.buscarPlatoPorId(Integer.parseInt(eq[0])); Plato plato2 = daoPlato.buscarPlatoPorId(Integer.parseInt(eq[1])); if (!daoMenu.buscarMenuPorId(idMenu).getProductos().contains(plato1.getIdPlato())) throw new Exception("El menu con id " + idMenu + " no posee el producto " + plato1.getNombre()); if (!daoPlato.getIdPlatosEquivalentes(plato1.getIdPlato()).contains(plato2.getIdPlato())) throw new Exception("Los productos " + plato1.getNombre() + " y " + plato2.getNombre() + " no son equivalentes"); if (plato1.getRestaurante().equalsIgnoreCase(eq[2]) == false) throw new Exception("Los productos no pertenecen al restaurante " + eq[2]); pedido.setCambios("Cambiar el producto " + plato1.getNombre() + " por el producto " + plato2.getNombre()); daoPedido.addPedido(pedido); PedidoMenu pedidoMenu = new PedidoMenu(pedido.getNumPedido(), idMenu); daoPedidoMenu.addPedidoMenu(pedidoMenu); conn.commit(); } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoPedido.cerrarRecursos(); daoPedidoMenu.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } } /** * REQUERIMIENTO F9 * Metodo que modela la transaccion que agrega un solo pedidoPlato a la base de datos. * <b> post: </b> se ha agregado el pedidoPlato que entra como parametro * @param pedidoPlato - el pedidoPlato a agregar. pedidoPlato != null * @throws Exception - cualquier error que se genere agregando el pedidoPlato */ public void addPedidoPlato(Pedido pedido, int idPlato) throws Exception { DAOTablaPedido daoPedido = new DAOTablaPedido(); DAOTablaPedidoPlato daoPedidoPlato = new DAOTablaPedidoPlato(); DAOTablaPlato daoPlato = new DAOTablaPlato(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoPedido.setConn(conn); daoPedidoPlato.setConn(conn); daoPlato.setConn(conn); if (daoPlato.buscarPlatoPorId(idPlato).getDisponibles() < 1) throw new Exception("No hay disponibilidad del plato " + daoPlato.buscarPlatoPorId(idPlato).getNombre()); daoPedido.addPedido(pedido); PedidoPlato pedidoPlato = new PedidoPlato(pedido.getNumPedido(), idPlato); daoPedidoPlato.addPedidoPlato(pedidoPlato); conn.commit(); } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoPedido.cerrarRecursos(); daoPedidoPlato.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } } /** * REQUERIMIENTO F10 y RF16 * Metodo que modela la transaccion que agrega un solo pedidoPlato a la base de datos. * <b> post: </b> se ha agregado el pedidoPlato que entra como parametro * @param pedidoPlato - el pedidoPlato a agregar. pedidoPlato != null * @throws Exception - cualquier error que se genere agregando el pedidoPlato */ public void pedidoEntregado(Pedido pedido) throws Exception { DAOTablaPedido daoPedido = new DAOTablaPedido(); DAOTablaPedidoPlato daoPedidoPlato = new DAOTablaPedidoPlato(); DAOTablaPedidoMenu daoPedidoMenu = new DAOTablaPedidoMenu(); DAOTablaMenu daoMenu = new DAOTablaMenu(); DAOTablaPlato daoPlato = new DAOTablaPlato(); ArrayList<PedidoPlato> pedidosPlatos = new ArrayList<>(); ArrayList<PedidoMenu> pedidosMenus = new ArrayList<>(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoPedido.setConn(conn); daoPedidoPlato.setConn(conn); daoPedidoMenu.setConn(conn); daoMenu.setConn(conn); daoPlato.setConn(conn); daoPedidoMenu.setConn(conn); daoMenu.setConn(conn); if (daoPedido.darPedido(pedido.getNumPedido()) == null) throw new Exception ("No existe ningun pedido con el numero " + pedido.getNumPedido()); daoPedido.updatePedido(pedido); pedidosPlatos = daoPedidoPlato.bucarPedidoPlatoPorIdPedido(pedido.getNumPedido()); for (PedidoPlato p : pedidosPlatos) daoPlato.SeVendioProducto(p.getIdPlato()); pedidosMenus = daoPedidoMenu.bucarPedidoMenuPorIdPedido(pedido.getNumPedido()); for (PedidoMenu m : pedidosMenus) daoMenu.SeVendioMenu(m.getIdMenu()); conn.commit(); } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoPedido.cerrarRecursos(); daoPedidoPlato.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } } /** * * Metodo que modela la transaccion que agrega un solo plato a la base de datos. * <b> post: </b> se ha agregado el plato que entra como parametro * @param plato - el plato a agregar. plato != null * @throws Exception - cualquier error que se genere agregando el restaurante */ public void addIngredienteAPlato(int idPlato, String nomIngrediente) throws Exception { DAOTablaPlato daoPlato = new DAOTablaPlato(); DAOTablaIngredientesPlato daoPlatoIngrediente = new DAOTablaIngredientesPlato(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoPlato.setConn(conn); daoPlatoIngrediente.setConn(conn); IngredientesPlato ingPlato = new IngredientesPlato(idPlato, nomIngrediente); daoPlatoIngrediente.addIngredientesPlato(ingPlato); conn.commit(); } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoPlato.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } } /** * REQUERIMIENTO F6.2 * Metodo que modela la transaccion que agrega un solo pedidoPlato a la base de datos. * <b> post: </b> se ha agregado el pedidoPlato que entra como parametro * @param pedidoPlato - el pedidoPlato a agregar. pedidoPlato != null * @throws Exception - cualquier error que se genere agregando el pedidoPlato */ public void addMenuPlato(Menu menu, int idPlato) throws Exception { DAOTablaMenu daoMenu = new DAOTablaMenu(); DAOTablaMenuPlato daoMenuPlato = new DAOTablaMenuPlato(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoMenu.setConn(conn); daoMenuPlato.setConn(conn); daoMenu.addMenu(menu); MenuPlato menuPlato = new MenuPlato(menu.getIdMenu(), idPlato); daoMenuPlato.addMenuPlato(menuPlato); conn.commit(); } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoMenu.cerrarRecursos(); daoMenuPlato.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } } /** * REQUERIMIENTO F6.3 * Metodo que modela la transaccion que agrega un solo pedidoPlato a la base de datos. * <b> post: </b> se ha agregado el pedidoPlato que entra como parametro * @param pedidoPlato - el pedidoPlato a agregar. pedidoPlato != null * @throws Exception - cualquier error que se genere agregando el pedidoPlato */ public void addPlatoMenu(Menu menu, int idPlato) throws Exception { DAOTablaMenu daoMenu = new DAOTablaMenu(); DAOTablaMenuPlato daoMenuPlato = new DAOTablaMenuPlato(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoMenu.setConn(conn); daoMenuPlato.setConn(conn); MenuPlato menuPlato = new MenuPlato(menu.getIdMenu(), idPlato); daoMenuPlato.addMenuPlato(menuPlato); conn.commit(); } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoMenu.cerrarRecursos(); daoMenuPlato.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } } /** * REQUERIMIENTO RF18 */ public InfoPedido resgistrarProductosMesaGlobal(InfoPedido infoPedido) throws Exception { DAOTablaPedido daoPedido = new DAOTablaPedido(); InfoPedido retorno = new InfoPedido(new ArrayList<ItemPedido>(), infoPedido.getEmail(), infoPedido.getZonaRotonda()); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_SERIALIZABLE); daoPedido.setConn(conn); List<ItemPedido> pedidos = daoPedido.registrarPedidoGlobal(infoPedido); retorno.setPedidos(pedidos); conn.commit(); } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoPedido.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } return retorno; } /** * REQUERIMIENTO RF19 */ public void disableRestaurante(String nombre) throws Exception { DAOTablaRestaurante daoRestaurante = new DAOTablaRestaurante(); try { //////transaccion this.conn = darConexion(); conn.setTransactionIsolation(conn.TRANSACTION_READ_COMMITTED); daoRestaurante.setConn(conn); daoRestaurante.disable(nombre); conn.commit(); } catch (SQLException e) { conn.rollback(); System.err.println("SQLException:" + e.getMessage()); e.printStackTrace(); throw e; } catch (Exception e) { conn.rollback(); System.err.println("GeneralException:" + e.getMessage()); e.printStackTrace(); throw e; } finally { try { daoRestaurante.cerrarRecursos(); if(this.conn!=null) this.conn.close(); } catch (SQLException exception) { System.err.println("SQLException closing resources:" + exception.getMessage()); exception.printStackTrace(); throw exception; } } } public void twoPhaseCommit(String name) throws Exception { try { File arch = new File(this.connectionDataPath); Properties prop = new Properties(); FileInputStream in = new FileInputStream(arch); prop.load(in); in.close(); String user2 = prop.getProperty("usuario2"); String password2 = prop.getProperty("clave2"); String user3=prop.getProperty("usuario3"); String password3=prop.getProperty("clave3"); String sql1=prop.getProperty("sql1").replaceAll("nombreRestaurante", name); String sql2=prop.getProperty("sql2").replaceAll("nombreRestaurante", name); String sql3=prop.getProperty("sql3").replaceAll("nombreRestaurante", name); // Create a XADataSource instance OracleXADataSource oxds1 = new OracleXADataSource(); oxds1.setURL(url); oxds1.setUser(user); oxds1.setPassword(password); System.out.println(oxds1.getURL()+";;;"+oxds1.getUser()); OracleXADataSource oxds2 = new OracleXADataSource(); oxds2.setURL(url); oxds2.setUser(user2); oxds2.setPassword(password2); System.out.println(oxds2.getURL()+";;;"+oxds2.getUser()); OracleXADataSource oxds3 = new OracleXADataSource(); oxds3.setURL(url); oxds3.setUser(user3); oxds3.setPassword(password3); System.out.println(oxds3.getURL()+";;;"+oxds3.getUser()); // Get a XA connection to the underlying data source XAConnection pc1 = oxds1.getXAConnection(); // We can use the same data source XAConnection pc2 = oxds2.getXAConnection(); // Get the Physical Connections Connection conn1 = pc1.getConnection(); Connection conn2 = pc2.getConnection(); // Get the XA Resources XAResource oxar1 = pc1.getXAResource(); XAResource oxar2 = pc2.getXAResource(); // Create the Xids With the Same Global Ids Xid xid1 = createXid(1); Xid xid2 = createXid(2); // Start the Resources oxar1.start (xid1, XAResource.TMNOFLAGS); oxar2.start (xid2, XAResource.TMNOFLAGS); //RESOURCE 3 XAConnection pc3=oxds3.getXAConnection(); Connection conn3=pc3.getConnection(); XAResource oxar3=pc3.getXAResource(); Xid xid3=createXid(3); oxar3.start (xid3, XAResource.TMNOFLAGS); // Do  something with conn1 and conn2 System.out.println(1); doSomeWork (conn1,sql1); System.out.println(2); //doSomeWork (conn2,sql2); System.out.println(3); doSomeWork(conn3,sql3); // END both the branches -- THIS IS MUST oxar1.end(xid1, XAResource.TMSUCCESS); oxar2.end(xid2, XAResource.TMSUCCESS); oxar3.end(xid3,XAResource.TMSUCCESS); // Prepare the RMs int prp1 = oxar1.prepare (xid1); int prp2 = oxar2.prepare (xid2); int prp3=oxar3.prepare(xid3); System.out.println("Return value of prepare 1 is " + prp1); System.out.println("Return value of prepare 2 is " + prp2); System.out.println("Return value of prepare 3 is " + prp3); boolean do_commit = true; if (!((prp1 == XAResource.XA_OK) || (prp1 == XAResource.XA_RDONLY))) do_commit = false; if (!((prp2 == XAResource.XA_OK) || (prp2 == XAResource.XA_RDONLY))) do_commit = false; if (!((prp3 == XAResource.XA_OK) || (prp3 == XAResource.XA_RDONLY))) do_commit = false; System.out.println("do_commit is " + do_commit); System.out.println("Is oxar1 same as oxar2 ? " + oxar1.isSameRM(oxar2)); System.out.println("Is oxar1 same as oxar3 ? " + oxar1.isSameRM(oxar3)); System.out.println("Is oxar2 same as oxar3 ? " + oxar2.isSameRM(oxar3)); if (prp1 == XAResource.XA_OK) if (do_commit) oxar1.commit (xid1, false); else oxar1.rollback (xid1); if (prp2 == XAResource.XA_OK) if (do_commit) oxar2.commit (xid2, false); else oxar2.rollback (xid2); if (prp3 == XAResource.XA_OK) if (do_commit) oxar3.commit (xid3, false); else oxar3.rollback (xid3); // Close connections conn1.close(); conn1 = null; conn2.close(); conn2 = null; //conn3.close(); //conn3 = null; pc1.close(); pc1 = null; pc2.close(); pc2 = null; pc3.close(); pc3 = null; } catch (SQLException sqe) { sqe.printStackTrace(); } catch (XAException xae) { if (xae instanceof OracleXAException) { System.out.println("XA Error is " + ((OracleXAException)xae).getXAError()); System.out.println("SQL Error is " + ((OracleXAException)xae).getOracleError()); } } } Xid createXid(int bids) throws XAException { byte[] gid = new byte[1]; gid[0]= (byte) 9; byte[] bid = new byte[1]; bid[0]= (byte) bids; byte[] gtrid = new byte[64]; byte[] bqual = new byte[64]; System.arraycopy (gid, 0, gtrid, 0, 1); System.arraycopy (bid, 0, bqual, 0, 1); Xid xid = new OracleXid(0x1234, gtrid, bqual); return xid; } private void doSomeWork (Connection conn, String sql) throws SQLException { // Create a Statement PreparedStatement stmt = conn.prepareStatement(sql); ResultSet rs=stmt.executeQuery(); System.out.println(sql); stmt.close(); stmt = null;} }
package stanhebben.zenscript.type; import org.objectweb.asm.*; import stanhebben.zenscript.TypeExpansion; import stanhebben.zenscript.annotations.*; import stanhebben.zenscript.compiler.*; import stanhebben.zenscript.expression.*; import stanhebben.zenscript.expression.partial.IPartialExpression; import stanhebben.zenscript.type.casting.*; import stanhebben.zenscript.type.natives.JavaMethod; import stanhebben.zenscript.util.*; import stanhebben.zenscript.value.IAny; import static stanhebben.zenscript.util.AnyClassWriter.*; import static stanhebben.zenscript.util.ZenTypeUtil.*; public class ZenTypeShort extends ZenType { public static final ZenTypeShort INSTANCE = new ZenTypeShort(); // private static final JavaMethod SHORT_TOSTRING = // JavaMethod.get(EMPTY_REGISTRY, Short.class, "toString", short.class); private static final String ANY_NAME = "any/AnyShort"; private static final String ANY_NAME_2 = "any.AnyShort"; private ZenTypeShort() { } @Override public IZenIterator makeIterator(int numValues, IEnvironmentMethod environment) { return null; } @Override public void constructCastingRules(IEnvironmentGlobal environment, ICastingRuleDelegate rules, boolean followCasters) { rules.registerCastingRule(BYTE, new CastingRuleI2B(null)); rules.registerCastingRule(BYTEOBJECT, new CastingRuleStaticMethod(BYTE_VALUEOF)); rules.registerCastingRule(SHORTOBJECT, new CastingRuleStaticMethod(SHORT_VALUEOF)); rules.registerCastingRule(INT, new CastingRuleNone(SHORT, INT)); rules.registerCastingRule(INTOBJECT, new CastingRuleStaticMethod(INT_VALUEOF)); rules.registerCastingRule(LONG, new CastingRuleI2L(null)); rules.registerCastingRule(LONGOBJECT, new CastingRuleStaticMethod(LONG_VALUEOF, new CastingRuleI2L(null))); rules.registerCastingRule(FLOAT, new CastingRuleI2F(null)); rules.registerCastingRule(FLOATOBJECT, new CastingRuleStaticMethod(FLOAT_VALUEOF, new CastingRuleI2F(null))); rules.registerCastingRule(DOUBLE, new CastingRuleI2D(null)); rules.registerCastingRule(DOUBLEOBJECT, new CastingRuleStaticMethod(DOUBLE_VALUEOF, new CastingRuleI2D(null))); rules.registerCastingRule(STRING, new CastingRuleStaticMethod(SHORT_TOSTRING_STATIC)); rules.registerCastingRule(ANY, new CastingRuleStaticMethod(JavaMethod.getStatic(getAnyClassName(environment), "valueOf", ANY, BYTE))); if(followCasters) { constructExpansionCastingRules(environment, rules); } } /* * @Override public boolean canCastImplicit(ZenType type, IEnvironmentGlobal * environment) { return (type.getNumberType() != 0 && type.getNumberType() * >= NUM_SHORT) || type == ZenTypeString.INSTANCE || type == ANY || * canCastExpansion(environment, type); } * * @Override public boolean canCastExplicit(ZenType type, IEnvironmentGlobal * environment) { return canCastImplicit(type, environment); } * * @Override public Expression cast(ZenPosition position, IEnvironmentGlobal * environment, Expression value, ZenType type) { if (type.getNumberType() > * 0 || type == STRING) { return new ExpressionAs(position, value, type); } * else if (canCastExpansion(environment, type)) { return * castExpansion(position, environment, value, type); } else { return new * ExpressionAs(position, value, type); } } */ @Override public Type toASMType() { return Type.SHORT_TYPE; } @Override public int getNumberType() { return NUM_SHORT; } @Override public IPartialExpression getMember(ZenPosition position, IEnvironmentGlobal environment, IPartialExpression value, String name) { IPartialExpression result = memberExpansion(position, environment, value.eval(environment), name); if(result == null) { environment.error(position, "bool value has no members"); return new ExpressionInvalid(position, ZenTypeAny.INSTANCE); } else { return result; } } @Override public IPartialExpression getStaticMember(ZenPosition position, IEnvironmentGlobal environment, String name) { return null; } @Override public String getSignature() { return "S"; } @Override public boolean isPointer() { return false; } /* * @Override public void compileCast(ZenPosition position, * IEnvironmentMethod environment, ZenType type) { MethodOutput output = * environment.getOutput(); * * if (type == BYTE) { output.i2b(); } else if (type == * ZenTypeByteObject.INSTANCE) { output.i2b(); * output.invokeStatic(Byte.class, "valueOf", Byte.class, byte.class); } * else if (type == SHORT) { // nothing to do } else if (type == * ZenTypeShortObject.INSTANCE) { output.invokeStatic(Short.class, * "valueOf", Short.class, short.class); } else if (type == INT) { // * nothing to do } else if (type == ZenTypeIntObject.INSTANCE) { * output.invokeStatic(Integer.class, "valueOf", Integer.class, int.class); * } else if (type == LONG) { output.i2l(); } else if (type == * ZenTypeLongObject.INSTANCE) { output.i2l(); * output.invokeStatic(Long.class, "valueOf", Long.class, long.class); } * else if (type == FLOAT) { output.i2f(); } else if (type == * ZenTypeFloatObject.INSTANCE) { output.i2f(); * output.invokeStatic(Float.class, "valueOf", Float.class, float.class); } * else if (type == DOUBLE) { output.i2d(); } else if (type == * ZenTypeDoubleObject.INSTANCE) { output.i2d(); * output.invokeStatic(Double.class, "valueOf", Double.class, double.class); * } else if (type == STRING) { output.invokeStatic(Short.class, "toString", * String.class, short.class); } else if (type == ANY) { * output.invokeStatic(getAnyClassName(environment), "valueOf", "(S)" + * signature(IAny.class)); } else if (!compileCastExpansion(position, * environment, type)) { environment.error(position, "cannot cast " + this + * " to " + type); } } */ @Override public Expression unary(ZenPosition position, IEnvironmentGlobal environment, Expression value, OperatorType operator) { return new ExpressionArithmeticUnary(position, operator, value); } @Override public Expression binary(ZenPosition position, IEnvironmentGlobal environment, Expression left, Expression right, OperatorType operator) { if(operator == OperatorType.CAT) { return STRING.binary(position, environment, left.cast(position, environment, STRING), right.cast(position, environment, STRING), OperatorType.CAT); } return new ExpressionArithmeticBinary(position, operator, left, right.cast(position, environment, this)); } @Override public Expression trinary(ZenPosition position, IEnvironmentGlobal environment, Expression first, Expression second, Expression third, OperatorType operator) { environment.error(position, "short doesn't support this operation"); return new ExpressionInvalid(position); } @Override public Expression compare(ZenPosition position, IEnvironmentGlobal environment, Expression left, Expression right, CompareType type) { return new ExpressionArithmeticCompare(position, type, left, right.cast(position, environment, this)); } @Override public Expression call(ZenPosition position, IEnvironmentGlobal environment, Expression receiver, Expression... arguments) { environment.error(position, "cannot call short values"); return new ExpressionInvalid(position); } @Override public Class toJavaClass() { return short.class; } @Override public String getName() { return "short"; } @Override public String getAnyClassName(IEnvironmentGlobal environment) { if(!environment.containsClass(ANY_NAME_2)) { environment.putClass(ANY_NAME_2, new byte[0]); environment.putClass(ANY_NAME_2, AnyClassWriter.construct(new AnyDefinitionShort(environment), ANY_NAME, Type.SHORT_TYPE)); } return ANY_NAME; } @Override public Expression defaultValue(ZenPosition position) { return new ExpressionInt(position, 0, SHORT); } private class AnyDefinitionShort implements IAnyDefinition { private final IEnvironmentGlobal environment; public AnyDefinitionShort(IEnvironmentGlobal environment) { this.environment = environment; } @Override public void defineMembers(ClassVisitor output) { output.visitField(Opcodes.ACC_PRIVATE, "value", "S", null, null); MethodOutput valueOf = new MethodOutput(output, Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "valueOf", "(S)" + signature(IAny.class), null, null); valueOf.start(); valueOf.newObject(ANY_NAME); valueOf.dup(); valueOf.load(Type.SHORT_TYPE, 0); valueOf.construct(ANY_NAME, "S"); valueOf.returnObject(); valueOf.end(); MethodOutput constructor = new MethodOutput(output, Opcodes.ACC_PUBLIC, "<init>", "(S)V", null, null); constructor.start(); constructor.loadObject(0); constructor.invokeSpecial(internal(Object.class), "<init>", "()V"); constructor.loadObject(0); constructor.load(Type.SHORT_TYPE, 1); constructor.putField(ANY_NAME, "value", "S"); constructor.returnType(Type.VOID_TYPE); constructor.end(); } @Override public void defineStaticCanCastImplicit(MethodOutput output) { Label lblCan = new Label(); output.constant(Type.BYTE_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); output.constant(Type.SHORT_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); output.constant(Type.INT_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); output.constant(Type.LONG_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); output.constant(Type.FLOAT_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); output.constant(Type.DOUBLE_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); TypeExpansion expansion = environment.getExpansion(getName()); if(expansion != null) { expansion.compileAnyCanCastImplicit(SHORT, output, environment, 0); } output.iConst0(); output.returnInt(); output.label(lblCan); output.iConst1(); output.returnInt(); } @Override public void defineStaticAs(MethodOutput output) { TypeExpansion expansion = environment.getExpansion(getName()); if(expansion != null) { expansion.compileAnyCast(SHORT, output, environment, 0, 1); } throwCastException(output, "short", 1); } @Override public void defineNot(MethodOutput output) { output.newObject(ANY_NAME); output.dup(); getValue(output); output.iNot(); output.invokeSpecial(ANY_NAME, "<init>", "(S)V"); output.returnObject(); } @Override public void defineNeg(MethodOutput output) { output.newObject(ANY_NAME); output.dup(); getValue(output); output.iNeg(); output.invokeSpecial(ANY_NAME, "<init>", "(S)V"); output.returnObject(); } @Override public void defineAdd(MethodOutput output) { output.newObject(ANY_NAME); output.dup(); getValue(output); output.loadObject(1); METHOD_ASSHORT.invokeVirtual(output); output.iAdd(); output.invokeSpecial(ANY_NAME, "<init>", "(S)V"); output.returnObject(); } @Override public void defineSub(MethodOutput output) { output.newObject(ANY_NAME); output.dup(); getValue(output); output.loadObject(1); METHOD_ASSHORT.invokeVirtual(output); output.iSub(); output.invokeSpecial(ANY_NAME, "<init>", "(S)V"); output.returnObject(); } @Override public void defineCat(MethodOutput output) { // StringBuilder builder = new StringBuilder(); // builder.append(value); // builder.append(other.asString()); // return new AnyString(builder.toString()); output.newObject(StringBuilder.class); output.dup(); output.invokeSpecial(internal(StringBuilder.class), "<init>", "()V"); getValue(output); output.invokeVirtual(StringBuilder.class, "append", StringBuilder.class, int.class); output.loadObject(1); METHOD_ASSTRING.invokeVirtual(output); output.invokeVirtual(StringBuilder.class, "append", StringBuilder.class, String.class); output.invokeVirtual(StringBuilder.class, "toString", String.class); output.invokeStatic(STRING.getAnyClassName(environment), "valueOf", "(Ljava/lang/String;)" + signature(IAny.class)); output.returnObject(); } @Override public void defineMul(MethodOutput output) { output.newObject(ANY_NAME); output.dup(); getValue(output); output.loadObject(1); METHOD_ASSHORT.invokeVirtual(output); output.iMul(); output.invokeSpecial(ANY_NAME, "<init>", "(S)V"); output.returnObject(); } @Override public void defineDiv(MethodOutput output) { output.newObject(ANY_NAME); output.dup(); getValue(output); output.loadObject(1); METHOD_ASSHORT.invokeVirtual(output); output.iDiv(); output.invokeSpecial(ANY_NAME, "<init>", "(S)V"); output.returnObject(); } @Override public void defineMod(MethodOutput output) { output.newObject(ANY_NAME); output.dup(); getValue(output); output.loadObject(1); METHOD_ASSHORT.invokeVirtual(output); output.iRem(); output.invokeSpecial(ANY_NAME, "<init>", "(S)V"); output.returnObject(); } @Override public void defineAnd(MethodOutput output) { output.newObject(ANY_NAME); output.dup(); getValue(output); output.loadObject(1); METHOD_ASSHORT.invokeVirtual(output); output.iAnd(); output.invokeSpecial(ANY_NAME, "<init>", "(S)V"); output.returnObject(); } @Override public void defineOr(MethodOutput output) { output.newObject(ANY_NAME); output.dup(); getValue(output); output.loadObject(1); METHOD_ASSHORT.invokeVirtual(output); output.iOr(); output.invokeSpecial(ANY_NAME, "<init>", "(S)V"); output.returnObject(); } @Override public void defineXor(MethodOutput output) { output.newObject(ANY_NAME); output.dup(); getValue(output); output.loadObject(1); METHOD_ASSHORT.invokeVirtual(output); output.iXor(); output.invokeSpecial(ANY_NAME, "<init>", "(S)V"); output.returnObject(); } @Override public void defineRange(MethodOutput output) { // TODO output.aConstNull(); output.returnObject(); } @Override public void defineCompareTo(MethodOutput output) { getValue(output); output.loadObject(1); METHOD_ASSHORT.invokeVirtual(output); output.iSub(); output.returnInt(); } @Override public void defineContains(MethodOutput output) { throwUnsupportedException(output, "short", "in"); } @Override public void defineMemberGet(MethodOutput output) { // TODO output.aConstNull(); output.returnObject(); } @Override public void defineMemberSet(MethodOutput output) { // TODO output.returnType(Type.VOID_TYPE); } @Override public void defineMemberCall(MethodOutput output) { // TODO output.aConstNull(); output.returnObject(); } @Override public void defineIndexGet(MethodOutput output) { throwUnsupportedException(output, "short", "get []"); } @Override public void defineIndexSet(MethodOutput output) { throwUnsupportedException(output, "short", "set []"); } @Override public void defineCall(MethodOutput output) { throwUnsupportedException(output, "short", "call"); } @Override public void defineAsBool(MethodOutput output) { throwCastException(output, ANY_NAME, "bool"); } @Override public void defineAsByte(MethodOutput output) { getValue(output); output.i2b(); output.returnType(Type.BYTE_TYPE); } @Override public void defineAsShort(MethodOutput output) { getValue(output); output.returnType(Type.SHORT_TYPE); } @Override public void defineAsInt(MethodOutput output) { getValue(output); output.returnType(Type.INT_TYPE); } @Override public void defineAsLong(MethodOutput output) { getValue(output); output.i2l(); output.returnType(Type.LONG_TYPE); } @Override public void defineAsFloat(MethodOutput output) { getValue(output); output.i2f(); output.returnType(Type.FLOAT_TYPE); } @Override public void defineAsDouble(MethodOutput output) { getValue(output); output.i2d(); output.returnType(Type.DOUBLE_TYPE); } @Override public void defineAsString(MethodOutput output) { getValue(output); output.invokeStatic(Short.class, "toString", String.class, short.class); output.returnObject(); } @Override public void defineAs(MethodOutput output) { int localValue = output.local(Type.SHORT_TYPE); getValue(output); output.store(Type.SHORT_TYPE, localValue); TypeExpansion expansion = environment.getExpansion(getName()); if(expansion != null) { expansion.compileAnyCast(SHORT, output, environment, localValue, 1); } throwCastException(output, "short", 1); } @Override public void defineIs(MethodOutput output) { Label lblEq = new Label(); output.loadObject(1); output.constant(Type.SHORT_TYPE); output.ifACmpEq(lblEq); output.iConst0(); output.returnInt(); output.label(lblEq); output.iConst1(); output.returnInt(); } @Override public void defineGetNumberType(MethodOutput output) { output.constant(IAny.NUM_SHORT); output.returnInt(); } @Override public void defineIteratorSingle(MethodOutput output) { throwUnsupportedException(output, "short", "iterator"); } @Override public void defineIteratorMulti(MethodOutput output) { throwUnsupportedException(output, "short", "iterator"); } private void getValue(MethodOutput output) { output.loadObject(0); output.getField(ANY_NAME, "value", "S"); } @Override public void defineEquals(MethodOutput output) { Label lblNope = new Label(); output.loadObject(1); output.instanceOf(IAny.NAME); output.ifEQ(lblNope); getValue(output); output.loadObject(1); METHOD_ASSHORT.invokeVirtual(output); output.ifICmpNE(lblNope); output.iConst1(); output.returnInt(); output.label(lblNope); output.iConst0(); output.returnInt(); } @Override public void defineHashCode(MethodOutput output) { getValue(output); output.returnInt(); } } }
package org.openoffice.accessibility; import com.sun.star.accessibility.AccessibleRole; import com.sun.star.accessibility.XAccessible; import com.sun.star.accessibility.XAccessibleContext; import com.sun.star.awt.XExtendedToolkit; import com.sun.star.awt.XTopWindow; import com.sun.star.awt.XTopWindowListener; import com.sun.star.awt.XWindow; import com.sun.star.comp.loader.FactoryHelper; import com.sun.star.lang.XComponent; import com.sun.star.lang.XInitialization; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.lang.XSingleServiceFactory; import com.sun.star.registry.*; import com.sun.star.uno.*; import org.openoffice.java.accessibility.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import javax.accessibility.Accessible; public class AccessBridge { protected static java.util.Hashtable topWindowMap = new java.util.Hashtable(); private static java.awt.Window getTopWindowImpl(XAccessible xAccessible) { // Because it can not be garantied that // WindowsAccessBridgeAdapter.registerTopWindow() is called // before windowOpened(), we have to make this operation // atomic. synchronized (topWindowMap) { String oid = UnoRuntime.generateOid(xAccessible); java.awt.Window w = (java.awt.Window) topWindowMap.get(oid); if (w == null) { w = AccessibleObjectFactory.getTopWindow(xAccessible); if (w != null) { topWindowMap.put(oid, w); } } return w; } } protected static java.awt.Window getTopWindow(XAccessible xAccessible) { if (xAccessible != null) { XAccessibleContext xAccessibleContext = xAccessible.getAccessibleContext(); if (xAccessibleContext != null) { // Toolkit reports the VCL peer windows as toplevels. These have an // accessible parent which represents the native frame window switch(xAccessibleContext.getAccessibleRole()) { case AccessibleRole.ROOT_PANE: case AccessibleRole.POPUP_MENU: return getTopWindow(xAccessibleContext.getAccessibleParent()); case AccessibleRole.WINDOW: case AccessibleRole.FRAME: case AccessibleRole.DIALOG: case AccessibleRole.ALERT: return getTopWindowImpl(xAccessible); default: break; } } } return null; } protected static java.awt.Window removeTopWindow(XAccessible xAccessible) { if (xAccessible != null) { XAccessibleContext xAccessibleContext = xAccessible.getAccessibleContext(); if (xAccessibleContext != null) { // Toolkit reports the VCL peer windows as toplevels. These have an // accessible parent which represents the native frame window switch(xAccessibleContext.getAccessibleRole()) { case AccessibleRole.ROOT_PANE: case AccessibleRole.POPUP_MENU: return removeTopWindow(xAccessibleContext.getAccessibleParent()); case AccessibleRole.WINDOW: case AccessibleRole.FRAME: case AccessibleRole.DIALOG: return (java.awt.Window) topWindowMap.remove(UnoRuntime.generateOid(xAccessible)); default: break; } } } return null; } public static XSingleServiceFactory __getServiceFactory(String implName, XMultiServiceFactory multiFactory, XRegistryKey regKey) { XSingleServiceFactory xSingleServiceFactory = null; if (implName.equals(AccessBridge.class.getName())) { // Initialize toolkit to register at Java <-> Windows access bridge java.awt.Toolkit tk = java.awt.Toolkit.getDefaultToolkit(); xSingleServiceFactory = FactoryHelper.getServiceFactory(_AccessBridge.class, _AccessBridge._serviceName, multiFactory, regKey); } return xSingleServiceFactory; } public static boolean __writeRegistryServiceInfo(XRegistryKey regKey) { return FactoryHelper.writeRegistryServiceInfo(AccessBridge.class.getName(), _AccessBridge._serviceName, regKey); } static public class _AccessBridge implements XTopWindowListener, XInitialization, XComponent { static final String _serviceName = "com.sun.star.accessibility.AccessBridge"; XComponentContext xComponentContext; public _AccessBridge(XComponentContext xComponentContext) { this.xComponentContext = xComponentContext; } /* * XInitialization */ public void initialize(java.lang.Object[] arguments) { try { // FIXME: Currently there is no way to determine if key event forwarding is needed or not, // so we have to do it always .. XExtendedToolkit unoToolkit = (XExtendedToolkit) AnyConverter.toObject(new Type( XExtendedToolkit.class), arguments[0]); if (unoToolkit != null) { // FIXME this should be done in VCL unoToolkit.addTopWindowListener(this); String os = (String) System.getProperty("os.name"); // Try to initialize the WindowsAccessBridgeAdapter if (os.startsWith("Windows")) { WindowsAccessBridgeAdapter.attach(xComponentContext); } else { unoToolkit.addKeyHandler(new KeyHandler()); } } else if (Build.DEBUG) { System.err.println( "argument 0 is not of type XExtendedToolkit."); } } catch (com.sun.star.lang.IllegalArgumentException e) { // FIXME: output } } /* * XTopWindowListener */ public void windowOpened(com.sun.star.lang.EventObject event) { XAccessible xAccessible = (XAccessible) UnoRuntime.queryInterface(XAccessible.class, event.Source); java.awt.Window w = getTopWindow(xAccessible); } public void windowActivated(com.sun.star.lang.EventObject event) { } public void windowDeactivated(com.sun.star.lang.EventObject event) { } public void windowMinimized(com.sun.star.lang.EventObject event) { } public void windowNormalized(com.sun.star.lang.EventObject event) { } public void windowClosing(com.sun.star.lang.EventObject event) { } public void windowClosed(com.sun.star.lang.EventObject event) { XAccessible xAccessible = (XAccessible) UnoRuntime.queryInterface(XAccessible.class, event.Source); java.awt.Window w = removeTopWindow(xAccessible); if (w != null) { w.dispose(); } } public void disposing(com.sun.star.lang.EventObject event) { } /* * XComponent */ public void addEventListener(com.sun.star.lang.XEventListener listener) { } public void removeEventListener(com.sun.star.lang.XEventListener listener) { } public void dispose() { try { java.awt.Toolkit.getDefaultToolkit().getSystemEventQueue().invokeAndWait( new Runnable() { public void run() { } } ); } catch (java.lang.InterruptedException e) { } catch (java.lang.reflect.InvocationTargetException e) { } } } }
import com.sun.star.awt.Point; import com.sun.star.awt.Size; import com.sun.star.awt.XControlModel; import com.sun.star.beans.XPropertySet; import com.sun.star.wizards.common.*; import com.sun.star.wizards.db.FieldColumn; import com.sun.star.sdbc.*; import com.sun.star.uno.Exception; import com.sun.star.uno.UnoRuntime; import com.sun.star.container.XNameAccess; import com.sun.star.container.XNameContainer; import com.sun.star.container.XNamed; import com.sun.star.form.XGridColumnFactory; import com.sun.star.lang.XMultiServiceFactory; public class GridControl extends Shape{ FieldColumn[] fieldcolumns; public XNameContainer xNameContainer; public XGridColumnFactory xGridColumnFactory; public XPropertySet xPropertySet; XNameAccess xNameAccess; final String SODEFAULTNAME = "Grid1"; XControlModel xControlModel; public GridControl(XMultiServiceFactory _xMSF, String _sname, FormHandler _oFormHandler, XNameContainer _xFormName, FieldColumn[] _fieldcolumns, Point _aPoint, Size _aSize) { super(_oFormHandler, _aPoint, _aSize); try { fieldcolumns = _fieldcolumns; Object oGridModel = oFormHandler.xMSFDoc.createInstance(oFormHandler.sModelServices[FormHandler.SOGRIDCONTROL]); xNameContainer = (XNameContainer) UnoRuntime.queryInterface(XNameContainer.class, oGridModel); xNameAccess = (XNameAccess) UnoRuntime.queryInterface(XNameAccess.class, oGridModel); _xFormName.insertByName(_sname, oGridModel); xControlModel = (XControlModel) UnoRuntime.queryInterface(XControlModel.class, oGridModel); xControlShape.setControl(xControlModel); xPropertySet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, oGridModel); oFormHandler.xDrawPage.add(xShape); xGridColumnFactory = (XGridColumnFactory) UnoRuntime.queryInterface(XGridColumnFactory.class, oGridModel); // Helper.setUnoPropertyValue(oGridModel, "Name", _sname); for (int i = 0; i < fieldcolumns.length; i++){ FieldColumn curfieldcolumn = fieldcolumns[i]; if (curfieldcolumn.FieldType == DataType.TIMESTAMP){ TimeStampControl oControl = new TimeStampControl(new Resource(_xMSF, "", "dbw"),this, curfieldcolumn); } else{ Control oControl = new DatabaseControl(this, curfieldcolumn); } } } catch (Exception e) { e.printStackTrace(System.out); }} }
package com.ggstudios.lolcraft; import android.content.Context; import android.graphics.Color; import android.os.AsyncTask; import android.util.SparseIntArray; import com.ggstudios.lolcraft.ChampionInfo.Skill; import com.google.gson.Gson; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Stack; import timber.log.Timber; /** * Class that holds information about a build, such as build order, stats and cost. */ public class Build { public static final int RUNE_TYPE_RED = 0; public static final int RUNE_TYPE_BLUE = 1; public static final int RUNE_TYPE_YELLOW = 2; public static final int RUNE_TYPE_BLACK = 3; public static final double MAX_ATTACK_SPEED = 2.5; public static final double MAX_CDR = 0.4; private static final int[] RUNE_COUNT_MAX = new int[] { 9, 9, 9, 3 }; private static final int[] GROUP_COLOR = new int[] { 0xff2ecc71, // emerald //0xffe74c3c, // alizarin 0xff3498db, // peter river 0xff9b59b6, // amethyst 0xffe67e22, // carrot 0xff34495e, // wet asphalt 0xff1abc9c, // turquoise 0xfff1c40f, // sun flower }; private static final int CHAMPION_ID_AKALI = 84; private static final int CHAMPION_ID_CORKI = 42; private static final int CHAMPION_ID_HEIM = 74; private static final int CHAMPION_ID_TEEMO = 17; private static final int FLAG_SCALING = 0x80000000; public static final String SN_NULL = "null"; public static final int STAT_NULL = 0; public static final int STAT_HP = 1; public static final int STAT_HPR = 2; public static final int STAT_MP = 3; public static final int STAT_MPR = 4; public static final int STAT_AD = 5; //public static final int STAT_BASE_AS = asdf; public static final int STAT_ASP = 6; public static final int STAT_AR = 7; public static final int STAT_MR = 8; public static final int STAT_MS = 9; public static final int STAT_RANGE = 10; public static final int STAT_CRIT = 11; public static final int STAT_AP = 12; public static final int STAT_LS = 13; public static final int STAT_MSP = 14; public static final int STAT_CDR = 15; public static final int STAT_ARPEN = 16; public static final int STAT_NRG = 17; public static final int STAT_NRGR = 18; public static final int STAT_GP10 = 19; public static final int STAT_MRP = 20; public static final int STAT_CD = 21; public static final int STAT_DT = 22; public static final int STAT_APP = 23; public static final int STAT_SV = 24; public static final int STAT_MPENP = 25; public static final int STAT_APENP = 26; public static final int STAT_DMG_REDUCTION = 27; public static final int STAT_CC_RED = 28; public static final int STAT_AA_TRUE_DAMAGE = 29; public static final int STAT_AA_MAGIC_DAMAGE = 30; public static final int STAT_MAGIC_DMG_REDUCTION = 31; public static final int STAT_MAGIC_HP = 32; public static final int STAT_INVULNERABILITY = 33; public static final int STAT_SPELL_BLOCK = 34; public static final int STAT_CC_IMMUNE = 35; public static final int STAT_INVULNERABILITY_ALL_BUT_ONE = 36; public static final int STAT_AOE_DPS_MAGIC = 37; public static final int STAT_PERCENT_HP_MISSING = 38; public static final int STAT_UNDYING = 39; public static final int STAT_TOTAL_AR = 40; public static final int STAT_TOTAL_AD = 41; public static final int STAT_TOTAL_HP = 42; public static final int STAT_CD_MOD = 43; public static final int STAT_TOTAL_AP = 44; public static final int STAT_TOTAL_MS = 45; public static final int STAT_TOTAL_MR = 46; public static final int STAT_AS = 47; public static final int STAT_LEVEL = 48; public static final int STAT_TOTAL_RANGE = 49; public static final int STAT_TOTAL_MP = 50; public static final int STAT_BONUS_AD = 60; public static final int STAT_BONUS_HP = 61; public static final int STAT_BONUS_MS = 62; public static final int STAT_BONUS_AP = 44; // note that cause base AP is always 0, bonusAp always = totalAp public static final int STAT_BONUS_AR = 63; public static final int STAT_BONUS_MR = 64; public static final int STAT_LEVEL_MINUS_ONE = 65; public static final int STAT_CRIT_DMG = 66; public static final int STAT_AA_DPS = 70; public static final int STAT_NAUTILUS_Q_CD = 80; public static final int STAT_RENGAR_Q_BASE_DAMAGE = 81; public static final int STAT_VI_W = 82; public static final int STAT_STACKS = 83; // generic stat... could be used for Ashe/Nasus, etc public static final int STAT_SOULS = 84; public static final int STAT_JAX_R_ARMOR_SCALING = 85; public static final int STAT_JAX_R_MR_SCALING = 86; public static final int STAT_DARIUS_R_MAX_DAMAGE = 87; public static final int STAT_ENEMY_MISSING_HP = 100; public static final int STAT_ENEMY_CURRENT_HP = 101; public static final int STAT_ENEMY_MAX_HP = 102; public static final int STAT_TARGET_AP = 103; public static final int STAT_ONE = 120; public static final int STAT_TYPE_DEFAULT = 0; public static final int STAT_TYPE_PERCENT = 1; private static final int MAX_STATS = 121; private static final int MAX_ACTIVE_ITEMS = 6; public static final String JSON_KEY_RUNES = "runes"; public static final String JSON_KEY_ITEMS = "items"; public static final String JSON_KEY_BUILD_NAME = "build_name"; public static final String JSON_KEY_COLOR = "color"; private static final Map<String, Integer> statKeyToIndex = new HashMap<String, Integer>(); private static final SparseIntArray statIdToStringId = new SparseIntArray(); private static final SparseIntArray statIdToSkillStatDescStringId = new SparseIntArray(); private static final int COLOR_AP = 0xFF59BD1A; private static final int COLOR_AD = 0xFFFAA316; private static final int COLOR_TANK = 0xFF1092E8; private static final float STAT_VALUE_HP = 2.66f; private static final float STAT_VALUE_AR = 20f; private static final float STAT_VALUE_MR = 20f; private static final float STAT_VALUE_AD = 36f; private static final float STAT_VALUE_AP = 21.75f; private static final float STAT_VALUE_CRIT = 50f; private static final float STAT_VALUE_ASP = 30f; private static ItemLibrary itemLibrary; private static RuneLibrary runeLibrary; private static final double[] RENGAR_Q_BASE = new double[] { 30, 45, 60, 75, 90, 105, 120, 135, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240 }; static { statKeyToIndex.put("FlatArmorMod", STAT_AR); statKeyToIndex.put("FlatAttackSpeedMod", STAT_NULL); statKeyToIndex.put("FlatBlockMod", STAT_NULL); statKeyToIndex.put("FlatCritChanceMod", STAT_CRIT); statKeyToIndex.put("FlatCritDamageMod", STAT_NULL); statKeyToIndex.put("FlatEXPBonus", STAT_NULL); statKeyToIndex.put("FlatEnergyPoolMod", STAT_NULL); statKeyToIndex.put("FlatEnergyRegenMod", STAT_NULL); statKeyToIndex.put("FlatHPPoolMod", STAT_HP); statKeyToIndex.put("FlatHPRegenMod", STAT_HPR); statKeyToIndex.put("FlatMPPoolMod", STAT_MP); statKeyToIndex.put("FlatMPRegenMod", STAT_MPR); statKeyToIndex.put("FlatMagicDamageMod", STAT_AP); statKeyToIndex.put("FlatMovementSpeedMod", STAT_MS); statKeyToIndex.put("FlatPhysicalDamageMod", STAT_AD); statKeyToIndex.put("FlatSpellBlockMod", STAT_MR); statKeyToIndex.put("FlatCoolDownRedMod", STAT_CDR); statKeyToIndex.put("PercentArmorMod", STAT_NULL); statKeyToIndex.put("PercentAttackSpeedMod", STAT_ASP); statKeyToIndex.put("PercentBlockMod", STAT_NULL); statKeyToIndex.put("PercentCritChanceMod", STAT_NULL); statKeyToIndex.put("PercentCritDamageMod", STAT_NULL); statKeyToIndex.put("PercentDodgeMod", STAT_NULL); statKeyToIndex.put("PercentEXPBonus", STAT_NULL); statKeyToIndex.put("PercentHPPoolMod", STAT_NULL); statKeyToIndex.put("PercentHPRegenMod", STAT_NULL); statKeyToIndex.put("PercentLifeStealMod", STAT_LS); statKeyToIndex.put("PercentMPPoolMod", STAT_NULL); statKeyToIndex.put("PercentMPRegenMod", STAT_NULL); statKeyToIndex.put("PercentMagicDamageMod", STAT_APP); statKeyToIndex.put("PercentMovementSpeedMod", STAT_MSP); statKeyToIndex.put("PercentPhysicalDamageMod", STAT_NULL); statKeyToIndex.put("PercentSpellBlockMod", STAT_NULL); statKeyToIndex.put("PercentSpellVampMod", STAT_SV); statKeyToIndex.put("CCRed", STAT_CC_RED); statKeyToIndex.put("FlatAaTrueDamageMod", STAT_AA_TRUE_DAMAGE); statKeyToIndex.put("FlatAaMagicDamageMod", STAT_AA_MAGIC_DAMAGE); statKeyToIndex.put("magic_aoe_dps", STAT_AOE_DPS_MAGIC); statKeyToIndex.put("perpercenthpmissing", STAT_PERCENT_HP_MISSING); statKeyToIndex.put("rFlatArmorModPerLevel", STAT_AR | FLAG_SCALING); statKeyToIndex.put("rFlatArmorPenetrationMod", STAT_ARPEN); statKeyToIndex.put("rFlatArmorPenetrationModPerLevel", STAT_ARPEN | FLAG_SCALING); statKeyToIndex.put("rFlatEnergyModPerLevel", STAT_NRG | FLAG_SCALING); statKeyToIndex.put("rFlatEnergyRegenModPerLevel", STAT_NRGR | FLAG_SCALING); statKeyToIndex.put("rFlatGoldPer10Mod", STAT_GP10); statKeyToIndex.put("rFlatHPModPerLevel", STAT_HP | FLAG_SCALING); statKeyToIndex.put("rFlatHPRegenModPerLevel", STAT_HPR | FLAG_SCALING); statKeyToIndex.put("rFlatMPModPerLevel", STAT_MP | FLAG_SCALING); statKeyToIndex.put("rFlatMPRegenModPerLevel", STAT_MPR | FLAG_SCALING); statKeyToIndex.put("rFlatMagicDamageModPerLevel", STAT_AP | FLAG_SCALING); statKeyToIndex.put("rFlatMagicPenetrationMod", STAT_MRP); statKeyToIndex.put("rFlatMagicPenetrationModPerLevel", STAT_MRP | FLAG_SCALING); statKeyToIndex.put("rFlatPhysicalDamageModPerLevel", STAT_AD | FLAG_SCALING); statKeyToIndex.put("rFlatSpellBlockModPerLevel", STAT_MR | FLAG_SCALING); statKeyToIndex.put("rPercentCooldownMod", STAT_CD); // negative val... statKeyToIndex.put("rPercentCooldownModPerLevel", STAT_CD | FLAG_SCALING); statKeyToIndex.put("rPercentTimeDeadMod", STAT_DT); statKeyToIndex.put("rPercentTimeDeadModPerLevel", STAT_DT | FLAG_SCALING); statKeyToIndex.put("rPercentMagicPenetrationMod", STAT_MPENP); statKeyToIndex.put("rPercentArmorPenetrationMod", STAT_APENP); statKeyToIndex.put("damagereduction", STAT_DMG_REDUCTION); statKeyToIndex.put("magicaldamagereduction", STAT_MAGIC_DMG_REDUCTION); statKeyToIndex.put("FlatMagicHp", STAT_MAGIC_HP); statKeyToIndex.put("Invulnerability", STAT_INVULNERABILITY); statKeyToIndex.put("SpellBlock", STAT_SPELL_BLOCK); statKeyToIndex.put("CcImmune", STAT_CC_IMMUNE); statKeyToIndex.put("InvulnerabilityButOne", STAT_INVULNERABILITY_ALL_BUT_ONE); statKeyToIndex.put("Undying", STAT_UNDYING); // keys used for skills... statKeyToIndex.put("spelldamage", STAT_TOTAL_AP); statKeyToIndex.put("attackdamage", STAT_TOTAL_AD); statKeyToIndex.put("bonushealth", STAT_BONUS_HP); statKeyToIndex.put("armor", STAT_TOTAL_AR); statKeyToIndex.put("bonusattackdamage", STAT_BONUS_AD); statKeyToIndex.put("health", STAT_TOTAL_HP); statKeyToIndex.put("bonusarmor", STAT_BONUS_AR); statKeyToIndex.put("bonusspellblock", STAT_BONUS_MR); statKeyToIndex.put("levelMinusOne", STAT_LEVEL_MINUS_ONE); statKeyToIndex.put("level", STAT_LEVEL); statKeyToIndex.put("RangeMod", STAT_RANGE); statKeyToIndex.put("mana", STAT_TOTAL_MP); statKeyToIndex.put("critdamage", STAT_CRIT_DMG); statKeyToIndex.put("enemymissinghealth", STAT_ENEMY_MISSING_HP); statKeyToIndex.put("enemycurrenthealth", STAT_ENEMY_CURRENT_HP); statKeyToIndex.put("enemymaxhealth", STAT_ENEMY_MAX_HP); statKeyToIndex.put("movementspeed", STAT_TOTAL_MS); statKeyToIndex.put("targetspelldamage", STAT_TARGET_AP); // special keys... statKeyToIndex.put("@special.BraumWArmor", STAT_NULL); statKeyToIndex.put("@special.BraumWMR", STAT_NULL); statKeyToIndex.put("@special.jaycew", STAT_NULL); statKeyToIndex.put("@special.jaxrarmor", STAT_JAX_R_ARMOR_SCALING); statKeyToIndex.put("@special.jaxrmr", STAT_JAX_R_MR_SCALING); statKeyToIndex.put("@cooldownchampion", STAT_CD_MOD); statKeyToIndex.put("@stacks", STAT_STACKS); statKeyToIndex.put("@souls", STAT_SOULS); // heim statKeyToIndex.put("@dynamic.abilitypower", STAT_AP); // rengar statKeyToIndex.put("@dynamic.attackdamage", STAT_RENGAR_Q_BASE_DAMAGE); statKeyToIndex.put("@special.nautilusq", STAT_NAUTILUS_Q_CD); statKeyToIndex.put("@special.viw", STAT_VI_W); // darius statKeyToIndex.put("@special.dariusr3", STAT_DARIUS_R_MAX_DAMAGE); statKeyToIndex.put("null", STAT_NULL); SparseIntArray a = statIdToStringId; a.put(STAT_NULL, R.string.stat_desc_null); a.put(STAT_HP, R.string.stat_desc_hp); a.put(STAT_HPR, R.string.stat_desc_hpr); a.put(STAT_MP, R.string.stat_desc_mp); a.put(STAT_MPR, R.string.stat_desc_mpr); a.put(STAT_AD, R.string.stat_desc_ad); a.put(STAT_ASP, R.string.stat_desc_asp); a.put(STAT_AR, R.string.stat_desc_ar); a.put(STAT_MR, R.string.stat_desc_mr); a.put(STAT_LEVEL_MINUS_ONE, R.string.stat_desc_level_minus_one); a.put(STAT_MS, R.string.stat_desc_ms); a.put(STAT_RANGE, R.string.stat_desc_range); a.put(STAT_ENEMY_MAX_HP, R.string.stat_desc_enemy_max_hp); a.put(STAT_TOTAL_MP, R.string.stat_desc_total_mp); a.put(STAT_AA_MAGIC_DAMAGE, R.string.stat_desc_aa_magic_damage); a.put(STAT_AA_TRUE_DAMAGE, R.string.stat_desc_aa_true_damage); // public static final int STAT_CRIT = 11; // public static final int STAT_AP = 12; // public static final int STAT_LS = 13; // public static final int STAT_MSP = 14; // public static final int STAT_CDR = 15; // public static final int STAT_ARPEN = 16; // public static final int STAT_NRG = 17; // public static final int STAT_NRGR = 18; // public static final int STAT_GP10 = 19; // public static final int STAT_MRP = 20; // public static final int STAT_CD = 21; // public static final int STAT_DT = 22; // public static final int STAT_APP = 23; // public static final int STAT_SV = 24; // public static final int STAT_MPENP = 25; // public static final int STAT_APENP = 26; a.put(STAT_DMG_REDUCTION, R.string.stat_desc_damage_reduction); // public static final int STAT_TOTAL_AR = 40; // public static final int STAT_TOTAL_AD = 41; // public static final int STAT_TOTAL_HP = 42; // public static final int STAT_CD_MOD = 43; // public static final int STAT_TOTAL_AP = 44; // public static final int STAT_TOTAL_MS = 45; // public static final int STAT_TOTAL_MR = 46; // public static final int STAT_AS = 47; // public static final int STAT_LEVEL = 48; // public static final int STAT_BONUS_AD = 50; // public static final int STAT_BONUS_HP = 51; // public static final int STAT_BONUS_MS = 52; // public static final int STAT_BONUS_AP = 44; // note that cause base AP is always 0, bonusAp always = totalAp // public static final int STAT_BONUS_AR = 53; // public static final int STAT_BONUS_MR = 54; // public static final int STAT_AA_DPS = 60; SparseIntArray b = statIdToSkillStatDescStringId; b.put(STAT_NULL, R.string.skill_stat_null); b.put(STAT_TOTAL_AP, R.string.skill_stat_ap); b.put(STAT_LEVEL_MINUS_ONE, R.string.skill_stat_level_minus_one); b.put(STAT_TOTAL_AD, R.string.skill_stat_ad); b.put(STAT_BONUS_AD, R.string.skill_stat_bonus_ad); b.put(STAT_CD_MOD, R.string.skill_stat_cd_mod); b.put(STAT_STACKS, R.string.skill_stat_stacks); b.put(STAT_ONE, R.string.skill_stat_one); b.put(STAT_BONUS_HP, R.string.skill_stat_bonus_hp); b.put(STAT_TOTAL_AR, R.string.skill_stat_total_ar); b.put(STAT_TOTAL_MP, R.string.skill_stat_total_mp); b.put(STAT_JAX_R_ARMOR_SCALING, R.string.skill_stat_bonus_ad); b.put(STAT_JAX_R_MR_SCALING, R.string.skill_stat_ap); // public static final int STAT_TOTAL_AR = 40; // public static final int STAT_TOTAL_AD = 41; // public static final int STAT_TOTAL_HP = 42; // public static final int STAT_CD_MOD = 43; // public static final int STAT_TOTAL_MS = 45; // public static final int STAT_TOTAL_MR = 46; // public static final int STAT_AS = 47; // public static final int STAT_LEVEL = 48; // public static final int STAT_TOTAL_RANGE = 49; // public static final int STAT_TOTAL_MP = 50; // public static final int STAT_BONUS_HP = 61; // public static final int STAT_BONUS_MS = 62; // public static final int STAT_BONUS_AP = 44; // note that cause base AP is always 0, bonusAp always = totalAp // public static final int STAT_BONUS_AR = 63; // public static final int STAT_BONUS_MR = 64; // public static final int STAT_LEVEL_MINUS_ONE = 65; // public static final int STAT_CRIT_DMG = 66; } private String buildName; private List<BuildSkill> activeSkills; private List<BuildRune> runeBuild; private List<BuildItem> itemBuild; private ChampionInfo champ; private int champLevel; private List<BuildObserver> observers = new ArrayList<BuildObserver>(); private int enabledBuildStart = 0; private int enabledBuildEnd = 0; private int currentGroupCounter = 0; private int[] runeCount = new int[4]; private double[] stats = new double[MAX_STATS]; private double[] statsWithActives = new double[MAX_STATS]; private boolean itemBuildDirty = false; private Gson gson; private boolean buildLoading = false; private OnRuneCountChangedListener onRuneCountChangedListener = new OnRuneCountChangedListener() { @Override public void onRuneCountChanged(BuildRune rune, int oldCount, int newCount) { Build.this.onRuneCountChanged(rune, oldCount, newCount); } }; public Build() { itemBuild = new ArrayList<BuildItem>(); runeBuild = new ArrayList<BuildRune>(); activeSkills = new ArrayList<BuildSkill>(); gson = StateManager.getInstance().getGson(); if (itemLibrary == null) { itemLibrary = LibraryManager.getInstance().getItemLibrary(); } if (runeLibrary == null) { runeLibrary = LibraryManager.getInstance().getRuneLibrary(); } champLevel = 1; } public void setBuildName(String name) { buildName = name; } public String getBuildName() { return buildName; } private void clearGroups() { for (BuildItem item : itemBuild) { item.group = -1; item.to = null; item.depth = 0; item.from.clear(); } currentGroupCounter = 0; } private void recalculateAllGroups() { clearGroups(); for (int i = 0; i < itemBuild.size(); i++) { labelAllIngredients(itemBuild.get(i), i); } } private BuildItem getFreeItemWithId(int id, int index) { for (int i = index - 1; i >= 0; i if (itemBuild.get(i).getId() == id && itemBuild.get(i).to == null) { return itemBuild.get(i); } } return null; } private void labelAllIngredients(BuildItem item, int index) { int curGroup = currentGroupCounter; boolean grouped = false; Stack<Integer> from = new Stack<Integer>(); from.addAll(item.info.from); while (!from.empty()) { int i = from.pop(); BuildItem ingredient = getFreeItemWithId(i, index); if (ingredient != null && ingredient.to == null) { if (ingredient.group != -1) { curGroup = ingredient.group; } ingredient.to = item; item.from.add(ingredient); grouped = true; calculateItemCost(item); } else { from.addAll(itemLibrary.getItemInfo(i).from); } } if (grouped) { increaseIngredientDepth(item); for (BuildItem i : item.from) { i.group = curGroup; } item.group = curGroup; if (curGroup == currentGroupCounter) { currentGroupCounter++; } } } private void calculateItemCost(BuildItem item) { int p = item.info.totalGold; for (BuildItem i : item.from) { p -= i.info.totalGold; } item.costPer = p; } private void recalculateItemCosts() { for (BuildItem item : itemBuild) { calculateItemCost(item); } } private void increaseIngredientDepth(BuildItem item) { for (BuildItem i : item.from) { i.depth++; increaseIngredientDepth(i); } } public void addItem(ItemInfo item) { addItem(item, 1, true); } public void addItem(ItemInfo item, int count, boolean isAll) { BuildItem buildItem = null; BuildItem last = getLastItem(); if (last != null && item == last.info) { if (item.stacks > last.count) { last.count += count; buildItem = last; } } if (isAll == false) { itemBuildDirty = true; } boolean itemNull = buildItem == null; if (itemNull) { buildItem = new BuildItem(item); buildItem.count = Math.min(item.stacks, count); // check if ingredients of this item is already part of the build... labelAllIngredients(buildItem, itemBuild.size()); if (itemBuild.size() == enabledBuildEnd) { enabledBuildEnd++; } itemBuild.add(buildItem); calculateItemCost(buildItem); } if (isAll) { recalculateStats(); if (itemBuildDirty) { itemBuildDirty = false; buildItem = null; } notifyItemAdded(buildItem, itemNull); } } public void clearItems() { itemBuild.clear(); normalizeValues(); recalculateItemCosts(); recalculateAllGroups(); recalculateStats(); notifyBuildChanged(); } public void removeItemAt(int position) { BuildItem item = itemBuild.get(position); itemBuild.remove(position); normalizeValues(); recalculateItemCosts(); recalculateAllGroups(); recalculateStats(); notifyBuildChanged(); } public int getItemCount() { return itemBuild.size(); } private void clearStats(double[] stats) { for (int i = 0; i < stats.length; i++) { stats[i] = 0; } } private void recalculateStats() { calculateStats(stats, enabledBuildStart, enabledBuildEnd, false, champLevel); } private void calculateStats(double[] stats, int startItemBuild, int endItemBuild, boolean onlyDoRawCalculation, int champLevel) { clearStats(stats); int active = 0; for (BuildRune r : runeBuild) { appendStat(stats, r); } if (!onlyDoRawCalculation) { for (BuildItem item : itemBuild) { item.active = false; } } HashSet<Integer> alreadyAdded = new HashSet<Integer>(); for (int i = endItemBuild - 1; i >= startItemBuild; i BuildItem item = itemBuild.get(i); if (item.to == null || itemBuild.indexOf(item.to) >= enabledBuildEnd) { if (!onlyDoRawCalculation) { item.active = true; } ItemInfo info = item.info; appendStat(stats, info.stats); int id = info.id; if (info.uniquePassiveStat != null && !alreadyAdded.contains(id)) { alreadyAdded.add(info.id); appendStat(stats, info.uniquePassiveStat); } active++; if (active == MAX_ACTIVE_ITEMS) break; } } calculateTotalStats(stats, champLevel); if (!onlyDoRawCalculation) { notifyBuildStatsChanged(); } } private void appendStat(double[] stats, JSONObject jsonStats) { Iterator<?> iter = jsonStats.keys(); while (iter.hasNext()) { String key = (String) iter.next(); try { stats[getStatIndex(key)] += jsonStats.getDouble(key); } catch (JSONException e) { Timber.e("", e); } } } private void appendStat(double[] stats, BuildRune rune) { RuneInfo info = rune.info; Iterator<?> iter = info.stats.keys(); while (iter.hasNext()) { String key = (String) iter.next(); try { int f = getStatIndex(key); if ((f & FLAG_SCALING) != 0) { stats[f & ~FLAG_SCALING] += info.stats.getDouble(key) * champLevel * rune.count; } else { stats[f] += info.stats.getDouble(key) * rune.count; } } catch (JSONException e) { Timber.e("", e); } } } private void calculateTotalStats() { calculateTotalStats(stats, champLevel); } private void calculateTotalStats(double[] stats, int champLevel) { // do some stat normalization... stats[STAT_CDR] = Math.min(MAX_CDR, stats[STAT_CDR] - stats[STAT_CD]); int levMinusOne = champLevel - 1; stats[STAT_TOTAL_AR] = stats[STAT_AR] + champ.ar + champ.arG * levMinusOne; stats[STAT_TOTAL_AD] = stats[STAT_AD] + champ.ad + champ.adG * levMinusOne; stats[STAT_TOTAL_HP] = stats[STAT_HP] + champ.hp + champ.hpG * levMinusOne; stats[STAT_CD_MOD] = 1.0 - stats[STAT_CDR]; stats[STAT_TOTAL_MS] = (stats[STAT_MS] + champ.ms) * stats[STAT_MSP] + stats[STAT_MS] + champ.ms; stats[STAT_TOTAL_AP] = stats[STAT_AP] * (stats[STAT_APP] + 1); stats[STAT_TOTAL_MR] = stats[STAT_MR] + champ.mr + champ.mrG * levMinusOne; stats[STAT_AS] = Math.min(champ.as * (1 + levMinusOne * champ.asG + stats[STAT_ASP]), MAX_ATTACK_SPEED); stats[STAT_LEVEL] = champLevel; stats[STAT_TOTAL_RANGE] = stats[STAT_RANGE] + champ.range; stats[STAT_TOTAL_MP] = stats[STAT_MP] + champ.mp + champ.mpG * levMinusOne; stats[STAT_BONUS_AD] = stats[STAT_TOTAL_AD] - champ.ad; stats[STAT_BONUS_HP] = stats[STAT_TOTAL_HP] - champ.hp; stats[STAT_BONUS_MS] = stats[STAT_TOTAL_MS] - champ.ms; stats[STAT_BONUS_AR] = stats[STAT_TOTAL_AR] - champ.ar; stats[STAT_BONUS_MR] = stats[STAT_TOTAL_MR] - champ.mr; stats[STAT_LEVEL_MINUS_ONE] = stats[STAT_LEVEL] - 1; stats[STAT_CRIT_DMG] = stats[STAT_TOTAL_AD] * 2.0; // pure stats... stats[STAT_AA_DPS] = stats[STAT_TOTAL_AD] * stats[STAT_AS]; // static values... stats[STAT_NAUTILUS_Q_CD] = 0.5; stats[STAT_ONE] = 1; } private static int addColor(int base, int value) { double result = 1 - (1 - base / 256.0) * (1 - value / 256.0); return (int) (result * 256); } public int generateColorBasedOnBuild() { int r = 0, g = 0, b = 0; int hp = 0; int mr = 0; int ar = 0; int ad = 0; int ap = 0; int crit = 0; int as = 0; calculateTotalStats(stats, 1); hp = (int) (stats[STAT_BONUS_HP] * STAT_VALUE_HP); mr = (int) (stats[STAT_BONUS_MR] * STAT_VALUE_MR); ar = (int) (stats[STAT_BONUS_AR] * STAT_VALUE_AR); ad = (int) (stats[STAT_BONUS_AD] * STAT_VALUE_AD); ap = (int) (stats[STAT_BONUS_AP] * STAT_VALUE_AP); crit = (int) (stats[STAT_CRIT] * 100 * STAT_VALUE_CRIT); as = (int) (stats[STAT_ASP] * 100 * STAT_VALUE_ASP); int tank = hp + mr + ar; int dps = ad + as + crit; int burst = ap; double total = tank + dps + burst; double tankness = tank / total; double adness = dps / total; double apness = burst / total; r = addColor((int) (Color.red(COLOR_AD) * adness), r); r = addColor((int) (Color.red(COLOR_AP) * apness), r); r = addColor((int) (Color.red(COLOR_TANK) * tankness), r); g = addColor((int) (Color.green(COLOR_AD) * adness), g); g = addColor((int) (Color.green(COLOR_AP) * apness), g); g = addColor((int) (Color.green(COLOR_TANK) * tankness), g); b = addColor((int) (Color.blue(COLOR_AD) * adness), b); b = addColor((int) (Color.blue(COLOR_AP) * apness), b); b = addColor((int) (Color.blue(COLOR_TANK) * tankness), b); Timber.d(String.format("Tankiness: %f Apness: %f Adness: %f", tankness, apness, adness)); return Color.rgb(r, g, b); } public BuildRune addRune(RuneInfo rune) { return addRune(rune, 1, true); } public BuildRune addRune(RuneInfo rune, int count, boolean isAll) { // Check if this rune is already in the build... BuildRune r = null; for (BuildRune br : runeBuild) { if (br.id == rune.id) { r = br; break; } } if (r == null) { r = new BuildRune(rune, rune.id); r.listener = onRuneCountChangedListener; runeBuild.add(r); notifyRuneAdded(r); } r.addRune(count); recalculateStats(); return r; } public void clearRunes() { for (BuildRune r : runeBuild) { r.listener = null; notifyRuneRemoved(r); } runeBuild.clear(); recalculateStats(); } public boolean canAdd(RuneInfo rune) { return runeCount[rune.runeType] + 1 <= RUNE_COUNT_MAX[rune.runeType]; } public void removeRune(BuildRune rune) { rune.listener = null; runeBuild.remove(rune); recalculateStats(); notifyRuneRemoved(rune); } private void onRuneCountChanged(BuildRune rune, int oldCount, int newCount) { int runeType = rune.info.runeType; if (runeCount[runeType] + (newCount - oldCount) > RUNE_COUNT_MAX[runeType]) { rune.count = oldCount; return; } runeCount[runeType] += (newCount - oldCount); if (rune.getCount() == 0) { removeRune(rune); } else { recalculateStats(); } } public BuildSkill addActiveSkill(Skill skill, double base, double scaling, String scaleType, String bonusType) { BuildSkill sk = new BuildSkill(); sk.skill = skill; sk.base = base; sk.scaleTypeId = getStatIndex(scaleType); sk.bonusTypeId = getStatIndex(bonusType); sk.scaling = scaling; activeSkills.add(sk); Timber.d("Skill " + skill.name + " bonus: " + base + "; "); return sk; } public double[] calculateStatWithActives(int gold, int champLevel) { double[] s = new double[stats.length]; int itemEndIndex = itemBuild.size(); int buildCost = 0; for (int i = 0; i < itemBuild.size(); i++) { BuildItem item = itemBuild.get(i); int itemCost = item.costPer * item.count; if (buildCost + itemCost > gold) { itemEndIndex = i; break; } else { buildCost += itemCost; } } calculateStats(s, 0, itemEndIndex, true, champLevel); for (BuildSkill sk : activeSkills) { sk.totalBonus = s[sk.scaleTypeId] * sk.scaling + sk.base; s[sk.bonusTypeId] += sk.totalBonus; } calculateTotalStats(s, champLevel); return s; } public List<BuildSkill> getActives() { return activeSkills; } public void clearActiveSkills() { activeSkills.clear(); } public void setChampion(ChampionInfo champ) { this.champ = champ; recalculateStats(); } public void setChampionLevel(int level) { champLevel = level; recalculateStats(); } public void registerObserver(BuildObserver observer) { observers.add(observer); } public void unregisterObserver(BuildObserver observer) { observers.remove(observer); } private void notifyBuildLoading() { buildLoading = true; for (BuildObserver o : observers) { o.onBuildLoading(); } } private void notifyBuildLoadingComplete() { buildLoading = false; for (BuildObserver o : observers) { o.onBuildLoadingComplete(); } } public boolean isBuildLoading() { return buildLoading; } private void notifyBuildChanged() { for (BuildObserver o : observers) { o.onBuildChanged(this); } } private void notifyItemAdded(BuildItem item, boolean isNewItem) { for (BuildObserver o : observers) { o.onItemAdded(this, item, isNewItem); } } private void notifyRuneAdded(BuildRune rune) { for (BuildObserver o : observers) { o.onRuneAdded(this, rune); } } private void notifyRuneRemoved(BuildRune rune) { for (BuildObserver o : observers) { o.onRuneRemoved(this, rune); } } private void notifyBuildStatsChanged() { for (BuildObserver o : observers) { o.onBuildStatsChanged(); } } private void normalizeValues() { if (enabledBuildStart < 0) { enabledBuildStart = 0; } if (enabledBuildEnd > itemBuild.size()) { enabledBuildEnd = itemBuild.size(); } } public BuildItem getItem(int index) { return itemBuild.get(index); } public int getBuildSize() { return itemBuild.size(); } public BuildRune getRune(int index) { return runeBuild.get(index); } public int getRuneCount() { return runeBuild.size(); } public BuildItem getLastItem() { if (itemBuild.size() == 0) return null; return itemBuild.get(itemBuild.size() - 1); } public double getBonusHp() { return stats[STAT_HP]; } public double getBonusHpRegen() { return stats[STAT_HPR]; } public double getBonusMp() { if (champ.partype == ChampionInfo.TYPE_MANA) { return stats[STAT_MP]; } else { return 0; } } public double getBonusMpRegen() { if (champ.partype == ChampionInfo.TYPE_MANA) { return stats[STAT_MPR]; } else { return 0; } } public double getBonusAd() { return stats[STAT_AD]; } public double getBonusAs() { return stats[STAT_ASP]; } public double getBonusAr() { return stats[STAT_AR]; } public double getBonusMr() { return stats[STAT_MR]; } public double getBonusMs() { return stats[STAT_BONUS_MS]; } public double getBonusRange() { return stats[STAT_RANGE]; } public double getBonusAp() { return stats[STAT_BONUS_AP]; } public double getBonusEnergy() { return stats[STAT_NRG]; } public double getBonusEnergyRegen() { return stats[STAT_NRGR]; } public double[] getRawStats() { return stats; } public double getStat(String key) { int statId = getStatIndex(key); switch (statId) { case STAT_NULL: stats[STAT_NULL] = 0; break; case STAT_RENGAR_Q_BASE_DAMAGE: // refresh rengar q base damage since it looks like we are going to be using it... stats[STAT_RENGAR_Q_BASE_DAMAGE] = RENGAR_Q_BASE[champLevel - 1]; break; } return stats[statId]; } public double getStat(int statId) { if (statId == STAT_NULL) return 0.0; return stats[statId]; } public String getSpecialString(Context context, String specialKey) { int statId = getStatIndex(specialKey); StringBuilder sb = new StringBuilder(); switch (statId) { case STAT_RENGAR_Q_BASE_DAMAGE: // refresh rengar q base damage since it looks like we are going to be using it... sb.append("["); sb.append(context.getString(R.string.level_dependent_base_damage)); sb.append(" "); for (double val : RENGAR_Q_BASE) { sb.append(val); sb.append(" / "); } sb.setLength(sb.length() - 2); sb.append("(+"); sb.append(0.5 * stats[STAT_AD]); sb.append(")"); sb.append("]"); break; case STAT_VI_W: sb.append((int)( 0.028571428 * stats[STAT_BONUS_AD])); break; case STAT_JAX_R_ARMOR_SCALING: sb.append(context.getString(R.string.base_value)); sb.append(" (+"); sb.append(((int)0.5 * stats[STAT_BONUS_AD])); sb.append(")"); break; case STAT_JAX_R_MR_SCALING: sb.append(context.getString(R.string.base_value)); sb.append(" (+"); sb.append(((int)0.2 * stats[STAT_AP])); sb.append(")"); break; case STAT_NAUTILUS_Q_CD: sb.append("0.5"); break; case STAT_STACKS: sb.append(context.getString(R.string.stacks)); break; case STAT_CD_MOD: switch (champ.id) { case CHAMPION_ID_AKALI: sb.append("30 / 22.5 / 15"); break; case CHAMPION_ID_CORKI: sb.append("12 / 10 / 8"); break; case CHAMPION_ID_HEIM: sb.append("24 / 23 / 22 / 21 / 20"); break; case CHAMPION_ID_TEEMO: sb.append("35 / 31 / 27"); break; default: throw new RuntimeException("Cooldown for champion " + champ.name + " cannot be found."); } break; case STAT_DARIUS_R_MAX_DAMAGE: sb.append("320 / 500 / 680 (+1.5 per bonus attack damage)"); break; default: throw new RuntimeException("Stat with name " + specialKey + " and id " + statId + " cannot be resolved."); } return sb.toString(); } public void reorder(int itemOldPosition, int itemNewPosition) { BuildItem item = itemBuild.get(itemOldPosition); itemBuild.remove(itemOldPosition); itemBuild.add(itemNewPosition, item); recalculateAllGroups(); recalculateStats(); notifyBuildStatsChanged(); } public int getEnabledBuildStart() { return enabledBuildStart; } public int getEnabledBuildEnd() { return enabledBuildEnd; } public void setEnabledBuildStart(int start) { enabledBuildStart = start; recalculateStats(); notifyBuildStatsChanged(); } public void setEnabledBuildEnd(int end) { enabledBuildEnd = end; recalculateStats(); notifyBuildStatsChanged(); } public BuildSaveObject toSaveObject() { BuildSaveObject o = new BuildSaveObject(); for (BuildRune r : runeBuild) { o.runes.add(r.info.id); o.runes.add(r.count); } for (BuildItem i : itemBuild) { o.items.add(i.info.id); o.items.add(i.count); } o.buildName = buildName; o.buildColor = generateColorBasedOnBuild(); return o; } public void fromSaveObject(final Context context, final BuildSaveObject o) { new AsyncTask<Void, Void, Void>() { @Override protected void onPreExecute() { notifyBuildLoading(); } @Override protected Void doInBackground(Void... params) { try { LibraryUtils.initItemLibrary(context); LibraryUtils.initRuneLibrary(context); } catch (JSONException e) { Timber.e("", e); } catch (IOException e) { Timber.e("", e); } return null; } @Override protected void onPostExecute(Void result) { notifyBuildLoadingComplete(); clearItems(); clearRunes(); int count = o.runes.size(); for (int i = 0; i < count; i += 2) { addRune(runeLibrary.getRuneInfo(o.runes.get(i)), o.runes.get(i + 1), i + 2 >= count); } count = o.items.size(); for (int i = 0; i < count; i += 2) { int itemId = o.items.get(i); int c = o.items.get(i + 1); addItem(itemLibrary.getItemInfo(itemId), c, i == count - 2); } buildName = o.buildName; } }.execute(); } public static int getSuggestedColorForGroup(int groupId) { return GROUP_COLOR[groupId % GROUP_COLOR.length]; } public static interface BuildObserver { public void onBuildLoading(); public void onBuildLoadingComplete(); public void onBuildChanged(Build build); public void onItemAdded(Build build, BuildItem item, boolean isNewItem); public void onRuneAdded(Build build, BuildRune rune); public void onRuneRemoved(Build build, BuildRune rune); public void onBuildStatsChanged(); } public static class BuildItem { ItemInfo info; int group = -1; boolean active = true; int count = 1; int costPer = 0; int depth = 0; List<BuildItem> from; BuildItem to; private BuildItem(ItemInfo info) { this.info = info; from = new ArrayList<BuildItem>(); } public int getId() { return info.id; } } public static class BuildRune { RuneInfo info; Object tag; int id; private int count; private OnRuneCountChangedListener listener; private OnRuneCountChangedListener onRuneCountChangedListener; private BuildRune(RuneInfo info, int id) { this.info = info; count = 0; this.id = id; } public void addRune() { addRune(1); } public void addRune(int n) { count += n; int c = count; listener.onRuneCountChanged(this, count - n, count); if (c == count && onRuneCountChangedListener != null) { onRuneCountChangedListener.onRuneCountChanged(this, count - n, count); } } public void removeRune() { if (count == 0) return; count int c = count; listener.onRuneCountChanged(this, count + 1, count); if (c == count && onRuneCountChangedListener != null) { onRuneCountChangedListener.onRuneCountChanged(this, count + 1, count); } } public int getCount() { return count; } public void setOnRuneCountChangedListener(OnRuneCountChangedListener listener) { onRuneCountChangedListener = listener; } } public static class BuildSkill { public double totalBonus; Skill skill; double base; double scaling; int scaleTypeId; int bonusTypeId; } public static interface OnRuneCountChangedListener { public void onRuneCountChanged(BuildRune rune, int oldCount, int newCount); } public static int getStatIndex(String statName) { Integer i; i = statKeyToIndex.get(statName); if (i == null) { throw new RuntimeException("Stat name not found: " + statName); } return i; } public static int getSkillStatDesc(int statId) { int i; i = statIdToSkillStatDescStringId.get(statId); if (i == 0) { throw new RuntimeException("Stat id does not have a skill stat description: " + statId); } return i; } public static int getStatName(int statId) { int i; i = statIdToStringId.get(statId); if (i == 0) { throw new RuntimeException("Stat id does not have string resource: " + statId); } return i; } public static int getStatType(int statId) { switch (statId) { case STAT_DMG_REDUCTION: case STAT_ENEMY_MAX_HP: case STAT_ENEMY_CURRENT_HP: case STAT_ENEMY_MISSING_HP: return STAT_TYPE_PERCENT; default: return STAT_TYPE_DEFAULT; } } public static int getScalingType(int statId) { switch (statId) { case STAT_CD_MOD: case STAT_STACKS: case STAT_ONE: return STAT_TYPE_DEFAULT; default: return STAT_TYPE_PERCENT; } } }
package com.hexad.snackmate; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.GridView; import android.widget.Spinner; import android.widget.Toast; public class HomePage extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home_page); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); // Set up gridview on the homepage GridView gridView = (GridView) findViewById(R.id.homepage_gridview); gridView.setAdapter(new ImageAdapter(this)); Spinner menu = (Spinner) findViewById(R.id.spinner1); String[] names = new String[]{"C", "Japan", "Korea", "China", "Others"}; ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, names); menu.setAdapter(adapter); Spinner menu1 = (Spinner) findViewById(R.id.spinner2); String[] names1 = new String[]{"T", "Spicy", "Salty","Sweet"}; ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, names1); menu1.setAdapter(adapter1); Spinner menu2 = (Spinner) findViewById(R.id.spinner3); String[] names2 = new String[]{"R", "5", "4", "3", "2", "1"}; ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, names2); menu2.setAdapter(adapter2); Spinner menu3 = (Spinner) findViewById(R.id.spinner4); String[] names3 = new String[]{"P", "from High to Low", "from Low to High"}; ArrayAdapter<String> adapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, names3); menu3.setAdapter(adapter3); Spinner menu4 = (Spinner) findViewById(R.id.spinner5); String[] names4 = new String[]{"O", "A-Z", "Z-A"}; ArrayAdapter<String> adapter4 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, names4); menu4.setAdapter(adapter4); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.home_page, menu); MenuItem searchItem = menu.findItem(R.id.action_search); //SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_camara) { // Handle the camera action } else if (id == R.id.nav_gallery) { } else if (id == R.id.nav_slideshow) { } else if (id == R.id.nav_manage) { } else if (id == R.id.nav_share) { } else if (id == R.id.nav_send) { } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } }
package com.meedamian.info; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.provider.Settings; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Set; public class BasicData { public static final String SUBSCRIBER_ID = "subscriber"; public static final String PHONE_NO = "phone"; public static final String LOCATION = "location"; public static final String VANITY = "vanity"; private BasicData() {} private static SharedPreferences getSp(Context c) { return PreferenceManager.getDefaultSharedPreferences(c); } private static String getUpdatedKey(String key) { return key + "_updated"; } public static String getString(Context c, String key) { return getSp(c).getString(key, null); } public static Set<String> getStringSet(Context c, String key) { return getSp(c).getStringSet(key, null); } public static Integer getInt(Context c, String key) { int i = getSp(c).getInt(key, -666); return i != -666 ? i : null; } private static SharedPreferences.Editor getSpEd(Context c) { return getSp(c).edit(); } private static void saveSpEd(String key, SharedPreferences.Editor ed) { ed.putLong(getUpdatedKey(key), System.currentTimeMillis()).apply(); } public static void update(Context c, String key, String val) { saveSpEd(key, getSpEd(c).putString(key, val)); } public static void update(Context c, String key, Set<String> val) { saveSpEd(key, getSpEd(c).putStringSet(key, val)); } public static void update(Context c, String key, Integer val) { saveSpEd(key, getSpEd(c).putInt(key, val)); } protected static String getPrivateId(Context c) { return Settings.Secure.getString(c.getContentResolver(), Settings.Secure.ANDROID_ID); } public static String getPublicId(Context c) { String id = getPrivateId(c); // TODO: shorten the string try { MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); messageDigest.update(id.getBytes()); return new String(messageDigest.digest()); } catch (NoSuchAlgorithmException e) { return null; } } }
package org.commcare.android.util; import java.util.Vector; import org.commcare.dalvik.application.CommCareApp; import org.commcare.dalvik.application.CommCareApplication; import org.javarosa.core.model.instance.FormInstance; import org.javarosa.core.model.instance.TreeReference; import org.javarosa.core.services.storage.IStorageUtilityIndexed; import org.javarosa.core.util.ArrayUtilities; import org.javarosa.xpath.expr.XPathExpression; /** * Basically Copy+Paste code from CCJ2ME that needs to be unified or re-indexed to somewhere more reasonable. * * @author ctsims * */ public class CommCareUtil { public static FormInstance loadFixture(String refId, String userId) { IStorageUtilityIndexed<FormInstance> userFixtureStorage = CommCareApplication._().getUserStorage("fixture", FormInstance.class); IStorageUtilityIndexed<FormInstance> appFixtureStorage = CommCareApplication._().getAppStorage("fixture", FormInstance.class); Vector<Integer> userFixtures = userFixtureStorage.getIDsForValue(FormInstance.META_ID, refId); ///... Nooooot so clean. if(userFixtures.size() == 1) { //easy case, one fixture, use it return (FormInstance)userFixtureStorage.read(userFixtures.elementAt(0).intValue()); //TODO: Userid check anyway? } else if(userFixtures.size() > 1){ //intersect userid and fixtureid set. //TODO: Replace context call here with something from the session, need to stop relying on that coupling Vector<Integer> relevantUserFixtures = userFixtureStorage.getIDsForValue(FormInstance.META_XMLNS, userId); if(relevantUserFixtures.size() != 0) { Integer userFixture = ArrayUtilities.intersectSingle(userFixtures, relevantUserFixtures); if(userFixture != null) { return (FormInstance)userFixtureStorage.read(userFixture.intValue()); } } } //ok, so if we've gotten here there were no fixtures for the user, let's try the app fixtures. Vector<Integer> appFixtures = appFixtureStorage.getIDsForValue(FormInstance.META_ID, refId); Integer globalFixture = ArrayUtilities.intersectSingle(appFixtureStorage.getIDsForValue(FormInstance.META_XMLNS, ""), appFixtures); if(globalFixture != null) { return (FormInstance)appFixtureStorage.read(globalFixture.intValue()); } else { //See if we have one manually placed in the suite Integer userFixture = ArrayUtilities.intersectSingle(appFixtureStorage.getIDsForValue(FormInstance.META_XMLNS, userId), appFixtures); if(userFixture != null) { return (FormInstance)appFixtureStorage.read(userFixture.intValue()); } //Otherwise, nothing return null; } } /** * Used around to count up the degree of specificity for this reference * * @param reference * @return */ public static int countPreds(TreeReference reference) { int preds = 0; for(int i =0 ; i < reference.size(); ++i) { Vector<XPathExpression> predicates = reference.getPredicate(i); if(predicates != null) { preds += predicates.size(); } } return preds; } }
package models; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonRootName; import com.fasterxml.jackson.annotation.JsonView; import play.data.validation.Constraints; import play.db.ebean.Model; import utilities.ControllerHelper; import javax.persistence.*; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; @Entity @Table(name="useraccount") @JsonRootName("user") @JsonIgnoreProperties(ignoreUnknown = true) public class User extends Model { private static final long MIN_PASSWORD_LENGTH = 8; public final static Finder<Long, User> FIND = new Finder<Long, User>(Long.class, User.class); @JsonView({ControllerHelper.Summary.class}) @Id private Long id; @Column(length = 256, nullable = false) @Constraints.Required @Constraints.MinLength(1) @Constraints.MaxLength(256) private String firstName; @Column(length = 256, nullable = false) @Constraints.Required @Constraints.MinLength(1) @Constraints.MaxLength(256) private String lastName; @Column(nullable = false, updatable = false) private Date creationDate; @JsonView({ControllerHelper.Summary.class}) @Column(length = 256, unique = true, nullable = false) @Constraints.MaxLength(256) @Constraints.Required @Constraints.Email private String email; @Enumerated(EnumType.STRING) private Role role; @JsonIgnore @Column(length = 64, nullable = false) private byte[] shaPassword; // TODO: allow multiple browsers @JsonIgnore private String authToken; public User() { this.authToken = UUID.randomUUID().toString(); role = Role.USER; this.creationDate = new Date(); } public User(String email, String password, String firstName, String lastName) { this(); setEmail(email); setPassword(password); this.firstName = firstName; this.lastName = lastName; } public Date getCreationDate() { return creationDate; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } public byte[] getShaPassword() { return shaPassword; } public void setPassword(String password) { shaPassword = getSha512(password); } public String getAuthToken() { // create a token if non exists for this user if(authToken == null) { authToken = UUID.randomUUID().toString(); save(); } return authToken; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email.toLowerCase(); } public static byte[] getSha512(String value) { try { return MessageDigest.getInstance("SHA-512").digest(value.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { play.Logger.error(e.getMessage(), e); } catch (UnsupportedEncodingException e) { play.Logger.error(e.getMessage(), e); } // TODO: fix exception handling return value.getBytes(); } public boolean checkPassword(String password) { byte[] hash = getSha512(password); return Arrays.equals(shaPassword, hash); } public static User findByAuthToken(String authToken) { if (authToken == null) return null; try { return FIND.where().eq("authToken", authToken).findUnique(); } catch (Exception e) { play.Logger.error(e.getMessage(), e); return null; } } public void invalidateAuthToken() { authToken = null; save(); } public static User findByEmail(String emailAddress) { return FIND.where().eq("email", emailAddress.toLowerCase()).findUnique(); } public static User authenticate(String email, String password) { User user = findByEmail(email); if(user != null && user.checkPassword(password)) { return user; } return null; } public static String validatePassword(String password) { if(password == null) { return "required"; } if(password.length() < 8) { return "min length " + MIN_PASSWORD_LENGTH; } return null; } @Override public boolean equals(Object obj) { if(obj == this) return true; if(obj == null || !(obj instanceof User)) return false; User other = (User) obj; boolean isEqual = this.id.equals(other.id); isEqual &= this.firstName.equals(other.firstName); isEqual &= this.lastName.equals(other.lastName); isEqual &= this.email.equals(other.email); return isEqual && this.role.equals(other.role); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (id != null ? id.hashCode() : 0); result = 31 * result + (firstName != null ? firstName.hashCode() : 0); result = 31 * result + (lastName != null ? lastName.hashCode() : 0); result = 31 * result + (creationDate != null ? creationDate.hashCode() : 0); result = 31 * result + (email != null ? email.hashCode() : 0); result = 31 * result + (role != null ? role.hashCode() : 0); result = 31 * result + (shaPassword != null ? Arrays.hashCode(shaPassword) : 0); result = 31 * result + (authToken != null ? authToken.hashCode() : 0); return result; } public static enum Role { USER, ADMIN, READONLY_ADMIN } }
package com.mapswithme.maps.settings; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.speech.tts.TextToSpeech; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.support.v7.preference.ListPreference; import android.support.v7.preference.Preference; import android.support.v7.preference.PreferenceScreen; import android.support.v7.preference.TwoStatePreference; import android.text.Spannable; import android.text.SpannableString; import android.text.style.ForegroundColorSpan; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; import com.mapswithme.maps.BuildConfig; import com.mapswithme.maps.Framework; import com.mapswithme.maps.MwmApplication; import com.mapswithme.maps.R; import com.mapswithme.maps.downloader.MapManager; import com.mapswithme.maps.downloader.OnmapDownloader; import com.mapswithme.maps.editor.ProfileActivity; import com.mapswithme.maps.location.LocationHelper; import com.mapswithme.maps.location.TrackRecorder; import com.mapswithme.maps.search.SearchFragment; import com.mapswithme.maps.sound.LanguageData; import com.mapswithme.maps.sound.TtsPlayer; import com.mapswithme.util.Config; import com.mapswithme.util.NetworkPolicy; import com.mapswithme.util.ThemeSwitcher; import com.mapswithme.util.UiUtils; import com.mapswithme.util.concurrency.UiThread; import com.mapswithme.util.log.LoggerFactory; import com.mapswithme.util.statistics.AlohaHelper; import com.mapswithme.util.statistics.MytargetHelper; import com.mapswithme.util.statistics.Statistics; import java.util.HashMap; import java.util.List; import java.util.Map; public class SettingsPrefsFragment extends BaseXmlSettingsFragment { private static final int REQUEST_INSTALL_DATA = 1; private static final String TTS_SCREEN_KEY = MwmApplication.get() .getString(R.string.pref_tts_screen); private static final String TTS_INFO_LINK = MwmApplication.get() .getString(R.string.tts_info_link); @NonNull private final StoragePathManager mPathManager = new StoragePathManager(); @Nullable private Preference mStoragePref; @Nullable private TwoStatePreference mPrefEnabled; @Nullable private ListPreference mPrefLanguages; @Nullable private Preference mLangInfo; @Nullable private Preference mLangInfoLink; private PreferenceScreen mPreferenceScreen; @NonNull private final Map<String, LanguageData> mLanguages = new HashMap<>(); private LanguageData mCurrentLanguage; private String mSelectedLanguage; private boolean singleStorageOnly() { return !mPathManager.hasMoreThanOneStorage(); } private void updateStoragePrefs() { Preference old = findPreference(getString(R.string.pref_storage)); if (singleStorageOnly()) { if (old != null) getPreferenceScreen().removePreference(old); } else { if (old == null && mStoragePref != null) getPreferenceScreen().addPreference(mStoragePref); } } private final Preference.OnPreferenceChangeListener mEnabledListener = new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { Statistics.INSTANCE.trackEvent(Statistics.EventName.Settings.VOICE_ENABLED, Statistics.params().add(Statistics.EventParam.ENABLED, newValue.toString())); Preference root = findPreference(getString(R.string.pref_tts_screen)); boolean set = (Boolean)newValue; if (!set) { TtsPlayer.setEnabled(false); if (mPrefLanguages != null) mPrefLanguages.setEnabled(false); if (mLangInfo != null) mLangInfo.setSummary(R.string.prefs_languages_information_off); if (mLangInfoLink != null && isOnTtsScreen()) getPreferenceScreen().addPreference(mLangInfoLink); if (root != null) root.setSummary(R.string.off); if (mPrefEnabled != null) mPrefEnabled.setTitle(R.string.off); return true; } if (mLangInfo != null) mLangInfo.setSummary(R.string.prefs_languages_information); if (root != null) root.setSummary(R.string.on); if (mPrefEnabled != null) mPrefEnabled.setTitle(R.string.on); if (mLangInfoLink != null) getPreferenceScreen().removePreference(mLangInfoLink); if (mCurrentLanguage != null && mCurrentLanguage.downloaded) { setLanguage(mCurrentLanguage); return true; } return false; } }; private final Preference.OnPreferenceChangeListener mLangListener = new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { if (newValue == null) return false; mSelectedLanguage = (String)newValue; Statistics.INSTANCE.trackEvent(Statistics.EventName.Settings.VOICE_LANGUAGE, Statistics.params().add(Statistics.EventParam.LANGUAGE, mSelectedLanguage)); LanguageData lang = mLanguages.get(mSelectedLanguage); if (lang == null) return false; if (lang.downloaded) setLanguage(lang); else startActivityForResult(new Intent(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA), REQUEST_INSTALL_DATA); return false; } }; private void enableListeners(boolean enable) { if (mPrefEnabled != null) mPrefEnabled.setOnPreferenceChangeListener(enable ? mEnabledListener : null); if (mPrefLanguages != null) mPrefLanguages.setOnPreferenceChangeListener(enable ? mLangListener : null); } private void setLanguage(@NonNull LanguageData lang) { Config.setTtsEnabled(true); TtsPlayer.INSTANCE.setLanguage(lang); if (mPrefLanguages != null) mPrefLanguages.setSummary(lang.name); updateTts(); } private void updateTts() { if (mPrefEnabled == null || mPrefLanguages == null || mLangInfo == null || mLangInfoLink == null) return; enableListeners(false); List<LanguageData> languages = TtsPlayer.INSTANCE.refreshLanguages(); mLanguages.clear(); mCurrentLanguage = null; Preference root = findPreference(getString(R.string.pref_tts_screen)); if (languages.isEmpty()) { mPrefEnabled.setChecked(false); mPrefEnabled.setEnabled(false); mPrefEnabled.setSummary(R.string.pref_tts_unavailable); mPrefEnabled.setTitle(R.string.off); mPrefLanguages.setEnabled(false); mPrefLanguages.setSummary(null); mLangInfo.setSummary(R.string.prefs_languages_information_off); if (isOnTtsScreen()) getPreferenceScreen().addPreference(mLangInfoLink); if (root != null) root.setSummary(R.string.off); enableListeners(true); return; } boolean enabled = TtsPlayer.INSTANCE.isEnabled(); mPrefEnabled.setChecked(enabled); mPrefEnabled.setSummary(null); mPrefEnabled.setTitle(enabled ? R.string.on : R.string.off); mLangInfo.setSummary(enabled ? R.string.prefs_languages_information : R.string.prefs_languages_information_off); if (enabled) getPreferenceScreen().removePreference(mLangInfoLink); else if (isOnTtsScreen()) getPreferenceScreen().addPreference(mLangInfoLink); if (root != null) root.setSummary(enabled ? R.string.on : R.string.off); final CharSequence[] entries = new CharSequence[languages.size()]; final CharSequence[] values = new CharSequence[languages.size()]; for (int i = 0; i < languages.size(); i++) { LanguageData lang = languages.get(i); entries[i] = lang.name; values[i] = lang.internalCode; mLanguages.put(lang.internalCode, lang); } mPrefLanguages.setEntries(entries); mPrefLanguages.setEntryValues(values); mCurrentLanguage = TtsPlayer.getSelectedLanguage(languages); boolean available = (mCurrentLanguage != null && mCurrentLanguage.downloaded); mPrefLanguages.setEnabled(available && TtsPlayer.INSTANCE.isEnabled()); mPrefLanguages.setSummary(available ? mCurrentLanguage.name : null); mPrefLanguages.setValue(available ? mCurrentLanguage.internalCode : null); mPrefEnabled.setChecked(available && TtsPlayer.INSTANCE.isEnabled()); enableListeners(true); } private boolean isOnTtsScreen() { return mPreferenceScreen.getKey() != null && mPreferenceScreen.getKey().equals(TTS_SCREEN_KEY); } @Override public Fragment getCallbackFragment() { return this; } @Override protected int getXmlResources() { return R.xml.prefs_main; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPreferenceScreen = getPreferenceScreen(); mStoragePref = findPreference(getString(R.string.pref_storage)); mPrefEnabled = (TwoStatePreference) findPreference(getString(R.string.pref_tts_enabled)); mPrefLanguages = (ListPreference) findPreference(getString(R.string.pref_tts_language)); mLangInfo = findPreference(getString(R.string.pref_tts_info)); mLangInfoLink = findPreference(getString(R.string.pref_tts_info_link)); initLangInfoLink(); updateStoragePrefs(); initStoragePrefCallbacks(); initMeasureUnitsPrefsCallbacks(); initZoomPrefsCallbacks(); initMapStylePrefsCallbacks(); initAutoDownloadPrefsCallbacks(); initLargeFontSizePrefsCallbacks(); init3dModePrefsCallbacks(); initPerspectivePrefsCallbacks(); initTrackRecordPrefsCallbacks(); initStatisticsPrefsCallback(); initPlayServicesPrefsCallbacks(); initAutoZoomPrefsCallbacks(); initSimplifiedTrafficColorsPrefsCallbacks(); if (!MytargetHelper.isShowcaseSwitchedOnServer()) getPreferenceScreen().removePreference(findPreference(getString(R.string.pref_showcase_switched_on))); initLoggingEnabledPrefsCallbacks(); initUseMobileDataPrefsCallbacks(); updateTts(); } @Override public void onResume() { super.onResume(); initTrackRecordPrefsCallbacks(); updateTts(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { // Do not check resultCode here as it is always RESULT_CANCELED super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_INSTALL_DATA) { updateTts(); LanguageData lang = mLanguages.get(mSelectedLanguage); if (lang != null && lang.downloaded) setLanguage(lang); } } @Override public boolean onPreferenceTreeClick(Preference preference) { if (preference.getKey() != null && preference.getKey().equals(getString(R.string.pref_help))) { Statistics.INSTANCE.trackEvent(Statistics.EventName.Settings.HELP); AlohaHelper.logClick(AlohaHelper.Settings.HELP); } else if (preference.getKey() != null && preference.getKey().equals(getString(R.string.pref_about))) { Statistics.INSTANCE.trackEvent(Statistics.EventName.Settings.ABOUT); AlohaHelper.logClick(AlohaHelper.Settings.ABOUT); } else if (preference.getKey() != null && preference.getKey().equals(getString(R.string.pref_osm_profile))) { Statistics.INSTANCE.trackEvent(Statistics.EventName.Settings.OSM_PROFILE); startActivity(new Intent(getActivity(), ProfileActivity.class)); } return super.onPreferenceTreeClick(preference); } private void initLangInfoLink() { if (mLangInfoLink != null) { Spannable link = new SpannableString(getString(R.string.prefs_languages_information_off_link)); link.setSpan(new ForegroundColorSpan(ContextCompat.getColor(getContext(), UiUtils.getStyledResourceId(getContext(), R.attr.colorAccent))), 0, link.length(), 0); mLangInfoLink.setSummary(link); mLangInfoLink.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { final Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(TTS_INFO_LINK)); getContext().startActivity(intent); return false; } }); mPreferenceScreen.removePreference(mLangInfoLink); } } private void initSimplifiedTrafficColorsPrefsCallbacks() { final TwoStatePreference prefSimplifiedColors = (TwoStatePreference)findPreference( getString(R.string.pref_traffic_simplified_colors)); if (prefSimplifiedColors == null) return; boolean simplifiedColorsEnabled = Framework.nativeGetSimplifiedTrafficColorsEnabled(); prefSimplifiedColors.setChecked(simplifiedColorsEnabled); prefSimplifiedColors.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { Framework.nativeSetSimplifiedTrafficColorsEnabled((Boolean)newValue); return true; } }); } private void initLargeFontSizePrefsCallbacks() { Preference pref = findPreference(getString(R.string.pref_large_fonts_size)); if (pref == null) return; ((TwoStatePreference)pref).setChecked(Config.isLargeFontsSize()); pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { boolean oldVal = Config.isLargeFontsSize(); boolean newVal = (Boolean) newValue; if (oldVal != newVal) Config.setLargeFontsSize(newVal); return true; } }); } private void initUseMobileDataPrefsCallbacks() { final ListPreference mobilePref = (ListPreference)findPreference( getString(R.string.pref_use_mobile_data)); if (mobilePref == null) return; int curValue = Config.getUseMobileDataSettings(); if (curValue != NetworkPolicy.NOT_TODAY && curValue != NetworkPolicy.TODAY) { mobilePref.setValue(String.valueOf(curValue)); mobilePref.setSummary(mobilePref.getEntry()); } else { mobilePref.setSummary(getString(R.string.mobile_data_description)); } mobilePref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { String valueStr = (String)newValue; switch (Integer.parseInt(valueStr)) { case NetworkPolicy.ASK: Config.setUseMobileDataSettings(NetworkPolicy.ASK); break; case NetworkPolicy.ALWAYS: Config.setUseMobileDataSettings(NetworkPolicy.ALWAYS); break; case NetworkPolicy.NEVER: Config.setUseMobileDataSettings(NetworkPolicy.NEVER); break; default: throw new AssertionError("Wrong NetworkPolicy type!"); } UiThread.runLater(new Runnable() { @Override public void run() { mobilePref.setSummary(mobilePref.getEntry()); } }); return true; } }); } private void initLoggingEnabledPrefsCallbacks() { Preference pref = findPreference(getString(R.string.pref_enable_logging)); if (pref == null) return; if (!MwmApplication.prefs().getBoolean(SearchFragment.PREFS_SHOW_ENABLE_LOGGING_SETTING, BuildConfig.BUILD_TYPE.equals("beta"))) { getPreferenceScreen().removePreference(pref); } else { final boolean isLoggingEnabled = LoggerFactory.INSTANCE.isFileLoggingEnabled(); ((TwoStatePreference) pref).setChecked(isLoggingEnabled); pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { boolean oldVal = isLoggingEnabled; boolean newVal = (Boolean) newValue; if (oldVal != newVal) { LoggerFactory.INSTANCE.setFileLoggingEnabled(newVal); } return true; } }); } } private void initAutoZoomPrefsCallbacks() { final TwoStatePreference pref = (TwoStatePreference)findPreference(getString(R.string.pref_auto_zoom)); if (pref == null) return; boolean autozoomEnabled = Framework.nativeGetAutoZoomEnabled(); pref.setChecked(autozoomEnabled); pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { Framework.nativeSetAutoZoomEnabled((Boolean)newValue); return true; } }); } private void initPlayServicesPrefsCallbacks() { Preference pref = findPreference(getString(R.string.pref_play_services)); if (pref == null) return; if (GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(MwmApplication.get()) != ConnectionResult.SUCCESS) getPreferenceScreen().removePreference(pref); else { ((TwoStatePreference) pref).setChecked(Config.useGoogleServices()); pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { boolean oldVal = Config.useGoogleServices(); boolean newVal = (Boolean) newValue; if (oldVal != newVal) { Config.setUseGoogleService(newVal); LocationHelper.INSTANCE.restart(); } return true; } }); } } private void initStatisticsPrefsCallback() { Preference pref = findPreference(getString(R.string.pref_send_statistics)); if (pref == null) return; ((TwoStatePreference)pref).setChecked(Config.isStatisticsEnabled()); pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { Statistics.INSTANCE.setStatEnabled((Boolean) newValue); return true; } }); } private void initTrackRecordPrefsCallbacks() { final ListPreference trackPref = (ListPreference)findPreference(getString(R.string.pref_track_record)); final Preference pref = findPreference(getString(R.string.pref_track_record_time)); final Preference root = findPreference(getString(R.string.pref_track_screen)); if (trackPref == null || pref == null) return; boolean enabled = TrackRecorder.isEnabled(); ((TwoStatePreference)pref).setChecked(enabled); trackPref.setEnabled(enabled); if (root != null) root.setSummary(enabled ? R.string.on : R.string.off); pref.setTitle(enabled ? R.string.on : R.string.off); pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { boolean enabled = (Boolean) newValue; TrackRecorder.setEnabled(enabled); Statistics.INSTANCE.setStatEnabled(enabled); trackPref.setEnabled(enabled); if (root != null) root.setSummary(enabled ? R.string.on : R.string.off); pref.setTitle(enabled ? R.string.on : R.string.off); trackPref.performClick(); return true; } }); String value = (enabled ? String.valueOf(TrackRecorder.getDuration()) : "0"); trackPref.setValue(value); trackPref.setSummary(trackPref.getEntry()); trackPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(final Preference preference, Object newValue) { int value = Integer.valueOf((String)newValue); boolean enabled = value != 0; if (enabled) TrackRecorder.setDuration(value); TrackRecorder.setEnabled(enabled); ((TwoStatePreference) pref).setChecked(enabled); trackPref.setEnabled(enabled); if (root != null) root.setSummary(enabled ? R.string.on : R.string.off); pref.setTitle(enabled ? R.string.on : R.string.off); UiThread.runLater(new Runnable() { @Override public void run() { trackPref.setSummary(trackPref.getEntry()); } }); return true; } }); } private void init3dModePrefsCallbacks() { final TwoStatePreference pref = (TwoStatePreference)findPreference(getString(R.string.pref_3d_buildings)); if (pref == null) return; final Framework.Params3dMode _3d = new Framework.Params3dMode(); Framework.nativeGet3dMode(_3d); pref.setChecked(_3d.buildings); pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { Framework.nativeSet3dMode(_3d.enabled, (Boolean)newValue); return true; } }); } private void initPerspectivePrefsCallbacks() { final TwoStatePreference pref = (TwoStatePreference)findPreference(getString(R.string.pref_3d)); if (pref == null) return; final Framework.Params3dMode _3d = new Framework.Params3dMode(); Framework.nativeGet3dMode(_3d); pref.setChecked(_3d.enabled); pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { Framework.nativeSet3dMode((Boolean) newValue, _3d.buildings); return true; } }); } private void initAutoDownloadPrefsCallbacks() { TwoStatePreference pref = (TwoStatePreference)findPreference(getString(R.string.pref_autodownload)); if (pref == null) return; pref.setChecked(Config.isAutodownloadEnabled()); pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { boolean value = (Boolean)newValue; Config.setAutodownloadEnabled(value); if (value) OnmapDownloader.setAutodownloadLocked(false); return true; } }); } private void initMapStylePrefsCallbacks() { final ListPreference pref = (ListPreference)findPreference(getString(R.string.pref_map_style)); if (pref == null) return; String curTheme = Config.getUiThemeSettings(); pref.setValue(curTheme); pref.setSummary(pref.getEntry()); pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { String themeName = (String)newValue; if (!Config.setUiThemeSettings(themeName)) return true; ThemeSwitcher.restart(false); Statistics.INSTANCE.trackEvent(Statistics.EventName.Settings.MAP_STYLE, Statistics.params().add(Statistics.EventParam.NAME, themeName)); UiThread.runLater(new Runnable() { @Override public void run() { pref.setSummary(pref.getEntry()); } }); return true; } }); } private void initZoomPrefsCallbacks() { Preference pref = findPreference(getString(R.string.pref_show_zoom_buttons)); if (pref == null) return; ((TwoStatePreference)pref).setChecked(Config.showZoomButtons()); pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { Statistics.INSTANCE.trackEvent(Statistics.EventName.Settings.ZOOM); Config.setShowZoomButtons((Boolean) newValue); return true; } }); } private void initMeasureUnitsPrefsCallbacks() { Preference pref = findPreference(getString(R.string.pref_munits)); if (pref == null) return; ((ListPreference)pref).setValue(String.valueOf(UnitLocale.getUnits())); pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { UnitLocale.setUnits(Integer.parseInt((String) newValue)); Statistics.INSTANCE.trackEvent(Statistics.EventName.Settings.UNITS); AlohaHelper.logClick(AlohaHelper.Settings.CHANGE_UNITS); return true; } }); } private void initStoragePrefCallbacks() { if (mStoragePref == null) return; mStoragePref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { if (MapManager.nativeIsDownloading()) new AlertDialog.Builder(getActivity()) .setTitle(getString(R.string.downloading_is_active)) .setMessage(getString(R.string.cant_change_this_setting)) .setPositiveButton(getString(R.string.ok), null) .show(); else // getSettingsActivity().switchToFragment(StoragePathFragment.class, R.string.maps_storage); getSettingsActivity().replaceFragment(StoragePathFragment.class, getString(R.string.maps_storage), null); return true; } }); } @Override public void onAttach(Context context) { super.onAttach(context); if (!(context instanceof Activity)) return; mPathManager.startExternalStorageWatching((Activity) context, new StoragePathManager.OnStorageListChangedListener() { @Override public void onStorageListChanged(List<StorageItem> storageItems, int currentStorageIndex) { updateStoragePrefs(); } }, null); } @Override public void onDetach() { super.onDetach(); mPathManager.stopExternalStorageWatching(); } }
package com.mapswithme.maps.widget.placepage; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.location.Location; import android.os.Build; import android.support.annotation.ColorInt; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.NestedScrollView; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.Html; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.TextUtils; import android.text.style.ForegroundColorSpan; import android.text.util.Linkify; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.widget.GridView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupMenu; import android.widget.RelativeLayout; import android.widget.TextView; import com.mapswithme.maps.Framework; import com.mapswithme.maps.MwmActivity; import com.mapswithme.maps.MwmApplication; import com.mapswithme.maps.R; import com.mapswithme.maps.ads.LocalAdInfo; import com.mapswithme.maps.api.ParsedMwmRequest; import com.mapswithme.maps.base.Detachable; import com.mapswithme.maps.bookmarks.PlaceDescriptionActivity; import com.mapswithme.maps.bookmarks.PlaceDescriptionFragment; import com.mapswithme.maps.bookmarks.data.Bookmark; import com.mapswithme.maps.bookmarks.data.BookmarkManager; import com.mapswithme.maps.bookmarks.data.DistanceAndAzimut; import com.mapswithme.maps.bookmarks.data.MapObject; import com.mapswithme.maps.bookmarks.data.Metadata; import com.mapswithme.maps.bookmarks.data.RoadWarningMarkType; import com.mapswithme.maps.downloader.CountryItem; import com.mapswithme.maps.downloader.DownloaderStatusIcon; import com.mapswithme.maps.downloader.MapManager; import com.mapswithme.maps.editor.Editor; import com.mapswithme.maps.editor.OpeningHours; import com.mapswithme.maps.editor.data.TimeFormatUtils; import com.mapswithme.maps.editor.data.Timetable; import com.mapswithme.maps.gallery.Constants; import com.mapswithme.maps.gallery.FullScreenGalleryActivity; import com.mapswithme.maps.gallery.GalleryActivity; import com.mapswithme.maps.gallery.Items; import com.mapswithme.maps.gallery.impl.BaseItemSelectedListener; import com.mapswithme.maps.gallery.impl.Factory; import com.mapswithme.maps.gallery.impl.RegularCatalogPromoListener; import com.mapswithme.maps.location.LocationHelper; import com.mapswithme.maps.metrics.UserActionsLogger; import com.mapswithme.maps.promo.Promo; import com.mapswithme.maps.promo.PromoCityGallery; import com.mapswithme.maps.promo.PromoEntity; import com.mapswithme.maps.review.Review; import com.mapswithme.maps.routing.RoutingController; import com.mapswithme.maps.search.FilterUtils; import com.mapswithme.maps.search.HotelsFilter; import com.mapswithme.maps.search.Popularity; import com.mapswithme.maps.settings.RoadType; import com.mapswithme.maps.taxi.TaxiType; import com.mapswithme.maps.ugc.Impress; import com.mapswithme.maps.ugc.UGCController; import com.mapswithme.maps.widget.ArrowView; import com.mapswithme.maps.widget.LineCountTextView; import com.mapswithme.maps.widget.RatingView; import com.mapswithme.maps.widget.recycler.ItemDecoratorFactory; import com.mapswithme.maps.widget.recycler.RecyclerClickListener; import com.mapswithme.util.ConnectionState; import com.mapswithme.util.Graphics; import com.mapswithme.util.NetworkPolicy; import com.mapswithme.util.SponsoredLinks; import com.mapswithme.util.StringUtils; import com.mapswithme.util.ThemeUtils; import com.mapswithme.util.UTM; import com.mapswithme.util.UiUtils; import com.mapswithme.util.Utils; import com.mapswithme.util.concurrency.UiThread; import com.mapswithme.util.log.Logger; import com.mapswithme.util.log.LoggerFactory; import com.mapswithme.util.sharing.ShareOption; import com.mapswithme.util.statistics.AlohaHelper; import com.mapswithme.util.statistics.GalleryPlacement; import com.mapswithme.util.statistics.GalleryType; import com.mapswithme.util.statistics.Statistics; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Objects; import static com.mapswithme.maps.widget.placepage.PlacePageButtons.Item.BOOKING; import static com.mapswithme.util.statistics.Statistics.EventName.PP_HOTEL_DESCRIPTION_LAND; import static com.mapswithme.util.statistics.Statistics.EventName.PP_HOTEL_FACILITIES; import static com.mapswithme.util.statistics.Statistics.EventName.PP_HOTEL_GALLERY_OPEN; import static com.mapswithme.util.statistics.Statistics.EventName.PP_HOTEL_REVIEWS_LAND; import static com.mapswithme.util.statistics.Statistics.EventName.PP_SPONSORED_ACTION; import static com.mapswithme.util.statistics.Statistics.EventName.PP_SPONSORED_DETAILS; import static com.mapswithme.util.statistics.Statistics.EventName.PP_SPONSORED_OPENTABLE; public class PlacePageView extends NestedScrollView implements View.OnClickListener, View.OnLongClickListener, Sponsored.OnPriceReceivedListener, Sponsored.OnHotelInfoReceivedListener, LineCountTextView.OnLineCountCalculatedListener, RecyclerClickListener, NearbyAdapter.OnItemClickListener, EditBookmarkFragment.EditBookmarkListener, Detachable<Activity>, Promo.Listener { private static final Logger LOGGER = LoggerFactory.INSTANCE.getLogger(LoggerFactory.Type.MISC); private static final String TAG = PlacePageView.class.getSimpleName(); private static final String PREF_USE_DMS = "use_dms"; private static final String DISCOUNT_PREFIX = "-"; private static final String DISCOUNT_SUFFIX = "%"; private boolean mIsDocked; private boolean mIsFloating; // Preview. private ViewGroup mPreview; private Toolbar mToolbar; private TextView mTvTitle; private TextView mTvSecondaryTitle; private TextView mTvSubtitle; private ArrowView mAvDirection; private TextView mTvDistance; private TextView mTvAddress; private View mPreviewRatingInfo; private RatingView mRatingView; private TextView mTvSponsoredPrice; @SuppressWarnings("NullableProblems") @NonNull private RatingView mHotelDiscount; private View mPhone; private TextView mTvPhone; private View mWebsite; private TextView mTvWebsite; private TextView mTvLatlon; private View mOpeningHours; private TextView mFullOpeningHours; private TextView mTodayOpeningHours; private View mWifi; private View mEmail; private TextView mTvEmail; private View mOperator; private TextView mTvOperator; private View mCuisine; private TextView mTvCuisine; private View mWiki; private View mEntrance; private TextView mTvEntrance; private View mTaxiShadow; private View mTaxiDivider; private View mTaxi; private View mEditPlace; private View mAddOrganisation; private View mAddPlace; private View mLocalAd; private TextView mTvLocalAd; private View mEditTopSpace; // Bookmark private View mBookmarkFrame; private WebView mWvBookmarkNote; private TextView mTvBookmarkNote; private boolean mBookmarkSet; // Place page buttons private PlacePageButtons mButtons; private ImageView mBookmarkButtonIcon; // Hotel private View mHotelDescription; private LineCountTextView mTvHotelDescription; private View mHotelMoreDescription; private View mHotelFacilities; private View mHotelMoreFacilities; private View mHotelGallery; private RecyclerView mRvHotelGallery; private View mHotelNearby; private View mHotelReview; private TextView mHotelRating; private TextView mHotelRatingBase; private View mHotelMore; @Nullable private View mBookmarkButtonFrame; @SuppressWarnings("NullableProblems") @NonNull private View mPlaceDescriptionContainer; @SuppressWarnings("NullableProblems") @NonNull private TextView mPlaceDescriptionView; @SuppressWarnings("NullableProblems") @NonNull private View mPlaceDescriptionMoreBtn; @SuppressWarnings("NullableProblems") @NonNull private View mPopularityView; @SuppressWarnings("NullableProblems") @NonNull private UGCController mUgcController; // Data @Nullable private MapObject mMapObject; @Nullable private Sponsored mSponsored; private String mSponsoredPrice; private boolean mIsLatLonDms; @NonNull private final FacilitiesAdapter mFacilitiesAdapter = new FacilitiesAdapter(); @NonNull private final com.mapswithme.maps.widget.placepage.GalleryAdapter mGalleryAdapter; @NonNull private final NearbyAdapter mNearbyAdapter = new NearbyAdapter(this); @NonNull private final ReviewAdapter mReviewAdapter = new ReviewAdapter(); // Downloader`s stuff private DownloaderStatusIcon mDownloaderIcon; private TextView mDownloaderInfo; private int mStorageCallbackSlot; @Nullable private CountryItem mCurrentCountry; private boolean mScrollable = true; private final MapManager.StorageCallback mStorageCallback = new MapManager.StorageCallback() { @Override public void onStatusChanged(List<MapManager.StorageCallbackData> data) { if (mCurrentCountry == null) return; for (MapManager.StorageCallbackData item : data) if (mCurrentCountry.id.equals(item.countryId)) { updateDownloader(); return; } } @Override public void onProgress(String countryId, long localSize, long remoteSize) { if (mCurrentCountry != null && mCurrentCountry.id.equals(countryId)) updateDownloader(); } }; private final Runnable mDownloaderDeferredDetachProc = new Runnable() { @Override public void run() { detachCountry(); } }; @NonNull private final EditBookmarkClickListener mEditBookmarkClickListener = new EditBookmarkClickListener(); @NonNull private OnClickListener mDownloadClickListener = new OnClickListener() { @Override public void onClick(View v) { MapManager.warn3gAndDownload(getActivity(), mCurrentCountry.id, this::onDownloadClick); } private void onDownloadClick() { String scenario = mCurrentCountry.isExpandable() ? "download_group" : "download"; Statistics.INSTANCE.trackEvent(Statistics.EventName.DOWNLOADER_ACTION, Statistics.params() .add(Statistics.EventParam.ACTION, "download") .add(Statistics.EventParam.FROM, "placepage") .add("is_auto", "false") .add("scenario", scenario)); } }; @NonNull private OnClickListener mCancelDownloadListener = new OnClickListener() { @Override public void onClick(View v) { MapManager.nativeCancel(mCurrentCountry.id); Statistics.INSTANCE.trackEvent(Statistics.EventName.DOWNLOADER_CANCEL, Statistics.params() .add(Statistics.EventParam.FROM, "placepage")); } }; @SuppressWarnings("NullableProblems") @NonNull private PlacePageButtonsListener mPlacePageButtonsListener; @Nullable private Closable mClosable; @Nullable private RoutingModeListener mRoutingModeListener; @SuppressWarnings("NullableProblems") @NonNull private RecyclerView mCatalogPromoRecycler; @SuppressWarnings("NullableProblems") @NonNull private View mCatalogPromoTitleView; @SuppressWarnings("NullableProblems") @NonNull private com.mapswithme.maps.gallery.GalleryAdapter mCatalogPromoLoadingAdapter; void setScrollable(boolean scrollable) { mScrollable = scrollable; } void addClosable(@NonNull Closable closable) { mClosable = closable; } @Override public boolean onTouchEvent(MotionEvent ev) { switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: return mScrollable && super.onTouchEvent(ev); default: return super.onTouchEvent(ev); } } @Override public boolean onInterceptTouchEvent(MotionEvent event) { return mScrollable && super.onInterceptTouchEvent(event); } @Override public void attach(@NonNull Activity object) { Promo.INSTANCE.setListener(this); } @Override public void detach() { Promo.INSTANCE.setListener(null); } @Override public void onCityGalleryReceived(@NonNull PromoCityGallery gallery) { String url = gallery.getMoreUrl(); RegularCatalogPromoListener promoListener = new RegularCatalogPromoListener(getActivity(), GalleryPlacement.PLACEPAGE); com.mapswithme.maps.gallery.GalleryAdapter adapter = Factory.createCatalogPromoAdapter(getContext(), gallery, url, promoListener, GalleryPlacement.PLACEPAGE); mCatalogPromoRecycler.setAdapter(adapter); } @Override public void onErrorReceived() { com.mapswithme.maps.gallery.GalleryAdapter adapter = Factory.createCatalogPromoErrorAdapter(null); mCatalogPromoRecycler.setAdapter(adapter); Statistics.INSTANCE.trackGalleryError(GalleryType.PROMO, GalleryPlacement.PLACEPAGE, Statistics.ParamValue.NO_PRODUCTS); } public interface SetMapObjectListener { void onSetMapObjectComplete(@NonNull NetworkPolicy policy, boolean isSameObject); } public PlacePageView(Context context) { this(context, null, 0); } public PlacePageView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public PlacePageView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs); mIsLatLonDms = MwmApplication.prefs().getBoolean(PREF_USE_DMS, false); mGalleryAdapter = new com.mapswithme.maps.widget.placepage.GalleryAdapter(context); init(attrs, defStyleAttr); } @Override protected void onFinishInflate() { super.onFinishInflate(); mPreview = findViewById(R.id.pp__preview); mTvTitle = mPreview.findViewById(R.id.tv__title); mPopularityView = findViewById(R.id.popular_rating_view); mTvSecondaryTitle = mPreview.findViewById(R.id.tv__secondary_title); mToolbar = findViewById(R.id.toolbar); mTvSubtitle = mPreview.findViewById(R.id.tv__subtitle); View directionFrame = mPreview.findViewById(R.id.direction_frame); mTvDistance = mPreview.findViewById(R.id.tv__straight_distance); mAvDirection = mPreview.findViewById(R.id.av__direction); directionFrame.setOnClickListener(this); mTvAddress = mPreview.findViewById(R.id.tv__address); mPreview.findViewById(R.id.search_hotels_btn).setOnClickListener(this); mPreviewRatingInfo = mPreview.findViewById(R.id.preview_rating_info); mRatingView = mPreviewRatingInfo.findViewById(R.id.rating_view); mTvSponsoredPrice = mPreviewRatingInfo.findViewById(R.id.tv__hotel_price); mHotelDiscount = mPreviewRatingInfo.findViewById(R.id.discount_in_percents); RelativeLayout address = findViewById(R.id.ll__place_name); mPhone = findViewById(R.id.ll__place_phone); mPhone.setOnClickListener(this); mTvPhone = findViewById(R.id.tv__place_phone); mWebsite = findViewById(R.id.ll__place_website); mWebsite.setOnClickListener(this); mTvWebsite = findViewById(R.id.tv__place_website); LinearLayout latlon = findViewById(R.id.ll__place_latlon); latlon.setOnClickListener(this); mTvLatlon = findViewById(R.id.tv__place_latlon); mOpeningHours = findViewById(R.id.ll__place_schedule); mFullOpeningHours = findViewById(R.id.opening_hours); mTodayOpeningHours = findViewById(R.id.today_opening_hours); mWifi = findViewById(R.id.ll__place_wifi); mEmail = findViewById(R.id.ll__place_email); mEmail.setOnClickListener(this); mTvEmail = findViewById(R.id.tv__place_email); mOperator = findViewById(R.id.ll__place_operator); mOperator.setOnClickListener(this); mTvOperator = findViewById(R.id.tv__place_operator); mCuisine = findViewById(R.id.ll__place_cuisine); mTvCuisine = findViewById(R.id.tv__place_cuisine); mWiki = findViewById(R.id.ll__place_wiki); mWiki.setOnClickListener(this); mEntrance = findViewById(R.id.ll__place_entrance); mTvEntrance = mEntrance.findViewById(R.id.tv__place_entrance); mTaxiShadow = findViewById(R.id.place_page_taxi_shadow); mTaxiDivider = findViewById(R.id.place_page_taxi_divider); mTaxi = findViewById(R.id.ll__place_page_taxi); TextView orderTaxi = mTaxi.findViewById(R.id.tv__place_page_order_taxi); orderTaxi.setOnClickListener(this); mEditPlace = findViewById(R.id.ll__place_editor); mEditPlace.setOnClickListener(this); mAddOrganisation = findViewById(R.id.ll__add_organisation); mAddOrganisation.setOnClickListener(this); mAddPlace = findViewById(R.id.ll__place_add); mAddPlace.setOnClickListener(this); mLocalAd = findViewById(R.id.ll__local_ad); mLocalAd.setOnClickListener(this); mTvLocalAd = mLocalAd.findViewById(R.id.tv__local_ad); mEditTopSpace = findViewById(R.id.edit_top_space); latlon.setOnLongClickListener(this); address.setOnLongClickListener(this); mPhone.setOnLongClickListener(this); mWebsite.setOnLongClickListener(this); mOpeningHours.setOnLongClickListener(this); mEmail.setOnLongClickListener(this); mOperator.setOnLongClickListener(this); mWiki.setOnLongClickListener(this); mBookmarkFrame = findViewById(R.id.bookmark_frame); mWvBookmarkNote = mBookmarkFrame.findViewById(R.id.wv__bookmark_notes); mWvBookmarkNote.getSettings().setJavaScriptEnabled(false); mTvBookmarkNote = mBookmarkFrame.findViewById(R.id.tv__bookmark_notes); initEditMapObjectBtn(); mHotelMore = findViewById(R.id.ll__more); mHotelMore.setOnClickListener(this); initHotelDescriptionView(); initHotelFacilitiesView(); initHotelGalleryView(); initHotelNearbyView(); initHotelRatingView(); initCatalogPromoView(); mUgcController = new UGCController(this); mDownloaderIcon = new DownloaderStatusIcon(mPreview.findViewById(R.id.downloader_status_frame)); mDownloaderInfo = mPreview.findViewById(R.id.tv__downloader_details); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) setElevation(UiUtils.dimen(R.dimen.placepage_elevation)); if (UiUtils.isLandscape(getContext())) setBackgroundResource(0); Sponsored.setPriceListener(this); Sponsored.setInfoListener(this); initPlaceDescriptionView(); } public void initButtons(@NonNull ViewGroup buttons, @NonNull PlacePageButtonsListener listener) { mPlacePageButtonsListener = listener; mButtons = new PlacePageButtons(this, buttons, new PlacePageButtons.ItemListener() { public void onPrepareVisibleView(@NonNull PlacePageButtons.PlacePageButton item, @NonNull View frame, @NonNull ImageView icon, @NonNull TextView title) { int color; switch (item.getType()) { case BOOKING: case BOOKING_SEARCH: case OPENTABLE: // Warning: the following code is autogenerated. // Do NOT change it manually. // %PartnersExtender.Switch case PARTNER1: case PARTNER3: case PARTNER18: case PARTNER19: case PARTNER20: // /%PartnersExtender.Switch // End of autogenerated code. frame.setBackgroundResource(item.getBackgroundResource()); color = Color.WHITE; break; case PARTNER2: frame.setBackgroundResource(item.getBackgroundResource()); color = Color.BLACK; break; case BOOKMARK: mBookmarkButtonIcon = icon; mBookmarkButtonFrame = frame; updateBookmarkButton(); color = ThemeUtils.getColor(getContext(), R.attr.iconTint); break; default: color = ThemeUtils.getColor(getContext(), R.attr.iconTint); icon.setColorFilter(color); break; } title.setTextColor(color); } @Override public void onItemClick(PlacePageButtons.PlacePageButton item) { switch (item.getType()) { case BOOKMARK: onBookmarkBtnClicked(); break; case SHARE: onShareBtnClicked(); break; case BACK: onBackBtnClicked(); break; case ROUTE_FROM: onRouteFromBtnClicked(); break; case ROUTE_TO: onRouteToBtnClicked(); break; case ROUTE_ADD: onRouteAddBtnClicked(); break; case ROUTE_REMOVE: onRouteRemoveBtnClicked(); break; case ROUTE_AVOID_TOLL: onAvoidTollBtnClicked(); break; case ROUTE_AVOID_UNPAVED: onAvoidUnpavedBtnClicked(); break; case ROUTE_AVOID_FERRY: onAvoidFerryBtnClicked(); break; case BOOKING: case OPENTABLE: // Warning: the following code is autogenerated. // Do NOT change it manually. // %PartnersExtender.SwitchClick case PARTNER1: case PARTNER2: case PARTNER3: case PARTNER18: case PARTNER19: case PARTNER20: // /%PartnersExtender.SwitchClick // End of autogenerated code. onSponsoredClick(true /* book */, false); break; case BOOKING_SEARCH: onBookingSearchBtnClicked(); break; case CALL: onCallBtnClicked(); break; } } }); } private void onBookmarkBtnClicked() { if (mMapObject == null) { LOGGER.e(TAG, "Bookmark cannot be managed, mMapObject is null!"); return; } Statistics.INSTANCE.trackEvent(Statistics.EventName.PP_BOOKMARK); AlohaHelper.logClick(AlohaHelper.PP_BOOKMARK); toggleIsBookmark(mMapObject); mPlacePageButtonsListener.onBookmarkSet(mBookmarkSet); } private void onShareBtnClicked() { if (mMapObject == null) { LOGGER.e(TAG, "A map object cannot be shared, it's null!"); return; } Statistics.INSTANCE.trackEvent(Statistics.EventName.PP_SHARE); AlohaHelper.logClick(AlohaHelper.PP_SHARE); ShareOption.ANY.shareMapObject(getActivity(), mMapObject, mSponsored); } private void onBackBtnClicked() { if (mMapObject == null) { LOGGER.e(TAG, "A mwm request cannot be handled, mMapObject is null!"); getActivity().finish(); return; } if (ParsedMwmRequest.hasRequest()) { ParsedMwmRequest request = ParsedMwmRequest.getCurrentRequest(); if (ParsedMwmRequest.isPickPointMode()) request.setPointData(mMapObject.getLat(), mMapObject.getLon(), mMapObject.getTitle(), ""); request.sendResponseAndFinish(getActivity(), true); } else getActivity().finish(); } private void onRouteFromBtnClicked() { RoutingController controller = RoutingController.get(); if (!controller.isPlanning()) { controller.prepare(mMapObject, null); close(); } else if (controller.setStartPoint(mMapObject)) { close(); } } private void onRouteToBtnClicked() { if (RoutingController.get().isPlanning()) { RoutingController.get().setEndPoint(mMapObject); close(); } else { getActivity().startLocationToPoint(getMapObject(), true); } } private void onRouteAddBtnClicked() { if (mMapObject != null) RoutingController.get().addStop(mMapObject); } private void onRouteRemoveBtnClicked() { if (mMapObject != null) RoutingController.get().removeStop(mMapObject); } private void onCallBtnClicked() { Utils.callPhone(getContext(), mTvPhone.getText().toString()); } private void onBookingSearchBtnClicked() { if (mMapObject != null && !TextUtils.isEmpty(mMapObject.getBookingSearchUrl())) { Statistics.INSTANCE.trackBookingSearchEvent(mMapObject); Utils.openUrl(getContext(), mMapObject.getBookingSearchUrl()); } } public void setRoutingModeListener(@Nullable RoutingModeListener routingModeListener) { mRoutingModeListener = routingModeListener; } private void onAvoidUnpavedBtnClicked() { onAvoidBtnClicked(RoadType.Dirty); } private void onAvoidFerryBtnClicked() { onAvoidBtnClicked(RoadType.Ferry); } private void onAvoidTollBtnClicked() { onAvoidBtnClicked(RoadType.Toll); } private void onAvoidBtnClicked(@NonNull RoadType roadType) { if (mRoutingModeListener == null) return; mRoutingModeListener.toggleRouteSettings(roadType); Statistics.INSTANCE.trackEvent(Statistics.EventName.PP_DRIVING_OPTIONS_ACTION, Statistics.params().add(Statistics.EventParam.TYPE, roadType.name())); } private void initPlaceDescriptionView() { mPlaceDescriptionContainer = findViewById(R.id.poi_description_container); mPlaceDescriptionView = findViewById(R.id.poi_description); mPlaceDescriptionMoreBtn = findViewById(R.id.more_btn); mPlaceDescriptionMoreBtn.setOnClickListener(v -> showDescriptionScreen()); } private void showDescriptionScreen() { Statistics.INSTANCE.trackEvent(Statistics.EventName.PLACEPAGE_DESCRIPTION_MORE); Context context = mPlaceDescriptionContainer.getContext(); String description = Objects.requireNonNull(mMapObject).getDescription(); Intent intent = new Intent(context, PlaceDescriptionActivity.class) .putExtra(PlaceDescriptionFragment.EXTRA_DESCRIPTION, description); context.startActivity(intent); } private void initEditMapObjectBtn() { boolean isEditSupported = isEditableMapObject(); View editBookmarkBtn = mBookmarkFrame.findViewById(R.id.tv__bookmark_edit); UiUtils.showIf(isEditSupported, editBookmarkBtn); editBookmarkBtn.setOnClickListener(isEditSupported ? mEditBookmarkClickListener : null); } public boolean isEditableMapObject() { boolean isBookmark = MapObject.isOfType(MapObject.BOOKMARK, mMapObject); if (isBookmark) { long id = Utils.<Bookmark>castTo(mMapObject).getBookmarkId(); return BookmarkManager.INSTANCE.isEditableBookmark(id); } return true; } private void initHotelRatingView() { mHotelReview = findViewById(R.id.ll__place_hotel_rating); RecyclerView rvHotelReview = findViewById(R.id.rv__place_hotel_review); rvHotelReview.setLayoutManager(new LinearLayoutManager(getContext())); rvHotelReview.getLayoutManager().setAutoMeasureEnabled(true); rvHotelReview.setNestedScrollingEnabled(false); rvHotelReview.setHasFixedSize(false); rvHotelReview.setAdapter(mReviewAdapter); mHotelRating = findViewById(R.id.tv__place_hotel_rating); mHotelRatingBase = findViewById(R.id.tv__place_hotel_rating_base); View hotelMoreReviews = findViewById(R.id.tv__place_hotel_reviews_more); hotelMoreReviews.setOnClickListener(this); } private void initHotelNearbyView() { mHotelNearby = findViewById(R.id.ll__place_hotel_nearby); GridView gvHotelNearby = findViewById(R.id.gv__place_hotel_nearby); gvHotelNearby.setAdapter(mNearbyAdapter); } private void initHotelGalleryView() { mHotelGallery = findViewById(R.id.ll__place_hotel_gallery); mRvHotelGallery = findViewById(R.id.rv__place_hotel_gallery); mRvHotelGallery.setNestedScrollingEnabled(false); LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false); mRvHotelGallery.setLayoutManager(layoutManager); RecyclerView.ItemDecoration decor = ItemDecoratorFactory .createHotelGalleryDecorator(getContext(), LinearLayoutManager.HORIZONTAL); mRvHotelGallery.addItemDecoration(decor); mGalleryAdapter.setListener(this); mRvHotelGallery.setAdapter(mGalleryAdapter); } private void initCatalogPromoView() { mCatalogPromoRecycler = findViewById(R.id.catalog_promo_recycler); mCatalogPromoTitleView = findViewById(R.id.catalog_promo_title); mCatalogPromoLoadingAdapter = Factory.createCatalogPromoLoadingAdapter(); mCatalogPromoRecycler.setNestedScrollingEnabled(false); LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false); mCatalogPromoRecycler.setLayoutManager(layoutManager); RecyclerView.ItemDecoration decor = ItemDecoratorFactory.createSponsoredGalleryDecorator(getContext(), LinearLayoutManager.HORIZONTAL); mCatalogPromoRecycler.addItemDecoration(decor); mCatalogPromoRecycler.setAdapter(mCatalogPromoLoadingAdapter); } private void initHotelFacilitiesView() { mHotelFacilities = findViewById(R.id.ll__place_hotel_facilities); RecyclerView rvHotelFacilities = findViewById(R.id.rv__place_hotel_facilities); rvHotelFacilities.setLayoutManager(new GridLayoutManager(getContext(), 2)); rvHotelFacilities.getLayoutManager().setAutoMeasureEnabled(true); rvHotelFacilities.setNestedScrollingEnabled(false); rvHotelFacilities.setHasFixedSize(false); mHotelMoreFacilities = findViewById(R.id.tv__place_hotel_facilities_more); rvHotelFacilities.setAdapter(mFacilitiesAdapter); mHotelMoreFacilities.setOnClickListener(this); } private void initHotelDescriptionView() { mHotelDescription = findViewById(R.id.ll__place_hotel_description); mTvHotelDescription = findViewById(R.id.tv__place_hotel_details); mHotelMoreDescription = findViewById(R.id.tv__place_hotel_more); View hotelMoreDescriptionOnWeb = findViewById(R.id.tv__place_hotel_more_on_web); mTvHotelDescription.setListener(this); mHotelMoreDescription.setOnClickListener(this); hotelMoreDescriptionOnWeb.setOnClickListener(this); } @Override public void onPriceReceived(@NonNull HotelPriceInfo priceInfo) { if (mSponsored == null || !TextUtils.equals(priceInfo.getId(), mSponsored.getId())) return; String price = makePrice(getContext(), priceInfo); if (price != null) mSponsoredPrice = price; if (mMapObject == null) { LOGGER.e(TAG, "A sponsored info cannot be updated, mMapObject is null!"); return; } refreshPreview(mMapObject, priceInfo); } @Nullable private static String makePrice(@NonNull Context context, @NonNull HotelPriceInfo priceInfo) { if (TextUtils.isEmpty(priceInfo.getPrice()) || TextUtils.isEmpty(priceInfo.getCurrency())) return null; String text = Utils.formatCurrencyString(priceInfo.getPrice(), priceInfo.getCurrency()); return context.getString(R.string.place_page_starting_from, text); } @Override public void onHotelInfoReceived(@NonNull String id, @NonNull Sponsored.HotelInfo info) { if (mSponsored == null || !TextUtils.equals(id, mSponsored.getId())) return; updateHotelDetails(info); updateHotelFacilities(info); updateHotelGallery(info); updateHotelNearby(info); updateHotelRating(info); } private void updateHotelRating(@NonNull Sponsored.HotelInfo info) { if (info.mReviews == null || info.mReviews.length == 0) { UiUtils.hide(mHotelReview); } else { UiUtils.show(mHotelReview); mReviewAdapter.setItems(new ArrayList<>(Arrays.asList(info.mReviews))); //noinspection ConstantConditions mHotelRating.setText(mSponsored.getRating()); int reviewsCount = (int) info.mReviewsAmount; String text = getResources().getQuantityString( R.plurals.placepage_summary_rating_description, reviewsCount, reviewsCount); mHotelRatingBase.setText(text); TextView previewReviewCountView = mPreviewRatingInfo.findViewById(R.id.tv__review_count); previewReviewCountView.setText(text); } } private void updateHotelNearby(@NonNull Sponsored.HotelInfo info) { if (info.mNearby == null || info.mNearby.length == 0) { UiUtils.hide(mHotelNearby); } else { UiUtils.show(mHotelNearby); mNearbyAdapter.setItems(Arrays.asList(info.mNearby)); } } private void updateHotelGallery(@NonNull Sponsored.HotelInfo info) { if (info.mPhotos == null || info.mPhotos.length == 0) { UiUtils.hide(mHotelGallery); } else { UiUtils.show(mHotelGallery); mGalleryAdapter.setItems(new ArrayList<>(Arrays.asList(info.mPhotos))); mRvHotelGallery.scrollToPosition(0); } } private void updateHotelFacilities(@NonNull Sponsored.HotelInfo info) { if (info.mFacilities == null || info.mFacilities.length == 0) { UiUtils.hide(mHotelFacilities); } else { UiUtils.show(mHotelFacilities); mFacilitiesAdapter.setShowAll(false); mFacilitiesAdapter.setItems(Arrays.asList(info.mFacilities)); mHotelMoreFacilities.setVisibility(info.mFacilities.length > FacilitiesAdapter.MAX_COUNT ? VISIBLE : GONE); } } private void updateHotelDetails(@NonNull Sponsored.HotelInfo info) { mTvHotelDescription.setMaxLines(getResources().getInteger(R.integer.pp_hotel_description_lines)); refreshMetadataOrHide(info.mDescription, mHotelDescription, mTvHotelDescription); mHotelMoreDescription.setVisibility(GONE); } private void clearHotelViews() { mTvHotelDescription.setText(""); mHotelMoreDescription.setVisibility(GONE); mFacilitiesAdapter.setItems(Collections.emptyList()); mHotelMoreFacilities.setVisibility(GONE); mGalleryAdapter.setItems(new ArrayList<>()); mNearbyAdapter.setItems(Collections.emptyList()); mReviewAdapter.setItems(new ArrayList<Review>()); mHotelRating.setText(""); mHotelRatingBase.setText(""); mTvSponsoredPrice.setText(""); mGalleryAdapter.setItems(new ArrayList<>()); } @Override public void onLineCountCalculated(boolean grater) { UiUtils.showIf(grater, mHotelMoreDescription); } @Override public void onItemClick(View v, int position) { if (mMapObject == null || mSponsored == null) { LOGGER.e(TAG, "A photo gallery cannot be started, mMapObject/mSponsored is null!"); return; } Statistics.INSTANCE.trackHotelEvent(PP_HOTEL_GALLERY_OPEN, mSponsored, mMapObject); if (position == com.mapswithme.maps.widget.placepage.GalleryAdapter.MAX_COUNT - 1 && mGalleryAdapter.getItems().size() > com.mapswithme.maps.widget.placepage.GalleryAdapter.MAX_COUNT) { GalleryActivity.start(getContext(), mGalleryAdapter.getItems(), mMapObject.getTitle()); } else { FullScreenGalleryActivity.start(getContext(), mGalleryAdapter.getItems(), position); } } @Override public void onItemClick(@NonNull Sponsored.NearbyObject item) { // TODO go to selected object on map } private void onSponsoredClick(final boolean book, final boolean isDetails) { Utils.checkConnection( getActivity(), R.string.common_check_internet_connection_dialog, new Utils.Proc<Boolean>() { @Override public void invoke(@NonNull Boolean result) { if (!result) return; Sponsored info = mSponsored; if (info == null) return; Utils.PartnerAppOpenMode partnerAppOpenMode = Utils.PartnerAppOpenMode.None; switch (info.getType()) { case Sponsored.TYPE_BOOKING: if (mMapObject == null) break; if (book) { partnerAppOpenMode = Utils.PartnerAppOpenMode.Direct; UserActionsLogger.logBookingBookClicked(); Statistics.INSTANCE.trackBookHotelEvent(info, mMapObject); } else if (isDetails) { UserActionsLogger.logBookingDetailsClicked(); Statistics.INSTANCE.trackHotelEvent(PP_SPONSORED_DETAILS, info, mMapObject); } else { UserActionsLogger.logBookingMoreClicked(); Statistics.INSTANCE.trackHotelEvent(PP_HOTEL_DESCRIPTION_LAND, info, mMapObject); } break; case Sponsored.TYPE_OPENTABLE: if (mMapObject != null) Statistics.INSTANCE.trackRestaurantEvent(PP_SPONSORED_OPENTABLE, info, mMapObject); break; case Sponsored.TYPE_PARTNER: if (mMapObject != null && !info.getPartnerName().isEmpty()) Statistics.INSTANCE.trackSponsoredObjectEvent(PP_SPONSORED_ACTION, info, mMapObject); break; case Sponsored.TYPE_NONE: break; } try { if (partnerAppOpenMode != Utils.PartnerAppOpenMode.None) { SponsoredLinks links = new SponsoredLinks(info.getDeepLink(), info.getUrl()); String packageName = Sponsored.getPackageName(info.getType()); Utils.openPartner(getContext(), links, packageName, partnerAppOpenMode); } else { if (book) Utils.openUrl(getContext(), info.getUrl()); else Utils.openUrl(getContext(), isDetails ? info.getDescriptionUrl() : info.getMoreUrl()); } } catch (ActivityNotFoundException e) { LOGGER.e(TAG, "Failed to handle click on sponsored: ", e); AlohaHelper.logException(e); } } }); } private void init(AttributeSet attrs, int defStyleAttr) { LayoutInflater.from(getContext()).inflate(R.layout.place_page, this); if (isInEditMode()) return; final TypedArray attrArray = getContext().obtainStyledAttributes(attrs, R.styleable.PlacePageView, defStyleAttr, 0); final int animationType = attrArray.getInt(R.styleable.PlacePageView_animationType, 0); mIsDocked = attrArray.getBoolean(R.styleable.PlacePageView_docked, false); mIsFloating = attrArray.getBoolean(R.styleable.PlacePageView_floating, false); attrArray.recycle(); } public boolean isDocked() { return mIsDocked; } public boolean isFloating() { return mIsFloating; } @Nullable public MapObject getMapObject() { return mMapObject; } /** * @param mapObject new MapObject * @param listener listener */ public void setMapObject(@Nullable MapObject mapObject, @Nullable final SetMapObjectListener listener) { if (MapObject.same(mMapObject, mapObject)) { mMapObject = mapObject; NetworkPolicy policy = NetworkPolicy.newInstance(NetworkPolicy.getCurrentNetworkUsageStatus()); refreshViews(policy); if (listener != null) { listener.onSetMapObjectComplete(policy, true); } return; } mMapObject = mapObject; mSponsored = (mMapObject == null ? null : Sponsored.nativeGetCurrent()); if (isNetworkNeeded()) { NetworkPolicy.checkNetworkPolicy(getActivity().getSupportFragmentManager(), new NetworkPolicy.NetworkPolicyListener() { @Override public void onResult(@NonNull NetworkPolicy policy) { setMapObjectInternal(policy); if (listener != null) listener.onSetMapObjectComplete(policy, false); } }); } else { NetworkPolicy policy = NetworkPolicy.newInstance(false); setMapObjectInternal(policy); if (listener != null) listener.onSetMapObjectComplete(policy, false); } } private void setMapObjectInternal(@NonNull NetworkPolicy policy) { detachCountry(); if (mMapObject != null) { clearHotelViews(); processSponsored(policy); initEditMapObjectBtn(); mUgcController.clearViewsFor(mMapObject); String country = MapManager.nativeGetSelectedCountry(); if (country != null && !RoutingController.get().isNavigating()) attachCountry(country); } refreshViews(policy); } private void processSponsored(@NonNull NetworkPolicy policy) { updateCatalogPromoGallery(policy); if (mSponsored == null || mMapObject == null) return; mSponsored.updateId(mMapObject); mSponsoredPrice = mSponsored.getPrice(); String currencyCode = Utils.getCurrencyCode(); if (mSponsored.getId() == null || TextUtils.isEmpty(currencyCode)) return; if (mSponsored.getType() != Sponsored.TYPE_BOOKING) return; Sponsored.requestPrice(mSponsored.getId(), currencyCode, policy); Sponsored.requestInfo(mSponsored, Locale.getDefault().toString(), policy); } private void updateCatalogPromoGallery(@NonNull NetworkPolicy policy) { boolean hasPromoGallery = mSponsored != null && mSponsored.getType() == Sponsored.TYPE_PROMO_CATALOG; toggleCatalogPromoGallery(hasPromoGallery); if (mSponsored == null || mMapObject == null) return; if (hasPromoGallery && policy.canUseNetwork()) { mCatalogPromoRecycler.setAdapter(mCatalogPromoLoadingAdapter); Promo.INSTANCE.nativeRequestCityGallery(policy, mMapObject.getLat(), mMapObject.getLon(), UTM.UTM_PLACEPAGE_GALLERY); } else if (hasPromoGallery) { ErrorCatalogPromoListener<Items.Item> listener = new ErrorCatalogPromoListener<>(getActivity(), networkPolicy -> onNetworkPolicyResult(networkPolicy, mMapObject)); com.mapswithme.maps.gallery.GalleryAdapter adapter = Factory.createCatalogPromoErrorAdapter(listener); mCatalogPromoRecycler.setAdapter(adapter); } } private void onNetworkPolicyResult(@NonNull NetworkPolicy policy, @NonNull MapObject mapObject) { if (policy.canUseNetwork()) { Promo.INSTANCE.nativeRequestCityGallery(policy, mapObject.getLat(), mapObject.getLon(), UTM.UTM_PLACEPAGE_GALLERY); mCatalogPromoRecycler.setAdapter(Factory.createCatalogPromoLoadingAdapter()); } } private boolean isNetworkNeeded() { return mMapObject != null && (isSponsored() || mMapObject.getBanners() != null); } void refreshViews(@NonNull NetworkPolicy policy) { if (mMapObject == null) { LOGGER.e(TAG, "A place page views cannot be refreshed, mMapObject is null"); return; } refreshPreview(mMapObject, null); refreshDetails(mMapObject); refreshHotelDetailViews(policy); refreshViewsInternal(mMapObject); mUgcController.getUGC(mMapObject); updateCatalogPromoGallery(policy); } private void refreshViewsInternal(@NonNull MapObject mapObject) { final Location loc = LocationHelper.INSTANCE.getSavedLocation(); switch (mapObject.getMapObjectType()) { case MapObject.BOOKMARK: refreshDistanceToObject(mapObject, loc); showBookmarkDetails(mapObject); updateBookmarkButton(); setButtons(mapObject, false, true); break; case MapObject.POI: case MapObject.SEARCH: refreshDistanceToObject(mapObject, loc); hideBookmarkDetails(); setButtons(mapObject, false, true); setPlaceDescription(mapObject); break; case MapObject.API_POINT: refreshDistanceToObject(mapObject, loc); hideBookmarkDetails(); setButtons(mapObject, true, true); break; case MapObject.MY_POSITION: refreshMyPosition(mapObject, loc); hideBookmarkDetails(); setButtons(mapObject, false, false); break; } } private void setPlaceDescription(@NonNull MapObject mapObject) { boolean isDescriptionAbsent = TextUtils.isEmpty(mapObject.getDescription()); UiUtils.hideIf(isDescriptionAbsent, mPlaceDescriptionContainer); mPlaceDescriptionView.setText(Html.fromHtml(mapObject.getDescription())); } private void colorizeSubtitle() { String text = mTvSubtitle.getText().toString(); if (TextUtils.isEmpty(text)) return; int start = text.indexOf(""); if (start > -1) { SpannableStringBuilder sb = new SpannableStringBuilder(text); sb.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.base_yellow)), start, sb.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); mTvSubtitle.setText(sb); } } private void refreshPreview(@NonNull MapObject mapObject, @Nullable HotelPriceInfo priceInfo) { UiUtils.setTextAndHideIfEmpty(mTvTitle, mapObject.getTitle()); UiUtils.setTextAndHideIfEmpty(mTvSecondaryTitle, mapObject.getSecondaryTitle()); boolean isPopular = mapObject.getPopularity().getType() == Popularity.Type.POPULAR; UiUtils.showIf(isPopular, mPopularityView); if (mToolbar != null) mToolbar.setTitle(mapObject.getTitle()); UiUtils.setTextAndHideIfEmpty(mTvSubtitle, mapObject.getSubtitle()); colorizeSubtitle(); UiUtils.hide(mAvDirection); UiUtils.setTextAndHideIfEmpty(mTvAddress, mapObject.getAddress()); boolean sponsored = isSponsored(); UiUtils.showIf(sponsored || mapObject.shouldShowUGC(), mPreviewRatingInfo); UiUtils.showIf(sponsored, mHotelDiscount); UiUtils.showIf(mapObject.getHotelType() != null, mPreview, R.id.search_hotels_btn); if (sponsored) refreshSponsoredViews(mapObject, priceInfo); } private void refreshSponsoredViews(@NonNull MapObject mapObject, @Nullable HotelPriceInfo priceInfo) { boolean isPriceEmpty = TextUtils.isEmpty(mSponsoredPrice); @SuppressWarnings("ConstantConditions") boolean isRatingEmpty = TextUtils.isEmpty(mSponsored.getRating()); Impress impress = Impress.values()[mSponsored.getImpress()]; mRatingView.setRating(impress, mSponsored.getRating()); UiUtils.showIf(!isRatingEmpty, mRatingView); mTvSponsoredPrice.setText(mSponsoredPrice); UiUtils.showIf(!isPriceEmpty, mTvSponsoredPrice); boolean isBookingInfoExist = (!isRatingEmpty || !isPriceEmpty) && mSponsored.getType() == Sponsored.TYPE_BOOKING; UiUtils.showIf(isBookingInfoExist || mapObject.shouldShowUGC(), mPreviewRatingInfo); String discount = getHotelDiscount(priceInfo); UiUtils.hideIf(TextUtils.isEmpty(discount), mHotelDiscount); mHotelDiscount.setRating(Impress.DISCOUNT, discount); } @Nullable private String getHotelDiscount(@Nullable HotelPriceInfo priceInfo) { boolean hasPercentsDiscount = priceInfo != null && priceInfo.getDiscount() > 0; if (hasPercentsDiscount) return DISCOUNT_PREFIX + priceInfo.getDiscount() + DISCOUNT_SUFFIX; return priceInfo != null && priceInfo.hasSmartDeal() ? DISCOUNT_SUFFIX : null; } private boolean isSponsored() { return mSponsored != null && mSponsored.getType() != Sponsored.TYPE_NONE; } @Nullable public Sponsored getSponsored() { return mSponsored; } private void refreshDetails(@NonNull MapObject mapObject) { refreshLatLon(mapObject); if (mSponsored == null || mSponsored.getType() != Sponsored.TYPE_BOOKING) { String website = mapObject.getMetadata(Metadata.MetadataType.FMD_WEBSITE); String url = mapObject.getMetadata(Metadata.MetadataType.FMD_URL); refreshMetadataOrHide(TextUtils.isEmpty(website) ? url : website, mWebsite, mTvWebsite); } refreshMetadataOrHide(mapObject.getMetadata(Metadata.MetadataType.FMD_PHONE_NUMBER), mPhone, mTvPhone); refreshMetadataOrHide(mapObject.getMetadata(Metadata.MetadataType.FMD_EMAIL), mEmail, mTvEmail); refreshMetadataOrHide(mapObject.getMetadata(Metadata.MetadataType.FMD_OPERATOR), mOperator, mTvOperator); refreshMetadataOrHide(Framework.nativeGetActiveObjectFormattedCuisine(), mCuisine, mTvCuisine); refreshMetadataOrHide(mapObject.getMetadata(Metadata.MetadataType.FMD_WIKIPEDIA), mWiki, null); refreshMetadataOrHide(mapObject.getMetadata(Metadata.MetadataType.FMD_INTERNET), mWifi, null); refreshMetadataOrHide(mapObject.getMetadata(Metadata.MetadataType.FMD_FLATS), mEntrance, mTvEntrance); refreshOpeningHours(mapObject); showTaxiOffer(mapObject); boolean inRouting = RoutingController.get().isNavigating() || RoutingController.get().isPlanning(); if (inRouting || MapManager.nativeIsLegacyMode()) { UiUtils.hide(mEditPlace, mAddOrganisation, mAddPlace, mLocalAd, mEditTopSpace); } else { UiUtils.showIf(Editor.nativeShouldShowEditPlace(), mEditPlace); UiUtils.showIf(Editor.nativeShouldShowAddBusiness(), mAddOrganisation); UiUtils.showIf(Editor.nativeShouldShowAddPlace(), mAddPlace); UiUtils.showIf(UiUtils.isVisible(mEditPlace) || UiUtils.isVisible(mAddOrganisation) || UiUtils.isVisible(mAddPlace), mEditTopSpace); refreshLocalAdInfo(mapObject); } setPlaceDescription(mapObject); } private void refreshHotelDetailViews(@NonNull NetworkPolicy policy) { if (mSponsored == null) { hideHotelDetailViews(); return; } boolean isConnected = ConnectionState.isConnected(); if (isConnected && policy.canUseNetwork()) showHotelDetailViews(); else hideHotelDetailViews(); if (mSponsored.getType() == Sponsored.TYPE_BOOKING) { UiUtils.hide(mWebsite); UiUtils.show(mHotelMore); } if (mSponsored.getType() != Sponsored.TYPE_BOOKING) hideHotelDetailViews(); } private void showTaxiOffer(@NonNull MapObject mapObject) { List<TaxiType> taxiTypes = mapObject.getReachableByTaxiTypes(); boolean showTaxiOffer = taxiTypes != null && !taxiTypes.isEmpty() && LocationHelper.INSTANCE.getMyPosition() != null && ConnectionState.isConnected() && mapObject.getRoadWarningMarkType() == RoadWarningMarkType.UNKNOWN; UiUtils.showIf(showTaxiOffer, mTaxi, mTaxiShadow, mTaxiDivider); if (!showTaxiOffer) return; // At this moment we display only a one taxi provider at the same time. TaxiType type = taxiTypes.get(0); ImageView logo = mTaxi.findViewById(R.id.iv__place_page_taxi); logo.setImageResource(type.getIcon()); TextView title = mTaxi.findViewById(R.id.tv__place_page_taxi); title.setText(type.getTitle()); } private void hideHotelDetailViews() { UiUtils.hide(mHotelDescription, mHotelFacilities, mHotelGallery, mHotelNearby, mHotelReview, mHotelMore); } private void showHotelDetailViews() { UiUtils.show(mHotelDescription, mHotelFacilities, mHotelGallery, mHotelNearby, mHotelReview, mHotelMore); } private void refreshLocalAdInfo(@NonNull MapObject mapObject) { LocalAdInfo localAdInfo = mapObject.getLocalAdInfo(); boolean isLocalAdAvailable = localAdInfo != null && localAdInfo.isAvailable(); if (isLocalAdAvailable && !TextUtils.isEmpty(localAdInfo.getUrl()) && !localAdInfo.isHidden()) { mTvLocalAd.setText(localAdInfo.isCustomer() ? R.string.view_campaign_button : R.string.create_campaign_button); UiUtils.show(mLocalAd); } else { UiUtils.hide(mLocalAd); } } private void refreshOpeningHours(@NonNull MapObject mapObject) { final Timetable[] timetables = OpeningHours.nativeTimetablesFromString(mapObject.getMetadata(Metadata.MetadataType.FMD_OPEN_HOURS)); if (timetables == null || timetables.length == 0) { UiUtils.hide(mOpeningHours); return; } UiUtils.show(mOpeningHours); final Resources resources = getResources(); if (timetables[0].isFullWeek()) { refreshTodayOpeningHours((timetables[0].isFullday ? resources.getString(R.string.twentyfour_seven) : resources.getString(R.string.daily) + " " + timetables[0].workingTimespan), ThemeUtils.getColor(getContext(), android.R.attr.textColorPrimary)); UiUtils.clearTextAndHide(mFullOpeningHours); return; } boolean containsCurrentWeekday = false; final int currentDay = Calendar.getInstance().get(Calendar.DAY_OF_WEEK); for (Timetable tt : timetables) { if (tt.containsWeekday(currentDay)) { containsCurrentWeekday = true; String workingTime; if (tt.isFullday) { String allDay = resources.getString(R.string.editor_time_allday); workingTime = Utils.unCapitalize(allDay); } else { workingTime = tt.workingTimespan.toString(); } refreshTodayOpeningHours(resources.getString(R.string.today) + " " + workingTime, ThemeUtils.getColor(getContext(), android.R.attr.textColorPrimary)); break; } } UiUtils.setTextAndShow(mFullOpeningHours, TimeFormatUtils.formatTimetables(timetables)); if (!containsCurrentWeekday) refreshTodayOpeningHours(resources.getString(R.string.day_off_today), resources.getColor(R.color.base_red)); } private void refreshTodayOpeningHours(String text, @ColorInt int color) { UiUtils.setTextAndShow(mTodayOpeningHours, text); mTodayOpeningHours.setTextColor(color); } private void updateBookmarkButton() { if (mBookmarkButtonIcon == null || mBookmarkButtonFrame == null) return; if (mBookmarkSet) mBookmarkButtonIcon.setImageResource(R.drawable.ic_bookmarks_on); else mBookmarkButtonIcon.setImageDrawable(Graphics.tint(getContext(), R.drawable.ic_bookmarks_off, R.attr.iconTint)); boolean isEditable = isEditableMapObject(); mBookmarkButtonFrame.setEnabled(isEditable); if (isEditable) return; final int resId = PlacePageButtons.Item.BOOKMARK.getIcon().getDisabledStateResId(); Drawable drawable = Graphics.tint(getContext(), resId, R.attr.iconTintDisabled); mBookmarkButtonIcon.setImageDrawable(drawable); } private void hideBookmarkDetails() { mBookmarkSet = false; UiUtils.hide(mBookmarkFrame); updateBookmarkButton(); } private void showBookmarkDetails(@NonNull MapObject mapObject) { mBookmarkSet = true; UiUtils.show(mBookmarkFrame); final String notes = ((Bookmark) mapObject).getBookmarkDescription(); if (TextUtils.isEmpty(notes)) { UiUtils.hide(mTvBookmarkNote, mWvBookmarkNote); return; } if (StringUtils.nativeIsHtml(notes)) { mWvBookmarkNote.loadData(notes, "text/html; charset=utf-8", null); UiUtils.show(mWvBookmarkNote); UiUtils.hide(mTvBookmarkNote); } else { mTvBookmarkNote.setText(notes); Linkify.addLinks(mTvBookmarkNote, Linkify.ALL); UiUtils.show(mTvBookmarkNote); UiUtils.hide(mWvBookmarkNote); } } @NonNull private static PlacePageButtons.Item toPlacePageButton(@NonNull RoadWarningMarkType type) { switch (type) { case DIRTY: return PlacePageButtons.Item.ROUTE_AVOID_UNPAVED; case FERRY: return PlacePageButtons.Item.ROUTE_AVOID_FERRY; case TOLL: return PlacePageButtons.Item.ROUTE_AVOID_TOLL; default: throw new AssertionError("Unsupported road warning type: " + type); } } private void setButtons(@NonNull MapObject mapObject, boolean showBackButton, boolean showRoutingButton) { List<PlacePageButtons.PlacePageButton> buttons = new ArrayList<>(); if (mapObject.getRoadWarningMarkType() != RoadWarningMarkType.UNKNOWN) { RoadWarningMarkType markType = mapObject.getRoadWarningMarkType(); PlacePageButtons.Item roadType = toPlacePageButton(markType); buttons.add(roadType); mButtons.setItems(buttons); return; } if (RoutingController.get().isRoutePoint(mapObject)) { buttons.add(PlacePageButtons.Item.ROUTE_REMOVE); mButtons.setItems(buttons); return; } if (showBackButton || ParsedMwmRequest.isPickPointMode()) buttons.add(PlacePageButtons.Item.BACK); if (mSponsored != null) { switch (mSponsored.getType()) { case Sponsored.TYPE_BOOKING: buttons.add(BOOKING); break; case Sponsored.TYPE_OPENTABLE: buttons.add(PlacePageButtons.Item.OPENTABLE); break; case Sponsored.TYPE_PARTNER: int partnerIndex = mSponsored.getPartnerIndex(); if (partnerIndex >= 0 && !mSponsored.getUrl().isEmpty()) buttons.add(PlacePageButtons.getPartnerItem(partnerIndex)); break; case Sponsored.TYPE_NONE: break; } } if (!TextUtils.isEmpty(mapObject.getBookingSearchUrl())) buttons.add(PlacePageButtons.Item.BOOKING_SEARCH); if (mapObject.hasPhoneNumber()) buttons.add(PlacePageButtons.Item.CALL); buttons.add(PlacePageButtons.Item.BOOKMARK); if (RoutingController.get().isPlanning() || showRoutingButton) { buttons.add(PlacePageButtons.Item.ROUTE_FROM); buttons.add(PlacePageButtons.Item.ROUTE_TO); if (RoutingController.get().isStopPointAllowed()) buttons.add(PlacePageButtons.Item.ROUTE_ADD); } buttons.add(PlacePageButtons.Item.SHARE); mButtons.setItems(buttons); } public void refreshLocation(Location l) { if (mMapObject == null) { LOGGER.e(TAG, "A location cannot be refreshed, mMapObject is null!"); return; } if (MapObject.isOfType(MapObject.MY_POSITION, mMapObject)) refreshMyPosition(mMapObject, l); else refreshDistanceToObject(mMapObject, l); } private void refreshMyPosition(@NonNull MapObject mapObject, Location l) { UiUtils.hide(mTvDistance); if (l == null) return; final StringBuilder builder = new StringBuilder(); if (l.hasAltitude()) { double altitude = l.getAltitude(); builder.append(altitude >= 0 ? "" : ""); builder.append(Framework.nativeFormatAltitude(altitude)); } if (l.hasSpeed()) builder.append(" ") .append(Framework.nativeFormatSpeed(l.getSpeed())); UiUtils.setTextAndHideIfEmpty(mTvSubtitle, builder.toString()); mapObject.setLat(l.getLatitude()); mapObject.setLon(l.getLongitude()); refreshLatLon(mapObject); } private void refreshDistanceToObject(@NonNull MapObject mapObject, Location l) { UiUtils.showIf(l != null, mTvDistance); if (l == null) return; mTvDistance.setVisibility(View.VISIBLE); double lat = mapObject.getLat(); double lon = mapObject.getLon(); DistanceAndAzimut distanceAndAzimuth = Framework.nativeGetDistanceAndAzimuthFromLatLon(lat, lon, l.getLatitude(), l.getLongitude(), 0.0); mTvDistance.setText(distanceAndAzimuth.getDistance()); } private void refreshLatLon(@NonNull MapObject mapObject) { final double lat = mapObject.getLat(); final double lon = mapObject.getLon(); final String[] latLon = Framework.nativeFormatLatLonToArr(lat, lon, mIsLatLonDms); if (latLon.length == 2) mTvLatlon.setText(String.format(Locale.US, "%1$s, %2$s", latLon[0], latLon[1])); } private static void refreshMetadataOrHide(String metadata, View metaLayout, TextView metaTv) { if (!TextUtils.isEmpty(metadata)) { metaLayout.setVisibility(View.VISIBLE); if (metaTv != null) metaTv.setText(metadata); } else metaLayout.setVisibility(View.GONE); } public void refreshAzimuth(double northAzimuth) { if (mMapObject == null || MapObject.isOfType(MapObject.MY_POSITION, mMapObject)) return; final Location location = LocationHelper.INSTANCE.getSavedLocation(); if (location == null) return; final double azimuth = Framework.nativeGetDistanceAndAzimuthFromLatLon(mMapObject.getLat(), mMapObject.getLon(), location.getLatitude(), location.getLongitude(), northAzimuth).getAzimuth(); if (azimuth >= 0) { UiUtils.show(mAvDirection); mAvDirection.setAzimuth(azimuth); } } private void addOrganisation() { Statistics.INSTANCE.trackEvent(Statistics.EventName.EDITOR_ADD_CLICK, Statistics.params() .add(Statistics.EventParam.FROM, "placepage")); getActivity().showPositionChooser(true, false); } private void addPlace() { // TODO add statistics getActivity().showPositionChooser(false, true); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.ll__place_editor: getActivity().showEditor(); break; case R.id.ll__add_organisation: addOrganisation(); break; case R.id.ll__place_add: addPlace(); break; case R.id.ll__local_ad: if (mMapObject != null) { LocalAdInfo localAdInfo = mMapObject.getLocalAdInfo(); if (localAdInfo == null) throw new AssertionError("A local ad must be non-null if button is shown!"); if (!TextUtils.isEmpty(localAdInfo.getUrl())) { Statistics.INSTANCE.trackPPOwnershipButtonClick(mMapObject); Utils.openUrl(getContext(), localAdInfo.getUrl()); } } break; case R.id.ll__more: onSponsoredClick(false /* book */, true /* isMoreDetails */); break; case R.id.tv__place_hotel_more_on_web: onSponsoredClick(false /* book */, false /* isMoreDetails */); break; case R.id.ll__place_latlon: mIsLatLonDms = !mIsLatLonDms; MwmApplication.prefs().edit().putBoolean(PREF_USE_DMS, mIsLatLonDms).apply(); if (mMapObject == null) { LOGGER.e(TAG, "A LatLon cannot be refreshed, mMapObject is null"); break; } refreshLatLon(mMapObject); break; case R.id.ll__place_phone: Utils.callPhone(getContext(), mTvPhone.getText().toString()); if (mMapObject != null) Framework.logLocalAdsEvent(Framework.LocalAdsEventType.LOCAL_ADS_EVENT_CLICKED_PHONE, mMapObject); break; case R.id.ll__place_website: Utils.openUrl(getContext(), mTvWebsite.getText().toString()); if (mMapObject != null) Framework.logLocalAdsEvent(Framework.LocalAdsEventType.LOCAL_ADS_EVENT_CLICKED_WEBSITE, mMapObject); break; case R.id.ll__place_wiki: // TODO: Refactor and use separate getters for Wiki and all other PP meta info too. if (mMapObject == null) { LOGGER.e(TAG, "Cannot follow url, mMapObject is null!"); break; } Utils.openUrl(getContext(), mMapObject.getMetadata(Metadata.MetadataType.FMD_WIKIPEDIA)); break; case R.id.direction_frame: Statistics.INSTANCE.trackEvent(Statistics.EventName.PP_DIRECTION_ARROW); AlohaHelper.logClick(AlohaHelper.PP_DIRECTION_ARROW); showBigDirection(); break; case R.id.ll__place_email: Utils.sendTo(getContext(), mTvEmail.getText().toString()); break; case R.id.tv__place_hotel_more: UiUtils.hide(mHotelMoreDescription); mTvHotelDescription.setMaxLines(Integer.MAX_VALUE); break; case R.id.tv__place_hotel_facilities_more: if (mSponsored != null && mMapObject != null) Statistics.INSTANCE.trackHotelEvent(PP_HOTEL_FACILITIES, mSponsored, mMapObject); UiUtils.hide(mHotelMoreFacilities); mFacilitiesAdapter.setShowAll(true); break; case R.id.tv__place_hotel_reviews_more: if (isSponsored()) { //null checking is done in 'isSponsored' method //noinspection ConstantConditions Utils.openUrl(getContext(), mSponsored.getReviewUrl()); UserActionsLogger.logBookingReviewsClicked(); if (mMapObject != null) Statistics.INSTANCE.trackHotelEvent(PP_HOTEL_REVIEWS_LAND, mSponsored, mMapObject); } break; case R.id.tv__place_page_order_taxi: RoutingController.get().prepare(LocationHelper.INSTANCE.getMyPosition(), mMapObject, Framework.ROUTER_TYPE_TAXI); close(); if (mMapObject != null) { List<TaxiType> types = mMapObject.getReachableByTaxiTypes(); if (types != null && !types.isEmpty()) { String providerName = types.get(0).getProviderName(); Statistics.INSTANCE.trackTaxiEvent(Statistics.EventName.ROUTING_TAXI_CLICK_IN_PP, providerName); } } break; case R.id.search_hotels_btn: if (mMapObject == null) break; @FilterUtils.RatingDef int filterRating = mSponsored != null ? Framework.getFilterRating(mSponsored.getRating()) : FilterUtils.RATING_ANY; HotelsFilter filter = FilterUtils.createHotelFilter(filterRating, mMapObject.getPriceRate(), mMapObject.getHotelType()); getActivity().onSearchSimilarHotels(filter); String provider = mSponsored != null && mSponsored.getType() == Sponsored.TYPE_BOOKING ? Statistics.ParamValue.BOOKING_COM : Statistics.ParamValue.OSM; Statistics.INSTANCE.trackEvent(Statistics.EventName.PP_HOTEL_SEARCH_SIMILAR, Statistics.params().add(Statistics.EventParam.PROVIDER, provider)); break; } } private void toggleIsBookmark(@NonNull MapObject mapObject) { if (MapObject.isOfType(MapObject.BOOKMARK, mapObject)) setMapObject(Framework.nativeDeleteBookmarkFromMapObject(), null); else setMapObject(BookmarkManager.INSTANCE.addNewBookmark(mapObject.getLat(), mapObject.getLon()), null); } private void showBigDirection() { final DirectionFragment fragment = (DirectionFragment) Fragment.instantiate(getActivity(), DirectionFragment.class .getName(), null); fragment.setMapObject(mMapObject); fragment.show(getActivity().getSupportFragmentManager(), null); } @Override public boolean onLongClick(View v) { final Object tag = v.getTag(); final String tagStr = tag == null ? "" : tag.toString(); AlohaHelper.logLongClick(tagStr); final PopupMenu popup = new PopupMenu(getContext(), v); final Menu menu = popup.getMenu(); final List<String> items = new ArrayList<>(); switch (v.getId()) { case R.id.ll__place_latlon: if (mMapObject == null) { LOGGER.e(TAG, "A long click tap on LatLon cannot be handled, mMapObject is null!"); break; } final double lat = mMapObject.getLat(); final double lon = mMapObject.getLon(); items.add(Framework.nativeFormatLatLon(lat, lon, false)); items.add(Framework.nativeFormatLatLon(lat, lon, true)); break; case R.id.ll__place_website: items.add(mTvWebsite.getText().toString()); break; case R.id.ll__place_email: items.add(mTvEmail.getText().toString()); break; case R.id.ll__place_phone: items.add(mTvPhone.getText().toString()); break; case R.id.ll__place_schedule: String text = UiUtils.isVisible(mFullOpeningHours) ? mFullOpeningHours.getText().toString() : mTodayOpeningHours.getText().toString(); items.add(text); break; case R.id.ll__place_operator: items.add(mTvOperator.getText().toString()); break; case R.id.ll__place_wiki: if (mMapObject == null) { LOGGER.e(TAG, "A long click tap on wiki cannot be handled, mMapObject is null!"); break; } items.add(mMapObject.getMetadata(Metadata.MetadataType.FMD_WIKIPEDIA)); break; } final String copyText = getResources().getString(android.R.string.copy); for (int i = 0; i < items.size(); i++) menu.add(Menu.NONE, i, i, String.format("%s %s", copyText, items.get(i))); popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { final int id = item.getItemId(); final Context ctx = getContext(); Utils.copyTextToClipboard(ctx, items.get(id)); Utils.toastShortcut(ctx, ctx.getString(R.string.copied_to_clipboard, items.get(id))); Statistics.INSTANCE.trackEvent(Statistics.EventName.PP_METADATA_COPY + ":" + tagStr); AlohaHelper.logClick(AlohaHelper.PP_METADATA_COPY + ":" + tagStr); return true; } }); popup.show(); return true; } private void close() { if (mClosable != null) mClosable.closePlacePage(); } void reset() { resetScroll(); detachCountry(); } void resetScroll() { scrollTo(0, 0); } private static boolean isInvalidDownloaderStatus(int status) { return (status != CountryItem.STATUS_DOWNLOADABLE && status != CountryItem.STATUS_ENQUEUED && status != CountryItem.STATUS_FAILED && status != CountryItem.STATUS_PARTLY && status != CountryItem.STATUS_PROGRESS && status != CountryItem.STATUS_APPLYING); } private void updateDownloader(CountryItem country) { if (isInvalidDownloaderStatus(country.status)) { if (mStorageCallbackSlot != 0) UiThread.runLater(mDownloaderDeferredDetachProc); return; } mDownloaderIcon.update(country); StringBuilder sb = new StringBuilder(StringUtils.getFileSizeString(country.totalSize)); if (country.isExpandable()) sb.append(String.format(Locale.US, " • %s: %d", getContext().getString(R.string.downloader_status_maps), country.totalChildCount)); mDownloaderInfo.setText(sb.toString()); } private void updateDownloader() { if (mCurrentCountry == null) return; mCurrentCountry.update(); updateDownloader(mCurrentCountry); } private void attachCountry(String country) { CountryItem map = CountryItem.fill(country); if (isInvalidDownloaderStatus(map.status)) return; mCurrentCountry = map; if (mStorageCallbackSlot == 0) mStorageCallbackSlot = MapManager.nativeSubscribe(mStorageCallback); mDownloaderIcon.setOnIconClickListener(mDownloadClickListener) .setOnCancelClickListener(mCancelDownloadListener); mDownloaderIcon.show(true); UiUtils.show(mDownloaderInfo); updateDownloader(mCurrentCountry); } private void detachCountry() { if (mStorageCallbackSlot == 0) return; MapManager.nativeUnsubscribe(mStorageCallbackSlot); mStorageCallbackSlot = 0; mCurrentCountry = null; mDownloaderIcon.setOnIconClickListener(null) .setOnCancelClickListener(null); mDownloaderIcon.show(false); UiUtils.hide(mDownloaderInfo); } MwmActivity getActivity() { return (MwmActivity) getContext(); } @Override public void onBookmarkSaved(long bookmarkId) { setMapObject(BookmarkManager.INSTANCE.getBookmark(bookmarkId), null); NetworkPolicy policy = NetworkPolicy.newInstance(NetworkPolicy.getCurrentNetworkUsageStatus()); refreshViews(policy); } int getPreviewHeight() { return mPreview.getHeight(); } public void toggleCatalogPromoGallery(boolean enabled) { UiUtils.showIf(enabled, mCatalogPromoRecycler); UiUtils.showIf(enabled, mCatalogPromoTitleView); } @NonNull public static List<PromoEntity> toEntities(@NonNull PromoCityGallery gallery) { List<PromoEntity> items = new ArrayList<>(); for (PromoCityGallery.Item each : gallery.getItems()) { PromoEntity item = new PromoEntity(Constants.TYPE_PRODUCT, each.getName(), each.getAuthor().getName(), each.getUrl(), each.getLuxCategory(), each.getImageUrl()); items.add(item); } return items; } private class EditBookmarkClickListener implements OnClickListener { @Override public void onClick(View v) { if (mMapObject == null) { LOGGER.e(TAG, "A bookmark cannot be edited, mMapObject is null!"); return; } Bookmark bookmark = (Bookmark) mMapObject; EditBookmarkFragment.editBookmark(bookmark.getCategoryId(), bookmark.getBookmarkId(), getActivity(), getActivity().getSupportFragmentManager(), PlacePageView.this); } } }
package rnxmpp.service; import android.support.annotation.Nullable; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.WritableArray; import com.facebook.react.bridge.WritableMap; import com.facebook.react.modules.core.RCTNativeAppEventEmitter; import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.packet.Presence; import org.jivesoftware.smack.roster.Roster; import org.jivesoftware.smack.roster.RosterEntry; import org.jivesoftware.smack.roster.RosterGroup; import rnxmpp.utils.Parser; public class RNXMPPCommunicationBridge implements XmppServiceListener { public static final String RNXMPP_ERROR = "RNXMPPError"; public static final String RNXMPP_LOGIN_ERROR = "RNXMPPLoginError"; public static final String RNXMPP_MESSAGE = "RNXMPPMessage"; public static final String RNXMPP_ROSTER = "RNXMPPRoster"; public static final String RNXMPP_IQ = "RNXMPPIQ"; public static final String RNXMPP_PRESENCE = "RNXMPPPresence"; public static final String RNXMPP_CONNECT = "RNXMPPConnect"; public static final String RNXMPP_DISCONNECT = "RNXMPPDisconnect"; public static final String RNXMPP_LOGIN = "RNXMPPLogin"; ReactContext reactContext; public RNXMPPCommunicationBridge(ReactContext reactContext) { this.reactContext = reactContext; } @Override public void onError(Exception e) { sendEvent(reactContext, RNXMPP_ERROR, e.getLocalizedMessage()); } @Override public void onLoginError(String errorMessage) { sendEvent(reactContext, RNXMPP_LOGIN_ERROR, errorMessage); } @Override public void onLoginError(Exception e) { this.onLoginError(e.getLocalizedMessage()); } @Override public void onMessage(Message message) { WritableMap params = Arguments.createMap(); params.putString("thread", message.getThread()); params.putString("subject", message.getSubject()); params.putString("body", message.getBody()); params.putString("from", message.getFrom()); params.putString("src", message.toXML().toString()); sendEvent(reactContext, RNXMPP_MESSAGE, params); } @Override public void onRosterReceived(Roster roster) { WritableArray rosterResponse = Arguments.createArray(); for (RosterEntry rosterEntry : roster.getEntries()) { WritableMap rosterProps = Arguments.createMap(); rosterProps.putString("username", rosterEntry.getUser()); rosterProps.putString("displayName", rosterEntry.getName()); WritableArray groupArray = Arguments.createArray(); for (RosterGroup rosterGroup : rosterEntry.getGroups()) { groupArray.pushString(rosterGroup.getName()); } rosterProps.putArray("groups", groupArray); rosterProps.putString("subscription", rosterEntry.getType().toString()); rosterResponse.pushMap(rosterProps); } sendEvent(reactContext, RNXMPP_ROSTER, rosterResponse); } @Override public void onIQ(IQ iq) { sendEvent(reactContext, RNXMPP_IQ, Parser.parse(iq.toString())); } @Override public void onPresence(Presence presence) { sendEvent(reactContext, RNXMPP_PRESENCE, presence.toString()); } @Override public void onConnnect(String username, String password) { WritableMap params = Arguments.createMap(); params.putString("username", username); params.putString("password", password); sendEvent(reactContext, RNXMPP_CONNECT, params); } @Override public void onDisconnect(Exception e) { sendEvent(reactContext, RNXMPP_DISCONNECT, e.getLocalizedMessage()); } @Override public void onLogin(String username, String password) { WritableMap params = Arguments.createMap(); params.putString("username", username); params.putString("password", password); sendEvent(reactContext, RNXMPP_LOGIN, params); } void sendEvent(ReactContext reactContext, String eventName, @Nullable Object params) { reactContext .getJSModule(RCTNativeAppEventEmitter.class) .emit(eventName, params); } }
package project2.jdbc; public interface JDBCProperty { String DRIVER = "com.mysql.jdbc.Driver"; String CONNECTION_URL = "jdbc:mysql://54.183.102.98:3306/moviedb"; String USERNAME = "caoyh"; String PASSWORD = "cyhwwq"; int SIZE = 20; }
package org.motechproject.nms.api.web; import org.motechproject.nms.api.web.contract.FlwUserResponse; import org.motechproject.nms.api.web.contract.LogHelper; import org.motechproject.nms.api.web.contract.UserResponse; import org.motechproject.nms.api.web.contract.kilkari.KilkariUserResponse; import org.motechproject.nms.api.web.exception.NotAuthorizedException; import org.motechproject.nms.api.web.exception.NotDeployedException; import org.motechproject.nms.flw.domain.FrontLineWorker; import org.motechproject.nms.flw.domain.ServiceUsage; import org.motechproject.nms.flw.domain.ServiceUsageCap; import org.motechproject.nms.flw.service.FrontLineWorkerService; import org.motechproject.nms.flw.service.ServiceUsageCapService; import org.motechproject.nms.flw.service.ServiceUsageService; import org.motechproject.nms.kilkari.domain.MctsChild; import org.motechproject.nms.kilkari.domain.MctsMother; import org.motechproject.nms.kilkari.domain.Subscriber; import org.motechproject.nms.kilkari.domain.Subscription; import org.motechproject.nms.kilkari.domain.SubscriptionStatus; import org.motechproject.nms.kilkari.service.SubscriberService; import org.motechproject.nms.props.domain.Service; import org.motechproject.nms.region.domain.Circle; import org.motechproject.nms.region.domain.Language; import org.motechproject.nms.region.domain.State; import org.motechproject.nms.region.service.CircleService; import org.motechproject.nms.region.service.LanguageService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import java.util.HashSet; import java.util.List; import java.util.Set; @Controller public class UserController extends BaseController { public static final String SERVICE_NAME = "serviceName"; @Autowired private SubscriberService subscriberService; @Autowired private FrontLineWorkerService frontLineWorkerService; @Autowired private ServiceUsageService serviceUsageService; @Autowired private ServiceUsageCapService serviceUsageCapService; @Autowired private CircleService circleService; @Autowired private LanguageService languageService; /** * 2.2.1 Get User Details API * IVR shall invoke this API when to retrieve details specific to the user identified by callingNumber. * In case user specific details are not available in the database, the API will attempt to load system * defaults based on the operator and circle provided. * /api/mobileacademy/user?callingNumber=9999999900&operator=A&circle=AP&callId=123456789012345 * 3.2.1 Get User Details API * IVR shall invoke this API when to retrieve details specific to the user identified by callingNumber. * In case user specific details are not available in the database, the API will attempt to load system * defaults based on the operator and circle provided. * /api/mobilekunji/user?callingNumber=9999999900&operator=A&circle=AP&callId=234000011111111 * */ @RequestMapping("/{serviceName}/user") // NO CHECKSTYLE Cyclomatic Complexity @ResponseBody @Transactional public UserResponse getUserDetails(@PathVariable String serviceName, @RequestParam(required = false) Long callingNumber, @RequestParam(required = false) String operator, @RequestParam(required = false) String circle, @RequestParam(required = false) Long callId) { log(String.format("REQUEST: /%s/user", serviceName), String.format( "callingNumber=%s, callId=%s, operator=%s, callId=%s", LogHelper.obscure(callingNumber), operator, circle, callId)); StringBuilder failureReasons = validate(callingNumber, callId, operator, circle); if (failureReasons.length() > 0) { throw new IllegalArgumentException(failureReasons.toString()); } Circle circleObj = circleService.getByName(circle); UserResponse user = null; /* Make sure the url the user hit corresponds to a service we are expecting */ if (!(MOBILE_ACADEMY.equals(serviceName) || MOBILE_KUNJI.equals(serviceName) || KILKARI.equals(serviceName))) { failureReasons.append(String.format(INVALID, SERVICE_NAME)); } if (failureReasons.length() > 0) { throw new IllegalArgumentException(failureReasons.toString()); } /* Handle the FLW services */ if (MOBILE_ACADEMY.equals(serviceName) || MOBILE_KUNJI.equals(serviceName)) { user = getFrontLineWorkerResponseUser(serviceName, callingNumber, circleObj); } /* Kilkari in the house! */ if (KILKARI.equals(serviceName)) { if (!validateKilkariServiceAvailability(callingNumber, circleObj)) { throw new NotDeployedException(String.format(NOT_DEPLOYED, Service.KILKARI)); } user = getKilkariResponseUser(callingNumber); } Language defaultLanguage = null; if (circleObj != null) { defaultLanguage = circleObj.getDefaultLanguage(); } // If no circle was provided, or if the provided circle doesn't have a default language, use the national if (defaultLanguage == null) { defaultLanguage = languageService.getNationalDefaultLanguage(); } if (defaultLanguage != null && user != null) { user.setDefaultLanguageLocationCode(defaultLanguage.getCode()); } // If the user does not have a language location code we want to return the allowed language location // codes for the provided circle, or all if no circle was provided Set<Language> languages = new HashSet<>(); if (user.getLanguageLocationCode() == null && circleObj != null) { languages = languageService.getAllForCircle(circleObj); } if (user.getLanguageLocationCode() == null && circleObj == null) { languages = languageService.getAll(); } if (languages.size() > 0) { Set<String> allowedLanguageLocations = new HashSet<>(); for (Language language : languages) { allowedLanguageLocations.add(language.getCode()); } user.setAllowedLanguageLocationCodes(allowedLanguageLocations); } log(String.format("RESPONSE: /%s/user", serviceName), String.format("callId=%s, %s", callId, user.toString())); return user; } private boolean validateKilkariServiceAvailability(Long callingNumber, Circle circle) { Subscriber subscriber = subscriberService.getSubscriber(callingNumber); if (subscriber != null) { MctsMother mother = subscriber.getMother(); if (mother != null) { return serviceDeployedInUserState(Service.KILKARI, mother.getState()); } MctsChild child = subscriber.getChild(); if (child != null) { return serviceDeployedInUserState(Service.KILKARI, child.getState()); } } // Try to validate from circle since we don't have MCTS data for state or no subscriber Circle currentCircle = (subscriber != null) ? subscriber.getCircle() : circle; if (currentCircle == null) { // No circle available return true; } List<State> stateList = currentCircle.getStates(); if (stateList == null || stateList.isEmpty()) { // No state available return true; } if (stateList.size() == 1) { // only one state available return serviceDeployedInUserState(Service.KILKARI, stateList.get(0)); } boolean serviceAvailable = false; for (State currentState : stateList) { // multiple states, false if undeployed in all states serviceAvailable = serviceDeployedInUserState(Service.KILKARI, currentState); } return serviceAvailable; } private UserResponse getKilkariResponseUser(Long callingNumber) { Subscriber subscriber = subscriberService.getSubscriber(callingNumber); if (subscriber == null) { return new KilkariUserResponse(); } KilkariUserResponse user = new KilkariUserResponse(); Set<String> packs = new HashSet<>(); Set<Subscription> subscriptions = subscriber.getSubscriptions(); for (Subscription subscription : subscriptions) { if ((subscription.getStatus() == SubscriptionStatus.ACTIVE) || (subscription.getStatus() == SubscriptionStatus.PENDING_ACTIVATION)) { packs.add(subscription.getSubscriptionPack().getName()); } } user.setSubscriptionPackList(packs); Language subscriberLanguage = subscriber.getLanguage(); if (subscriberLanguage != null) { user.setLanguageLocationCode(subscriberLanguage.getCode()); } return user; } private UserResponse getFrontLineWorkerResponseUser(String serviceName, Long callingNumber, Circle circle) { FlwUserResponse user = new FlwUserResponse(); Service service = getServiceFromName(serviceName); ServiceUsage serviceUsage = new ServiceUsage(null, service, 0, 0, false); FrontLineWorker flw = frontLineWorkerService.getByContactNumber(callingNumber); State state = getStateForFrontLineWorker(flw, circle); if (!serviceDeployedInUserState(service, state)) { throw new NotDeployedException(String.format(NOT_DEPLOYED, service)); } if (null != flw) { Language language = flw.getLanguage(); if (null != language) { user.setLanguageLocationCode(language.getCode()); } serviceUsage = serviceUsageService.getCurrentMonthlyUsageForFLWAndService(flw, service); if (!frontLineWorkerAuthorizedForAccess(flw, state)) { throw new NotAuthorizedException(String.format(NOT_AUTHORIZED, CALLING_NUMBER)); } } ServiceUsageCap serviceUsageCap = serviceUsageCapService.getServiceUsageCap(state, service); user.setCurrentUsageInPulses(serviceUsage.getUsageInPulses()); user.setEndOfUsagePromptCounter(serviceUsage.getEndOfUsage()); user.setWelcomePromptFlag(serviceUsage.getWelcomePrompt()); user.setMaxAllowedUsageInPulses(serviceUsageCap.getMaxUsageInPulses()); user.setMaxAllowedEndOfUsagePrompt(2); return user; } }
package bisq.apitest.linux; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import lombok.extern.slf4j.Slf4j; @Slf4j class SystemCommandExecutor { private final List<String> cmdOptions; private final String sudoPassword; private ThreadedStreamHandler inputStreamHandler; private ThreadedStreamHandler errorStreamHandler; /* * Note: I've removed the other constructor that was here to support executing * the sudo command. I'll add that back in when I get the sudo command * working to the point where it won't hang when the given password is * wrong. */ public SystemCommandExecutor(final List<String> cmdOptions) { if (cmdOptions == null) throw new IllegalStateException("No command params specified."); this.cmdOptions = cmdOptions; this.sudoPassword = null; } // Execute a system command and return its status code (0 or 1). // The system command's output (stderr or stdout) can be accessed from accessors. public int execCommand() throws IOException, InterruptedException { Process process = new ProcessBuilder(cmdOptions).start(); // you need this if you're going to write something to the command's input stream // (such as when invoking the 'sudo' command, and it prompts you for a password). OutputStream stdOutput = process.getOutputStream(); // i'm currently doing these on a separate line here in case i need to set them to null // to get the threads to stop. InputStream inputStream = process.getInputStream(); InputStream errorStream = process.getErrorStream(); // these need to run as java threads to get the standard output and error from the command. // the inputstream handler gets a reference to our stdOutput in case we need to write // something to it, such as with the sudo command inputStreamHandler = new ThreadedStreamHandler(inputStream, stdOutput, sudoPassword); errorStreamHandler = new ThreadedStreamHandler(errorStream); // TODO the inputStreamHandler has a nasty side-effect of hanging if the given password is wrong; fix it. inputStreamHandler.start(); errorStreamHandler.start(); int exitStatus = process.waitFor(); inputStreamHandler.interrupt(); errorStreamHandler.interrupt(); inputStreamHandler.join(); errorStreamHandler.join(); return exitStatus; } // Get the standard error from an executed system command. public StringBuilder getStandardErrorFromCommand() { return errorStreamHandler.getOutputBuffer(); } // Get the standard output from an executed system command. public StringBuilder getStandardOutputFromCommand() { return inputStreamHandler.getOutputBuffer(); } }
package de.test.antennapod.ui; import android.content.Context; import android.content.res.Resources; import android.test.ActivityInstrumentationTestCase2; import android.test.FlakyTest; import com.robotium.solo.Condition; import com.robotium.solo.Solo; import com.robotium.solo.Timeout; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.concurrent.TimeUnit; import de.danoeh.antennapod.R; import de.danoeh.antennapod.activity.PreferenceActivity; import de.danoeh.antennapod.core.preferences.UserPreferences; public class PreferencesTest extends ActivityInstrumentationTestCase2<PreferenceActivity> { private static final String TAG = "PreferencesTest"; private Solo solo; private Context context; private Resources res; public PreferencesTest() { super(PreferenceActivity.class); } @Override public void setUp() throws Exception { super.setUp(); solo = new Solo(getInstrumentation(), getActivity()); Timeout.setSmallTimeout(500); Timeout.setLargeTimeout(1000); context = getInstrumentation().getTargetContext(); res = getActivity().getResources(); UserPreferences.init(context); } @Override public void tearDown() throws Exception { solo.finishOpenedActivities(); super.tearDown(); } public void testSwitchTheme() { final int theme = UserPreferences.getTheme(); int otherTheme; if(theme == de.danoeh.antennapod.core.R.style.Theme_AntennaPod_Light) { otherTheme = R.string.pref_theme_title_dark; } else { otherTheme = R.string.pref_theme_title_light; } solo.clickOnText(solo.getString(R.string.pref_set_theme_title)); solo.waitForDialogToOpen(); solo.clickOnText(solo.getString(otherTheme)); assertTrue(solo.waitForCondition(() -> UserPreferences.getTheme() != theme, Timeout.getLargeTimeout())); } public void testSwitchThemeBack() { final int theme = UserPreferences.getTheme(); int otherTheme; if(theme == de.danoeh.antennapod.core.R.style.Theme_AntennaPod_Light) { otherTheme = R.string.pref_theme_title_dark; } else { otherTheme = R.string.pref_theme_title_light; } solo.clickOnText(solo.getString(R.string.pref_set_theme_title)); solo.waitForDialogToOpen(1000); solo.clickOnText(solo.getString(otherTheme)); assertTrue(solo.waitForCondition(() -> UserPreferences.getTheme() != theme, Timeout.getLargeTimeout())); } public void testExpandNotification() { final int priority = UserPreferences.getNotifyPriority(); solo.clickOnText(solo.getString(R.string.pref_expandNotify_title)); assertTrue(solo.waitForCondition(() -> priority != UserPreferences.getNotifyPriority(), Timeout.getLargeTimeout())); solo.clickOnText(solo.getString(R.string.pref_expandNotify_title)); assertTrue(solo.waitForCondition(() -> priority == UserPreferences.getNotifyPriority(), Timeout.getLargeTimeout())); } public void testEnablePersistentPlaybackControls() { final boolean persistNotify = UserPreferences.isPersistNotify(); solo.clickOnText(solo.getString(R.string.pref_persistNotify_title)); assertTrue(solo.waitForCondition(() -> persistNotify != UserPreferences.isPersistNotify(), Timeout.getLargeTimeout())); solo.clickOnText(solo.getString(R.string.pref_persistNotify_title)); assertTrue(solo.waitForCondition(() -> persistNotify == UserPreferences.isPersistNotify(), Timeout.getLargeTimeout())); } public void testEnqueueAtFront() { final boolean enqueueAtFront = UserPreferences.enqueueAtFront(); solo.clickOnText(solo.getString(R.string.pref_queueAddToFront_title)); assertTrue(solo.waitForCondition(() -> enqueueAtFront != UserPreferences.enqueueAtFront(), Timeout.getLargeTimeout())); solo.clickOnText(solo.getString(R.string.pref_queueAddToFront_title)); assertTrue(solo.waitForCondition(() -> enqueueAtFront == UserPreferences.enqueueAtFront(), Timeout.getLargeTimeout())); } public void testHeadPhonesDisconnect() { final boolean pauseOnHeadsetDisconnect = UserPreferences.isPauseOnHeadsetDisconnect(); solo.clickOnText(solo.getString(R.string.pref_pauseOnHeadsetDisconnect_title)); assertTrue(solo.waitForCondition(() -> pauseOnHeadsetDisconnect != UserPreferences.isPauseOnHeadsetDisconnect(), Timeout.getLargeTimeout())); solo.clickOnText(solo.getString(R.string.pref_pauseOnHeadsetDisconnect_title)); assertTrue(solo.waitForCondition(() -> pauseOnHeadsetDisconnect == UserPreferences.isPauseOnHeadsetDisconnect(), Timeout.getLargeTimeout())); } public void testHeadPhonesReconnect() { if(UserPreferences.isPauseOnHeadsetDisconnect() == false) { solo.clickOnText(solo.getString(R.string.pref_pauseOnHeadsetDisconnect_title)); assertTrue(solo.waitForCondition(() -> UserPreferences.isPauseOnHeadsetDisconnect(), Timeout.getLargeTimeout())); } final boolean unpauseOnHeadsetReconnect = UserPreferences.isUnpauseOnHeadsetReconnect(); solo.clickOnText(solo.getString(R.string.pref_unpauseOnHeadsetReconnect_title)); assertTrue(solo.waitForCondition(() -> unpauseOnHeadsetReconnect != UserPreferences.isUnpauseOnHeadsetReconnect(), Timeout.getLargeTimeout())); solo.clickOnText(solo.getString(R.string.pref_unpauseOnHeadsetReconnect_title)); assertTrue(solo.waitForCondition(() -> unpauseOnHeadsetReconnect == UserPreferences.isUnpauseOnHeadsetReconnect(), Timeout.getLargeTimeout())); } public void testContinuousPlayback() { final boolean continuousPlayback = UserPreferences.isFollowQueue(); solo.clickOnText(solo.getString(R.string.pref_followQueue_title)); assertTrue(solo.waitForCondition(() -> continuousPlayback != UserPreferences.isFollowQueue(), Timeout.getLargeTimeout())); solo.clickOnText(solo.getString(R.string.pref_followQueue_title)); assertTrue(solo.waitForCondition(() -> continuousPlayback == UserPreferences.isFollowQueue(), Timeout.getLargeTimeout())); } public void testAutoDelete() { final boolean autoDelete = UserPreferences.isAutoDelete(); solo.clickOnText(solo.getString(R.string.pref_auto_delete_title)); assertTrue(solo.waitForCondition(() -> autoDelete != UserPreferences.isAutoDelete(), Timeout.getLargeTimeout())); solo.clickOnText(solo.getString(R.string.pref_auto_delete_title)); assertTrue(solo.waitForCondition(() -> autoDelete == UserPreferences.isAutoDelete(), Timeout.getLargeTimeout())); } public void testPlaybackSpeeds() { solo.clickOnText(solo.getString(R.string.pref_playback_speed_title)); solo.waitForDialogToOpen(1000); assertTrue(solo.searchText(solo.getString(R.string.no_playback_plugin_title))); solo.clickOnText(solo.getString(R.string.close_label)); solo.waitForDialogToClose(1000); } public void testPauseForInterruptions() { final boolean pauseForFocusLoss = UserPreferences.shouldPauseForFocusLoss(); solo.clickOnText(solo.getString(R.string.pref_pausePlaybackForFocusLoss_title)); assertTrue(solo.waitForCondition(() -> pauseForFocusLoss != UserPreferences.shouldPauseForFocusLoss(), Timeout.getLargeTimeout())); solo.clickOnText(solo.getString(R.string.pref_pausePlaybackForFocusLoss_title)); assertTrue(solo.waitForCondition(() -> pauseForFocusLoss == UserPreferences.shouldPauseForFocusLoss(), Timeout.getLargeTimeout())); } public void testDisableUpdateInterval() { solo.clickOnText(solo.getString(R.string.pref_autoUpdateIntervallOrTime_sum)); solo.waitForDialogToOpen(); solo.clickOnText(solo.getString(R.string.pref_autoUpdateIntervallOrTime_Disable)); assertTrue(solo.waitForCondition(() -> UserPreferences.getUpdateInterval() == 0, 1000)); } public void testSetUpdateInterval() { solo.clickOnText(solo.getString(R.string.pref_autoUpdateIntervallOrTime_title)); solo.waitForDialogToOpen(); solo.clickOnText(solo.getString(R.string.pref_autoUpdateIntervallOrTime_Interval)); solo.waitForDialogToOpen(); String search = "12 " + solo.getString(R.string.pref_update_interval_hours_plural); solo.clickOnText(search); solo.waitForDialogToClose(); assertTrue(solo.waitForCondition(() -> UserPreferences.getUpdateInterval() == TimeUnit.HOURS.toMillis(12), Timeout.getLargeTimeout())); } public void testMobileUpdates() { final boolean mobileUpdates = UserPreferences.isAllowMobileUpdate(); solo.clickOnText(solo.getString(R.string.pref_mobileUpdate_title)); assertTrue(solo.waitForCondition(() -> mobileUpdates != UserPreferences.isAllowMobileUpdate(), Timeout.getLargeTimeout())); solo.clickOnText(solo.getString(R.string.pref_mobileUpdate_title)); assertTrue(solo.waitForCondition(() -> mobileUpdates == UserPreferences.isAllowMobileUpdate(), Timeout.getLargeTimeout())); } public void testSetSequentialDownload() { solo.clickOnText(solo.getString(R.string.pref_parallel_downloads_title)); solo.waitForDialogToOpen(); solo.clearEditText(0); solo.enterText(0, "1"); solo.clickOnText(solo.getString(android.R.string.ok)); assertTrue(solo.waitForCondition(() -> UserPreferences.getParallelDownloads() == 1, Timeout.getLargeTimeout())); } public void testSetParallelDownloads() { solo.clickOnText(solo.getString(R.string.pref_parallel_downloads_title)); solo.waitForDialogToOpen(); solo.clearEditText(0); solo.enterText(0, "10"); solo.clickOnText(solo.getString(android.R.string.ok)); assertTrue(solo.waitForCondition(() -> UserPreferences.getParallelDownloads() == 10, Timeout.getLargeTimeout())); } public void testSetParallelDownloadsInvalidInput() { solo.clickOnText(solo.getString(R.string.pref_parallel_downloads_title)); solo.waitForDialogToOpen(); solo.clearEditText(0); solo.enterText(0, "0"); assertEquals("1", solo.getEditText(0).getText().toString()); solo.clearEditText(0); solo.enterText(0, "100"); assertEquals("50", solo.getEditText(0).getText().toString()); } public void testSetEpisodeCache() { String[] entries = res.getStringArray(R.array.episode_cache_size_entries); String[] values = res.getStringArray(R.array.episode_cache_size_values); String entry = entries[entries.length/2]; final int value = Integer.valueOf(values[values.length/2]); solo.clickOnText(solo.getString(R.string.pref_episode_cache_title)); solo.waitForDialogToOpen(); solo.clickOnText(entry); assertTrue(solo.waitForCondition(() -> UserPreferences.getEpisodeCacheSize() == value, Timeout.getLargeTimeout())); } public void testSetEpisodeCacheMin() { String[] entries = res.getStringArray(R.array.episode_cache_size_entries); String[] values = res.getStringArray(R.array.episode_cache_size_values); String minEntry = entries[0]; final int minValue = Integer.valueOf(values[0]); solo.clickOnText(solo.getString(R.string.pref_episode_cache_title)); solo.waitForDialogToOpen(1000); solo.scrollUp(); solo.clickOnText(minEntry); assertTrue(solo.waitForCondition(() -> UserPreferences.getEpisodeCacheSize() == minValue, Timeout.getLargeTimeout())); } public void testSetEpisodeCacheMax() { String[] entries = res.getStringArray(R.array.episode_cache_size_entries); String[] values = res.getStringArray(R.array.episode_cache_size_values); String maxEntry = entries[entries.length-1]; final int maxValue = Integer.valueOf(values[values.length-1]); solo.clickOnText(solo.getString(R.string.pref_episode_cache_title)); solo.waitForDialogToOpen(); solo.clickOnText(maxEntry); assertTrue(solo.waitForCondition(() -> UserPreferences.getEpisodeCacheSize() == maxValue, Timeout.getLargeTimeout())); } public void testAutomaticDownload() { final boolean automaticDownload = UserPreferences.isEnableAutodownload(); solo.clickOnText(solo.getString(R.string.pref_automatic_download_title)); solo.waitForText(solo.getString(R.string.pref_automatic_download_title)); solo.clickOnText(solo.getString(R.string.pref_automatic_download_title)); assertTrue(solo.waitForCondition(() -> automaticDownload != UserPreferences.isEnableAutodownload(), Timeout.getLargeTimeout())); if(UserPreferences.isEnableAutodownload() == false) { solo.clickOnText(solo.getString(R.string.pref_automatic_download_title)); } assertTrue(solo.waitForCondition(() -> UserPreferences.isEnableAutodownload() == true, Timeout.getLargeTimeout())); final boolean enableAutodownloadOnBattery = UserPreferences.isEnableAutodownloadOnBattery(); solo.clickOnText(solo.getString(R.string.pref_automatic_download_on_battery_title)); assertTrue(solo.waitForCondition(() -> enableAutodownloadOnBattery != UserPreferences.isEnableAutodownloadOnBattery(), Timeout.getLargeTimeout())); solo.clickOnText(solo.getString(R.string.pref_automatic_download_on_battery_title)); assertTrue(solo.waitForCondition(() -> enableAutodownloadOnBattery == UserPreferences.isEnableAutodownloadOnBattery(), Timeout.getLargeTimeout())); final boolean enableWifiFilter = UserPreferences.isEnableAutodownloadWifiFilter(); solo.clickOnText(solo.getString(R.string.pref_autodl_wifi_filter_title)); assertTrue(solo.waitForCondition(() -> enableWifiFilter != UserPreferences.isEnableAutodownloadWifiFilter(), Timeout.getLargeTimeout())); solo.clickOnText(solo.getString(R.string.pref_autodl_wifi_filter_title)); assertTrue(solo.waitForCondition(() -> enableWifiFilter == UserPreferences.isEnableAutodownloadWifiFilter(), Timeout.getLargeTimeout())); } }
package cl.monsoon.s1next.widget; import android.content.res.Resources; import android.util.LruCache; import com.bumptech.glide.Priority; import com.bumptech.glide.disklrucache.DiskLruCache; import com.bumptech.glide.load.Key; import com.bumptech.glide.load.data.DataFetcher; import com.bumptech.glide.load.model.GlideUrl; import com.bumptech.glide.util.ContentLengthInputStream; import com.bumptech.glide.util.Util; import com.google.common.io.Closeables; import com.squareup.okhttp.Call; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import com.squareup.okhttp.ResponseBody; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import cl.monsoon.s1next.App; import cl.monsoon.s1next.BuildConfig; import cl.monsoon.s1next.R; import cl.monsoon.s1next.data.api.Api; import cl.monsoon.s1next.data.pref.DownloadPreferencesManager; import static com.squareup.okhttp.internal.http.StatusLine.HTTP_PERM_REDIRECT; import static com.squareup.okhttp.internal.http.StatusLine.HTTP_TEMP_REDIRECT; import static java.net.HttpURLConnection.HTTP_BAD_METHOD; import static java.net.HttpURLConnection.HTTP_GONE; import static java.net.HttpURLConnection.HTTP_MOVED_PERM; import static java.net.HttpURLConnection.HTTP_MOVED_TEMP; import static java.net.HttpURLConnection.HTTP_MULT_CHOICE; import static java.net.HttpURLConnection.HTTP_NOT_AUTHORITATIVE; import static java.net.HttpURLConnection.HTTP_NOT_FOUND; import static java.net.HttpURLConnection.HTTP_NOT_IMPLEMENTED; import static java.net.HttpURLConnection.HTTP_NO_CONTENT; import static java.net.HttpURLConnection.HTTP_OK; import static java.net.HttpURLConnection.HTTP_REQ_TOO_LONG; final class OkHttpStreamFetcher implements DataFetcher<InputStream> { private final Resources mResources; private final DownloadPreferencesManager mDownloadPreferencesManager; private final OkHttpClient mOkHttpClient; private final GlideUrl mGlideUrl; private volatile Call mCall; private ResponseBody mResponseBody; private InputStream mInputStream; public OkHttpStreamFetcher(OkHttpClient okHttpClient, GlideUrl glideUrl) { this.mOkHttpClient = okHttpClient; this.mGlideUrl = glideUrl; mResources = App.get().getResources(); mDownloadPreferencesManager = App.getAppComponent(App.get()).getDownloadPreferencesManager(); } @Override public InputStream loadData(Priority priority) throws IOException { Key key = null; String url = mGlideUrl.toStringUrl(); if (Api.isAvatarUrl(url)) { key = new OriginalKey(url, mDownloadPreferencesManager.getAvatarCacheInvalidationIntervalSignature()); if (AvatarUrlsCache.has(key)) { // already have cached this avatar url mInputStream = mResources.openRawResource(+R.drawable.ic_avatar_placeholder); return mInputStream; } } Request request = new Request.Builder() .url(url) .build(); mCall = mOkHttpClient.newCall(request); Response response = mCall.execute(); mResponseBody = response.body(); if (!response.isSuccessful()) { // if (this this a avatar URL) && (this URL is cacheable) if (key != null && isCacheable(response)) { AvatarUrlsCache.put(key); mInputStream = mResources.openRawResource(+R.drawable.ic_avatar_placeholder); return mInputStream; } throw new IOException("Response (status code " + response.code() + ") is unsuccessful."); } long contentLength = mResponseBody.contentLength(); mInputStream = ContentLengthInputStream.obtain(mResponseBody.byteStream(), contentLength); return mInputStream; } @Override public void cleanup() { Closeables.closeQuietly(mInputStream); try { Closeables.close(mResponseBody, true); } catch (IOException ignored) { } } @Override public String getId() { return mGlideUrl.getCacheKey(); } @Override public void cancel() { if (mCall != null) { mCall.cancel(); mCall = null; } } /** * Forked form {@link com.squareup.okhttp.internal.http.CacheStrategy#isCacheable(Response, Request)}. */ private static boolean isCacheable(Response response) { // Always go to network for uncacheable response codes (RFC 7231 section 6.1), // This implementation doesn't support caching partial content. switch (response.code()) { case HTTP_OK: case HTTP_NOT_AUTHORITATIVE: case HTTP_NO_CONTENT: case HTTP_MULT_CHOICE: case HTTP_MOVED_PERM: case HTTP_NOT_FOUND: case HTTP_BAD_METHOD: case HTTP_GONE: case HTTP_REQ_TOO_LONG: case HTTP_NOT_IMPLEMENTED: case HTTP_PERM_REDIRECT: // These codes can be cached unless headers forbid it. break; case HTTP_MOVED_TEMP: case HTTP_TEMP_REDIRECT: // These codes can only be cached with the right response headers. // http://tools.ietf.org/html/rfc7234#section-3 // s-maxage is not checked because OkHttp is a private cache that should ignore s-maxage. if (response.header("Expires") != null || response.cacheControl().maxAgeSeconds() != -1 || response.cacheControl().isPublic() || response.cacheControl().isPrivate()) { break; } // Fall-through. default: // All other codes cannot be cached. return false; } return true; } private enum AvatarUrlsCache { INSTANCE; private static final int MEMORY_CACHE_MAX_NUMBER = 1000; private static final String DISK_CACHE_DIRECTORY = "avatar_urls_disk_cache"; private static final long DISK_CACHE_MAX_SIZE = 1000 * 1000; // 1MB /** * We only cache the avatar URLs as keys. * So we use this to represent the * null value because {@link android.util.LruCache} * doesn't accept null as a value. */ private static final Object NULL_VALUE = new Object(); private static final Object DISK_CACHE_LOCK = new Object(); /** * We use both disk cache and memory cache. */ private final DiskLruCache diskLruCache; private final LruCache<String, Object> lruCache; private final KeyGenerator keyGenerator; AvatarUrlsCache() { lruCache = new LruCache<>(MEMORY_CACHE_MAX_NUMBER); File file = new File(App.get().getCacheDir().getPath() + File.separator + DISK_CACHE_DIRECTORY); try { diskLruCache = DiskLruCache.open(file, BuildConfig.VERSION_CODE, 1, DISK_CACHE_MAX_SIZE); } catch (IOException e) { throw new RuntimeException("Failed to open the cache in " + file + ".", e); } keyGenerator = new KeyGenerator(); } private static boolean has(Key key) { String encodedKey = INSTANCE.keyGenerator.getKey(key); if (encodedKey == null) { return false; } if (INSTANCE.lruCache.get(encodedKey) != null) { return true; } try { synchronized (DISK_CACHE_LOCK) { return INSTANCE.diskLruCache.get(encodedKey) != null; } } catch (IOException ignore) { return false; } } private static void put(Key key) { String encodedKey = INSTANCE.keyGenerator.getKey(key); if (encodedKey == null) { return; } INSTANCE.lruCache.put(encodedKey, NULL_VALUE); try { synchronized (DISK_CACHE_LOCK) { DiskLruCache.Editor editor = INSTANCE.diskLruCache.edit(encodedKey); if (editor.getFile(0).createNewFile()) { editor.commit(); } else { editor.abort(); } } } catch (IOException ignore) { } } /** * Forked from {@link com.bumptech.glide.load.engine.cache.SafeKeyGenerator}. */ private static final class KeyGenerator { private static final int AVATAR_URL_KEYS_MEMORY_CACHE_MAX_NUMBER = 1000; private final LruCache<Key, String> lruCache = new LruCache<>(AVATAR_URL_KEYS_MEMORY_CACHE_MAX_NUMBER); public String getKey(Key key) { String value = lruCache.get(key); if (value == null) { try { MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); key.updateDiskCacheKey(messageDigest); value = Util.sha256BytesToHex(messageDigest.digest()); lruCache.put(key, value); } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { throw new RuntimeException(e); } } return value; } } } /** * Forked from {@link com.bumptech.glide.load.engine.OriginalKey}. */ private static final class OriginalKey implements Key { private final String id; private final Key signature; public OriginalKey(String id, Key signature) { this.id = id; this.signature = signature; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } OriginalKey that = (OriginalKey) o; return id.equals(that.id) && signature.equals(that.signature); } @Override public int hashCode() { int result = id.hashCode(); result = 31 * result + signature.hashCode(); return result; } @Override public void updateDiskCacheKey(MessageDigest messageDigest) throws UnsupportedEncodingException { messageDigest.update(id.getBytes(STRING_CHARSET_NAME)); signature.updateDiskCacheKey(messageDigest); } } }
package dr.math; import dr.util.NumberFormatter; import java.text.NumberFormat; import java.text.ParseException; /** * Handy utility functions which have some Mathematical relavance. * * @author Matthew Goode * @author Alexei Drummond * @author Gerton Lunter * @version $Id: MathUtils.java,v 1.13 2006/08/31 14:57:24 rambaut Exp $ */ public class MathUtils { private MathUtils() { } /** * A random number generator that is initialized with the clock when this * class is loaded into the JVM. Use this for all random numbers. * Note: This method or getting random numbers in not thread-safe. Since * MersenneTwisterFast is currently (as of 9/01) not synchronized using * this function may cause concurrency issues. Use the static get methods of the * MersenneTwisterFast class for access to a single instance of the class, that * has synchronization. */ private static final MersenneTwisterFast random = MersenneTwisterFast.DEFAULT_INSTANCE; // Chooses one category if a cumulative probability distribution is given public static int randomChoice(double[] cf) { double U = MathUtils.nextDouble(); int s; if (U <= cf[0]) { s = 0; } else { for (s = 1; s < cf.length; s++) { if (U <= cf[s] && U > cf[s - 1]) { break; } } } return s; } /** * @param pdf array of unnormalized probabilities * @return a sample according to an unnormalized probability distribution */ public static int randomChoicePDF(double[] pdf) { double U = MathUtils.nextDouble() * getTotal(pdf); for (int i = 0; i < pdf.length; i++) { U -= pdf[i]; if (U < 0.0) { return i; } } for (int i = 0; i < pdf.length; i++) { System.err.println(i + "\t" + pdf[i]); } throw new Error("randomChoicePDF falls through -- negative, infinite or NaN components in input " + "distribution, or all zeroes?"); } /** * @param logpdf array of unnormalised log probabilities * @return a sample according to an unnormalised probability distribution * <p/> * Use this if probabilities are rounding to zero when converted to real space */ public static int randomChoiceLogPDF(double[] logpdf) { double scalingFactor = Double.NEGATIVE_INFINITY; for (double aLogpdf : logpdf) { if (aLogpdf > scalingFactor) { scalingFactor = aLogpdf; } } if (scalingFactor == Double.NEGATIVE_INFINITY) { throw new Error("randomChoiceLogPDF falls through -- all -INF components in input distribution"); } for (int j = 0; j < logpdf.length; j++) { logpdf[j] = logpdf[j] - scalingFactor; } double[] pdf = new double[logpdf.length]; for (int j = 0; j < logpdf.length; j++) { pdf[j] = Math.exp(logpdf[j]); } return randomChoicePDF(pdf); } /** * @param array to normalize * @return a new double array where all the values sum to 1. * Relative ratios are preserved. */ public static double[] getNormalized(double[] array) { double[] newArray = new double[array.length]; double total = getTotal(array); for (int i = 0; i < array.length; i++) { newArray[i] = array[i] / total; } return newArray; } /** * @param array entries to be summed * @param start start position * @param end the index of the element after the last one to be included * @return the total of a the values in a range of an array */ public static double getTotal(double[] array, int start, int end) { double total = 0.0; for (int i = start; i < end; i++) { total += array[i]; } return total; } /** * @param array to sum over * @return the total of the values in an array */ public static double getTotal(double[] array) { return getTotal(array, 0, array.length); } /** * Access a default instance of this class, access is synchronized */ public static long getSeed() { synchronized (random) { return random.getSeed(); } } /** * Access a default instance of this class, access is synchronized */ public static void setSeed(long seed) { synchronized (random) { random.setSeed(seed); } } /** * Access a default instance of this class, access is synchronized */ public static byte nextByte() { synchronized (random) { return random.nextByte(); } } /** * Access a default instance of this class, access is synchronized */ public static boolean nextBoolean() { synchronized (random) { return random.nextBoolean(); } } /** * Access a default instance of this class, access is synchronized */ public static void nextBytes(byte[] bs) { synchronized (random) { random.nextBytes(bs); } } /** * Access a default instance of this class, access is synchronized */ public static char nextChar() { synchronized (random) { return random.nextChar(); } } /** * Access a default instance of this class, access is synchronized */ public static double nextGaussian() { synchronized (random) { return random.nextGaussian(); } } //Mean = alpha / lambda //Variance = alpha / (lambda*lambda) public static double nextGamma(double alpha, double lambda) { synchronized (random) { return random.nextGamma(alpha, lambda); } } //Mean = alpha/(alpha+beta) //Variance = (alpha*beta)/(alpha+beta)^2*(alpha+beta+1) public static double nextBeta(double alpha, double beta) { double x = nextGamma(alpha, 1); double y = nextGamma(beta, 1); return x / (x + y); } /** * Access a default instance of this class, access is synchronized * * @return a pseudo random double precision floating point number in [01) */ public static double nextDouble() { synchronized (random) { return random.nextDouble(); } } /** * @return log of random variable in [0,1] */ public static double randomLogDouble() { return Math.log(nextDouble()); } /** * Access a default instance of this class, access is synchronized */ public static double nextExponential(double lambda) { synchronized (random) { return -1.0 * Math.log(1 - random.nextDouble()) / lambda; } } /** * Access a default instance of this class, access is synchronized */ public static double nextInverseGaussian(double mu, double lambda) { synchronized (random) { /* CODE TAKEN FROM WIKIPEDIA. TESTING DONE WITH RESULTS GENERATED IN R AND LOOK COMPARABLE */ double v = random.nextGaussian(); // sample from a normal distribution with a mean of 0 and 1 standard deviation double y = v * v; double x = mu + (mu * mu * y) / (2 * lambda) - (mu / (2 * lambda)) * Math.sqrt(4 * mu * lambda * y + mu * mu * y * y); double test = MathUtils.nextDouble(); // sample from a uniform distribution between 0 and 1 if (test <= (mu) / (mu + x)) { return x; } else { return (mu * mu) / x; } } } /** * Access a default instance of this class, access is synchronized */ public static float nextFloat() { synchronized (random) { return random.nextFloat(); } } /** * Access a default instance of this class, access is synchronized */ public static long nextLong() { synchronized (random) { return random.nextLong(); } } /** * Access a default instance of this class, access is synchronized */ public static short nextShort() { synchronized (random) { return random.nextShort(); } } /** * Access a default instance of this class, access is synchronized */ public static int nextInt() { synchronized (random) { return random.nextInt(); } } /** * Access a default instance of this class, access is synchronized */ public static int nextInt(int n) { synchronized (random) { return random.nextInt(n); } } /** * @param low * @param high * @return uniform between low and high */ public static double uniform(double low, double high) { return low + nextDouble() * (high - low); } /** * Shuffles an array. */ public static void shuffle(int[] array) { synchronized (random) { random.shuffle(array); } } /** * Shuffles an array. Shuffles numberOfShuffles times */ public static void shuffle(int[] array, int numberOfShuffles) { synchronized (random) { random.shuffle(array, numberOfShuffles); } } /** * Returns an array of shuffled indices of length l. * * @param l length of the array required. */ public static int[] shuffled(int l) { synchronized (random) { return random.shuffled(l); } } public static int[] sampleIndicesWithReplacement(int length) { synchronized (random) { int[] result = new int[length]; for (int i = 0; i < length; i++) result[i] = random.nextInt(length); return result; } } /** * Permutes an array. */ public static void permute(int[] array) { synchronized (random) { random.permute(array); } } /** * Returns a uniform random permutation of 0,...,l-1 * * @param l length of the array required. */ public static int[] permuted(int l) { synchronized (random) { return random.permuted(l); } } public static double logHyperSphereVolume(int dimension, double radius) { return dimension * (0.5723649429247001 + Math.log(radius)) + -GammaFunction.lnGamma(dimension / 2.0 + 1.0); } /** * Returns sqrt(a^2 + b^2) without under/overflow. */ public static double hypot(double a, double b) { double r; if (Math.abs(a) > Math.abs(b)) { r = b / a; r = Math.abs(a) * Math.sqrt(1 + r * r); } else if (b != 0) { r = a / b; r = Math.abs(b) * Math.sqrt(1 + r * r); } else { r = 0.0; } return r; } /** * return double *.???? * * @param value * @param sf * @return */ public static double round(double value, int sf) { NumberFormatter formatter = new NumberFormatter(sf); try { return NumberFormat.getInstance().parse(formatter.format(value)).doubleValue(); } catch (ParseException e) { return value; } } public static int[] getRandomState() { synchronized (random) { return random.getRandomState(); } } public static void setRandomState(int[] rngState) { synchronized (random) { random.setRandomState(rngState); } } public static boolean isClose(double[] x, double[] y, double tolerance) { if (x.length != y.length) return false; for (int i = 0, dim = x.length; i < dim; ++i) { if (Double.isNaN(x[i]) || Double.isNaN(y[i])) return false; if (Math.abs(x[i] - y[i]) > tolerance) return false; } return true; } public static boolean isClose(double x, double y, double tolerance) { return Math.abs(x - y) < tolerance; } public static boolean isRelativelyClose(double[] x, double[] y, double relativeTolerance) { if (x.length != y.length) return false; for (int i = 0, dim = x.length; i < dim; ++i) { if (!isRelativelyClose(x[i], y[i], relativeTolerance)) { return false; } } return true; } public static boolean isRelativelyClose(double x, double y, double relativeTolerance) { double relativeDifference = 2 * (x - y) / (x + y); if (Math.abs(relativeDifference) > relativeTolerance) { return false; } return true; } public static double maximum(double[] array) { double max = array[0]; for (double x : array) { if (x > max) { max = x; } } return max; } }
package co.epitre.aelf_lectures.data; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.text.SimpleDateFormat; import java.util.GregorianCalendar; import java.util.List; import android.annotation.SuppressLint; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteStatement; import android.preference.PreferenceManager; import android.util.Log; import com.getsentry.raven.android.Raven; import org.piwik.sdk.Tracker; import org.piwik.sdk.extra.PiwikApplication; import org.piwik.sdk.extra.TrackHelper; /** * Internal cache manager (SQLite). There is one table per office and one line per day. * Each line tracks the * - office date * - office content (serialized list<LectureItem>) * - when this office was loaded --> used for server initiated invalidation * - which version of the application was used --> used for upgrade initiated invalidation */ final class AelfCacheHelper extends SQLiteOpenHelper { private static final String TAG = "AELFCacheHelper"; private static final int DB_VERSION = 3; private static final String DB_NAME = "aelf_cache.db"; private SharedPreferences preference = null; private Context ctx; Tracker tracker; private static final String DB_TABLE_CREATE = "CREATE TABLE IF NOT EXISTS `%s` (" + "date TEXT PRIMARY KEY," + "lectures BLOB," + "create_date TEXT," + "create_version INTEGER" + ")"; private static final String DB_TABLE_SET = "INSERT OR REPLACE INTO `%s` VALUES (?,?,?,?)"; @SuppressLint("SimpleDateFormat") private static final SimpleDateFormat keyFormatter = new SimpleDateFormat("yyyy-MM-dd"); // TODO: prepare requests AelfCacheHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); preference = PreferenceManager.getDefaultSharedPreferences(context); ctx = context; tracker = ((PiwikApplication) context.getApplicationContext()).getTracker(); } /** * Api */ @SuppressLint("SimpleDateFormat") private String computeKey(GregorianCalendar when) { if (when == null) { return "0000-00-00"; } return keyFormatter.format(when.getTime()); } private void onSqliteError(SQLiteException e) { // If a migration did not go well, the best we can do is drop the database and re-create // it from scratch. This is hackish but should allow more or less graceful recoveries. Log.e(TAG, "Critical database error. Droping + Re-creating", e); Raven.capture(e); TrackHelper.track().event("Office", "cache.db.error").name("critical").value(1f).with(tracker); // Close and drop the database. It will be re-opened automatically close(); ctx.deleteDatabase(DB_NAME); } private boolean _execute_stmt(SQLiteStatement stmt, int max_retries) { // Attempt to run this statement up to max_retries times do { try { stmt.execute(); return true; } catch(SQLiteException e) { Log.w(TAG, "Failed to save item in cache (SQLiteException): "+e.toString()); Raven.capture(e); } catch(IllegalStateException e) { Log.w(TAG, "Failed to save item in cache (IllegalStateException): "+e.toString()); Raven.capture(e); } } while (--max_retries > 0); // All attempts failed return false; } void store(LecturesController.WHAT what, GregorianCalendar when, List<LectureItem> lectures) { String key = computeKey(when); String create_date = computeKey(new GregorianCalendar()); // Build version number long create_version = preference.getInt("version", -1); // build blob byte[] blob; try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos; oos = new ObjectOutputStream(bos); oos.writeObject(lectures); blob = bos.toByteArray(); } catch (IOException e) { Raven.capture(e); throw new RuntimeException(e); } // insert into the database String sql = String.format(DB_TABLE_SET, what); SQLiteStatement stmt; try { stmt = getWritableDatabase().compileStatement(sql); } catch (SQLiteException e) { // Drop DB and retry onSqliteError(e); stmt = getWritableDatabase().compileStatement(sql); } stmt.bindString(1, key); stmt.bindBlob(2, blob); stmt.bindString(3, create_date); stmt.bindLong(4, create_version); // Multiple attempts. On failure ignore. This is cache --> best effort _execute_stmt(stmt, 3); } // cleaner helper method void truncateBefore(LecturesController.WHAT what, GregorianCalendar when) { String key = computeKey(when); SQLiteDatabase db = getWritableDatabase(); try { db.delete(what.toString(), "`date` < ?", new String[] {key}); } catch (SQLiteException e) { // Drop DB and retry onSqliteError(e); db.delete(what.toString(), "`date` < ?", new String[] {key}); } } // cast is not checked when decoding the blob but we where responsible for its creation so... dont care @SuppressWarnings("unchecked") List<LectureItem> load(LecturesController.WHAT what, GregorianCalendar when, GregorianCalendar minLoadDate, Long minLoadVersion) { String key = computeKey(when); String min_create_date = computeKey(minLoadDate); String min_create_version = String.valueOf(minLoadVersion); byte[] blob; // load from db Log.i(TAG, "Trying to load lecture from cache create_date>="+min_create_date+" create_version>="+min_create_version); SQLiteDatabase db = getReadableDatabase(); Cursor cur; try { cur = db.query( what.toString(), // FROM new String[]{"lectures", "create_date", "create_version"}, // SELECT "`date`=? AND `create_date` >= ? AND create_version >= ?", // WHERE new String[]{key, min_create_date, min_create_version}, // params null, null, null, "1" // GROUP BY, HAVING, ORDER, LIMIT ); } catch (SQLiteException e) { // Drop DB and retry onSqliteError(e); cur = db.query( what.toString(), // FROM new String[]{"lectures", "create_date", "create_version"}, // SELECT "`date`=? AND `create_date` >= ? AND create_version >= ?", // WHERE new String[]{key, min_create_date, min_create_version}, // params null, null, null, "1" // GROUP BY, HAVING, ORDER, LIMIT ); } if(cur != null && cur.getCount() > 0) { // any records ? load it cur.moveToFirst(); blob = cur.getBlob(0); Log.i(TAG, "Loaded lecture from cache create_date="+cur.getString(1)+" create_version="+cur.getLong(2)); try { ByteArrayInputStream bis = new ByteArrayInputStream(blob); ObjectInputStream ois = new ObjectInputStream(bis); return (List<LectureItem>)ois.readObject(); } catch (ClassNotFoundException | IOException e) { Raven.capture(e); throw new RuntimeException(e); } finally { cur.close(); } } else { return null; } } /** * Internal logic */ private void createCache(SQLiteDatabase db, LecturesController.WHAT what) { String sql = String.format(DB_TABLE_CREATE, what); db.execSQL(sql); } @Override public void onCreate(SQLiteDatabase db) { for (LecturesController.WHAT what : LecturesController.WHAT.class.getEnumConstants()) { createCache(db, what); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if(oldVersion <= 1) { Log.i(TAG, "Upgrading DB from version 1"); createCache(db, LecturesController.WHAT.METAS); } if(oldVersion <= 2) { // Add create_date + create_version for finer grained invalidation Log.i(TAG, "Upgrading DB from version 2"); db.beginTransaction(); try { for (LecturesController.WHAT what: LecturesController.WHAT.values()) { db.execSQL("ALTER TABLE `" + what + "` ADD COLUMN create_date TEXT"); db.execSQL("ALTER TABLE `" + what + "` ADD COLUMN create_version INTEGER;"); db.execSQL("UPDATE `" + what + "` SET create_date = '0000-00-00', create_version = 0;"); } db.setTransactionSuccessful(); } catch (Exception e) { Raven.capture(e); throw e; } finally { db.endTransaction(); } } } }
package com.grarak.kerneladiutor.views; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AlertDialog; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import com.grarak.kerneladiutor.R; import com.grarak.kerneladiutor.utils.Prefs; import com.grarak.kerneladiutor.utils.Utils; import com.grarak.kerneladiutor.utils.ViewUtils; import java.io.IOException; import java.io.InputStream; import io.codetail.animation.SupportAnimator; import io.codetail.animation.ViewAnimationUtils; public class NavHeaderView extends LinearLayout { private interface Callback { void setImage(Uri uri) throws IOException; void animate(); } private static Callback sCallback; private ImageView mImage; public NavHeaderView(Context context) { this(context, null); } public NavHeaderView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public NavHeaderView(final Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); sCallback = new Callback() { @Override public void setImage(Uri uri) throws IOException { NavHeaderView.this.setImage(uri); } @Override public void animate() { animateBg(); } }; LayoutInflater.from(context).inflate(R.layout.nav_header_view, this); mImage = (ImageView) findViewById(R.id.nav_header_pic); boolean noPic; try { String uri = Prefs.getString("previewpicture", null, mImage.getContext()); if (uri == null || uri.equals("nopicture")) noPic = true; else { setImage(Uri.parse(uri)); noPic = false; } } catch (Exception e) { e.printStackTrace(); noPic = true; } if (noPic) Prefs.saveString("previewpicture", "nopicture", mImage.getContext()); findViewById(R.id.nav_header_fab).setOnClickListener(new OnClickListener() { @Override public void onClick(final View v) { new AlertDialog.Builder(context).setItems(v.getResources() .getStringArray(R.array.main_header_picture_items), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case 0: v.getContext().startActivity(new Intent(v.getContext(), MainHeaderActivity.class)); break; case 1: if (Prefs.getString("previewpicture", null, v.getContext()) .equals("nopicture")) return; Prefs.saveString("previewpicture", "nopicture", v.getContext()); mImage.setImageDrawable(null); animateBg(); break; } } }).show(); } }); } public static class MainHeaderActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); } else { intent = new Intent(); intent.setAction(Intent.ACTION_GET_CONTENT); }
package com.nexuslink.wenavi.presenter; import android.content.Context; import android.util.Log; import android.widget.EditText; import com.nexuslink.wenavi.callback.CallBack; import com.nexuslink.wenavi.callback.SimpleCallback; import com.nexuslink.wenavi.common.Constant; import com.nexuslink.wenavi.contract.MainContract; import com.nexuslink.wenavi.model.MainModel; import com.nexuslink.wenavi.model.TextMessage; import com.nexuslink.wenavi.model.WeNaviLocation; import com.nexuslink.wenavi.model.WeNaviMessage; import java.util.List; import java.util.Objects; import cn.jpush.im.android.api.JMessageClient; import cn.jpush.im.android.api.model.Conversation; import cn.jpush.im.api.BasicCallback; import static cn.jpush.im.android.tasks.GetUserInfoListTask.IDType.username; public class MainPresenter implements MainContract.Presenter, CallBack<Conversation>, SimpleCallback { private MainContract.View view; private MainModel model; private String targetName; private String tmpName; public MainPresenter(MainContract.View view, MainModel model) { this.view = view; this.model = model; view.setPresenter(this); model.setConversationCallback(this); model.setSendMessageCallback(this); } @Override public void start() { } @Override public void loadFriendsList() { model.loadConversation(); } @Override public void openFriendsList() { view.showBottomFriends(false); view.showFriendsSheet(); } @Override public void closeFriendList() { view.hideFriendsSheet(); } @Override public void openChatListFromFirst() { view.showChatSheet(); view.showEditorBar(true); view.friendListVisible(false); } @Override public void openChatListFromSelf() { view.showChatSheet(); view.showBottomChat(false); } @Override public void closeChatList() { view.chatListVisible(false); view.showEditorBar(false); view.showBottomChat(false); } /** * * * @param mMessageEdTx */ @Override public void sendTextMessage(EditText mMessageEdTx) { String text = mMessageEdTx.getText().toString(); if (Objects.equals(text, "")) { view.showInfo(""); } else { //WeNaviMessageJson WeNaviMessage weNaviMessage = new WeNaviMessage(); weNaviMessage.setType(Constant.SIMPLE_MESSAGE); weNaviMessage.setContent(text); String content = weNaviMessage.toJSONObject(); model.sendMessageToTarget(getTargetName(), text, Constant.CODE_MESSAGE_SEND); view.insertNewMessage(new TextMessage(Constant.CONVERSATION_ME, content)); // TODO: 17-9-4 //view.showSendProgress(true); } } /** * * * @param longitude * @param latitude */ @Override public void sendLocationMessage(Double longitude, Double latitude) { WeNaviMessage weNaviMessage = new WeNaviMessage(); weNaviMessage.setType(Constant.LOCATION_MESSAGE); weNaviMessage.setLocation(new WeNaviLocation(longitude, latitude)); String content = weNaviMessage.toJSONObject(); model.sendMessageToTarget(getTargetName(), content, Constant.CODE_LOCATION_SEND); } /** * Line * * @param locations */ @Override public void sendLineMessage(WeNaviLocation[] locations) { WeNaviMessage weNaviMessage = new WeNaviMessage(); weNaviMessage.setType(Constant.DRAW_MESSAGE); weNaviMessage.setLocations(locations); String content = weNaviMessage.toJSONObject(); model.sendMessageToTarget(getTargetName(), content, Constant.CODE_LINE_SEND); } /** * * * @param itemName Itemname */ @Override public void sendSureMessage(String itemName) { tmpName = itemName;//target WeNaviMessage weNaviMessage = new WeNaviMessage(); weNaviMessage.setType(Constant.CONNECT_MESSAGE); weNaviMessage.setConnect(true);//boolfalse String content = weNaviMessage.toJSONObject(); model.sendMessageToTarget(getTargetName(), content, Constant.CODE_SURE_SEND); } // TODO: 17-9-6 @Override public void onSuccess(List<Conversation> beans) { view.showFriendsList(beans); } @Override public void onSuccess(Conversation bean) { } /** * * * @param code code */ @Override public void onSuccess(int code) { switch (code) { case Constant.CODE_MESSAGE_SEND: // TODO: 17-9-4 progress //view.hideProgress(); view.cleanInput(); view.showInfo(""); break; case Constant.CODE_LOCATION_SEND: Log.d("debug", "..."); break; case Constant.CODE_LINE_SEND: view.showInfo(""); break; case Constant.CODE_SURE_SEND: //itemNametarget, // TODO: 17-9-6 Presentertarget view.showInfo(""); break; } } /** * * * @param code * @param exception */ @Override public void onFail(int code, String exception) { view.showInfo(exception); } public String getTargetName() { return targetName; } }
package com.pinomg.determinator; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.util.SparseBooleanArray; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; import java.util.Iterator; public class AddAnswerersActivity extends Activity { public ArrayList<Friend> friendList = new ArrayList<Friend>(); //Creates a list to store friends. private ArrayAdapter friendsAdapter; private ArrayList<Friend> checkedFriends = new ArrayList<Friend>(); private SparseBooleanArray checked; public TextView receiversText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_answerers); final ListView friendView = (ListView) findViewById(R.id.friendView); friendView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); createExampleFriendList(); friendsAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_multiple_choice, friendList); friendView.setAdapter(friendsAdapter); receiversText = (TextView) findViewById(R.id.receivers); checked = friendView.getCheckedItemPositions(); friendView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { if (checked.get(i)) { //Add to checkedFriends checkedFriends.add(friendList.get(i)); } else { // Remove from checkedFriends checkedFriends.remove(friendList.get(i)); } String receivers = ""; for(Iterator<Friend> j = checkedFriends.iterator(); j.hasNext(); ) { Friend f = j.next(); receivers += f.toString() + " "; } receiversText.setText(receivers); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_add_answerers, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void goToListActivity(View view) { finish(); } public void createExampleFriendList() { Friend friend1 = new Friend("Rasmus", 123); Friend friend2 = new Friend("Karin", 456); Friend friend3 = new Friend("Bubba", 789); friendList.add(friend1); friendList.add(friend2); friendList.add(friend3); } }
package dsl; import org.eclipse.jdt.core.dom.CatchClause; import org.eclipse.jdt.core.dom.TryStatement; import java.util.ArrayList; import java.util.List; public class DTryStatement extends DStatement { final String node = "DTryStatement"; final DBlock tryBlock; final List<DCatchClause> catchClauses; final DBlock finallyBlock; private DTryStatement(DBlock tryBlock, List<DCatchClause> catchClauses, DBlock finallyBlock) { this.tryBlock = tryBlock; this.catchClauses = catchClauses; this.finallyBlock = finallyBlock; } @Override public String sketch() { String s = "try " + (tryBlock == null? "{" + HOLE() + "}": tryBlock.sketch()); for (DCatchClause clause : catchClauses) s += clause == null? HOLE() : clause.sketch(); if (finallyBlock != null) s += "finally " + finallyBlock.sketch(); return s; } @Override public void updateSequences(List<Sequence> soFar) { tryBlock.updateSequences(soFar); for (DCatchClause clause : catchClauses) { List<Sequence> copy = new ArrayList<>(); for (Sequence seq : soFar) copy.add(new Sequence(seq.calls)); clause.updateSequences(copy); for (Sequence seq : copy) if (!soFar.contains(seq)) soFar.add(seq); } finallyBlock.updateSequences(soFar); } public static class Handle extends Handler { TryStatement statement; public Handle(TryStatement statement, Visitor visitor) { super(visitor); this.statement = statement; } @Override public DStatement handle() { DBlock tryBlock = new DBlock.Handle(statement.getBody(), visitor).handle(); List<DCatchClause> catchClauses = new ArrayList<>(); for (Object o : statement.catchClauses()) { CatchClause clause = (CatchClause) o; DCatchClause dclause = new DCatchClause.Handle(clause, visitor).handle(); if (dclause != null) catchClauses.add(dclause); } DBlock finallyBlock = new DBlock.Handle(statement.getFinally(), visitor).handle(); if (tryBlock != null && (catchClauses.size() > 0 || finallyBlock != null)) return new DTryStatement(tryBlock, catchClauses, finallyBlock); if (tryBlock != null) return tryBlock; return null; } } }